Bundles and gift vouchers: codes booked later, confirm without paying #7

Merged
reudy merged 5 commits from bundles-vouchers into main 2026-10-26 09:30:41 +01:00
5 changed files with 747 additions and 69 deletions
Showing only changes of commit e30e1d3beb - Show all commits

View file

@ -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": "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": "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": "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": "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_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_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": "num_itemcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true },
{ "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }, { "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} },
@ -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": "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": "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": "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_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
@ -416,13 +419,17 @@
{ "id": "date_blheldunt1", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" }, { "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": "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": "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_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [ "indexes": [
"CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)", "CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)",
"CREATE INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)", "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, "autodate": true,
"options": {} "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": "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": "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": "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": "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_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": "date_ordclntmail", "name": "clientEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
{ "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } }, { "id": "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": "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": "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": "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": "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": "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_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [ "indexes": [
"CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)", "CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)",
"CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)", "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, "autodate": true,
"options": {} "options": {}
@ -516,5 +525,37 @@
], ],
"autodate": true, "autodate": true,
"options": {} "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`)"
]
} }
] ]

View file

@ -9,6 +9,11 @@
// - baskets.email + baskets.customerDetails — set when checkout starts. A // - baskets.email + baskets.customerDetails — set when checkout starts. A
// paid basket's copy is cleared once the order exists; a basket that was // paid basket's copy is cleared once the order exists; a basket that was
// never paid for is deleted after `abandonedBasketDays`. // 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 // Outside this database: Stripe (receipt email, payment) and the email
// provider's send logs. Those are handled in their own dashboards. // 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) { function customerRecords(app, email) {
const wanted = normaliseEmail(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 // `~` is a case-insensitive LIKE, but also a substring match (and `_` is a
// wildcard), so narrow it to the exact address here. // wildcard), so narrow it to the exact address here.
const same = (record) => normaliseEmail(record.getString('email')) === wanted; const same = (record) => normaliseEmail(record.getString('email')) === wanted;
return { return {
orders: app.findRecordsByFilter('orders', 'email ~ {:email}', '-created', 0, 0, { email: wanted }).filter(same), 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) { 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; 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) { function applyRetention(app) {
const { abandonedBasketDays, anonymiseOrdersAfterMonths } = settings(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 // Unpaid baskets (their lines cascade). Active ones expire after a day
// and are swept to `abandoned`, so `updated` is when they were last used. // 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); 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)); console.log('[privacy] retention:', JSON.stringify(counts));
} }
return 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. */ /** Everything stored about one customer — the admin's detail view and the GDPR export. */
function customerData(app, email) { function customerData(app, email) {
const { orders, baskets } = customerRecords(app, email); const { orders, baskets, passes } = customerRecords(app, email);
return { return {
email: normaliseEmail(email), email: normaliseEmail(email),
exportedAt: new Date().toISOString(), 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. // Checkouts that were started but never paid for.
unpaidBaskets: baskets.map((basket) => ({ unpaidBaskets: baskets.map((basket) => ({
id: basket.id, id: basket.id,
@ -229,24 +276,36 @@ function updateCustomer(app, body) {
let updated = 0; let updated = 0;
app.runInTransaction((tx) => { app.runInTransaction((tx) => {
const { orders, baskets } = customerRecords(tx, email); const { orders, baskets, passes } = customerRecords(tx, email);
if (!orders.length && !baskets.length) throw new NotFoundError('No customer with that email'); if (!orders.length && !baskets.length && !passes.length) throw new NotFoundError('No customer with that email');
for (const record of [...orders, ...baskets]) { for (const record of [...orders, ...baskets]) {
record.set('customerDetails', Object.assign(details(record), patch)); record.set('customerDetails', Object.assign(details(record), patch));
if (patch.email) record.set('email', patch.email); if (patch.email) record.set('email', patch.email);
tx.save(record); tx.save(record);
updated++; 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 }; 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) { function eraseCustomer(app, body) {
const counts = { ordersAnonymised: 0, basketsDeleted: 0 }; const counts = { ordersAnonymised: 0, basketsDeleted: 0, passesAnonymised: 0 };
app.runInTransaction((tx) => { app.runInTransaction((tx) => {
const { orders, baskets } = customerRecords(tx, body.email); const { orders, baskets, passes } = customerRecords(tx, body.email);
if (!orders.length && !baskets.length) throw new NotFoundError('No customer with that 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) { for (const order of orders) {
anonymiseOrder(tx, order); anonymiseOrder(tx, order);
counts.ordersAnonymised++; counts.ordersAnonymised++;

View file

@ -41,7 +41,28 @@ routerAdd('POST', '/api/shop/stripe-webhook', (e) => {
routerAdd('GET', '/api/shop/order', (e) => { routerAdd('GET', '/api/shop/order', (e) => {
const shop = require(`${__hooks}/shop/lib.js`); 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) => { routerAdd('POST', '/api/shop/order-email-status', (e) => {

View file

@ -423,6 +423,272 @@ function guardedTransaction(app, fallback, fn) {
if (refusal) throw refusal; 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 ─────────────────────────────────────────────────── // ── 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` * 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 * type. Each line also gets `unitPrice` (0 when a code covers it; null: the
* offered at that length) and, for a booking, `end`. * 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) { function basketPayload(app, basket) {
if (!basket) return null; if (!basket) return null;
const lines = basketLines(app, basket.id); const lines = basketLines(app, basket.id);
for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null); for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null);
const pass = findOrNull(app, 'passes', basket.getString('pass'));
return { return {
record: plain(basket), record: plain(basket),
pass: pass ? passSummary(app, pass) : null,
lines: lines.map((line) => { lines: lines.map((line) => {
const json = plain(line); const json = plain(line);
const item = line.expandedOne('item'); 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')); const start = toMs(line.getString('start'));
if (!Number.isNaN(start)) json.end = new Date(start + line.getInt('minutes') * MINUTE_MS).toISOString(); 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; return json;
}) })
}; };
@ -512,6 +783,12 @@ function extendBasketHolds(app, basketId, durationMs) {
app.runInTransaction((tx) => { app.runInTransaction((tx) => {
const fresh = tx.findRecordById('basket_lines', line.id); const fresh = tx.findRecordById('basket_lines', line.id);
if (checkBooking(tx, lineRequest(fresh), { excludeLineId: fresh.id }).error) return; 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); fresh.set('heldUntil', until);
tx.save(fresh); tx.save(fresh);
}); });
@ -530,7 +807,7 @@ function basketAction(app, body) {
const action = String(body.action || ''); const action = String(body.action || '');
let basket = loadActiveBasket(app, body.basketId); 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'); if (!basket) throw new BadRequestError('No active basket — add an item first');
const lines = basketLines(app, basket.id); 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 quantity = Math.max(1, Math.floor(Number(body.quantity)) || 1);
const item = findOrNull(app, 'items', itemId); const item = findOrNull(app, 'items', itemId);
if (!item || !item.getBool('active')) throw new NotFoundError('Item not found'); 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 existing = lines.find((l) => l.getString('lineType') === 'item' && l.getString('item') === itemId);
const newQty = (existing ? existing.getInt('quantity') : 0) + quantity; const adding = newRecord(app, 'basket_lines', { basket: basket.id, item: itemId, quantity, lineType: 'item' });
const stock = item.get('stock'); const problem = stockProblem(app, productNeeds(app, lines, [adding]));
if (stock != null && stock !== '' && newQty > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`); if (problem) throw problem;
if (existing) { if (existing) {
const newQty = existing.getInt('quantity') + quantity;
existing.set('quantity', newQty); existing.set('quantity', newQty);
app.save(existing); app.save(existing);
} else { } else {
@ -587,7 +867,10 @@ function basketAction(app, body) {
}); });
line.set('quantity', line.getInt('quantity') + (booking.kind === 'session' ? request.seats : 1)); line.set('quantity', line.getInt('quantity') + (booking.kind === 'session' ? request.seats : 1));
line.set('heldUntil', isoIn(SLOT_HOLD_MS)); line.set('heldUntil', isoIn(SLOT_HOLD_MS));
// More places than the code covers: this line is paid for instead.
if (existing && existing.getString('pass')) existing.set('pass', '');
tx.save(line); tx.save(line);
coverWithPass(tx, tx.findRecordById('baskets', basket.id));
}); });
break; break;
} }
@ -607,18 +890,59 @@ function basketAction(app, body) {
if (check.error) return check.error; if (check.error) return check.error;
fresh.set('quantity', quantity); fresh.set('quantity', quantity);
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS)); fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
fresh.set('pass', ''); // re-covered below if the code has enough places
tx.save(fresh); tx.save(fresh);
coverWithPass(tx, tx.findRecordById('baskets', basket.id));
}); });
break; break;
} }
const item = findOrNull(app, 'items', line.getString('item')); const others = lines.filter((l) => l.id !== line.id);
const stock = item ? item.get('stock') : null; const changed = newRecord(app, 'basket_lines', { basket: basket.id, item: line.getString('item'), quantity, lineType: 'item' });
if (stock != null && stock !== '' && quantity > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`); const problem = stockProblem(app, productNeeds(app, others, [changed]));
if (problem) throw problem;
line.set('quantity', quantity); line.set('quantity', quantity);
app.save(line); app.save(line);
break; 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': { case 'renew_holds': {
// "Keep my reservation" at checkout. Holds that already lapsed were // "Keep my reservation" at checkout. Holds that already lapsed were
// swept above; the customer is told and picks the time again. // 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 * 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 * 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) { function startCheckout(app, body) {
const basketId = String(body.basketId || ''); const basketId = String(body.basketId || '');
@ -708,6 +1034,15 @@ function startCheckout(app, body) {
if (!customer.name) throw new BadRequestError('Name is required'); if (!customer.name) throw new BadRequestError('Name is required');
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(customer.email)) throw new BadRequestError('A valid email 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; let totalCents = 0;
const summary = []; const summary = [];
for (const line of lines) { 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())) { if (!findOrNull(app, 'slots', line.getString('slot')) || !(toMs(line.getString('heldUntil')) > Date.now())) {
throw conflict(`Your time slot for "${item.getString('name')}" has expired — please pick it again`); throw conflict(`Your time slot for "${item.getString('name')}" has expired — please pick it again`);
} }
} else { } else if (isBundle(item)) {
const stock = item.get('stock'); bundleSnapshot(app, item); // throws if it can't be sold
if (stock != null && stock !== '' && item.getInt('stock') < quantity) {
throw conflict(`Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock`);
}
} }
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`); 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; totalCents += Math.round(price * 100) * quantity;
summary.push(`${quantity}× ${item.getString('name')}`); summary.push(`${quantity}× ${item.getString('name')}`);
} }
if (totalCents <= 0) throw new BadRequestError('Basket total must be positive'); 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; let intent = null;
const existingId = basket.getString('stripePaymentIntentId'); const existingId = basket.getString('stripePaymentIntentId');
@ -764,8 +1117,6 @@ function startCheckout(app, body) {
} }
basket.set('stripePaymentIntentId', intent.id); basket.set('stripePaymentIntentId', intent.id);
basket.set('email', customer.email);
basket.set('customerDetails', customer);
app.save(basket); app.save(basket);
return { clientSecret: intent.client_secret }; return { clientSecret: intent.client_secret };
} }
@ -821,46 +1172,87 @@ function handleStripeWebhook(app, rawBody, signature) {
function createOrderFromIntent(app, intent) { function createOrderFromIntent(app, intent) {
const basketId = intent.metadata && intent.metadata.basket_id; const basketId = intent.metadata && intent.metadata.basket_id;
if (!basketId || !intent.id) return null; // not one of ours 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; let orderId = null;
app.runInTransaction((tx) => { app.runInTransaction((tx) => {
const existing = findAll(tx, 'orders', 'stripePaymentIntentId = {:id}', { id: intent.id }); if (payment.intentId && findAll(tx, 'orders', 'stripePaymentIntentId = {:id}', { id: payment.intentId }).length) return; // Stripe retried — already handled
if (existing.length) return; // Stripe retried — already handled
const basket = findOrNull(tx, 'baskets', basketId); const basket = findOrNull(tx, 'baskets', basketId);
if (!basket) return; if (!basket) return;
if (!payment.intentId && basket.getString('status') !== 'active') return;
const lines = basketLines(tx, basketId); const lines = basketLines(tx, basketId);
const order = newRecord(tx, 'orders', { const order = newRecord(tx, 'orders', {
basket: basketId, basket: basketId,
email: basket.getString('email') || intent.receipt_email || '', email: basket.getString('email') || payment.receiptEmail || '',
customerDetails: JSON.parse(toString(basket.get('customerDetails')) || 'null') || {}, customerDetails: JSON.parse(toString(basket.get('customerDetails')) || 'null') || {},
total: intent.amount / 100, total: payment.total,
status: 'paid', status: 'paid',
stripePaymentIntentId: intent.id stripePaymentIntentId: payment.intentId
}); });
tx.save(order); tx.save(order);
// Snapshot lines and decrement stock. A booked time moves from the // Snapshot lines and decrement stock. A booked time moves from the
// basket line (a hold) to the order line (a booking) in this same // basket line (a hold) to the order line (a booking) in this same
// transaction, so availability never sees 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) { for (const line of lines) {
const item = findOrNull(tx, 'items', line.getString('item')); const item = findOrNull(tx, 'items', line.getString('item'));
tx.save( const name = item ? item.getString('name') : 'Unknown item';
newRecord(tx, 'order_lines', { const quantity = line.getInt('quantity');
order: order.id, orderLine({
item: line.getString('item'), item: line.getString('item'),
slot: line.getString('slot'), slot: line.getString('slot'),
quantity: line.getInt('quantity'), pass: line.getString('pass'),
lineType: line.getString('lineType'), quantity,
name: item ? item.getString('name') : 'Unknown item', lineType: line.getString('lineType'),
price: (item && unitPrice(item, line.getInt('minutes'))) || 0, name,
start: line.getString('start'), price: line.getString('pass') ? 0 : (item && unitPrice(item, line.getInt('minutes'))) || 0,
minutes: line.getInt('minutes') start: line.getString('start'),
}) minutes: line.getInt('minutes')
); });
if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') { if (line.getString('lineType') !== 'item' || !item) continue;
item.set('stock', Math.max(0, item.getInt('stock') - line.getInt('quantity'))); if (!isBundle(item)) {
tx.save(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) { function orderEmailData(app, orderId) {
const order = app.findRecordById('orders', orderId); const order = app.findRecordById('orders', orderId);
const lines = findAll(app, 'order_lines', 'order = {:order}', { order: orderId }, 'start'); 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 { return {
order: plain(order), order: plain(order),
lines: lines.map(plain), lines: lines.map(plain),
passes: findAll(app, 'passes', 'order = {:order}', { order: orderId }, 'created').map(plain),
templates: { templates: {
customer_confirmation: emailTemplate(app, 'customer_confirmation'), customer_confirmation: emailTemplate(app, 'customer_confirmation'),
client_alert: emailTemplate(app, 'client_alert') 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; * Payment result page. After a payment, `paymentIntentId` comes from
* it is checked with Stripe first, so made-up ids reveal nothing. * 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 || ''); const id = String(paymentIntentId || '');
if (!/^pi_[A-Za-z0-9_]+$/.test(id)) return { state: 'missing' }; if (!/^pi_[A-Za-z0-9_]+$/.test(id)) return { state: 'missing' };
let intent; let intent;
@ -931,9 +1345,7 @@ function orderStatus(app, paymentIntentId) {
if (intent.status === 'succeeded') return { state: 'processing' }; if (intent.status === 'succeeded') return { state: 'processing' };
return { state: intent.status === 'canceled' ? 'canceled' : 'failed' }; return { state: intent.status === 'canceled' ? 'canceled' : 'failed' };
} }
const order = orders[0]; return paidOrder(app, orders[0]);
const lines = findAll(app, 'order_lines', 'order = {:order}', { order: order.id }, 'id');
return { state: 'paid', order: plain(order), lines: lines.map(plain) };
} }
/** /**
@ -953,6 +1365,9 @@ function recordEmailStatus(app, secretHeader, body) {
} }
module.exports = { module.exports = {
listPasses,
updatePass,
issuePass,
bookableTimes, bookableTimes,
slotDetails, slotDetails,
sweepExpiredHolds, sweepExpiredHolds,

View file

@ -0,0 +1,142 @@
/// <reference path="../pb_data/types.d.ts" />
// 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);
}
}
);