From e30e1d3bebae316f9a8c75db9f72928b52d8064e Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 25 Oct 2026 21:25:04 +0000 Subject: [PATCH 1/5] Shop hooks: bundles, codes (passes) and orders paid with codes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A bundle (items.type `bundle`) has its own price, parts (a service at a length × count, or a product × count) and a validity in months. Buying one creates a pass with an 8-character code; its parts are snapshotted with their share of the price. Applying a code to a basket covers matching bookings (same service and length) while places are left — counted from order lines and live holds, never stored. A fully covered basket is confirmed without Stripe. Admin routes list, void/extend and issue codes; GDPR export, correction, erasure and retention cover passes (erasure keeps the code working). orders.total, orders.stripePaymentIntentId and order_lines.price are no longer required: PocketBase treats 0 / '' as blank, and a code-paid order has neither a payment nor a price. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- pb_schema.json | 53 +- pocketbase/pb_hooks/privacy/lib.js | 83 ++- pocketbase/pb_hooks/shop.pb.js | 23 +- pocketbase/pb_hooks/shop/lib.js | 515 ++++++++++++++++-- .../1793200000_bundles_and_passes.js | 142 +++++ 5 files changed, 747 insertions(+), 69 deletions(-) create mode 100644 pocketbase/pb_migrations/1793200000_bundles_and_passes.js diff --git a/pb_schema.json b/pb_schema.json index 24d4ae6..0c938e5 100644 --- a/pb_schema.json +++ b/pb_schema.json @@ -328,9 +328,11 @@ { "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": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time", "bundle"] }, { "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": "json_itembundle1", "name": "bundleParts", "type": "json", "system": false, "required": false, "presentable": false, "hidden": false, "maxSize": 20000 }, + { "id": "num_itemvalidmo1", "name": "validMonths", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 1, "max": 120, "onlyInt": true }, { "id": "num_itembuffer1", "name": "bufferMinutes", "type": "number", "system": false, "required": false, "presentable": false, "min": 0, "max": null, "onlyInt": true }, { "id": "num_itemcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true }, { "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }, @@ -387,6 +389,7 @@ { "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": "rel_basketpass01", "name": "pass", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_passes00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1 }, {"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} ], @@ -416,13 +419,17 @@ { "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": "rel_blpass000001", "name": "pass", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_passes00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1 }, + { "id": "text_blgiftto001", "name": "giftTo", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 180, "pattern": "" }, + { "id": "text_blgiftmsg01", "name": "giftMessage", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 1000, "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_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`)" + "CREATE INDEX `idx_basket_lines_start` ON `basket_lines` (`start`)", + "CREATE INDEX `idx_basket_lines_pass` ON `basket_lines` (`pass`)" ], "autodate": true, "options": {} @@ -442,9 +449,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": "num_ordertotal01", "name": "total", "type": "number", "system": false, "required": false, "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": "text_orderstripe0", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "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": "" } }, @@ -477,16 +484,18 @@ { "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": "num_olprice00001", "name": "price", "type": "number", "system": false, "required": false, "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": "rel_olpass000001", "name": "pass", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_passes00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1 }, {"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`)" + "CREATE INDEX `idx_order_lines_start` ON `order_lines` (`start`)", + "CREATE INDEX `idx_order_lines_pass` ON `order_lines` (`pass`)" ], "autodate": true, "options": {} @@ -516,5 +525,37 @@ ], "autodate": true, "options": {} + }, + { + "id": "pbc_passes00001", + "name": "passes", + "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": "text_passcode001", "name": "code", "type": "text", "system": false, "required": true, "presentable": true, "hidden": false, "min": 6, "max": 20, "pattern": "^[A-Z0-9]+$" }, + { "id": "rel_passitem0001", "name": "item", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1 }, + { "id": "rel_passorder001", "name": "order", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_orders00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1 }, + { "id": "text_passname001", "name": "name", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 180, "pattern": "" }, + { "id": "json_passparts01", "name": "parts", "type": "json", "system": false, "required": false, "presentable": false, "hidden": false, "maxSize": 20000 }, + { "id": "text_passemail01", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 320, "pattern": "" }, + { "id": "text_passrecip01", "name": "recipientName", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 180, "pattern": "" }, + { "id": "text_passmessag1", "name": "message", "type": "text", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": 1000, "pattern": "" }, + { "id": "date_passexpire1", "name": "expiresAt", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" }, + { "id": "sel_passstatus01", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "hidden": false, "maxSelect": 1, "values": ["active", "void"] }, + { "id": "date_passanonym1", "name": "anonymisedAt", "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 UNIQUE INDEX `idx_passes_code` ON `passes` (`code`)", + "CREATE INDEX `idx_passes_order` ON `passes` (`order`)", + "CREATE INDEX `idx_passes_email` ON `passes` (`email`)" + ] } ] diff --git a/pocketbase/pb_hooks/privacy/lib.js b/pocketbase/pb_hooks/privacy/lib.js index 451841f..58efd1a 100644 --- a/pocketbase/pb_hooks/privacy/lib.js +++ b/pocketbase/pb_hooks/privacy/lib.js @@ -9,6 +9,11 @@ // - baskets.email + baskets.customerDetails — set when checkout starts. A // paid basket's copy is cleared once the order exists; a basket that was // never paid for is deleted after `abandonedBasketDays`. +// - passes.email (the buyer), recipientName and message (who a bundle or +// voucher is for). Erasure anonymises a pass but keeps its code working — +// it was paid for. Retention anonymises it with the orders, once it has +// expired or has nothing left to book. +// - basket_lines.giftTo / giftMessage — deleted with the basket. // Outside this database: Stripe (receipt email, payment) and the email // provider's send logs. Those are handled in their own dashboards. @@ -62,19 +67,40 @@ function settings(app) { }; } -/** Orders and unpaid baskets whose email is `email` (case-insensitive, exact). */ +/** Orders, unpaid baskets and bought codes whose email is `email` (case-insensitive, exact). */ function customerRecords(app, email) { const wanted = normaliseEmail(email); - if (!wanted) return { orders: [], baskets: [] }; + if (!wanted) return { orders: [], baskets: [], passes: [] }; // `~` is a case-insensitive LIKE, but also a substring match (and `_` is a // wildcard), so narrow it to the exact address here. const same = (record) => normaliseEmail(record.getString('email')) === wanted; return { orders: app.findRecordsByFilter('orders', 'email ~ {:email}', '-created', 0, 0, { email: wanted }).filter(same), - baskets: app.findRecordsByFilter('baskets', "email ~ {:email} && status != 'completed'", '-updated', 0, 0, { email: wanted }).filter(same) + baskets: app.findRecordsByFilter('baskets', "email ~ {:email} && status != 'completed'", '-updated', 0, 0, { email: wanted }).filter(same), + passes: app.findRecordsByFilter('passes', 'email ~ {:email}', '-created', 0, 0, { email: wanted }).filter(same) }; } +/** Keep the code (it was paid for); drop who bought it and who it's for. */ +function anonymisePass(app, pass) { + pass.set('email', ''); + pass.set('recipientName', ''); + pass.set('message', ''); + pass.set('anonymisedAt', new Date().toISOString()); + app.save(pass); +} + +/** Whether a pass can't be used any more: expired, void, or every booking used. */ +function passFinished(app, pass) { + const expires = Date.parse(pass.getString('expiresAt').replace(' ', 'T')); + if (pass.getString('status') !== 'active' || expires <= Date.now()) return true; + const parts = JSON.parse(toString(pass.get('parts')) || '[]') || []; + let booked = 0; + for (const line of app.findRecordsByFilter('order_lines', "pass = {:pass} && order.status != 'refunded'", '', 0, 0, { pass: pass.id })) booked += line.getInt('quantity'); + const bookable = parts.filter((p) => p.minutes).reduce((n, p) => n + p.count, 0); + return booked >= bookable; +} + function hasUpcomingBooking(app, orderId) { return app.findRecordsByFilter('order_lines', "order = {:order} && lineType = 'slot' && start > {:now}", '', 1, 0, { order: orderId, now: pbDate(Date.now()) }).length > 0; } @@ -97,7 +123,7 @@ function clearBasketDetails(app, basket) { function applyRetention(app) { const { abandonedBasketDays, anonymiseOrdersAfterMonths } = settings(app); - const counts = { basketsDeleted: 0, basketsCleared: 0, ordersAnonymised: 0 }; + const counts = { basketsDeleted: 0, basketsCleared: 0, ordersAnonymised: 0, passesAnonymised: 0 }; // Unpaid baskets (their lines cascade). Active ones expire after a day // and are swept to `abandoned`, so `updated` is when they were last used. @@ -134,9 +160,20 @@ function applyRetention(app) { console.error('[privacy] could not anonymise order', order.id, e); } } + // Codes: same age, and only once they can't be used any more (whoever + // holds one may still need it looked up). + for (const pass of app.findRecordsByFilter('passes', "anonymisedAt = '' && created < {:cutoff}", '', 0, 0, { cutoff: pbDate(cutoff.getTime()) })) { + if (!passFinished(app, pass)) continue; + try { + anonymisePass(app, pass); + counts.passesAnonymised++; + } catch (e) { + console.error('[privacy] could not anonymise pass', pass.id, e); + } + } } - if (counts.basketsDeleted || counts.basketsCleared || counts.ordersAnonymised) { + if (counts.basketsDeleted || counts.basketsCleared || counts.ordersAnonymised || counts.passesAnonymised) { console.log('[privacy] retention:', JSON.stringify(counts)); } return counts; @@ -176,7 +213,7 @@ function searchCustomers(app, query) { /** Everything stored about one customer — the admin's detail view and the GDPR export. */ function customerData(app, email) { - const { orders, baskets } = customerRecords(app, email); + const { orders, baskets, passes } = customerRecords(app, email); return { email: normaliseEmail(email), exportedAt: new Date().toISOString(), @@ -199,6 +236,16 @@ function customerData(app, email) { })) }; }), + // Bundle/voucher codes bought with this email, and who they are for. + codes: passes.map((pass) => ({ + code: pass.getString('code'), + name: pass.getString('name'), + created: pass.getString('created'), + expiresAt: pass.getString('expiresAt'), + status: pass.getString('status'), + recipientName: pass.getString('recipientName'), + message: pass.getString('message') + })), // Checkouts that were started but never paid for. unpaidBaskets: baskets.map((basket) => ({ id: basket.id, @@ -229,24 +276,36 @@ function updateCustomer(app, body) { let updated = 0; app.runInTransaction((tx) => { - const { orders, baskets } = customerRecords(tx, email); - if (!orders.length && !baskets.length) throw new NotFoundError('No customer with that email'); + const { orders, baskets, passes } = customerRecords(tx, email); + if (!orders.length && !baskets.length && !passes.length) throw new NotFoundError('No customer with that email'); for (const record of [...orders, ...baskets]) { record.set('customerDetails', Object.assign(details(record), patch)); if (patch.email) record.set('email', patch.email); tx.save(record); updated++; } + // Codes only hold the email. + if (patch.email) { + for (const pass of passes) { + pass.set('email', patch.email); + tx.save(pass); + updated++; + } + } }); return { updated, email: patch.email ? normaliseEmail(patch.email) : email }; } -/** Right to erasure: anonymise the customer's orders and delete their unpaid baskets. */ +/** Right to erasure: anonymise the customer's orders and codes, and delete their unpaid baskets. */ function eraseCustomer(app, body) { - const counts = { ordersAnonymised: 0, basketsDeleted: 0 }; + const counts = { ordersAnonymised: 0, basketsDeleted: 0, passesAnonymised: 0 }; app.runInTransaction((tx) => { - const { orders, baskets } = customerRecords(tx, body.email); - if (!orders.length && !baskets.length) throw new NotFoundError('No customer with that email'); + const { orders, baskets, passes } = customerRecords(tx, body.email); + if (!orders.length && !baskets.length && !passes.length) throw new NotFoundError('No customer with that email'); + for (const pass of passes) { + anonymisePass(tx, pass); + counts.passesAnonymised++; + } for (const order of orders) { anonymiseOrder(tx, order); counts.ordersAnonymised++; diff --git a/pocketbase/pb_hooks/shop.pb.js b/pocketbase/pb_hooks/shop.pb.js index c2950eb..cc0fff1 100644 --- a/pocketbase/pb_hooks/shop.pb.js +++ b/pocketbase/pb_hooks/shop.pb.js @@ -41,7 +41,28 @@ routerAdd('POST', '/api/shop/stripe-webhook', (e) => { routerAdd('GET', '/api/shop/order', (e) => { const shop = require(`${__hooks}/shop/lib.js`); - return e.json(200, shop.orderStatus($app, e.request.url.query().get('payment_intent'))); + const query = e.request.url.query(); + return e.json(200, shop.orderStatus($app, query.get('payment_intent'), { orderId: query.get('order'), basketId: query.get('basket') })); +}); + +// Bundle/voucher codes, for the signed-in admin (Vouchers & codes page). +// Customers only use codes through their basket (`apply_code`). +routerAdd('GET', '/api/shop/passes', (e) => { + if (!e.auth) throw new UnauthorizedError('Sign in to see codes'); + const shop = require(`${__hooks}/shop/lib.js`); + return e.json(200, { passes: shop.listPasses($app, e.request.url.query().get('q')) }); +}); + +routerAdd('POST', '/api/shop/passes/update', (e) => { + if (!e.auth) throw new UnauthorizedError('Sign in to change codes'); + const shop = require(`${__hooks}/shop/lib.js`); + return e.json(200, { pass: shop.updatePass($app, e.requestInfo().body) }); +}); + +routerAdd('POST', '/api/shop/passes/issue', (e) => { + if (!e.auth) throw new UnauthorizedError('Sign in to issue codes'); + const shop = require(`${__hooks}/shop/lib.js`); + return e.json(200, { pass: shop.issuePass($app, e.requestInfo().body) }); }); routerAdd('POST', '/api/shop/order-email-status', (e) => { diff --git a/pocketbase/pb_hooks/shop/lib.js b/pocketbase/pb_hooks/shop/lib.js index 0f4ecc5..5afa85a 100644 --- a/pocketbase/pb_hooks/shop/lib.js +++ b/pocketbase/pb_hooks/shop/lib.js @@ -423,6 +423,272 @@ function guardedTransaction(app, fallback, fn) { if (refusal) throw refusal; } +// ── Bundles and codes ─────────────────────────────────────────────────── +// +// A bundle is an item (type `bundle`) with its own price, made of parts: a +// service at one length × count, or a product × count. Buying one creates a +// pass with a code. Its service parts are booked later — by whoever has the +// code, until it expires — at no charge; product parts are handed over with +// the purchase (stock is taken then). +// +// A pass keeps a snapshot of its parts with each part's share of the price +// (`value`, for refunds). What's used is never stored: it is counted from +// order lines (not refunded) and live basket holds pointing at the pass, +// like slot availability. A basket line gets `pass` when a code covers it; +// that line then costs nothing. + +/** Codes are 8 characters from this alphabet (no 0/O or 1/I to misread). */ +const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; +const CODE_LENGTH = 8; + +function isBundle(item) { + return !!item && item.getString('type') === 'bundle'; +} + +/** A bundle's parts, `[{ item, minutes (null: a product), count }]`; invalid entries are left out. */ +function bundleParts(item) { + const list = jsonValue(item.get('bundleParts'), []); + return (Array.isArray(list) ? list : []) + .map((p) => ({ item: String((p && p.item) || ''), minutes: p && p.minutes ? Math.floor(Number(p.minutes)) : null, count: Math.floor(Number(p && p.count)) || 0 })) + .filter((p) => p.item && p.count > 0); +} + +/** + * A bundle's parts with names and each part's share of the bundle price + * (`value`, all its units together): the price split in proportion to what + * the parts cost on their own (evenly when those are all 0), in cents, with + * the rounding on the last part. Throws an ApiError when a part can't be + * sold — unless `lenient` (an order being created after payment), which + * keeps the part with what it can find. + */ +function bundleSnapshot(app, bundle, lenient) { + const name = bundle.getString('name'); + const parts = bundleParts(bundle).map((part) => { + const item = findOrNull(app, 'items', part.item); + const own = !item ? null : isService(item) ? unitPrice(item, part.minutes) : item.getFloat('price'); + if (own === null && !lenient) throw conflict(`"${name}" can't be bought right now — one of its parts is no longer offered`); + return { item: part.item, name: item ? item.getString('name') : 'Unknown item', minutes: isService(item) ? part.minutes : null, count: part.count, ownCents: Math.round((own || 0) * 100) }; + }); + if (!parts.length && !lenient) throw conflict(`"${name}" has nothing in it yet`); + const totalCents = Math.round(bundle.getFloat('price') * 100); + const units = parts.reduce((n, p) => n + p.count, 0); + const listCents = parts.reduce((sum, p) => sum + p.ownCents * p.count, 0); + let assigned = 0; + parts.forEach((p, i) => { + const share = listCents > 0 ? (p.ownCents * p.count) / listCents : p.count / units; + const cents = i === parts.length - 1 ? totalCents - assigned : Math.round(totalCents * share); + assigned += cents; + p.value = cents / 100; + delete p.ownCents; + }); + return parts; +} + +function normaliseCode(value) { + return String(value || '') + .toUpperCase() + .replace(/[^A-Z0-9]/g, ''); +} + +/** `ABCD2345` → `ABCD-2345`, as shown to people. */ +function formatCode(code) { + return code.length === CODE_LENGTH ? code.slice(0, 4) + '-' + code.slice(4) : code; +} + +function findPassByCode(app, code) { + const normalised = normaliseCode(code); + if (!normalised) return null; + return findAll(app, 'passes', 'code = {:code}', { code: normalised })[0] || null; +} + +function newCode(app) { + for (let attempt = 0; attempt < 10; attempt++) { + const code = $security.randomStringWithAlphabet(CODE_LENGTH, CODE_ALPHABET); + if (!findPassByCode(app, code)) return code; + } + throw new InternalServerError('Could not create a unique code'); +} + +/** Epoch ms `months` from now, or '' for no expiry. */ +function expiryIn(months) { + if (!(months > 0)) return ''; + const date = new Date(); + date.setUTCMonth(date.getUTCMonth() + months); + return date.toISOString(); +} + +/** Why a pass can't be used now (an ApiError), or null. */ +function passProblem(pass) { + if (!pass) return new NotFoundError('That code was not found — check it and try again'); + if (pass.getString('status') !== 'active') return conflict('That code is no longer valid'); + const expires = toMs(pass.getString('expiresAt')); + if (expires <= Date.now()) return conflict(`That code expired on ${new Date(expires).toISOString().slice(0, 10)}`); + return null; +} + +/** + * A pass's parts with what's used (paid bookings), held (live basket holds) + * and left. Product parts were handed over with the purchase: nothing left + * to redeem. `options.excludeLineId` leaves one basket line out. + */ +function passCredits(app, pass, options) { + const opts = options || {}; + const parts = jsonValue(pass.get('parts'), []); + const key = (item, minutes) => item + '|' + (minutes || 0); + const used = {}; + const held = {}; + for (const line of findAll(app, 'order_lines', "pass = {:pass} && order.status != 'refunded'", { pass: pass.id })) { + const k = key(line.getString('item'), line.getInt('minutes')); + used[k] = (used[k] || 0) + line.getInt('quantity'); + } + for (const line of findAll(app, 'basket_lines', 'pass = {:pass} && heldUntil > {:now}', { pass: pass.id, now: pbDate(Date.now()) })) { + if (line.id === opts.excludeLineId) continue; + const k = key(line.getString('item'), line.getInt('minutes')); + held[k] = (held[k] || 0) + line.getInt('quantity'); + } + return (Array.isArray(parts) ? parts : []).map((part) => { + const k = key(part.item, part.minutes); + const redeemable = !!part.minutes; + return Object.assign({}, part, { + redeemable, + used: redeemable ? used[k] || 0 : part.count, + held: held[k] || 0, + left: redeemable ? Math.max(0, part.count - (used[k] || 0) - (held[k] || 0)) : 0 + }); + }); +} + +/** How a pass is shown to the customer and the admin. */ +function passSummary(app, pass) { + return { + id: pass.id, + code: formatCode(pass.getString('code')), + name: pass.getString('name'), + expiresAt: pass.getString('expiresAt') ? new Date(toMs(pass.getString('expiresAt'))).toISOString() : '', + status: pass.getString('status'), + recipientName: pass.getString('recipientName'), + message: pass.getString('message'), + parts: passCredits(app, pass).map((p) => ({ item: p.item, name: p.name, minutes: p.minutes, count: p.count, value: p.value, redeemable: p.redeemable, used: p.used, held: p.held, left: p.left })) + }; +} + +/** + * Let the basket's code cover its bookings that match a part with places + * left (same service and length), oldest line first. Lines already covered + * stay covered. Call inside the transaction that added the lines. + */ +function coverWithPass(app, basket) { + const pass = findOrNull(app, 'passes', basket.getString('pass')); + if (!pass || passProblem(pass)) return; + const credits = passCredits(app, pass); + const lines = findAll(app, 'basket_lines', "basket = {:basket} && lineType = 'slot' && pass = ''", { basket: basket.id }, 'created'); + for (const line of lines) { + const part = credits.find((p) => p.redeemable && p.item === line.getString('item') && p.minutes === line.getInt('minutes') && p.left >= line.getInt('quantity')); + if (!part) continue; + part.left -= line.getInt('quantity'); + line.set('pass', pass.id); + app.save(line); + } +} + +function uncoverLines(app, basketId) { + for (const line of findAll(app, 'basket_lines', "basket = {:basket} && pass != ''", { basket: basketId })) { + line.set('pass', ''); + app.save(line); + } +} + +/** The passes an order bought, as shown on the confirmation page and in emails. */ +function orderPasses(app, orderId) { + return findAll(app, 'passes', 'order = {:order}', { order: orderId }, 'created').map((pass) => passSummary(app, pass)); +} + +/** Units of each product the basket needs: product lines plus products inside bundles. */ +function productNeeds(app, lines, extra) { + const needs = {}; + const add = (id, n) => (needs[id] = (needs[id] || 0) + n); + for (const line of lines.concat(extra || [])) { + if (line.getString('lineType') !== 'item') continue; + const item = findOrNull(app, 'items', line.getString('item')); + if (!item) continue; + if (isBundle(item)) { + for (const part of bundleParts(item)) { + const partItem = findOrNull(app, 'items', part.item); + if (partItem && !isService(partItem)) add(part.item, part.count * line.getInt('quantity')); + } + } else { + add(item.id, line.getInt('quantity')); + } + } + return needs; +} + +/** An ApiError when stock can't cover `needs`, or null. */ +function stockProblem(app, needs) { + for (const id of Object.keys(needs)) { + const item = findOrNull(app, 'items', id); + if (!item) continue; + const stock = item.get('stock'); + if (stock != null && stock !== '' && needs[id] > item.getInt('stock')) { + return conflict(item.getInt('stock') > 0 ? `Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock` : `"${item.getString('name')}" is sold out`); + } + } + return null; +} + +// ── Admin: codes ──────────────────────────────────────────────────────── + +/** Codes for the admin, newest first; `query` matches the code, email, recipient or bundle name. */ +function listPasses(app, query) { + const q = String(query || '').trim(); + const code = normaliseCode(q); + const filter = q ? '(code ~ {:code} || email ~ {:q} || recipientName ~ {:q} || name ~ {:q})' : "id != ''"; + return findAll(app, 'passes', filter, { q, code: code || q }, '-created') + .slice(0, 200) + .map((pass) => Object.assign(passSummary(app, pass), { email: pass.getString('email'), order: pass.getString('order'), created: pass.getString('created'), anonymisedAt: pass.getString('anonymisedAt') })); +} + +/** Void/reactivate a code or change when it expires. `body`: { id, status?, expiresAt? (ISO or '' for never) }. */ +function updatePass(app, body) { + const pass = findOrNull(app, 'passes', String(body.id || '')); + if (!pass) throw new NotFoundError('Code not found'); + if (body.status !== undefined) { + if (body.status !== 'active' && body.status !== 'void') throw new BadRequestError('Unknown status'); + pass.set('status', body.status); + } + if (body.expiresAt !== undefined) { + const ms = toMs(body.expiresAt); + if (body.expiresAt !== '' && Number.isNaN(ms)) throw new BadRequestError('Invalid expiry date'); + pass.set('expiresAt', body.expiresAt === '' ? '' : new Date(ms).toISOString()); + } + app.save(pass); + return passSummary(app, pass); +} + +/** + * Issue a code without a purchase (a gift from the studio, a replacement). + * `body`: { itemId (a bundle), email?, recipientName?, message?, months? }. + */ +function issuePass(app, body) { + const bundle = findOrNull(app, 'items', String(body.itemId || '')); + if (!isBundle(bundle)) throw new BadRequestError('Choose a bundle'); + const months = body.months === undefined || body.months === '' ? bundle.getInt('validMonths') : Math.floor(Number(body.months)); + if (!(months >= 0 && months <= 120)) throw new BadRequestError('Valid for 0 (no expiry) to 120 months'); + const pass = newRecord(app, 'passes', { + code: newCode(app), + item: bundle.id, + name: bundle.getString('name'), + parts: bundleSnapshot(app, bundle), + email: String(body.email || '').trim().slice(0, 320), + recipientName: String(body.recipientName || '').trim().slice(0, 180), + message: String(body.message || '').trim().slice(0, 1000), + expiresAt: expiryIn(months), + status: 'active' + }); + app.save(pass); + return passSummary(app, pass); +} + // ── Holds and baskets ─────────────────────────────────────────────────── /** @@ -461,21 +727,26 @@ function basketLines(app, basketId) { /** * 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`. + * type. Each line also gets `unitPrice` (0 when a code covers it; null: the + * service is no longer offered at that length), for a booking `end`, and + * for a bundle `bundle` (its parts and validity). `pass` is the applied + * code with what it has left. */ 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); + const pass = findOrNull(app, 'passes', basket.getString('pass')); return { record: plain(basket), + pass: pass ? passSummary(app, pass) : null, lines: lines.map((line) => { const json = plain(line); const item = line.expandedOne('item'); - json.unitPrice = item ? unitPrice(item, line.getInt('minutes')) : null; + json.unitPrice = line.getString('pass') ? 0 : 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(); + if (isBundle(item)) json.bundle = { validMonths: item.getInt('validMonths'), parts: bundleSnapshot(app, item, true) }; return json; }) }; @@ -512,6 +783,12 @@ function extendBasketHolds(app, basketId, durationMs) { app.runInTransaction((tx) => { const fresh = tx.findRecordById('basket_lines', line.id); if (checkBooking(tx, lineRequest(fresh), { excludeLineId: fresh.id }).error) return; + // A code's places may have been used up meanwhile: then the time is let go too. + const pass = findOrNull(tx, 'passes', fresh.getString('pass')); + if (pass) { + const part = passCredits(tx, pass, { excludeLineId: fresh.id }).find((p) => p.redeemable && p.item === fresh.getString('item') && p.minutes === fresh.getInt('minutes')); + if (passProblem(pass) || !part || part.left < fresh.getInt('quantity')) return; + } fresh.set('heldUntil', until); tx.save(fresh); }); @@ -530,7 +807,7 @@ function basketAction(app, body) { const action = String(body.action || ''); let basket = loadActiveBasket(app, body.basketId); - if (!basket && (action === 'add_item' || action === 'add_slot')) basket = createBasket(app); + if (!basket && (action === 'add_item' || action === 'add_slot' || action === 'apply_code')) basket = createBasket(app); if (!basket) throw new BadRequestError('No active basket — add an item first'); const lines = basketLines(app, basket.id); @@ -540,14 +817,17 @@ function basketAction(app, body) { const quantity = Math.max(1, Math.floor(Number(body.quantity)) || 1); const item = findOrNull(app, 'items', itemId); if (!item || !item.getBool('active')) throw new NotFoundError('Item not found'); - if (item.getString('type') !== 'item') throw new BadRequestError('Use add_slot for bookable services'); + if (isService(item)) throw new BadRequestError('Use add_slot for bookable services'); + if (isBundle(item)) bundleSnapshot(app, item); // throws if it can't be sold + // Stock for products, including those inside bundles, across the whole basket. const existing = lines.find((l) => l.getString('lineType') === 'item' && l.getString('item') === itemId); - const newQty = (existing ? existing.getInt('quantity') : 0) + quantity; - const stock = item.get('stock'); - if (stock != null && stock !== '' && newQty > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`); + const adding = newRecord(app, 'basket_lines', { basket: basket.id, item: itemId, quantity, lineType: 'item' }); + const problem = stockProblem(app, productNeeds(app, lines, [adding])); + if (problem) throw problem; if (existing) { + const newQty = existing.getInt('quantity') + quantity; existing.set('quantity', newQty); app.save(existing); } else { @@ -587,7 +867,10 @@ function basketAction(app, body) { }); line.set('quantity', line.getInt('quantity') + (booking.kind === 'session' ? request.seats : 1)); line.set('heldUntil', isoIn(SLOT_HOLD_MS)); + // More places than the code covers: this line is paid for instead. + if (existing && existing.getString('pass')) existing.set('pass', ''); tx.save(line); + coverWithPass(tx, tx.findRecordById('baskets', basket.id)); }); break; } @@ -607,18 +890,59 @@ function basketAction(app, body) { if (check.error) return check.error; fresh.set('quantity', quantity); fresh.set('heldUntil', isoIn(SLOT_HOLD_MS)); + fresh.set('pass', ''); // re-covered below if the code has enough places tx.save(fresh); + coverWithPass(tx, tx.findRecordById('baskets', basket.id)); }); break; } - const item = findOrNull(app, 'items', line.getString('item')); - const stock = item ? item.get('stock') : null; - if (stock != null && stock !== '' && quantity > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`); + const others = lines.filter((l) => l.id !== line.id); + const changed = newRecord(app, 'basket_lines', { basket: basket.id, item: line.getString('item'), quantity, lineType: 'item' }); + const problem = stockProblem(app, productNeeds(app, others, [changed])); + if (problem) throw problem; line.set('quantity', quantity); app.save(line); break; } + case 'apply_code': { + // A bundle/voucher code: bookings it covers cost nothing. + guardedTransaction(app, 'Could not apply the code — please try again', (tx) => { + const pass = findPassByCode(tx, body.code); + const problem = passProblem(pass); + if (problem) return problem; + const fresh = tx.findRecordById('baskets', basket.id); + if (fresh.getString('pass') !== pass.id) uncoverLines(tx, basket.id); + fresh.set('pass', pass.id); + tx.save(fresh); + coverWithPass(tx, fresh); + }); + basket = app.findRecordById('baskets', basket.id); + break; + } + + case 'remove_code': { + guardedTransaction(app, 'Could not remove the code — please try again', (tx) => { + uncoverLines(tx, basket.id); + const fresh = tx.findRecordById('baskets', basket.id); + fresh.set('pass', ''); + tx.save(fresh); + }); + basket = app.findRecordById('baskets', basket.id); + break; + } + + case 'set_gift': { + // Who a bundle is for: shown with its code in the confirmation email. + const line = lines.find((l) => l.id === String(body.lineId || '')); + if (!line) throw new NotFoundError('Line not found in your basket'); + if (!isBundle(findOrNull(app, 'items', line.getString('item')))) throw new BadRequestError('Only bundles and vouchers can be gifts'); + line.set('giftTo', String(body.giftTo || '').trim().slice(0, 180)); + line.set('giftMessage', String(body.giftMessage || '').trim().slice(0, 1000)); + app.save(line); + break; + } + case 'renew_holds': { // "Keep my reservation" at checkout. Holds that already lapsed were // swept above; the customer is told and picks the time again. @@ -684,7 +1008,9 @@ function currency() { /** * Start (or resume) payment for a basket: validate every line against the * database (the source of truth for the total), then create or update the - * Stripe PaymentIntent. Returns the client secret for Stripe Elements. + * Stripe PaymentIntent. Returns `{ clientSecret }` for Stripe Elements — or, + * when codes cover everything (total 0), creates the order at once and + * returns `{ free: true, orderId, orderEmail }` (no payment step). */ function startCheckout(app, body) { const basketId = String(body.basketId || ''); @@ -708,6 +1034,15 @@ function startCheckout(app, body) { if (!customer.name) throw new BadRequestError('Name is required'); if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(customer.email)) throw new BadRequestError('A valid email is required'); + // A code voided or expired since it was applied stops covering anything. + const applied = findOrNull(app, 'passes', basket.getString('pass')); + if (basket.getString('pass') && passProblem(applied)) { + uncoverLines(app, basket.id); + basket.set('pass', ''); + app.save(basket); + throw conflict(`Your code ${applied ? formatCode(applied.getString('code')) + ' ' : ''}can no longer be used — the bookings it covered are now charged. Please check your basket.`); + } + let totalCents = 0; const summary = []; for (const line of lines) { @@ -719,18 +1054,36 @@ function startCheckout(app, body) { if (!findOrNull(app, 'slots', line.getString('slot')) || !(toMs(line.getString('heldUntil')) > Date.now())) { throw conflict(`Your time slot for "${item.getString('name')}" has expired — please pick it again`); } - } else { - const stock = item.get('stock'); - if (stock != null && stock !== '' && item.getInt('stock') < quantity) { - throw conflict(`Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock`); - } + } else if (isBundle(item)) { + bundleSnapshot(app, item); // throws if it can't be sold } - const price = unitPrice(item, line.getInt('minutes')); + const price = line.getString('pass') ? 0 : 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'); + const stock = stockProblem(app, productNeeds(app, lines)); + if (stock) throw stock; + + basket.set('email', customer.email); + basket.set('customerDetails', customer); + if (totalCents === 0) { + // Everything is covered by a code: confirm without a payment. A payment + // started before the code was applied is cancelled, so it can't be paid too. + const staleIntent = basket.getString('stripePaymentIntentId'); + if (staleIntent) { + try { + stripe('POST', '/v1/payment_intents/' + encodeURIComponent(staleIntent) + '/cancel', {}); + } catch (e) { + console.error('[shop] could not cancel payment', staleIntent, e); + } + basket.set('stripePaymentIntentId', ''); + } + app.save(basket); + const orderId = createOrder(app, basket.id, { intentId: '', total: 0, receiptEmail: customer.email }); + if (!orderId) throw conflict('This basket was already checked out'); + return { free: true, orderId, orderEmail: orderEmailData(app, orderId) }; + } let intent = null; const existingId = basket.getString('stripePaymentIntentId'); @@ -764,8 +1117,6 @@ function startCheckout(app, body) { } basket.set('stripePaymentIntentId', intent.id); - basket.set('email', customer.email); - basket.set('customerDetails', customer); app.save(basket); return { clientSecret: intent.client_secret }; } @@ -821,46 +1172,87 @@ function handleStripeWebhook(app, rawBody, signature) { function createOrderFromIntent(app, intent) { const basketId = intent.metadata && intent.metadata.basket_id; if (!basketId || !intent.id) return null; // not one of ours + return createOrder(app, basketId, { intentId: intent.id, total: intent.amount / 100, receiptEmail: intent.receipt_email }); +} +function takeStock(app, item, quantity) { + if (!item || item.get('stock') == null || item.get('stock') === '') return; + item.set('stock', Math.max(0, item.getInt('stock') - quantity)); + app.save(item); +} + +/** + * Turn a basket into an order: after a Stripe payment (`payment.intentId`, + * idempotent per intent) or with nothing to pay (`intentId` '', only while + * the basket is still active). Bundles become passes with new codes. + * Returns the new order id, or null if there was nothing to do. + */ +function createOrder(app, basketId, payment) { let orderId = null; app.runInTransaction((tx) => { - const existing = findAll(tx, 'orders', 'stripePaymentIntentId = {:id}', { id: intent.id }); - if (existing.length) return; // Stripe retried — already handled + if (payment.intentId && findAll(tx, 'orders', 'stripePaymentIntentId = {:id}', { id: payment.intentId }).length) return; // Stripe retried — already handled const basket = findOrNull(tx, 'baskets', basketId); if (!basket) return; + if (!payment.intentId && basket.getString('status') !== 'active') return; const lines = basketLines(tx, basketId); const order = newRecord(tx, 'orders', { basket: basketId, - email: basket.getString('email') || intent.receipt_email || '', + email: basket.getString('email') || payment.receiptEmail || '', customerDetails: JSON.parse(toString(basket.get('customerDetails')) || 'null') || {}, - total: intent.amount / 100, + total: payment.total, status: 'paid', - stripePaymentIntentId: intent.id + stripePaymentIntentId: payment.intentId }); tx.save(order); // 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 it free in between. + // transaction, so availability never sees it free in between; the + // same goes for a code's places (`pass`). + const orderLine = (fields) => tx.save(newRecord(tx, 'order_lines', Object.assign({ order: order.id }, fields))); for (const line of lines) { const item = findOrNull(tx, 'items', line.getString('item')); - tx.save( - newRecord(tx, 'order_lines', { - order: order.id, - item: line.getString('item'), - slot: line.getString('slot'), - quantity: line.getInt('quantity'), - lineType: line.getString('lineType'), - name: item ? item.getString('name') : 'Unknown item', - 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') !== '') { - item.set('stock', Math.max(0, item.getInt('stock') - line.getInt('quantity'))); - tx.save(item); + const name = item ? item.getString('name') : 'Unknown item'; + const quantity = line.getInt('quantity'); + orderLine({ + item: line.getString('item'), + slot: line.getString('slot'), + pass: line.getString('pass'), + quantity, + lineType: line.getString('lineType'), + name, + price: line.getString('pass') ? 0 : (item && unitPrice(item, line.getInt('minutes'))) || 0, + start: line.getString('start'), + minutes: line.getInt('minutes') + }); + if (line.getString('lineType') !== 'item' || !item) continue; + if (!isBundle(item)) { + takeStock(tx, item, quantity); + continue; + } + // A bundle: one pass (code) per unit bought; its products go with this order. + const parts = bundleSnapshot(tx, item, true); + for (let i = 0; i < quantity; i++) { + tx.save( + newRecord(tx, 'passes', { + code: newCode(tx), + item: item.id, + order: order.id, + name, + parts, + email: order.getString('email'), + recipientName: line.getString('giftTo'), + message: line.getString('giftMessage'), + expiresAt: expiryIn(item.getInt('validMonths')), + status: 'active' + }) + ); + } + for (const part of parts) { + if (part.minutes) continue; + orderLine({ item: part.item, quantity: part.count * quantity, lineType: 'item', name: `${part.name} (in ${name})`, price: 0 }); + takeStock(tx, findOrNull(tx, 'items', part.item), part.count * quantity); } } @@ -898,10 +1290,11 @@ function emailTemplate(app, key) { function orderEmailData(app, orderId) { const order = app.findRecordById('orders', orderId); const lines = findAll(app, 'order_lines', 'order = {:order}', { order: orderId }, 'start'); - for (const line of lines) app.expandRecord(line, ['slot', 'item'], null); + for (const line of lines) app.expandRecord(line, ['slot', 'item', 'pass'], null); return { order: plain(order), lines: lines.map(plain), + passes: findAll(app, 'passes', 'order = {:order}', { order: orderId }, 'created').map(plain), templates: { customer_confirmation: emailTemplate(app, 'customer_confirmation'), client_alert: emailTemplate(app, 'client_alert') @@ -911,11 +1304,32 @@ function orderEmailData(app, orderId) { }; } +/** A paid order as the result page shows it: lines (with the code that paid each) and the codes it bought. */ +function paidOrder(app, order) { + const lines = findAll(app, 'order_lines', 'order = {:order}', { order: order.id }, 'id'); + return { + state: 'paid', + order: plain(order), + lines: lines.map((line) => { + const pass = findOrNull(app, 'passes', line.getString('pass')); + return Object.assign(plain(line), { passCode: pass ? formatCode(pass.getString('code')) : '' }); + }), + passes: orderPasses(app, order.id) + }; +} + /** - * Payment result page. The PaymentIntent id comes from Stripe's redirect; - * it is checked with Stripe first, so made-up ids reveal nothing. + * Payment result page. After a payment, `paymentIntentId` comes from + * Stripe's redirect and is checked with Stripe first, so made-up ids reveal + * nothing. An order with nothing to pay is looked up by `orderId` plus the + * customer's `basketId` (their cookie — the bearer secret for that basket). */ -function orderStatus(app, paymentIntentId) { +function orderStatus(app, paymentIntentId, free) { + if (free && free.orderId) { + const order = findOrNull(app, 'orders', String(free.orderId)); + if (!order || !free.basketId || order.getString('basket') !== String(free.basketId)) return { state: 'missing' }; + return paidOrder(app, order); + } const id = String(paymentIntentId || ''); if (!/^pi_[A-Za-z0-9_]+$/.test(id)) return { state: 'missing' }; let intent; @@ -931,9 +1345,7 @@ function orderStatus(app, paymentIntentId) { if (intent.status === 'succeeded') return { state: 'processing' }; return { state: intent.status === 'canceled' ? 'canceled' : 'failed' }; } - const order = orders[0]; - const lines = findAll(app, 'order_lines', 'order = {:order}', { order: order.id }, 'id'); - return { state: 'paid', order: plain(order), lines: lines.map(plain) }; + return paidOrder(app, orders[0]); } /** @@ -953,6 +1365,9 @@ function recordEmailStatus(app, secretHeader, body) { } module.exports = { + listPasses, + updatePass, + issuePass, bookableTimes, slotDetails, sweepExpiredHolds, diff --git a/pocketbase/pb_migrations/1793200000_bundles_and_passes.js b/pocketbase/pb_migrations/1793200000_bundles_and_passes.js new file mode 100644 index 0000000..ac1d894 --- /dev/null +++ b/pocketbase/pb_migrations/1793200000_bundles_and_passes.js @@ -0,0 +1,142 @@ +/// + +// Bundles and codes (vouchers). +// +// - items.type gains `bundle`: a shop item with its own price made of +// `bundleParts` ([{ item, minutes, count }] — a service at one length, or +// a product with minutes null), valid for `validMonths` after purchase. +// - passes: one per bundle bought (or issued by hand in the admin). `code` +// is what the customer types; `parts` is a snapshot of the bundle with +// each unit's share of the price (`value`). How much of a pass is used is +// never stored: it is counted from order lines and live basket holds that +// point at it (pb_hooks/shop/lib.js, passCredits). +// - baskets.pass: the code applied at checkout. basket_lines.pass / +// order_lines.pass: the pass that pays for that booking. +// - basket_lines.giftTo / giftMessage: who a bundle in the basket is for. +// - Not required any more, as PocketBase counts 0 / '' as blank: +// order_lines.price (a booking paid with a code, or a product inside a +// bundle, costs 0), orders.total and orders.stripePaymentIntentId (an +// order fully paid with codes has no payment). +// +// Commerce writes stay superuser-only (the shop hooks); signed-in admins +// can read passes and change them through /api/shop/passes/*. + +function find(app, name) { + try { + return app.findCollectionByNameOrId(name); + } catch (e) { + return null; // fresh install: pb_schema.json (already in this shape) is imported later + } +} + +const AUTH_ONLY = "@request.auth.id != ''"; + +migrate( + (app) => { + const items = find(app, 'items'); + const orders = find(app, 'orders'); + const baskets = find(app, 'baskets'); + const basketLines = find(app, 'basket_lines'); + const orderLines = find(app, 'order_lines'); + if (!items || !orders || !baskets || !basketLines || !orderLines) return; + + const type = items.fields.getByName('type'); + if (type && type.values.indexOf('bundle') < 0) type.values = [...type.values, 'bundle']; + if (!items.fields.getByName('bundleParts')) { + items.fields.add(new JSONField({ id: 'json_itembundle1', name: 'bundleParts', maxSize: 20000 })); + items.fields.add(new NumberField({ id: 'num_itemvalidmo1', name: 'validMonths', min: 1, max: 120, onlyInt: true })); + } + app.save(items); + + let passes = find(app, 'passes'); + if (!passes) { + passes = new Collection({ + id: 'pbc_passes00001', + type: 'base', + name: 'passes', + listRule: AUTH_ONLY, + viewRule: AUTH_ONLY, + createRule: null, + updateRule: null, + deleteRule: null, + fields: [ + { id: 'text_passcode001', name: 'code', type: 'text', required: true, min: 6, max: 20, pattern: '^[A-Z0-9]+$' }, + { id: 'rel_passitem0001', name: 'item', type: 'relation', collectionId: items.id, maxSelect: 1, cascadeDelete: false }, + { id: 'rel_passorder001', name: 'order', type: 'relation', collectionId: orders.id, maxSelect: 1, cascadeDelete: false }, + { id: 'text_passname001', name: 'name', type: 'text', max: 180 }, + { id: 'json_passparts01', name: 'parts', type: 'json', maxSize: 20000 }, + { id: 'text_passemail01', name: 'email', type: 'text', max: 320 }, + { id: 'text_passrecip01', name: 'recipientName', type: 'text', max: 180 }, + { id: 'text_passmessag1', name: 'message', type: 'text', max: 1000 }, + { id: 'date_passexpire1', name: 'expiresAt', type: 'date' }, + { id: 'sel_passstatus01', name: 'status', type: 'select', required: true, maxSelect: 1, values: ['active', 'void'] }, + { id: 'date_passanonym1', name: 'anonymisedAt', type: 'date' }, + { id: 'autodate_created', name: 'created', type: 'autodate', onCreate: true, onUpdate: false }, + { id: 'autodate_updated', name: 'updated', type: 'autodate', onCreate: true, onUpdate: true } + ], + indexes: ['CREATE UNIQUE INDEX `idx_passes_code` ON `passes` (`code`)', 'CREATE INDEX `idx_passes_order` ON `passes` (`order`)', 'CREATE INDEX `idx_passes_email` ON `passes` (`email`)'] + }); + app.save(passes); + } + + if (!baskets.fields.getByName('pass')) { + baskets.fields.add(new RelationField({ id: 'rel_basketpass01', name: 'pass', collectionId: passes.id, maxSelect: 1, cascadeDelete: false })); + app.save(baskets); + } + if (!basketLines.fields.getByName('pass')) { + basketLines.fields.add(new RelationField({ id: 'rel_blpass000001', name: 'pass', collectionId: passes.id, maxSelect: 1, cascadeDelete: false })); + basketLines.fields.add(new TextField({ id: 'text_blgiftto001', name: 'giftTo', max: 180 })); + basketLines.fields.add(new TextField({ id: 'text_blgiftmsg01', name: 'giftMessage', max: 1000 })); + basketLines.indexes = [...basketLines.indexes, 'CREATE INDEX `idx_basket_lines_pass` ON `basket_lines` (`pass`)']; + app.save(basketLines); + } + for (const [collection, name] of [[orderLines, 'price'], [orders, 'total'], [orders, 'stripePaymentIntentId']]) { + const field = collection.fields.getByName(name); + if (field && field.required) { + field.required = false; + app.save(collection); + } + } + if (!orderLines.fields.getByName('pass')) { + orderLines.fields.add(new RelationField({ id: 'rel_olpass000001', name: 'pass', collectionId: passes.id, maxSelect: 1, cascadeDelete: false })); + orderLines.indexes = [...orderLines.indexes, 'CREATE INDEX `idx_order_lines_pass` ON `order_lines` (`pass`)']; + app.save(orderLines); + } + }, + (app) => { + const orderLines = find(app, 'order_lines'); + if (orderLines && orderLines.fields.getByName('pass')) { + orderLines.fields.removeByName('pass'); + orderLines.indexes = orderLines.indexes.filter((index) => !index.includes('idx_order_lines_pass')); + app.save(orderLines); + } + const basketLines = find(app, 'basket_lines'); + if (basketLines && basketLines.fields.getByName('pass')) { + for (const name of ['pass', 'giftTo', 'giftMessage']) basketLines.fields.removeByName(name); + basketLines.indexes = basketLines.indexes.filter((index) => !index.includes('idx_basket_lines_pass')); + app.save(basketLines); + } + const baskets = find(app, 'baskets'); + if (baskets && baskets.fields.getByName('pass')) { + baskets.fields.removeByName('pass'); + app.save(baskets); + } + const passes = find(app, 'passes'); + if (passes) app.delete(passes); + const items = find(app, 'items'); + if (items) { + // Bundles can't exist without the type: make them inactive products. + for (const item of app.findRecordsByFilter('items', "type = 'bundle'", '', 0, 0)) { + item.set('type', 'item'); + item.set('active', false); + app.saveNoValidate(item); + } + const type = items.fields.getByName('type'); + if (type) type.values = type.values.filter((value) => value !== 'bundle'); + for (const name of ['bundleParts', 'validMonths']) { + if (items.fields.getByName(name)) items.fields.removeByName(name); + } + app.save(items); + } + } +); -- 2.51.2 From 32984ac01d351cc3c6b70658e4fb6400c1593274 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 25 Oct 2026 21:39:51 +0000 Subject: [PATCH 2/5] Stock: items.trackStock, so an empty stock really means unlimited MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PocketBase 0.23 can't store an empty number (it reads back as 0), so a product saved with "Unlimited when empty" stock was sold out — on main too. trackStock says whether stock counts; existing products get it on, so nothing that sells today changes. The shop maps untracked stock to null (unlimited), as the UI always assumed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- packages/shared/src/server/shop.ts | 16 +++++++++++++--- pb_schema.json | 1 + pocketbase/pb_hooks/shop/lib.js | 7 +++---- .../1793200000_bundles_and_passes.js | 19 ++++++++++++++++++- 4 files changed, 35 insertions(+), 8 deletions(-) diff --git a/packages/shared/src/server/shop.ts b/packages/shared/src/server/shop.ts index 0fbfe2a..5ef873a 100644 --- a/packages/shared/src/server/shop.ts +++ b/packages/shared/src/server/shop.ts @@ -1,12 +1,19 @@ import type PocketBase from 'pocketbase'; import { getFileUrl } from '../pb'; import { parseDurations } from '../items'; -import type { BookableTime, ItemRecord } from '../types'; +import type { BookableTime, BundlePart, ItemRecord, ItemType } from '../types'; + +/** A bundle's `bundleParts` field (JSON) → valid parts. */ +export function parseBundleParts(raw: unknown): BundlePart[] { + return (Array.isArray(raw) ? raw : []) + .map((p) => ({ item: String(p?.item || ''), minutes: p?.minutes ? Math.floor(Number(p.minutes)) : null, count: Math.floor(Number(p?.count)) || 0 })) + .filter((p) => p.item && p.count > 0); +} /** 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'; + const type: ItemType = record.type === 'item_with_time' || record.type === 'bundle' ? record.type : 'item'; return { id: record.id, name: String(record.name || ''), @@ -15,8 +22,11 @@ export function mapItemRecord(record: Record): ItemRecord { image: String(record.image || ''), imageUrl: media ? getFileUrl('media', media.id, media.file) : '', type, - stock: record.stock ?? null, + // null = unlimited: PocketBase reads an empty number back as 0, so `trackStock` says whether it counts. + stock: type === 'item' && record.trackStock ? Number(record.stock) || 0 : null, durations: type === 'item_with_time' ? parseDurations(record.durations) : [], + bundleParts: type === 'bundle' ? parseBundleParts(record.bundleParts) : [], + validMonths: type === 'bundle' ? Number(record.validMonths) || null : null, bufferMinutes: record.bufferMinutes ?? null, capacity: record.capacity ?? null, active: record.active !== false diff --git a/pb_schema.json b/pb_schema.json index 0c938e5..9cfcc85 100644 --- a/pb_schema.json +++ b/pb_schema.json @@ -330,6 +330,7 @@ { "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", "bundle"] }, { "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, + { "id": "bool_itemtrackst", "name": "trackStock", "type": "bool", "system": false, "required": false, "presentable": false, "hidden": false }, { "id": "json_itemdurations", "name": "durations", "type": "json", "system": false, "required": false, "presentable": false, "hidden": false, "maxSize": 20000 }, { "id": "json_itembundle1", "name": "bundleParts", "type": "json", "system": false, "required": false, "presentable": false, "hidden": false, "maxSize": 20000 }, { "id": "num_itemvalidmo1", "name": "validMonths", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 1, "max": 120, "onlyInt": true }, diff --git a/pocketbase/pb_hooks/shop/lib.js b/pocketbase/pb_hooks/shop/lib.js index 5afa85a..d5985f0 100644 --- a/pocketbase/pb_hooks/shop/lib.js +++ b/pocketbase/pb_hooks/shop/lib.js @@ -490,7 +490,7 @@ function normaliseCode(value) { .replace(/[^A-Z0-9]/g, ''); } -/** `ABCD2345` → `ABCD-2345`, as shown to people. */ +/** `ABCD2345` → `ABCD-2345`, as shown to people (formatCode in packages/shared/src/items.ts does the same). */ function formatCode(code) { return code.length === CODE_LENGTH ? code.slice(0, 4) + '-' + code.slice(4) : code; } @@ -628,8 +628,7 @@ function stockProblem(app, needs) { for (const id of Object.keys(needs)) { const item = findOrNull(app, 'items', id); if (!item) continue; - const stock = item.get('stock'); - if (stock != null && stock !== '' && needs[id] > item.getInt('stock')) { + if (item.getBool('trackStock') && needs[id] > item.getInt('stock')) { return conflict(item.getInt('stock') > 0 ? `Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock` : `"${item.getString('name')}" is sold out`); } } @@ -1176,7 +1175,7 @@ function createOrderFromIntent(app, intent) { } function takeStock(app, item, quantity) { - if (!item || item.get('stock') == null || item.get('stock') === '') return; + if (!item || !item.getBool('trackStock')) return; item.set('stock', Math.max(0, item.getInt('stock') - quantity)); app.save(item); } diff --git a/pocketbase/pb_migrations/1793200000_bundles_and_passes.js b/pocketbase/pb_migrations/1793200000_bundles_and_passes.js index ac1d894..5327280 100644 --- a/pocketbase/pb_migrations/1793200000_bundles_and_passes.js +++ b/pocketbase/pb_migrations/1793200000_bundles_and_passes.js @@ -13,6 +13,11 @@ // - baskets.pass: the code applied at checkout. basket_lines.pass / // order_lines.pass: the pass that pays for that booking. // - basket_lines.giftTo / giftMessage: who a bundle in the basket is for. +// - items.trackStock: whether `stock` is enforced. PocketBase can't store an +// empty number (it reads back as 0), so "unlimited when empty" never +// worked — every product without stock was sold out. Existing products +// get trackStock = true: nothing that sells today changes; clearing the +// stock field in the admin makes a product unlimited. // - Not required any more, as PocketBase counts 0 / '' as blank: // order_lines.price (a booking paid with a code, or a product inside a // bundle, costs 0), orders.total and orders.stripePaymentIntentId (an @@ -42,6 +47,18 @@ migrate( const type = items.fields.getByName('type'); if (type && type.values.indexOf('bundle') < 0) type.values = [...type.values, 'bundle']; + if (!items.fields.getByName('trackStock')) { + items.fields.add(new BoolField({ id: 'bool_itemtrackst', name: 'trackStock' })); + app.save(items); + for (const item of app.findRecordsByFilter('items', "type = 'item'", '', 0, 0)) { + item.set('trackStock', true); + try { + app.saveNoValidate(item); + } catch (e) { + console.log(`[migration] could not set trackStock on item ${item.id}: ${e}`); + } + } + } if (!items.fields.getByName('bundleParts')) { items.fields.add(new JSONField({ id: 'json_itembundle1', name: 'bundleParts', maxSize: 20000 })); items.fields.add(new NumberField({ id: 'num_itemvalidmo1', name: 'validMonths', min: 1, max: 120, onlyInt: true })); @@ -133,7 +150,7 @@ migrate( } const type = items.fields.getByName('type'); if (type) type.values = type.values.filter((value) => value !== 'bundle'); - for (const name of ['bundleParts', 'validMonths']) { + for (const name of ['bundleParts', 'validMonths', 'trackStock']) { if (items.fields.getByName(name)) items.fields.removeByName(name); } app.save(items); -- 2.51.2 From e824f16e310c26676472b4df39beaedbbbb5ebcc Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 25 Oct 2026 21:39:51 +0000 Subject: [PATCH 3/5] Shop and checkout: bundles, gift details, codes, confirm without paying Bundle cards list what they contain and how long the code is valid. In the basket a bundle can be marked as a gift (for / message). Checkout takes a code: covered bookings show "Paid with your code" and cost 0, with what the code has left; when nothing is left to pay the button is Confirm booking and no Stripe step happens. The result page and the confirmation email show bought codes and code-paid bookings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- app-public/src/lib/server/shop.ts | 19 ++- app-public/src/routes/api/basket/+server.ts | 3 + .../api/checkout/create-intent/+server.ts | 18 ++- .../routes/checkout/return/+page.server.ts | 22 ++- .../src/routes/checkout/return/+page.svelte | 26 ++++ packages/shared/src/basket.svelte.ts | 24 ++- .../shared/src/blocks/CheckoutBlock.svelte | 146 +++++++++++++++++- packages/shared/src/blocks/ShopBlock.svelte | 18 ++- packages/shared/src/email/render.ts | 65 +++++++- packages/shared/src/items.ts | 5 + packages/shared/src/server/email/index.ts | 31 +++- packages/shared/src/types.ts | 46 +++++- 12 files changed, 388 insertions(+), 35 deletions(-) diff --git a/app-public/src/lib/server/shop.ts b/app-public/src/lib/server/shop.ts index 2417c44..6b2d771 100644 --- a/app-public/src/lib/server/shop.ts +++ b/app-public/src/lib/server/shop.ts @@ -1,7 +1,7 @@ import { error, isHttpError, json, type RequestHandler } from '@sveltejs/kit'; import { env } from '$env/dynamic/private'; import { getFileUrl } from '$lib/pb'; -import type { Basket, BasketLine, OrderRecord } from '$lib/types'; +import type { Basket, BasketLine, OrderRecord, PassSummary } from '$lib/types'; import { sendOrderEmailsFromData, type OrderEmailData } from '$lib/server/email'; // Client for the shop API in PocketBase (pocketbase/pb_hooks/shop). All @@ -51,7 +51,7 @@ export function postJson(path: string, data: unknown): Promise { }); } -type BasketPayload = { record: Record; lines: Record[] } | null; +type BasketPayload = { record: Record; lines: Record[]; pass?: PassSummary | null } | null; /** PocketBase's "2026-01-01 10:00:00.000Z" → ISO. */ const pbInstant = (value: string) => new Date(String(value).replace(' ', 'T')).toISOString(); @@ -59,7 +59,7 @@ const pbInstant = (value: string) => new Date(String(value).replace(' ', 'T')).t /** 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; + const { record, lines, pass } = payload; const mappedLines: BasketLine[] = lines.map((line) => { const item = line.expand?.item; const slot = line.expand?.slot; @@ -79,6 +79,10 @@ export function mapBasket(payload: BasketPayload): Basket | null { itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined, slotKind: slot?.kind, slotCapacity: slot?.capacity, + passCovered: !!line.pass, + giftTo: line.giftTo || '', + giftMessage: line.giftMessage || '', + bundle: line.bundle || undefined, heldUntil: line.heldUntil ? pbInstant(line.heldUntil) : undefined }; }); @@ -90,6 +94,7 @@ export function mapBasket(payload: BasketPayload): Basket | null { customerDetails: record.customerDetails || null, stripePaymentIntentId: record.stripePaymentIntentId || null, lines: mappedLines, + pass: pass ?? null, serverNow: Date.now() }; } @@ -102,7 +107,7 @@ export async function getBasket(basketId: string | undefined): Promise, lines: Record[]): OrderRecord { +export function mapOrder(order: Record, lines: Record[], passes: PassSummary[] = []): OrderRecord { return { id: order.id, basket: order.basket, @@ -122,8 +127,10 @@ export function mapOrder(order: Record, lines: Record[ name: l.name, price: l.price, start: l.start || null, - minutes: l.minutes || null - })) + minutes: l.minutes || null, + passCode: l.passCode || '' + })), + passes }; } diff --git a/app-public/src/routes/api/basket/+server.ts b/app-public/src/routes/api/basket/+server.ts index 9b43946..48a9642 100644 --- a/app-public/src/routes/api/basket/+server.ts +++ b/app-public/src/routes/api/basket/+server.ts @@ -24,6 +24,9 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => { minutes: body.minutes, start: body.start, seats: body.seats, + code: body.code, + giftTo: body.giftTo, + giftMessage: body.giftMessage, lineId: body.lineId, quantity: body.quantity, basketId: cookies.get(BASKET_COOKIE) || '' diff --git a/app-public/src/routes/api/checkout/create-intent/+server.ts b/app-public/src/routes/api/checkout/create-intent/+server.ts index 9172923..08468ed 100644 --- a/app-public/src/routes/api/checkout/create-intent/+server.ts +++ b/app-public/src/routes/api/checkout/create-intent/+server.ts @@ -1,9 +1,15 @@ import { json, error } from '@sveltejs/kit'; import type { RequestHandler } from './$types'; -import { BASKET_COOKIE, jsonErrors, postJson } from '$lib/server/shop'; +import { BASKET_COOKIE, jsonErrors, postJson, sendAndRecordOrderEmails } from '$lib/server/shop'; +import type { OrderEmailData } from '$lib/server/email'; + +type CheckoutResult = { clientSecret: string } | { free: true; orderId: string; orderEmail: OrderEmailData }; // Starts payment: PocketBase re-validates the basket, extends slot holds and -// creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop). +// creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop). When codes +// cover the whole basket there is nothing to pay: PocketBase creates the +// order straight away, and the booking emails are sent from here (as the +// Stripe webhook route does after a payment). export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => { let body: Record; try { @@ -12,12 +18,16 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => { throw error(400, 'Invalid JSON body'); } - const { clientSecret } = await postJson<{ clientSecret: string }>('/checkout', { + const result = await postJson('/checkout', { basketId: cookies.get(BASKET_COOKIE) || '', name: body.name, email: body.email, phone: body.phone, notes: body.notes }); - return json({ clientSecret }); + if ('free' in result) { + void sendAndRecordOrderEmails(result.orderEmail); + return json({ free: true, orderId: result.orderId }); + } + return json({ clientSecret: result.clientSecret }); }); diff --git a/app-public/src/routes/checkout/return/+page.server.ts b/app-public/src/routes/checkout/return/+page.server.ts index 61e5eda..5082f23 100644 --- a/app-public/src/routes/checkout/return/+page.server.ts +++ b/app-public/src/routes/checkout/return/+page.server.ts @@ -1,19 +1,27 @@ import type { PageServerLoad } from './$types'; import { BASKET_COOKIE, mapOrder, shopFetch } from '$lib/server/shop'; +import type { PassSummary } from '$lib/types'; type OrderStatus = | { state: 'missing' | 'invalid' | 'processing' | 'canceled' | 'failed' } - | { state: 'paid'; order: Record; lines: Record[] }; + | { state: 'paid'; order: Record; lines: Record[]; passes: PassSummary[] }; export const load: PageServerLoad = async ({ url, cookies }) => { + // After a Stripe payment: ?payment_intent=… (checked with Stripe by + // PocketBase; the webhook may not have created the order yet). An order + // paid entirely with codes: ?order=…, which PocketBase only shows to the + // basket it came from (this visitor's cookie). const intentId = url.searchParams.get('payment_intent'); - if (!intentId) return { state: 'missing' as const }; + const orderId = url.searchParams.get('order'); + let query: string; + if (intentId) query = `payment_intent=${encodeURIComponent(intentId)}`; + else if (orderId) query = `order=${encodeURIComponent(orderId)}&basket=${encodeURIComponent(cookies.get(BASKET_COOKIE) || '')}`; + else return { state: 'missing' as const }; - // PocketBase checks the intent with Stripe and looks up the order (the - // webhook is the source of truth and may not have landed yet). - const status = await shopFetch(`/order?payment_intent=${encodeURIComponent(intentId)}`); + const status = await shopFetch(`/order?${query}`); if (status.state !== 'paid') return { state: status.state }; - cookies.delete(BASKET_COOKIE, { path: '/' }); - return { state: 'paid' as const, order: mapOrder(status.order, status.lines) }; + // Keep the cookie for a code-paid order: it is what lets this page show it on reload. + if (intentId) cookies.delete(BASKET_COOKIE, { path: '/' }); + return { state: 'paid' as const, order: mapOrder(status.order, status.lines, status.passes) }; }; diff --git a/app-public/src/routes/checkout/return/+page.svelte b/app-public/src/routes/checkout/return/+page.svelte index 01b0a30..4dbc374 100644 --- a/app-public/src/routes/checkout/return/+page.svelte +++ b/app-public/src/routes/checkout/return/+page.svelte @@ -1,6 +1,7 @@ @@ -48,7 +49,7 @@ updateData({ itemTypeFilter: v as ShopBlockData['itemTypeFilter'] })} formatLabel={(v) => typeFilterLabels[String(v)] || String(v)} diff --git a/app-admin/src/lib/admin/privacyTemplate.ts b/app-admin/src/lib/admin/privacyTemplate.ts index ba881f2..05125a9 100644 --- a/app-admin/src/lib/admin/privacyTemplate.ts +++ b/app-admin/src/lib/admin/privacyTemplate.ts @@ -30,6 +30,7 @@ export const privacyTemplateHtml = `

