From b3ecc1722b9c936d9c135966ba2895567f8d1ad7 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 25 Oct 2026 19:59:00 +0000 Subject: [PATCH 1/5] Shop hooks: several durations per service, slots become time windows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A service now has `durations` ([{ minutes, price }]) instead of one duration and price. A slot is either a `window` (a stretch of time with the services that can be booked in it, start times every 30 min or only at the edges of the free time) or a `session` (one service, fixed time, places — the old group slot). Basket and order lines carry their own start and minutes, so availability is computed from bookings alone. The migration keeps paid bookings blocking their time (order lines get minutes from their slot), then deletes the old slots — agreed: start fresh. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- pb_schema.json | 1031 +++++++++-------- pocketbase/pb_hooks/shop.pb.js | 9 +- pocketbase/pb_hooks/shop/lib.js | 510 +++++--- .../1793100000_durations_and_time_windows.js | 165 +++ 4 files changed, 1061 insertions(+), 654 deletions(-) create mode 100644 pocketbase/pb_migrations/1793100000_durations_and_time_windows.js diff --git a/pb_schema.json b/pb_schema.json index f2d9e40..a8343ec 100644 --- a/pb_schema.json +++ b/pb_schema.json @@ -1,512 +1,519 @@ -[ - { - "id": "pbc_pages000001", - "name": "pages", - "type": "base", - "system": false, - "listRule": "published = true || @request.auth.id != ''", - "viewRule": "published = true || @request.auth.id != ''", - "createRule": "@request.auth.id != ''", - "updateRule": "@request.auth.id != ''", - "deleteRule": "@request.auth.id != ''", - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { - "id": "text_slug00001", - "name": "slug", - "type": "text", - "system": false, - "required": true, - "presentable": true, - "unique": true, - "options": { - "min": null, - "max": 120, - "pattern": "" - } - }, - { - "id": "text_title0001", - "name": "title", - "type": "text", - "system": false, - "required": true, - "presentable": false, - "unique": false, - "options": { - "min": null, - "max": 180, - "pattern": "" - } - }, - { - "id": "json_blocks001", - "name": "blocks", - "type": "json", - "system": false, - "required": false, - "presentable": false, - "unique": false, - "options": { - "maxSize": 2000000 - } - }, - { - "id": "bool_published", - "name": "published", - "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} - ], - "indexes": [ - "CREATE UNIQUE INDEX `idx_pages_slug_unique` ON `pages` (`slug`)" - ], - "options": {} - }, - { - "id": "pbc_globals0001", - "name": "globals", - "type": "base", - "system": false, - "listRule": "", - "viewRule": "", - "createRule": "@request.auth.id != ''", - "updateRule": "@request.auth.id != ''", - "deleteRule": "@request.auth.id != ''", - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { - "id": "text_key000001", - "name": "key", - "type": "text", - "system": false, - "required": true, - "presentable": true, - "unique": true, - "options": { - "min": null, - "max": 80, - "pattern": "" - } - }, - { - "id": "json_data00001", - "name": "data", - "type": "json", - "system": false, - "required": false, - "presentable": false, - "unique": false, - "options": { - "maxSize": 1000000 - } - }, - {"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 UNIQUE INDEX `idx_globals_key_unique` ON `globals` (`key`)" - ], - "options": {} - }, - { - "id": "pbc_media00001", - "name": "media", - "type": "base", - "system": false, - "listRule": "", - "viewRule": "", - "createRule": "@request.auth.id != ''", - "updateRule": "@request.auth.id != ''", - "deleteRule": "@request.auth.id != ''", - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { - "id": "file_file00001", - "name": "file", - "type": "file", - "system": false, - "required": true, - "maxSelect": 1, - "maxSize": 20971520, - "mimeTypes": ["image/jpeg", "image/png", "image/webp", "image/gif", "image/svg+xml"], - "thumbs": ["300x300", "1200x0"], - "protected": false, - "presentable": false, - "unique": false, - "options": { - "mimeTypes": [ - "image/jpeg", - "image/png", - "image/webp", - "image/gif", - "image/svg+xml" - ], - "thumbs": [ - "300x300", - "1200x0" - ], - "maxSelect": 1, - "maxSize": 20971520, - "protected": false - } - }, - { - "id": "text_alt000001", - "name": "alt", - "type": "text", - "system": false, - "required": false, - "presentable": false, - "unique": false, - "options": { - "min": null, - "max": 180, - "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": [], - "options": {} - }, - { - "id": "pbc_events0001", - "name": "events", - "type": "base", - "system": false, - "listRule": "published = true || @request.auth.id != ''", - "viewRule": "published = true || @request.auth.id != ''", - "createRule": "@request.auth.id != ''", - "updateRule": "@request.auth.id != ''", - "deleteRule": "@request.auth.id != ''", - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { - "id": "text_eventname", - "name": "name", - "type": "text", - "system": false, - "required": true, - "presentable": true, - "unique": false, - "options": { - "min": null, - "max": 180, - "pattern": "" - } - }, - { - "id": "date_eventstart", - "name": "start", - "type": "date", - "system": false, - "required": true, - "presentable": false, - "unique": false, - "options": { - "min": "", - "max": "" - } - }, - { - "id": "date_eventend", - "name": "end", - "type": "date", - "system": false, - "required": false, - "presentable": false, - "unique": false, - "options": { - "min": "", - "max": "" - } - }, - { - "id": "text_eventdesc", - "name": "description", - "type": "text", - "system": false, - "required": false, - "presentable": false, - "unique": false, - "options": { - "min": null, - "max": 2000, - "pattern": "" - } - }, - { - "id": "text_eventcolor", - "name": "color", - "type": "text", - "system": false, - "required": false, - "presentable": false, - "unique": false, - "options": { - "min": null, - "max": 32, - "pattern": "" - } - }, - { - "id": "url_eventlink", - "name": "link", - "type": "text", - "system": false, - "required": false, - "presentable": false, - "unique": false, - "options": { - "min": null, - "max": 500, - "pattern": "" - } - }, - { - "id": "json_eventcats", - "name": "categories", - "type": "json", - "system": false, - "required": false, - "presentable": false, - "unique": false, - "options": { - "maxSize": 200000 - } - }, - { - "id": "bool_eventpub", - "name": "published", - "type": "bool", - "system": false, - "required": false, - "presentable": false, - "unique": false, - "options": {} - }, - { - "id": "bool_eventallday", - "name": "allDay", - "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} - ], - "indexes": [ - "CREATE INDEX `idx_events_start` ON `events` (`start`)", - "CREATE INDEX `idx_events_published` ON `events` (`published`)" - ], - "options": {} - }, - { - "id": "pbc_items00001", - "name": "items", - "type": "base", - "system": false, - "listRule": "active = true || @request.auth.id != ''", - "viewRule": "active = true || @request.auth.id != ''", - "createRule": "@request.auth.id != ''", - "updateRule": "@request.auth.id != ''", - "deleteRule": "@request.auth.id != ''", - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { "id": "text_itemname01", "name": "name", "type": "text", "system": false, "required": true, "presentable": true, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } }, - { "id": "text_itemdesc01", "name": "description", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } }, - { "id": "num_itemprice01", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, - { "id": "rel_itemimage01", "name": "image", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_media00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, - { "id": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time"] }, - { "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} - ], - "indexes": [], - "autodate": true, - "options": {} - }, - { - "id": "pbc_slots00001", - "name": "slots", - "type": "base", - "system": false, - "listRule": "@request.auth.id != ''", - "viewRule": "@request.auth.id != ''", - "createRule": "@request.auth.id != ''", - "updateRule": "@request.auth.id != ''", - "deleteRule": "@request.auth.id != ''", - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { "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": "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`)" - ], - "autodate": true, - "options": {} - }, - { - "id": "pbc_baskets0001", - "name": "baskets", - "type": "base", - "system": false, - "listRule": "@request.auth.id != ''", - "viewRule": "@request.auth.id != ''", - "createRule": null, - "updateRule": null, - "deleteRule": "@request.auth.id != ''", - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { "id": "sel_basketstat0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["active", "completed", "abandoned"] }, - { "id": "date_basketexp0", "name": "expiresAt", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, - { "id": "text_basketemai", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } }, - { "id": "json_basketcust", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } }, - { "id": "text_basketstrip", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "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_baskets_status` ON `baskets` (`status`)" - ], - "autodate": true, - "options": {} - }, - { - "id": "pbc_basketlines1", - "name": "basket_lines", - "type": "base", - "system": false, - "listRule": "@request.auth.id != ''", - "viewRule": "@request.auth.id != ''", - "createRule": null, - "updateRule": null, - "deleteRule": null, - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { "id": "rel_blbasket0001", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null }, - { "id": "rel_blitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "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": "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 INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)" - ], - "autodate": true, - "options": {} - }, - { - "id": "pbc_orders00001", - "name": "orders", - "type": "base", - "system": false, - "listRule": "@request.auth.id != ''", - "viewRule": "@request.auth.id != ''", - "createRule": null, - "updateRule": "@request.auth.id != ''", - "deleteRule": "@request.auth.id != ''", - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { "id": "rel_orderbasket0", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, - { "id": "text_orderemail0", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } }, - { "id": "json_ordercustde", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } }, - { "id": "num_ordertotal01", "name": "total", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, - { "id": "sel_orderstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["pending", "paid", "refunded"] }, - { "id": "text_orderstripe0", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } }, - { "id": "date_ordcustmail", "name": "customerEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, - { "id": "date_ordclntmail", "name": "clientEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, - { "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } }, - { "id": "date_ordanonym01", "name": "anonymisedAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "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_orders_basket` ON `orders` (`basket`)", - "CREATE INDEX `idx_orders_email` ON `orders` (`email`)" - ], - "autodate": true, - "options": {} - }, - { - "id": "pbc_orderlines01", - "name": "order_lines", - "type": "base", - "system": false, - "listRule": "@request.auth.id != ''", - "viewRule": "@request.auth.id != ''", - "createRule": null, - "updateRule": null, - "deleteRule": null, - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { "id": "rel_olorder00001", "name": "order", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null }, - { "id": "rel_olitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, - { "id": "rel_olslot000001", "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_olquantity01", "name": "quantity", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 1, "max": null } }, - { "id": "sel_ollinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] }, - { "id": "text_olname00001", "name": "name", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } }, - { "id": "num_olprice00001", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, - { "id": "date_olstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "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_order_lines_order` ON `order_lines` (`order`)", - "CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)" - ], - "autodate": true, - "options": {} - }, - { - "id": "pbc_emailtpl0001", - "name": "email_templates", - "type": "base", - "system": false, - "listRule": "@request.auth.id != ''", - "viewRule": "@request.auth.id != ''", - "createRule": "@request.auth.id != ''", - "updateRule": "@request.auth.id != ''", - "deleteRule": "@request.auth.id != ''", - "fields": [ - { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, - { "id": "text_etplkey0001", "name": "key", "type": "text", "system": false, "required": true, "presentable": true, "unique": true, "options": { "min": null, "max": 80, "pattern": "" } }, - { "id": "text_etplsubject", "name": "subject", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 300, "pattern": "" } }, - { "id": "json_etplblocks0", "name": "blocks", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 2000000 } }, - { "id": "text_etplrecips0", "name": "recipients", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } }, - { "id": "bool_etplenabled", "name": "enabled", "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} - ], - "indexes": [ - "CREATE UNIQUE INDEX `idx_email_templates_key` ON `email_templates` (`key`)" - ], - "autodate": true, - "options": {} - } -] +[ + { + "id": "pbc_pages000001", + "name": "pages", + "type": "base", + "system": false, + "listRule": "published = true || @request.auth.id != ''", + "viewRule": "published = true || @request.auth.id != ''", + "createRule": "@request.auth.id != ''", + "updateRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { + "id": "text_slug00001", + "name": "slug", + "type": "text", + "system": false, + "required": true, + "presentable": true, + "unique": true, + "options": { + "min": null, + "max": 120, + "pattern": "" + } + }, + { + "id": "text_title0001", + "name": "title", + "type": "text", + "system": false, + "required": true, + "presentable": false, + "unique": false, + "options": { + "min": null, + "max": 180, + "pattern": "" + } + }, + { + "id": "json_blocks001", + "name": "blocks", + "type": "json", + "system": false, + "required": false, + "presentable": false, + "unique": false, + "options": { + "maxSize": 2000000 + } + }, + { + "id": "bool_published", + "name": "published", + "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} + ], + "indexes": [ + "CREATE UNIQUE INDEX `idx_pages_slug_unique` ON `pages` (`slug`)" + ], + "options": {} + }, + { + "id": "pbc_globals0001", + "name": "globals", + "type": "base", + "system": false, + "listRule": "", + "viewRule": "", + "createRule": "@request.auth.id != ''", + "updateRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { + "id": "text_key000001", + "name": "key", + "type": "text", + "system": false, + "required": true, + "presentable": true, + "unique": true, + "options": { + "min": null, + "max": 80, + "pattern": "" + } + }, + { + "id": "json_data00001", + "name": "data", + "type": "json", + "system": false, + "required": false, + "presentable": false, + "unique": false, + "options": { + "maxSize": 1000000 + } + }, + {"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 UNIQUE INDEX `idx_globals_key_unique` ON `globals` (`key`)" + ], + "options": {} + }, + { + "id": "pbc_media00001", + "name": "media", + "type": "base", + "system": false, + "listRule": "", + "viewRule": "", + "createRule": "@request.auth.id != ''", + "updateRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { + "id": "file_file00001", + "name": "file", + "type": "file", + "system": false, + "required": true, + "maxSelect": 1, + "maxSize": 20971520, + "mimeTypes": ["image/jpeg", "image/png", "image/webp", "image/gif", "image/svg+xml"], + "thumbs": ["300x300", "1200x0"], + "protected": false, + "presentable": false, + "unique": false, + "options": { + "mimeTypes": [ + "image/jpeg", + "image/png", + "image/webp", + "image/gif", + "image/svg+xml" + ], + "thumbs": [ + "300x300", + "1200x0" + ], + "maxSelect": 1, + "maxSize": 20971520, + "protected": false + } + }, + { + "id": "text_alt000001", + "name": "alt", + "type": "text", + "system": false, + "required": false, + "presentable": false, + "unique": false, + "options": { + "min": null, + "max": 180, + "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": [], + "options": {} + }, + { + "id": "pbc_events0001", + "name": "events", + "type": "base", + "system": false, + "listRule": "published = true || @request.auth.id != ''", + "viewRule": "published = true || @request.auth.id != ''", + "createRule": "@request.auth.id != ''", + "updateRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { + "id": "text_eventname", + "name": "name", + "type": "text", + "system": false, + "required": true, + "presentable": true, + "unique": false, + "options": { + "min": null, + "max": 180, + "pattern": "" + } + }, + { + "id": "date_eventstart", + "name": "start", + "type": "date", + "system": false, + "required": true, + "presentable": false, + "unique": false, + "options": { + "min": "", + "max": "" + } + }, + { + "id": "date_eventend", + "name": "end", + "type": "date", + "system": false, + "required": false, + "presentable": false, + "unique": false, + "options": { + "min": "", + "max": "" + } + }, + { + "id": "text_eventdesc", + "name": "description", + "type": "text", + "system": false, + "required": false, + "presentable": false, + "unique": false, + "options": { + "min": null, + "max": 2000, + "pattern": "" + } + }, + { + "id": "text_eventcolor", + "name": "color", + "type": "text", + "system": false, + "required": false, + "presentable": false, + "unique": false, + "options": { + "min": null, + "max": 32, + "pattern": "" + } + }, + { + "id": "url_eventlink", + "name": "link", + "type": "text", + "system": false, + "required": false, + "presentable": false, + "unique": false, + "options": { + "min": null, + "max": 500, + "pattern": "" + } + }, + { + "id": "json_eventcats", + "name": "categories", + "type": "json", + "system": false, + "required": false, + "presentable": false, + "unique": false, + "options": { + "maxSize": 200000 + } + }, + { + "id": "bool_eventpub", + "name": "published", + "type": "bool", + "system": false, + "required": false, + "presentable": false, + "unique": false, + "options": {} + }, + { + "id": "bool_eventallday", + "name": "allDay", + "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} + ], + "indexes": [ + "CREATE INDEX `idx_events_start` ON `events` (`start`)", + "CREATE INDEX `idx_events_published` ON `events` (`published`)" + ], + "options": {} + }, + { + "id": "pbc_items00001", + "name": "items", + "type": "base", + "system": false, + "listRule": "active = true || @request.auth.id != ''", + "viewRule": "active = true || @request.auth.id != ''", + "createRule": "@request.auth.id != ''", + "updateRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { "id": "text_itemname01", "name": "name", "type": "text", "system": false, "required": true, "presentable": true, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } }, + { "id": "text_itemdesc01", "name": "description", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } }, + { "id": "num_itemprice01", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, + { "id": "rel_itemimage01", "name": "image", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_media00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, + { "id": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time"] }, + { "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, + { "id": "json_itemdurations", "name": "durations", "type": "json", "system": false, "required": false, "presentable": false, "hidden": false, "maxSize": 20000 }, + { "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} + ], + "indexes": [], + "autodate": true, + "options": {} + }, + { + "id": "pbc_slots00001", + "name": "slots", + "type": "base", + "system": false, + "listRule": "@request.auth.id != ''", + "viewRule": "@request.auth.id != ''", + "createRule": "@request.auth.id != ''", + "updateRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { "id": "sel_slotkind001", "name": "kind", "type": "select", "system": false, "required": true, "presentable": false, "hidden": false, "maxSelect": 1, "values": ["window", "session"] }, + { "id": "rel_slotitems01", "name": "items", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 50 }, + { "id": "sel_slotstarts1", "name": "startTimes", "type": "select", "system": false, "required": false, "presentable": false, "hidden": false, "maxSelect": 1, "values": ["grid", "edges"] }, + { "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": "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_start` ON `slots` (`start`)" + ], + "autodate": true, + "options": {} + }, + { + "id": "pbc_baskets0001", + "name": "baskets", + "type": "base", + "system": false, + "listRule": "@request.auth.id != ''", + "viewRule": "@request.auth.id != ''", + "createRule": null, + "updateRule": null, + "deleteRule": "@request.auth.id != ''", + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { "id": "sel_basketstat0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["active", "completed", "abandoned"] }, + { "id": "date_basketexp0", "name": "expiresAt", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, + { "id": "text_basketemai", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } }, + { "id": "json_basketcust", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } }, + { "id": "text_basketstrip", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "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_baskets_status` ON `baskets` (`status`)" + ], + "autodate": true, + "options": {} + }, + { + "id": "pbc_basketlines1", + "name": "basket_lines", + "type": "base", + "system": false, + "listRule": "@request.auth.id != ''", + "viewRule": "@request.auth.id != ''", + "createRule": null, + "updateRule": null, + "deleteRule": null, + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { "id": "rel_blbasket0001", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null }, + { "id": "rel_blitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "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": "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": "date_blstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" }, + { "id": "num_blminutes001", "name": "minutes", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": null, "onlyInt": true }, + {"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 INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)", + "CREATE INDEX `idx_basket_lines_start` ON `basket_lines` (`start`)" + ], + "autodate": true, + "options": {} + }, + { + "id": "pbc_orders00001", + "name": "orders", + "type": "base", + "system": false, + "listRule": "@request.auth.id != ''", + "viewRule": "@request.auth.id != ''", + "createRule": null, + "updateRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { "id": "rel_orderbasket0", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, + { "id": "text_orderemail0", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } }, + { "id": "json_ordercustde", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } }, + { "id": "num_ordertotal01", "name": "total", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, + { "id": "sel_orderstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["pending", "paid", "refunded"] }, + { "id": "text_orderstripe0", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } }, + { "id": "date_ordcustmail", "name": "customerEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, + { "id": "date_ordclntmail", "name": "clientEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, + { "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } }, + { "id": "date_ordanonym01", "name": "anonymisedAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "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_orders_basket` ON `orders` (`basket`)", + "CREATE INDEX `idx_orders_email` ON `orders` (`email`)" + ], + "autodate": true, + "options": {} + }, + { + "id": "pbc_orderlines01", + "name": "order_lines", + "type": "base", + "system": false, + "listRule": "@request.auth.id != ''", + "viewRule": "@request.auth.id != ''", + "createRule": null, + "updateRule": null, + "deleteRule": null, + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { "id": "rel_olorder00001", "name": "order", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null }, + { "id": "rel_olitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, + { "id": "rel_olslot000001", "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_olquantity01", "name": "quantity", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 1, "max": null } }, + { "id": "sel_ollinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] }, + { "id": "text_olname00001", "name": "name", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } }, + { "id": "num_olprice00001", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, + { "id": "date_olstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, + { "id": "num_olminutes001", "name": "minutes", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": null, "onlyInt": true }, + {"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_order_lines_order` ON `order_lines` (`order`)", + "CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)", + "CREATE INDEX `idx_order_lines_start` ON `order_lines` (`start`)" + ], + "autodate": true, + "options": {} + }, + { + "id": "pbc_emailtpl0001", + "name": "email_templates", + "type": "base", + "system": false, + "listRule": "@request.auth.id != ''", + "viewRule": "@request.auth.id != ''", + "createRule": "@request.auth.id != ''", + "updateRule": "@request.auth.id != ''", + "deleteRule": "@request.auth.id != ''", + "fields": [ + { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, + { "id": "text_etplkey0001", "name": "key", "type": "text", "system": false, "required": true, "presentable": true, "unique": true, "options": { "min": null, "max": 80, "pattern": "" } }, + { "id": "text_etplsubject", "name": "subject", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 300, "pattern": "" } }, + { "id": "json_etplblocks0", "name": "blocks", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 2000000 } }, + { "id": "text_etplrecips0", "name": "recipients", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } }, + { "id": "bool_etplenabled", "name": "enabled", "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} + ], + "indexes": [ + "CREATE UNIQUE INDEX `idx_email_templates_key` ON `email_templates` (`key`)" + ], + "autodate": true, + "options": {} + } +] diff --git a/pocketbase/pb_hooks/shop.pb.js b/pocketbase/pb_hooks/shop.pb.js index 724db81..c2950eb 100644 --- a/pocketbase/pb_hooks/shop.pb.js +++ b/pocketbase/pb_hooks/shop.pb.js @@ -3,16 +3,17 @@ /// 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`. +// Slot availability (windows, group sessions, blocking — see lib.js). +// 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) => { 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, 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) => { diff --git a/pocketbase/pb_hooks/shop/lib.js b/pocketbase/pb_hooks/shop/lib.js index dc68283..9a0d2e8 100644 --- a/pocketbase/pb_hooks/shop/lib.js +++ b/pocketbase/pb_hooks/shop/lib.js @@ -62,150 +62,346 @@ function pbDate(ms) { 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 ─────────────────────────────────────────────────── // -// 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). +// Nothing about bookings is stored on a slot. Bookings are paid order lines +// and basket lines whose hold (`heldUntil`) hasn't lapsed; each has its own +// `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 -// 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. +// A slot is either +// - a `window` (09:00–12:00 with the services that can be booked in it): +// a booking may start wherever its length plus get-ready time is free. +// `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). - * `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. + * Bookings starting in [rangeStart - 1 day, rangeEnd + 1 day), sorted by + * start: `{ lineId, slot, item, itemName, start, end, readyAt, quantity, + * status: 'booked' | 'held' }`. `options.excludeLineId` leaves one basket + * line out (when re-checking that line itself). */ -function slotStates(app, rangeStart, rangeEnd, options) { +function busyTimes(app, rangeStart, rangeEnd, item, 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', + const busy = []; + const add = (line, status) => { + const start = toMs(line.getString('start')); + if (Number.isNaN(start)) return; + const service = item(line.getString('item')); + const end = start + line.getInt('minutes') * MINUTE_MS; + busy.push({ + lineId: line.id, + slot: line.getString('slot'), + item: line.getString('item'), + itemName: service ? service.getString('name') : '', 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'); + readyAt: end + bufferMs(service), + quantity: line.getInt('quantity'), + status + }); + }; + const inRange = 'start >= {:from} && start < {:to}'; + for (const line of findAll(app, 'order_lines', "lineType = 'slot' && order.status != 'refunded' && " + inRange, range)) add(line, 'booked'); + const held = Object.assign({ now: pbDate(Date.now()) }, range); + for (const line of findAll(app, 'basket_lines', "lineType = 'slot' && heldUntil > {:now} && " + inRange, held)) { + if (line.id !== opts.excludeLineId) add(line, 'held'); } - 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); + return busy.sort((a, b) => a.start - b.start); } -/** 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) - })); +function overlapsBusy(busy, start, until) { + return busy.find((b) => b.start < until && start < b.readyAt) || null; } /** - * 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. + * Slots starting in [rangeStart, rangeEnd) (epoch ms) with what's booked + * 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) { - let states; + let slots; + let busy; + let from; + let to; if (query.id) { - const state = slotState(app, String(query.id)); - states = state ? [state] : []; + const record = findOrNull(app, 'slots', String(query.id)); + if (!record) return { slots: [], bookings: [] }; + from = toMs(record.getString('start')); + to = from + 1; + ({ slots, busy } = availability(app, from, to)); } else { - const from = toMs(query.from); - const to = toMs(query.to); + from = toMs(query.from); + 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); + ({ slots, busy } = availability(app, from, to)); + if (query.item) slots = slots.filter((s) => s.items.indexOf(String(query.item)) >= 0); } - 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 - })); + const iso = (ms) => new Date(ms).toISOString(); + 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 }); + return { + slots: slots.map((s) => { + 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 }; + if (s.kind === 'window') { + detail.startTimes = s.startTimes; + detail.free = freeTimes(s, busy).map((f) => ({ start: iso(f.start), end: iso(f.end) })); + } else { + detail.minutes = s.minutes; + 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 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); +/** Check a session can take `seats` more places; returns an ApiError to throw, or null. */ +function seatProblem(session, seats) { + 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'); + if (session.blockedBy) return conflict('This time is no longer available — please pick another'); + const free = freeSeats(session); 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; } +/** + * 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 * 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 }); } -/** 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) { if (!basket) return null; const lines = basketLines(app, basket.id); 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) { @@ -277,10 +487,10 @@ function createBasket(app) { * 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 * 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 - * 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. + * is extended, never shortened (it's already counted). A lapsed one that + * hasn't been swept yet is rescued only if its time could still be booked + * now — otherwise it's left for the sweep, and checkout tells the customer + * the time expired. */ function extendBasketHolds(app, basketId, durationMs) { const now = Date.now(); @@ -297,7 +507,7 @@ function extendBasketHolds(app, basketId, durationMs) { try { app.runInTransaction((tx) => { 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); tx.save(fresh); }); @@ -343,15 +553,35 @@ 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 || ''); - const seats = Math.max(1, Math.floor(Number(body.seats)) || 1); + // A window booking: `slotId` (the window), `itemId`, `minutes` and + // `start` (one of the listed times). A group session: `slotId` and + // `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) => { - 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); + const check = checkBooking(tx, request); + if (check.error) return check.error; + const booking = check.booking; + const existing = + 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)); tx.save(line); }); @@ -364,11 +594,13 @@ function basketAction(app, body) { 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. + // 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) => { const fresh = tx.findRecordById('basket_lines', line.id); - const problem = seatProblem(slotState(tx, fresh.getString('slot'), { excludeLineId: fresh.id }), quantity); - if (problem) return problem; + const slot = findOrNull(tx, 'slots', fresh.getString('slot')); + 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('heldUntil', isoIn(SLOT_HOLD_MS)); tx.save(fresh); @@ -489,7 +721,9 @@ function startCheckout(app, body) { 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')}`); } if (totalCents <= 0) throw new BadRequestError('Basket total must be positive'); @@ -602,12 +836,11 @@ function createOrderFromIntent(app, intent) { }); 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 - // transaction, so availability never sees them free in between. + // transaction, so availability never sees it free in between. for (const line of lines) { const item = findOrNull(tx, 'items', line.getString('item')); - const slot = findOrNull(tx, 'slots', line.getString('slot')); tx.save( newRecord(tx, 'order_lines', { order: order.id, @@ -616,8 +849,9 @@ function createOrderFromIntent(app, intent) { quantity: line.getInt('quantity'), lineType: line.getString('lineType'), name: item ? item.getString('name') : 'Unknown item', - price: item ? item.getFloat('price') : 0, - start: slot ? slot.getString('start') : '' + price: (item && unitPrice(item, line.getInt('minutes'))) || 0, + start: line.getString('start'), + minutes: line.getInt('minutes') }) ); if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') { @@ -715,7 +949,7 @@ function recordEmailStatus(app, secretHeader, body) { } module.exports = { - bookableSlots, + bookableTimes, slotDetails, sweepExpiredHolds, loadActiveBasket, diff --git a/pocketbase/pb_migrations/1793100000_durations_and_time_windows.js b/pocketbase/pb_migrations/1793100000_durations_and_time_windows.js new file mode 100644 index 0000000..346ee71 --- /dev/null +++ b/pocketbase/pb_migrations/1793100000_durations_and_time_windows.js @@ -0,0 +1,165 @@ +/// + +// 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); + } + } +); From 23df2ceced5026e665dab5b9adc63de915da1626 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 25 Oct 2026 20:12:46 +0000 Subject: [PATCH 2/5] Shop hooks: a slot lookup by id returns all of that slot's bookings Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- pocketbase/pb_hooks/shop/lib.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pocketbase/pb_hooks/shop/lib.js b/pocketbase/pb_hooks/shop/lib.js index 9a0d2e8..5bfa13c 100644 --- a/pocketbase/pb_hooks/shop/lib.js +++ b/pocketbase/pb_hooks/shop/lib.js @@ -308,6 +308,8 @@ function bookableTimes(app, query) { /** * 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. + * `bookings`: every booked/held time starting in the range, or for one + * slot, that slot's own. */ function slotDetails(app, query) { let slots; @@ -343,7 +345,7 @@ function slotDetails(app, query) { } return detail; }), - bookings: busy.filter((b) => b.start >= from && b.start < to).map(booking) + bookings: busy.filter((b) => (query.id ? b.slot === String(query.id) : b.start >= from && b.start < to)).map(booking) }; } From eac99b2abe017e7a1c2d1058752e235085a26cf6 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 25 Oct 2026 20:12:46 +0000 Subject: [PATCH 3/5] Shop: duration slider on services, times fetched per service and length Service cards step through their lengths with a slider and the price follows. The time picker loads bookable times for the chosen length and the months on screen from GET /api/slots (a proxy to the shop hook in each app), and reloads when the basket's bookings change. Checkout, emails and the basket show each booking's own length. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- app-admin/src/routes/api/slots/+server.ts | 6 + app-admin/src/routes/preview/+page.server.ts | 5 +- app-admin/src/routes/preview/+page.svelte | 2 +- app-public/src/lib/server/shop.ts | 18 +- app-public/src/routes/+layout.server.ts | 14 +- app-public/src/routes/+page.svelte | 2 +- app-public/src/routes/[slug]/+page.svelte | 2 +- app-public/src/routes/api/basket/+server.ts | 3 + app-public/src/routes/api/slots/+server.ts | 6 + packages/shared/src/basket.svelte.ts | 8 +- .../shared/src/blocks/BlockRenderer.svelte | 7 +- .../shared/src/blocks/CheckoutBlock.svelte | 13 +- packages/shared/src/blocks/ShopBlock.svelte | 354 ++++++++++++------ packages/shared/src/items.ts | 29 ++ packages/shared/src/server/email/index.ts | 10 +- packages/shared/src/server/shop.ts | 90 +++-- packages/shared/src/slots.ts | 79 +++- packages/shared/src/types.ts | 41 +- 18 files changed, 479 insertions(+), 210 deletions(-) create mode 100644 app-admin/src/routes/api/slots/+server.ts create mode 100644 app-public/src/routes/api/slots/+server.ts create mode 100644 packages/shared/src/items.ts diff --git a/app-admin/src/routes/api/slots/+server.ts b/app-admin/src/routes/api/slots/+server.ts new file mode 100644 index 0000000..bda83fa --- /dev/null +++ b/app-admin/src/routes/api/slots/+server.ts @@ -0,0 +1,6 @@ +import { bookableTimesResponse } from '$shared/server/shop'; +import type { RequestHandler } from './$types'; + +// Bookable times for the Shop block's picker (one service and duration). +// Public data from the shop hook in PocketBase — this only forwards it. +export const GET: RequestHandler = ({ locals, url }) => bookableTimesResponse(locals.pb, url); diff --git a/app-admin/src/routes/preview/+page.server.ts b/app-admin/src/routes/preview/+page.server.ts index f219859..f26feb0 100644 --- a/app-admin/src/routes/preview/+page.server.ts +++ b/app-admin/src/routes/preview/+page.server.ts @@ -3,14 +3,15 @@ import { loadShopData } from '$shared/server/shop'; import type { PageServerLoad } from './$types'; // The draft blocks come from sessionStorage (client-side), so load the data -// any block might need: shop items/slots and upcoming events. Failures leave +// any block might need: shop items and upcoming events (Shop blocks fetch +// bookable times themselves). Failures leave // the blocks empty rather than breaking the preview. export const load: PageServerLoad = async ({ locals }) => { const range = getUpcomingCalendarRange(); const [shop, events] = await Promise.all([ loadShopData(locals.pb).catch((e) => { console.warn('Preview: shop data unavailable:', e instanceof Error ? e.message : e); - return { items: [], slots: [] }; + return { items: [] }; }), locals.pb .collection('events') diff --git a/app-admin/src/routes/preview/+page.svelte b/app-admin/src/routes/preview/+page.svelte index 7627ae1..ce3ac68 100644 --- a/app-admin/src/routes/preview/+page.svelte +++ b/app-admin/src/routes/preview/+page.svelte @@ -27,7 +27,7 @@ {#if blocks.length} - + {:else}

No preview content

diff --git a/app-public/src/lib/server/shop.ts b/app-public/src/lib/server/shop.ts index bc1acc5..2417c44 100644 --- a/app-public/src/lib/server/shop.ts +++ b/app-public/src/lib/server/shop.ts @@ -53,7 +53,10 @@ export function postJson(path: string, data: unknown): Promise { type BasketPayload = { record: Record; lines: Record[] } | null; -/** Map the API's raw basket records to the `Basket` type used by the UI. */ +/** PocketBase's "2026-01-01 10:00:00.000Z" → ISO. */ +const pbInstant = (value: string) => new Date(String(value).replace(' ', 'T')).toISOString(); + +/** Map the API's raw basket records (plus `unitPrice`/`end` per line) to the `Basket` type used by the UI. */ export function mapBasket(payload: BasketPayload): Basket | null { if (!payload) return null; const { record, lines } = payload; @@ -68,13 +71,15 @@ export function mapBasket(payload: BasketPayload): Basket | null { slot: line.slot || null, quantity: line.quantity, lineType: line.lineType, + start: line.start ? pbInstant(line.start) : undefined, + end: line.end || undefined, + minutes: line.minutes || undefined, itemName: item?.name, - itemPrice: item?.price, + itemPrice: line.unitPrice ?? null, itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined, - slotStart: slot?.start, - slotEnd: slot?.end, + slotKind: slot?.kind, slotCapacity: slot?.capacity, - heldUntil: line.heldUntil ? new Date(String(line.heldUntil).replace(' ', 'T')).toISOString() : undefined + heldUntil: line.heldUntil ? pbInstant(line.heldUntil) : undefined }; }); return { @@ -116,7 +121,8 @@ export function mapOrder(order: Record, lines: Record[ lineType: l.lineType, name: l.name, price: l.price, - start: l.start || null + start: l.start || null, + minutes: l.minutes || null })) }; } diff --git a/app-public/src/routes/+layout.server.ts b/app-public/src/routes/+layout.server.ts index 5f630e4..9ffe08c 100644 --- a/app-public/src/routes/+layout.server.ts +++ b/app-public/src/routes/+layout.server.ts @@ -1,5 +1,5 @@ import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; -import type { ItemRecord, SlotRecord } from '$lib/types'; +import type { ItemRecord } from '$lib/types'; import { BASKET_COOKIE, getBasket } from '$lib/server/shop'; import { loadShopData } from '$shared/server/shop'; import { DEFAULT_TIMEZONE, shopCurrency } from '$shared/calendar'; @@ -17,8 +17,8 @@ async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { export const load: LayoutServerLoad = async ({ locals, cookies, url }) => { // Reading the path makes this load run again on every navigation, so the - // slots and basket are fresh on each page — places free up or get taken - // (holds lapse, other customers book) while the visitor browses. + // basket is fresh on each page (holds lapse while the visitor browses). + // Shop blocks fetch bookable times themselves (GET /api/slots). void url.pathname; const [header, footer, colors] = await Promise.all([ @@ -30,8 +30,8 @@ export const load: LayoutServerLoad = async ({ locals, cookies, url }) => { if (!header.homePage) header.homePage = defaultHeader.homePage; // Commerce data for the public site. The listing is public data (API - // rules allow active items / available slots); the basket comes from the - // shop API in PocketBase. Failures leave the shop empty, never break a page. + // rules allow active items); the basket comes from the shop API in + // PocketBase. Failures leave the shop empty, never break a page. const [shop, basket] = await Promise.all([ loadShopData(locals.pb).catch((e) => { console.warn('Shop data unavailable (shop blocks will be empty):', e instanceof Error ? e.message : e); @@ -40,12 +40,12 @@ export const load: LayoutServerLoad = async ({ locals, cookies, url }) => { getBasket(cookies.get(BASKET_COOKIE)).catch(() => null) ]); const items: ItemRecord[] = shop?.items ?? []; - const slots: SlotRecord[] = shop?.slots ?? []; + // Booking times are shown in the studio's timezone, wherever the visitor is. const timezone = env.SITE_TIMEZONE || DEFAULT_TIMEZONE; // Prices are shown in the currency Stripe charges in. const currency = shopCurrency(env.STRIPE_CURRENCY); - return { header, footer, colors, user: locals.user, basket, items, slots, timezone, currency }; + return { header, footer, colors, user: locals.user, basket, items, timezone, currency }; }; diff --git a/app-public/src/routes/+page.svelte b/app-public/src/routes/+page.svelte index 9a906bf..1c22991 100644 --- a/app-public/src/routes/+page.svelte +++ b/app-public/src/routes/+page.svelte @@ -8,4 +8,4 @@ {data.page.title} - + diff --git a/app-public/src/routes/[slug]/+page.svelte b/app-public/src/routes/[slug]/+page.svelte index 9dc42fd..584ebeb 100644 --- a/app-public/src/routes/[slug]/+page.svelte +++ b/app-public/src/routes/[slug]/+page.svelte @@ -7,4 +7,4 @@ {data.page.title} - + diff --git a/app-public/src/routes/api/basket/+server.ts b/app-public/src/routes/api/basket/+server.ts index 29a1d15..9b43946 100644 --- a/app-public/src/routes/api/basket/+server.ts +++ b/app-public/src/routes/api/basket/+server.ts @@ -21,6 +21,9 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => { action: body.action, itemId: body.itemId, slotId: body.slotId, + minutes: body.minutes, + start: body.start, + seats: body.seats, lineId: body.lineId, quantity: body.quantity, basketId: cookies.get(BASKET_COOKIE) || '' diff --git a/app-public/src/routes/api/slots/+server.ts b/app-public/src/routes/api/slots/+server.ts new file mode 100644 index 0000000..bda83fa --- /dev/null +++ b/app-public/src/routes/api/slots/+server.ts @@ -0,0 +1,6 @@ +import { bookableTimesResponse } from '$shared/server/shop'; +import type { RequestHandler } from './$types'; + +// Bookable times for the Shop block's picker (one service and duration). +// Public data from the shop hook in PocketBase — this only forwards it. +export const GET: RequestHandler = ({ locals, url }) => bookableTimesResponse(locals.pb, url); diff --git a/packages/shared/src/basket.svelte.ts b/packages/shared/src/basket.svelte.ts index 6440820..365a29d 100644 --- a/packages/shared/src/basket.svelte.ts +++ b/packages/shared/src/basket.svelte.ts @@ -72,8 +72,12 @@ export function createBasketStore(initial: Basket | null) { applyBasket(await callApi({ action: 'add_item', itemId, quantity })); } - async function addSlotLine(slotId: string) { - await applySlotChange(await callApi({ action: 'add_slot', slotId })); + /** + * Book a time: in a window, `slotId` plus the service, length and start + * picked; for a group session, `slotId` alone (one place). + */ + async function addSlotLine(slotId: string, booking: { itemId: string; minutes: number; start: string } | null = null) { + await applySlotChange(await callApi({ action: 'add_slot', slotId, ...booking })); } async function updateQuantity(lineId: string, quantity: number) { diff --git a/packages/shared/src/blocks/BlockRenderer.svelte b/packages/shared/src/blocks/BlockRenderer.svelte index 94524cb..67ba243 100644 --- a/packages/shared/src/blocks/BlockRenderer.svelte +++ b/packages/shared/src/blocks/BlockRenderer.svelte @@ -1,5 +1,5 @@
@@ -202,13 +287,14 @@
{#each visibleItems as item (item.id)} {@const ui = cardStates[item.id]} - {@const itemSlotsByDay = slotsByDay.get(item.id)} {@const isService = item.type === 'item_with_time'} + {@const duration = isService ? selectedDuration(item, ui) : null} + {@const bookable = !isService || !!duration} {@const soldOut = !isService && item.stock === 0} {@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
{#if item.imageUrl} @@ -234,18 +320,48 @@

{item.description}

{/if} -
- {formatPrice(item.price, currency)} - {#if isService && item.duration != null} - {item.duration} min - {:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5} - - Only {item.stock} left - - {:else if soldOut} - - Sold out - +
+ {#if isService && item.durations.length > 1 && ui} + + + + {:else} +
+ {formatPrice(duration?.price ?? lowestPrice(item.durations) ?? item.price, currency)} + {#if duration} + {formatDuration(duration.minutes)} + {:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5} + + Only {item.stock} left + + {:else if soldOut} + + Sold out + + {/if} +
{/if}
@@ -272,13 +388,14 @@ type="button" class="inline-flex items-center justify-center gap-2 rounded-full px-6 py-2.5 text-sm font-medium transition {ui?.pickerOpen ? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5' - : itemSlotsByDay?.size + : bookable ? 'bg-sage text-primary-content hover:bg-sage-dark' : 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}" - disabled={!itemSlotsByDay?.size && !ui?.pickerOpen} + disabled={!bookable && !ui?.pickerOpen} + aria-expanded={!!ui?.pickerOpen} onclick={() => togglePicker(item.id)} > - {itemSlotsByDay?.size ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'} + {bookable ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'} {:else}
- {#if isService && ui?.pickerOpen && itemSlotsByDay} - {@const availableKeys = [...itemSlotsByDay.keys()].sort()} + {#if isService && ui?.pickerOpen && duration} + {@const byDay = entriesByDay(item, ui, duration.minutes)} + {@const availableKeys = [...byDay.keys()].sort()} {@const months = pickerMonths(ui.monthOffset)} - {@const shownFrom = months[0].days.find((d) => d.inMonth)!.dateKey} - {@const shownTo = months[months.length - 1].days.findLast((d) => d.inMonth)!.dateKey} - {@const anyShown = availableKeys.some((key) => key >= shownFrom && key <= shownTo)} - {@const lastOffset = monthOffsetOf(availableKeys[availableKeys.length - 1]) - (MONTHS_SHOWN - 1)} + {@const shown = shownRange(ui.monthOffset)} + {@const anyShown = availableKeys.some((key) => key >= shown.from && key <= shown.to)}
-

Select a date

+

+ {#if ui.loading}{/if} + Select a date · {formatDuration(duration.minutes)} +

- {#if !anyShown && availableKeys.length} + {#if ui.loadError} + + {:else if !ui.loading && !anyShown}
- - {availableKeys[0] > shownTo ? 'The first available date is' : 'The next available date is'} - {formatDateKey(availableKeys.find((key) => key > shownTo) ?? availableKeys[0], { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}. - - + {#if ui.next} + The next available date for {formatDuration(duration.minutes)} is {longDate(zonedDateKey(ui.next, timezone))}. + + {:else} + No times are available for {formatDuration(duration.minutes)} in these months{item.durations.length > 1 ? ' — try another length' : ''}. + {/if}
{/if} @@ -358,7 +480,7 @@ {letter} {/each} {#each month.days as day (day.dateKey)} - {@const selectable = day.inMonth && itemSlotsByDay.has(day.dateKey)} + {@const selectable = day.inMonth && byDay.has(day.dateKey)} {@const selected = selectable && ui.selectedDayKey === day.dateKey} - {#if ui.pendingSlotId === slot.id}{:else}{line.quantity}{/if} - {line.quantity === 1 ? 'place' : 'places'} in your basket + {#if pending}{:else}{entry.line.quantity}{/if} + {entry.line.quantity === 1 ? 'place' : 'places'} in your basket @@ -424,27 +546,25 @@ {:else} {/if} {/each}
{:else if anyShown} -

- Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}. -

+

Days with availability are highlighted.

{/if} {#if ui.justAdded} diff --git a/packages/shared/src/items.ts b/packages/shared/src/items.ts new file mode 100644 index 0000000..2d1fd5c --- /dev/null +++ b/packages/shared/src/items.ts @@ -0,0 +1,29 @@ +// Services and their durations — pure helpers shared by the admin editor, +// the Shop block and the checkout. Which duration costs what is decided +// (and charged) by the shop hooks in PocketBase; this only reads and shows it. + +import type { ItemDuration } from './types'; + +/** A service's `durations` field (JSON, possibly hand-edited) → valid entries, shortest first, one per length. */ +export function parseDurations(raw: unknown): ItemDuration[] { + const list = Array.isArray(raw) ? raw : []; + const seen = new Set(); + return list + .map((d) => ({ minutes: Math.floor(Number(d?.minutes)), price: Number(d?.price) })) + .filter((d) => d.minutes > 0 && Number.isFinite(d.price) && d.price >= 0 && !seen.has(d.minutes) && seen.add(d.minutes)) + .sort((a, b) => a.minutes - b.minutes); +} + +/** `45` → "45 min", `60` → "1 hour", `120` → "2 hours", `90` → "1 h 30 min". */ +export function formatDuration(minutes: number) { + if (minutes < 60) return `${minutes} min`; + const hours = Math.floor(minutes / 60); + const rest = minutes % 60; + if (!rest) return `${hours} ${hours === 1 ? 'hour' : 'hours'}`; + return `${hours} h ${rest} min`; +} + +/** The lowest price among a service's durations (what "from …" shows), or null without any. */ +export function lowestPrice(durations: ItemDuration[]) { + return durations.length ? Math.min(...durations.map((d) => d.price)) : null; +} diff --git a/packages/shared/src/server/email/index.ts b/packages/shared/src/server/email/index.ts index 9b775e0..26c284e 100644 --- a/packages/shared/src/server/email/index.ts +++ b/packages/shared/src/server/email/index.ts @@ -148,14 +148,12 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) { const lineRecords = [...data.lines].sort((a, b) => String(a.start || '').localeCompare(String(b.start || ''))); const lines: EmailLine[] = lineRecords.map((line) => { + // A booking ends after its own length (order lines from before + // lengths were stored fall back to their slot's end). const start = line.start ? new Date(line.start).toISOString() : null; + const minutes = Number(line.minutes) || 0; const slotEnd = line.expand?.slot?.end; - const duration = Number(line.expand?.item?.duration) || 0; - const end = slotEnd - ? new Date(slotEnd).toISOString() - : start && duration - ? new Date(new Date(start).getTime() + duration * 60_000).toISOString() - : null; + const end = start && minutes ? new Date(new Date(start).getTime() + minutes * 60_000).toISOString() : slotEnd ? new Date(slotEnd).toISOString() : null; return { name: String(line.name || 'Item'), price: Number(line.price) || 0, diff --git a/packages/shared/src/server/shop.ts b/packages/shared/src/server/shop.ts index 9d8257a..0fbfe2a 100644 --- a/packages/shared/src/server/shop.ts +++ b/packages/shared/src/server/shop.ts @@ -1,39 +1,63 @@ import type PocketBase from 'pocketbase'; import { getFileUrl } from '../pb'; -import type { ItemRecord, SlotRecord } from '../types'; +import { parseDurations } from '../items'; +import type { BookableTime, ItemRecord } from '../types'; + +/** An `items` record (with `expand.image`) → `ItemRecord`. */ +export function mapItemRecord(record: Record): ItemRecord { + const media = record.expand?.image; + const type = record.type === 'item_with_time' ? 'item_with_time' : 'item'; + return { + id: record.id, + name: String(record.name || ''), + description: String(record.description || ''), + price: Number(record.price) || 0, + image: String(record.image || ''), + imageUrl: media ? getFileUrl('media', media.id, media.file) : '', + type, + stock: record.stock ?? null, + durations: type === 'item_with_time' ? parseDurations(record.durations) : [], + bufferMinutes: record.bufferMinutes ?? null, + capacity: record.capacity ?? null, + active: record.active !== false + }; +} /** - * Active items and bookable future slots, shaped for the Shop/Checkout - * blocks. Used by the public layout and the admin draft preview so both - * render the same shop. - * - * Works with an anonymous client: active items and media are public, and - * slots come from the shop hook (GET /api/shop/slots), which leaves out - * full slots and slots blocked by an overlapping booking. Errors propagate. + * Active items, shaped for the Shop/Checkout blocks. Used by the public + * layout and the admin draft preview so both render the same shop. Works + * with an anonymous client (active items and media are public). Bookable + * times are fetched by the Shop block itself, per service and duration + * (see `loadBookableTimes`). Errors propagate. */ -export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[]; slots: SlotRecord[] }> { - const [itemRecords, { slots }] = await Promise.all([ - pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }), - pb.send<{ slots: SlotRecord[] }>('/api/shop/slots', { requestKey: null }) - ]); - - const items = itemRecords.map((record): ItemRecord => { - const media = record.expand?.image; - return { - id: record.id, - name: record.name, - description: record.description || '', - price: record.price, - image: record.image || '', - imageUrl: media ? getFileUrl('media', media.id, media.file) : '', - type: record.type, - stock: record.stock ?? null, - duration: record.duration ?? null, - bufferMinutes: record.bufferMinutes ?? null, - capacity: record.capacity ?? null, - active: record.active - }; - }); - - return { items, slots }; +export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> { + const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }); + return { items: records.map(mapItemRecord) }; +} + +export type BookableTimesQuery = { item: string; minutes: string; from: string; to: string }; + +/** + * Times a customer can book for one service and duration, from the shop + * hook (GET /api/shop/slots), which applies every availability rule. When + * none start in [from, to), `next` is the first one after (or null). + */ +export function loadBookableTimes(pb: PocketBase, query: BookableTimesQuery) { + return pb.send<{ times: BookableTime[]; next: string | null }>('/api/shop/slots', { query, requestKey: null }); +} + +/** + * GET /api/slots in both apps (the Shop block's time picker): forwards + * ?item=&minutes=&from=&to= to the shop hook. A PocketBase error keeps its + * status and message; PocketBase being down is a 503. + */ +export async function bookableTimesResponse(pb: PocketBase, url: URL): Promise { + const param = (key: string) => url.searchParams.get(key) ?? ''; + try { + return Response.json(await loadBookableTimes(pb, { item: param('item'), minutes: param('minutes'), from: param('from'), to: param('to') })); + } catch (e) { + const status = Number((e as { status?: number })?.status) || 0; + const message = (e as { response?: { message?: string } })?.response?.message; + return Response.json({ message: message || 'Could not load the available times — please try again' }, { status: status >= 400 ? status : 503 }); + } } diff --git a/packages/shared/src/slots.ts b/packages/shared/src/slots.ts index 311ec0b..d02ba34 100644 --- a/packages/shared/src/slots.ts +++ b/packages/shared/src/slots.ts @@ -6,6 +6,7 @@ // zonedInputToIso, so a run across a DST change still starts at 09:00. import { DISPLAY_LOCALE, toZonedDatetimeInput, zonedInputToIso } from './calendar'; +import type { SlotKind, StartTimesMode } from './types'; /** A stretch of the day in which appointments may start and end, e.g. 09:00–12:00. */ export type TimeWindow = { from: string; to: string }; @@ -43,20 +44,49 @@ export type BulkResult = { }; /** - * A slot with its places and blocking, as the shop hook reports it to the - * admin (GET /api/shop/slots?detail=1). Places are taken by paid orders - * (`booked`) and by baskets whose hold hasn't lapsed (`held`); `blockedBy` - * is the overlapping slot whose booking/hold blocks this one. + * A booked or held time, as the shop hook reports it to the admin: paid + * order lines (`booked`) and basket lines whose hold hasn't lapsed + * (`held`). The practitioner is busy until `readyAt` (end + get-ready time). + */ +export type SlotBooking = PlannedSlot & { + slot: string; + item: string; + itemName: string; + readyAt: string; + quantity: number; + status: 'booked' | 'held'; +}; + +/** + * A slot with what's booked in it (GET /api/shop/slots?detail=1). A window + * counts its bookings in `booked`/`held` and lists its `free` stretches; a + * group session has places and may be blocked by an overlapping booking. */ export type SlotDetail = PlannedSlot & { id: string; - item: string; - itemName: string; - capacity: number; + kind: SlotKind; + items: string[]; + itemNames: string[]; notes: string; booked: number; held: number; - blockedBy: string; + // window + startTimes?: StartTimesMode; + free?: PlannedSlot[]; + // session + minutes?: number; + capacity?: number; + blockedBy?: SlotBooking | null; +}; + +export const START_TIMES_LABELS: Record = { + grid: 'Every 30 min', + edges: 'Next free time' +}; + +export const START_TIMES_HINTS: Record = { + grid: 'Customers can start at any half hour where their booking fits.', + edges: 'Customers can only book right at the start or the end of the free time, so the window shrinks from either end and no gaps are left.' }; export type SlotState = 'free' | 'held' | 'booked' | 'full' | 'blocked'; @@ -70,12 +100,18 @@ export const SLOT_STATE_LABELS: Record = { }; /** - * `full` only when paid bookings fill a group; a slot whose last places are - * in baskets reads `held`, since it frees up again if those holds lapse. + * A window is `full` once no free time is left. A session is `full` only + * when paid bookings fill a group; one whose last places are in baskets + * reads `held`, since it frees up again if those holds lapse. */ -export function slotState(slot: Pick): SlotState { - if (slot.booked >= slot.capacity) return slot.capacity > 1 ? 'full' : 'booked'; - if (slot.held && slot.booked + slot.held >= slot.capacity) return 'held'; +export function slotState(slot: Pick): SlotState { + if (slot.kind === 'window') { + if ((slot.booked || slot.held) && !slot.free?.length) return slot.booked ? 'full' : 'held'; + return slot.booked ? 'booked' : slot.held ? 'held' : 'free'; + } + const capacity = slot.capacity ?? 1; + if (slot.booked >= capacity) return capacity > 1 ? 'full' : 'booked'; + if (slot.held && slot.booked + slot.held >= capacity) return 'held'; if (slot.booked) return 'booked'; if (slot.held) return 'held'; return slot.blockedBy ? 'blocked' : 'free'; @@ -191,7 +227,22 @@ export type GeneratePlanInput = { timeZone: string; }; -/** Every slot the generator would create, before skipping overlaps/past ones. */ +/** Each chosen day's opening hours as windows (dates in `timeZone`), before skipping overlaps/past ones. */ +export function planWindows(input: Omit): PlannedSlot[] { + const days = new Set(input.weekdays); + const slots: PlannedSlot[] = []; + for (const key of dateKeysBetween(input.fromDate, input.toDate)) { + if (!days.has(weekdayOfKey(key))) continue; + for (const window of input.windows) { + const start = zonedInputToIso(`${key}T${window.from}`, input.timeZone); + const end = zonedInputToIso(`${key}T${window.to}`, input.timeZone); + if (start && end && end > start) slots.push({ start, end }); + } + } + return slots; +} + +/** Every group session the generator would create, before skipping overlaps/past ones. */ export function planGeneratedSlots(input: GeneratePlanInput): PlannedSlot[] { const times = startTimesInWindows(input.windows, input.durationMinutes, input.bufferMinutes); const days = new Set(input.weekdays); diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index 09e61c3..aa0a888 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -119,31 +119,42 @@ export const defaultPrivacy: PrivacyGlobal = { export type ItemType = 'item' | 'item_with_time'; +/** One length a service can be booked for, and its price. */ +export type ItemDuration = { minutes: number; price: number }; + export type ItemRecord = { id: string; name: string; description: string; + /** A product's price; for a service, its lowest duration price (kept in sync by the admin). */ price: number; image: string; // media record id imageUrl: string; // resolved URL (populated by server load) type: ItemType; stock: number | null; - duration: number | null; // minutes, for item_with_time - bufferMinutes: number | null; // get-ready time after each appointment; default gap when generating slots - capacity: number | null; // places per slot (default for new slots; >1 = group session) + durations: ItemDuration[]; // item_with_time: the lengths it can be booked for, shortest first + bufferMinutes: number | null; // get-ready time after each appointment + capacity: number | null; // places in a new group session (>1 = group) active: boolean; }; +/** `window`: a stretch of time in which its services can be booked; `session`: one service at a fixed time with places. */ +export type SlotKind = 'window' | 'session'; + +/** Where bookings may start in a window: every 30 minutes, or only at the start/end of the free time. */ +export type StartTimesMode = 'grid' | 'edges'; + /** - * A bookable slot as the shop lists it (GET /api/shop/slots): only slots - * with places left that no overlapping booking blocks. + * A time a customer can book, as the shop lists it (GET /api/shop/slots for + * one service and duration): a start time in a window, or a group session + * with places left. */ -export type SlotRecord = { - id: string; - item: string; // item id +export type BookableTime = { + slot: string; // slot id (window or session) + kind: SlotKind; start: string; end: string; - capacity: number; // places in total + capacity: number; // places in total (1 in a window) free: number; // places still bookable }; @@ -156,12 +167,16 @@ export type BasketLine = { slot: string | null; quantity: number; lineType: 'item' | 'slot'; + /** Slot lines: the booked time and length. */ + start?: string; + end?: string; + minutes?: number; // Expanded fields (populated server-side) itemName?: string; - itemPrice?: number; + /** Price of one unit (a product, or the service at this length); null if no longer offered. */ + itemPrice?: number | null; itemImageUrl?: string; - slotStart?: string; - slotEnd?: string; + slotKind?: SlotKind; slotCapacity?: number; /** Slot lines: when the reservation lapses and the line is dropped (ISO). */ heldUntil?: string; @@ -211,6 +226,8 @@ export type OrderLine = { name: string; price: number; start: string | null; + /** Slot lines: the booked length. */ + minutes: number | null; }; // ── Block data types ────────────────────────────────────────────────── From 636b59c706f8f751cddd6ae36432ec815a1530a2 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 25 Oct 2026 20:12:46 +0000 Subject: [PATCH 4/5] Admin: lengths and prices per service; windows and group sessions on /slots Services get rows of length + price. /slots creates windows (date, hours, services, start-times mode) and group sessions (service, length, start, places); the day view shows free time and bookings. Generate/copy/clear handle both kinds; windows may not overlap and can't shrink past a booking. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- .../src/lib/admin/slots/BulkActions.svelte | 4 +- .../lib/admin/slots/ClearSlotsModal.svelte | 4 +- .../src/lib/admin/slots/CopyWeekModal.svelte | 2 +- .../lib/admin/slots/GenerateSlotsModal.svelte | 133 ++++++-- app-admin/src/lib/server/slots.ts | 16 +- .../src/routes/emails/[key]/+page.server.ts | 6 +- app-admin/src/routes/items/+page.server.ts | 105 +++--- app-admin/src/routes/items/+page.svelte | 87 +++-- app-admin/src/routes/orders/+page.server.ts | 3 +- app-admin/src/routes/orders/+page.svelte | 3 +- app-admin/src/routes/slots/+page.server.ts | 316 ++++++++++------- app-admin/src/routes/slots/+page.svelte | 317 +++++++++++++----- 12 files changed, 667 insertions(+), 329 deletions(-) diff --git a/app-admin/src/lib/admin/slots/BulkActions.svelte b/app-admin/src/lib/admin/slots/BulkActions.svelte index bc7aedb..1345df1 100644 --- a/app-admin/src/lib/admin/slots/BulkActions.svelte +++ b/app-admin/src/lib/admin/slots/BulkActions.svelte @@ -26,9 +26,9 @@

Nothing to {deleting ? 'delete' : 'create'}.

{/if}
    - {#if preview.skippedOverlap}
  • {plural(preview.skippedOverlap, 'slot')} skipped — it would overlap a slot of the same service.
  • {/if} + {#if preview.skippedOverlap}
  • {plural(preview.skippedOverlap, 'slot')} skipped — it would overlap another window, or a session of the same service.
  • {/if} {#if preview.skippedPast}
  • {plural(preview.skippedPast, 'slot')} skipped — in the past.
  • {/if} - {#if preview.kept}
  • {plural(preview.kept, 'slot')} kept — booked, or in a customer’s basket right now.
  • {/if} + {#if preview.kept}
  • {plural(preview.kept, 'slot')} kept — something in it is booked, or in a customer’s basket right now.
  • {/if}
{/if} diff --git a/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte b/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte index 5ff93c6..2840345 100644 --- a/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte +++ b/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte @@ -33,7 +33,7 @@
-

Delete the free slots in a date range. Booked slots, and slots in a customer’s basket right now, are always kept.

+

Delete the windows and group sessions in a date range that have nothing booked. Slots with a booking, or with a time in a customer’s basket right now, are always kept.