Privacy policy

How long we keep it

  • Details entered at checkout without completing payment: deleted after [30] days.
  • +
  • Gift vouchers and bundles: the code is kept until it expires; your email and any recipient name and message you added are removed together with your order details.
  • Orders: your contact details are removed [after N months / when you ask]; the order record without them is kept for [N] years as required for our accounts.
  • Server logs (including IP addresses): [a few] days.
diff --git a/app-admin/src/lib/customers.ts b/app-admin/src/lib/customers.ts index f853d5a..a5e08c0 100644 --- a/app-admin/src/lib/customers.ts +++ b/app-admin/src/lib/customers.ts @@ -28,4 +28,6 @@ export type CustomerData = { lines: { name: string; quantity: number; price: number; start: string }[]; }[]; unpaidBaskets: { id: string; updated: string; status: string; customerDetails: CustomerDetails }[]; + /** Bundle/voucher codes bought with this email, and who they're for. */ + codes: { code: string; name: string; created: string; expiresAt: string; status: string; recipientName: string; message: string }[]; }; diff --git a/app-admin/src/lib/server/customers.ts b/app-admin/src/lib/server/customers.ts index 6e18d8e..8fd186a 100644 --- a/app-admin/src/lib/server/customers.ts +++ b/app-admin/src/lib/server/customers.ts @@ -20,5 +20,5 @@ export function updateCustomer(pb: Pb, body: { email: string; name?: string; new } export function eraseCustomer(pb: Pb, email: string) { - return pb.send<{ ordersAnonymised: number; basketsDeleted: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null }); + return pb.send<{ ordersAnonymised: number; basketsDeleted: number; passesAnonymised: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null }); } diff --git a/app-admin/src/lib/server/passes.ts b/app-admin/src/lib/server/passes.ts new file mode 100644 index 0000000..1ae8380 --- /dev/null +++ b/app-admin/src/lib/server/passes.ts @@ -0,0 +1,32 @@ +// Bundle/voucher codes for the admin. Codes are commerce data: they are +// only written by the shop hooks in PocketBase (/api/shop/passes*, signed-in +// admins only), which also count what each code has left. + +import { ClientResponseError } from 'pocketbase'; +import type { createPocketBase } from '$lib/pb'; +import type { PassSummary } from '$lib/types'; + +type Pb = ReturnType; + +/** A code as the admin list shows it: the summary plus who bought it and when. */ +export type AdminPass = PassSummary & { email: string; order: string; created: string; anonymisedAt: string }; + +export async function listPasses(pb: Pb, q: string) { + const { passes } = await pb.send<{ passes: AdminPass[] }>('/api/shop/passes', { query: { q }, requestKey: null }); + return passes; +} + +export function updatePass(pb: Pb, body: { id: string; status?: 'active' | 'void'; expiresAt?: string }) { + return pb.send<{ pass: PassSummary }>('/api/shop/passes/update', { method: 'POST', body, requestKey: null }); +} + +export function issuePass(pb: Pb, body: { itemId: string; email: string; recipientName: string; message: string; months: string }) { + return pb.send<{ pass: PassSummary }>('/api/shop/passes/issue', { method: 'POST', body, requestKey: null }); +} + +/** The hook's own message (e.g. "Choose a bundle"), or `fallback`. */ +export function hookError(e: unknown, fallback: string) { + if (e instanceof ClientResponseError && e.status >= 400 && e.status < 500 && e.response?.message) return String(e.response.message); + console.error(`[passes] ${fallback}`, e); + return fallback; +} diff --git a/app-admin/src/routes/+layout.svelte b/app-admin/src/routes/+layout.svelte index 30954ef..8e68676 100644 --- a/app-admin/src/routes/+layout.svelte +++ b/app-admin/src/routes/+layout.svelte @@ -41,6 +41,7 @@ { href: '/customers', label: 'Customers' }, { href: '/slots', label: 'Slots' }, { href: '/items', label: 'Services & products' }, + { href: '/passes', label: 'Vouchers & codes' }, { href: '/calendar', label: 'Events' } ] }, diff --git a/app-admin/src/routes/customers/+page.server.ts b/app-admin/src/routes/customers/+page.server.ts index 39fa972..ed3384d 100644 --- a/app-admin/src/routes/customers/+page.server.ts +++ b/app-admin/src/routes/customers/+page.server.ts @@ -63,10 +63,11 @@ export const actions: Actions = { const email = String((await request.formData()).get('email') || ''); const result = await attempt('Could not erase the customer.', () => eraseCustomer(locals.pb, email)); if (!result.ok) return result.failure; - const { ordersAnonymised, basketsDeleted } = result.value; + const { ordersAnonymised, basketsDeleted, passesAnonymised } = result.value; + const codes = passesAnonymised ? `, ${passesAnonymised} code${passesAnonymised === 1 ? '' : 's'} anonymised (still usable)` : ''; return { ok: true, - message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted.` + message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted${codes}.` }; }, diff --git a/app-admin/src/routes/customers/+page.svelte b/app-admin/src/routes/customers/+page.svelte index 9c0f8c3..3427d15 100644 --- a/app-admin/src/routes/customers/+page.svelte +++ b/app-admin/src/routes/customers/+page.svelte @@ -3,6 +3,7 @@ import { page } from '$app/state'; import { confirmSubmit } from '$lib/admin/confirm'; import { DISPLAY_LOCALE, formatDateTime } from '$lib/calendar'; + import { formatCode } from '$shared/items'; let { data, form } = $props(); let customer = $derived(data.customer); @@ -154,6 +155,16 @@ {/each} + {#if customer.codes?.length} +

Codes bought

+

Bundles and vouchers. Erasing keeps the codes usable but removes the email, recipient and message.

+
    + {#each customer.codes as code (code.code)} +
  • {formatCode(code.code)} — {code.name}{code.recipientName ? ` · for ${code.recipientName}` : ''}{code.message ? ` · “${code.message}”` : ''}
  • + {/each} +
+ {/if} + {#if customer.unpaidBaskets.length}

Unpaid checkouts

Details typed at checkout without paying. Deleted automatically after {data.settings.abandonedBasketDays} days.

@@ -167,7 +178,7 @@

Erase this customer

- For a request to be forgotten. Removes their name, email, phone and notes from every order (the amounts, services and dates stay, for your accounts) and deletes unpaid checkouts. + For a request to be forgotten. Removes their name, email, phone and notes from every order (the amounts, services and dates stay, for your accounts), removes their email and any recipient name and message from codes they bought (the codes keep working), and deletes unpaid checkouts. Their payment also exists in Stripe and their booking emails in your email provider's logs — handle those in those services.

{#if upcoming.length} diff --git a/app-admin/src/routes/items/+page.server.ts b/app-admin/src/routes/items/+page.server.ts index f6b2006..a16c016 100644 --- a/app-admin/src/routes/items/+page.server.ts +++ b/app-admin/src/routes/items/+page.server.ts @@ -1,7 +1,8 @@ import { fail } from '@sveltejs/kit'; import { attempt } from '$lib/server/actions'; +import { parseDurations } from '$shared/items'; import { mapItemRecord } from '$shared/server/shop'; -import type { ItemDuration, ItemType } from '$lib/types'; +import type { BundlePart, ItemDuration, ItemType } from '$lib/types'; import type { Actions, PageServerLoad } from './$types'; /** Longest bookable length, in minutes (a booking must fit in one day's window). */ @@ -25,8 +26,39 @@ function parseDurationRows(data: FormData): ItemDuration[] | { error: string } { return durations.sort((a, b) => a.minutes - b.minutes); } -function itemPayload(data: FormData) { - const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item'; +/** Most units of one thing a bundle can hold. */ +const MAX_PART_COUNT = 50; + +/** + * A bundle's parts from the form's `partItem`/`partMinutes`/`partCount` rows: + * services (at one of their lengths) and products, not other bundles. + */ +function parseBundleRows(data: FormData, items: Record[]): BundlePart[] | { error: string } { + const ids = data.getAll('partItem').map(String); + const minutes = data.getAll('partMinutes').map(String); + const counts = data.getAll('partCount').map(String); + const parts: BundlePart[] = []; + for (let i = 0; i < ids.length; i++) { + if (!ids[i]) continue; + const item = items.find((candidate) => candidate.id === ids[i]); + if (!item || item.type === 'bundle') return { error: 'A bundle can only contain services and products.' }; + const count = Number(counts[i]); + if (!Number.isInteger(count) || count < 1 || count > MAX_PART_COUNT) return { error: `How many of “${item.name}”: a whole number from 1 to ${MAX_PART_COUNT}.` }; + let length: number | null = null; + if (item.type === 'item_with_time') { + length = Number(minutes[i]); + if (!parseDurations(item.durations).some((d) => d.minutes === length)) return { error: `Choose one of the lengths “${item.name}” is offered for.` }; + } + if (parts.some((p) => p.item === item.id && p.minutes === length)) return { error: `“${item.name}” is listed twice — raise its count instead.` }; + parts.push({ item: item.id, minutes: length, count }); + } + if (!parts.some((p) => p.minutes)) return { error: 'A bundle needs at least one service — its code is what books it.' }; + return parts; +} + +function itemPayload(data: FormData, items: Record[]) { + const rawType = String(data.get('type')); + const type: ItemType = rawType === 'item_with_time' || rawType === 'bundle' ? rawType : 'item'; const name = String(data.get('name') || '').trim(); if (!name) return { error: 'Name is required.' }; const rawStock = String(data.get('stock') ?? '').trim(); @@ -35,7 +67,18 @@ function itemPayload(data: FormData) { let price: number; let durations: ItemDuration[] = []; - if (type === 'item_with_time') { + let bundleParts: BundlePart[] = []; + let validMonths: number | null = null; + if (type === 'bundle') { + const parsed = parseBundleRows(data, items.filter((item) => item.id !== String(data.get('id') || ''))); + if ('error' in parsed) return parsed; + bundleParts = parsed; + price = parseFloat(String(data.get('price') || '')); + if (Number.isNaN(price) || price <= 0) return { error: 'A bundle needs a price above 0.' }; + const rawMonths = String(data.get('validMonths') ?? '').trim(); + validMonths = rawMonths === '' ? null : Number(rawMonths); + if (validMonths !== null && !(Number.isInteger(validMonths) && validMonths >= 1 && validMonths <= 120)) return { error: 'Valid for: 1 to 120 months, or empty for no expiry.' }; + } else if (type === 'item_with_time') { const parsed = parseDurationRows(data); if ('error' in parsed) return parsed; durations = parsed; @@ -57,8 +100,12 @@ function itemPayload(data: FormData) { price, image: String(data.get('image') || '').trim(), type, - stock: Number.isNaN(stock) ? null : stock, + // Empty = unlimited (PocketBase can't store an empty number, hence the flag). + stock: Number.isNaN(stock) ? 0 : (stock ?? 0), + trackStock: stock !== null && !Number.isNaN(stock), durations, + bundleParts, + validMonths, bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes, capacity: Number.isNaN(capacity) ? null : capacity, active: String(data.get('active')) === 'true' @@ -66,6 +113,11 @@ function itemPayload(data: FormData) { }; } +/** Every item, for checking what a bundle may contain. */ +function allItems(pb: App.Locals['pb']) { + return pb.collection('items').getFullList({ fields: 'id,name,type,durations' }).catch(() => []); +} + export const load: PageServerLoad = async ({ locals }) => { const records = await locals.pb .collection('items') @@ -76,7 +128,7 @@ export const load: PageServerLoad = async ({ locals }) => { export const actions: Actions = { create: async ({ request, locals }) => { - const result = itemPayload(await request.formData()); + const result = itemPayload(await request.formData(), await allItems(locals.pb)); if ('error' in result) return fail(400, { message: result.error }); const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create(result.payload)); if (!created.ok) return created.failure; @@ -86,7 +138,7 @@ export const actions: Actions = { const data = await request.formData(); const id = String(data.get('id') || ''); if (!id) return fail(400, { message: 'Item id is required.' }); - const result = itemPayload(data); + const result = itemPayload(data, await allItems(locals.pb)); if ('error' in result) return fail(400, { message: result.error }); const updated = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, result.payload)); if (!updated.ok) return updated.failure; diff --git a/app-admin/src/routes/items/+page.svelte b/app-admin/src/routes/items/+page.svelte index 4e2b6cb..c917bbf 100644 --- a/app-admin/src/routes/items/+page.svelte +++ b/app-admin/src/routes/items/+page.svelte @@ -23,6 +23,9 @@ stock: string; /** Service lengths and prices, as typed (one form row each). */ durations: { minutes: string; price: string }[]; + /** Bundle contents, as typed (one form row each); minutes '' for a product. */ + parts: { item: string; minutes: string; count: string }[]; + validMonths: string; bufferMinutes: string; capacity: string; active: boolean; @@ -34,9 +37,48 @@ let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency })); function emptyDraft(): ItemDraft { - return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', durations: [{ minutes: '60', price: '' }], bufferMinutes: '', capacity: '', active: true }; + return { + id: '', + name: '', + description: '', + price: 0, + image: '', + imageUrl: '', + type: 'item', + stock: '', + durations: [{ minutes: '60', price: '' }], + parts: [{ item: '', minutes: '', count: '1' }], + validMonths: '12', + bufferMinutes: '', + capacity: '', + active: true + }; } + /** What a bundle can contain: services and products (never itself or another bundle). */ + let partChoices = $derived(items.filter((item) => item.type !== 'bundle' && item.id !== draft.id)); + + function choosePartItem(row: ItemDraft['parts'][number], id: string) { + row.item = id; + const item = items.find((candidate) => candidate.id === id); + row.minutes = item?.durations[0] ? String(item.durations[0].minutes) : ''; + } + + /** "3× Massage (1 hour), 1× Oil" for the table. */ + function bundleList(item: ItemRecord) { + const names = new Map(items.map((i) => [i.id, i.name])); + return item.bundleParts.map((p) => `${p.count}× ${names.get(p.item) ?? '?'}${p.minutes ? ` (${formatDuration(p.minutes)})` : ''}`).join(', '); + } + + /** What the parts cost on their own, to compare with the bundle price. */ + let partsListPrice = $derived( + draft.parts.reduce((sum, row) => { + const item = items.find((candidate) => candidate.id === row.item); + const unit = item?.type === 'item_with_time' ? (item.durations.find((d) => String(d.minutes) === row.minutes)?.price ?? 0) : (item?.price ?? 0); + return sum + unit * (Number(row.count) || 0); + }, 0) + ); + function addDuration() { const last = Number(draft.durations.at(-1)?.minutes) || 0; draft.durations.push({ minutes: last ? String(last + 30) : '60', price: '' }); @@ -64,6 +106,8 @@ type: item.type, stock: item.stock == null ? '' : String(item.stock), durations: item.durations.length ? item.durations.map((d) => ({ minutes: String(d.minutes), price: String(d.price) })) : [{ minutes: '60', price: '' }], + parts: item.bundleParts.length ? item.bundleParts.map((p) => ({ item: p.item, minutes: p.minutes ? String(p.minutes) : '', count: String(p.count) })) : [{ item: '', minutes: '', count: '1' }], + validMonths: item.type === 'bundle' ? (item.validMonths == null ? '' : String(item.validMonths)) : '12', bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes), capacity: item.capacity == null ? '' : String(item.capacity), active: item.active @@ -96,7 +140,7 @@

Services & products

-

Bookable services and products, shown in Shop blocks.

+

Bookable services, products and bundles (codes for sessions booked later), shown in Shop blocks.

@@ -120,10 +164,16 @@ {item.name}
- {item.type === 'item_with_time' ? 'Service' : 'Product'} + {item.type === 'item_with_time' ? 'Service' : item.type === 'bundle' ? 'Bundle' : 'Product'} {item.durations.length > 1 ? `from ${money.format(item.price)}` : money.format(item.price)} {item.type === 'item' ? (item.stock ?? '∞') : '—'} - {item.type === 'item_with_time' ? `${durationList(item)}${item.bufferMinutes ? ` + ${item.bufferMinutes} min get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'} + + {#if item.type === 'item_with_time'} + {durationList(item)}{item.bufferMinutes ? ` + ${item.bufferMinutes} min get-ready` : ''}{(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''} + {:else if item.type === 'bundle'} + {bundleList(item)} · {item.validMonths ? `valid ${item.validMonths} months` : 'no expiry'} + {:else}—{/if} + {item.active ? 'Active' : 'Inactive'} @@ -157,10 +207,52 @@ - {#if draft.type === 'item'} + {#if draft.type === 'bundle'} +
+ What’s in it +
+ {#each draft.parts as row, i} + {@const partItem = items.find((item) => item.id === row.item)} +
+ + × + + {#if partItem?.type === 'item_with_time'} + + {:else} + + {/if} + {#if draft.parts.length > 1} + + {/if} +
+ {/each} +
+ + The buyer gets a code; whoever has it books the services, each at the length set here, without paying again. Products are handed over with the purchase. A one-service voucher is a bundle with one part. +
+
+ + +
+ {:else if draft.type === 'item'}