@aglyn/plugins-commerce 1.13.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/account-subscriptions.d.ts +51 -0
- package/src/lib/components/account-subscriptions.js +168 -0
- package/src/lib/components/account-subscriptions.js.map +1 -0
- package/src/lib/components/account.js +12 -48
- package/src/lib/components/account.js.map +1 -1
- package/src/lib/components/cart.js +30 -6
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/commerce-console-sections.d.ts +1 -1
- package/src/lib/components/commerce-console-sections.js +5 -0
- package/src/lib/components/commerce-console-sections.js.map +1 -1
- package/src/lib/components/console/paid-media.d.ts +1 -0
- package/src/lib/components/console/paid-media.js +15 -4
- package/src/lib/components/console/paid-media.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
- package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
- package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
- package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
- package/src/lib/components/console/pos-cellular-control.component.js +5 -5
- package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
- package/src/lib/components/console/pos-hardware-card.component.js +77 -8
- package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
- package/src/lib/components/console/pos-page.component.js +19 -2
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +21 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
- package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
- package/src/lib/components/console/subscriptions-card.component.js +280 -0
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
- package/src/lib/components/hardware-terms-consent.d.ts +22 -0
- package/src/lib/components/hardware-terms-consent.js +85 -0
- package/src/lib/components/hardware-terms-consent.js.map +1 -0
- package/src/lib/components/product-detail.js +25 -5
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/constants/operator-alerts.d.ts +1 -1
- package/src/lib/constants/operator-alerts.js +4 -4
- package/src/lib/constants/operator-alerts.js.map +1 -1
- package/src/lib/model/commerce-orders.d.ts +6 -2
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +24 -0
- package/src/lib/model/commerce-payment-methods.js +35 -0
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/paid-media.d.ts +8 -0
- package/src/lib/model/paid-media.js +13 -0
- package/src/lib/model/paid-media.js.map +1 -1
- package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
- package/src/lib/model/pos-hardware-in-person.js +52 -20
- package/src/lib/model/pos-hardware-in-person.js.map +1 -1
- package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
- package/src/lib/model/pos-hardware-tax-summary.js +2 -1
- package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
- package/src/lib/model/pos-hardware-terms.d.ts +37 -2
- package/src/lib/model/pos-hardware-terms.js +68 -3
- package/src/lib/model/pos-hardware-terms.js.map +1 -1
- package/src/lib/model/pos-hardware.d.ts +101 -15
- package/src/lib/model/pos-hardware.js +128 -18
- package/src/lib/model/pos-hardware.js.map +1 -1
- package/src/lib/model/pos-reader-splash.js +2 -2
- package/src/lib/model/pos-reader-splash.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/model/subscription-view.d.ts +90 -0
- package/src/lib/model/subscription-view.js +176 -0
- package/src/lib/model/subscription-view.js.map +1 -0
- package/src/lib/server/billing-webhook.d.ts +4 -6
- package/src/lib/server/billing-webhook.js +109 -51
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cart-checkout.js +45 -10
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.js +15 -3
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/checkout.js +58 -16
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/draft-order.js +7 -3
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/membership-account.d.ts +22 -0
- package/src/lib/server/membership-account.js +52 -8
- package/src/lib/server/membership-account.js.map +1 -1
- package/src/lib/server/pos-auth.d.ts +3 -3
- package/src/lib/server/pos-auth.js +3 -3
- package/src/lib/server/pos-auth.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.js +1 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular-notify.js +1 -1
- package/src/lib/server/pos-cellular-notify.js.map +1 -1
- package/src/lib/server/pos-cellular.js +1 -1
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-hardware-admin.js +86 -13
- package/src/lib/server/pos-hardware-admin.js.map +1 -1
- package/src/lib/server/pos-hardware-attach.js +5 -5
- package/src/lib/server/pos-hardware-attach.js.map +1 -1
- package/src/lib/server/pos-hardware-cancel.js +65 -0
- package/src/lib/server/pos-hardware-cancel.js.map +1 -1
- package/src/lib/server/pos-hardware-closure-notices.js +2 -5
- package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
- package/src/lib/server/pos-hardware-closure.js +5 -8
- package/src/lib/server/pos-hardware-closure.js.map +1 -1
- package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
- package/src/lib/server/pos-hardware-in-person.js +72 -17
- package/src/lib/server/pos-hardware-in-person.js.map +1 -1
- package/src/lib/server/pos-hardware-notify.d.ts +2 -0
- package/src/lib/server/pos-hardware-notify.js +30 -5
- package/src/lib/server/pos-hardware-notify.js.map +1 -1
- package/src/lib/server/pos-hardware-readers.d.ts +25 -0
- package/src/lib/server/pos-hardware-readers.js +206 -85
- package/src/lib/server/pos-hardware-readers.js.map +1 -1
- package/src/lib/server/pos-hardware-returns.d.ts +8 -3
- package/src/lib/server/pos-hardware-returns.js +39 -7
- package/src/lib/server/pos-hardware-returns.js.map +1 -1
- package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
- package/src/lib/server/pos-hardware-sale-fields.js +114 -1
- package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
- package/src/lib/server/pos-hardware-sale.d.ts +2 -0
- package/src/lib/server/pos-hardware-sale.js +1 -0
- package/src/lib/server/pos-hardware-sale.js.map +1 -1
- package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
- package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
- package/src/lib/server/pos-hardware-webhook.js +16 -3
- package/src/lib/server/pos-hardware-webhook.js.map +1 -1
- package/src/lib/server/pos-hardware.d.ts +14 -3
- package/src/lib/server/pos-hardware.js +83 -18
- package/src/lib/server/pos-hardware.js.map +1 -1
- package/src/lib/server/pos-ops-routes.js +2 -10
- package/src/lib/server/pos-ops-routes.js.map +1 -1
- package/src/lib/server/quote-pay.js +8 -4
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/stream.d.ts +2 -0
- package/src/lib/server/stream.js +22 -2
- package/src/lib/server/stream.js.map +1 -1
- package/src/lib/server/tax-return-source.js +5 -1
- package/src/lib/server/tax-return-source.js.map +1 -1
- package/src/lib/server.js +2 -2
- package/src/lib/server.js.map +1 -1
|
@@ -16,7 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import * as Aglyn from "@aglyn/aglyn/server";
|
|
18
18
|
import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
19
|
-
import { normalizePosHardwareSerial, POS_HARDWARE_ORDER_ID, POS_HARDWARE_ORDERS_COLLECTION, posHardwareSaleRecord, posHardwareSaleSetOptions, posHardwareSku } from "../model/pos-hardware.js";
|
|
19
|
+
import { isPosHardwareSellerStoreSale, normalizePosHardwareSerial, POS_HARDWARE_ORDER_ID, POS_HARDWARE_ORDERS_COLLECTION, posHardwareSaleRecord, posHardwareSaleSetOptions, posHardwareOrderUnits, posHardwareSku } from "../model/pos-hardware.js";
|
|
20
20
|
import { posHardwareAttachmentOf } from "../model/pos-hardware-in-person.js";
|
|
21
21
|
import { fillPosHardwareBuyerAddress } from "./pos-hardware-buyer-record.js";
|
|
22
22
|
import { hardwareOrdersRef, posHardwareInPersonOrderId, posHardwareSaleRef } from "./pos-hardware.js";
|
|
@@ -114,8 +114,10 @@ function firestore() {
|
|
|
114
114
|
const from = await transaction.get(fromRef);
|
|
115
115
|
if (!from.exists) return false;
|
|
116
116
|
const before = from.data();
|
|
117
|
-
if (before.
|
|
118
|
-
|
|
117
|
+
if (before.status === 'canceled' || before.status === 'refunded') return false;
|
|
118
|
+
// Only a sale of the platform's own store can be nobody's yet; any
|
|
119
|
+
// other order is its workspace's (AGL-4038), set up before it shipped.
|
|
120
|
+
const pending = isPosHardwareSellerStoreSale(before) && ((_before_attachment = before.attachment) == null ? void 0 : _before_attachment.state) !== 'attached';
|
|
119
121
|
if (!pending && fromOrgId !== input.orgId) return false;
|
|
120
122
|
const units = withRegisteredUnit((_before_units = before.units) != null ? _before_units : [], serial, input.readerId, input.hostId, now);
|
|
121
123
|
if (!units) return false;
|
|
@@ -215,27 +217,10 @@ function firestore() {
|
|
|
215
217
|
const snapshot = await transaction.get(ref);
|
|
216
218
|
if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such card reader sale.', 404);
|
|
217
219
|
const before = snapshot.data();
|
|
218
|
-
if (before
|
|
219
|
-
throw new PosHardwareReaderRefusal('Only a card reader sold
|
|
220
|
+
if (!isPosHardwareSellerStoreSale(before) || ((_before_posSale = before.posSale) == null ? void 0 : _before_posSale.hostId) !== input.config.sellerHostId) {
|
|
221
|
+
throw new PosHardwareReaderRefusal('Only a card reader sold by this store takes serial numbers here.', 409);
|
|
220
222
|
}
|
|
221
|
-
const
|
|
222
|
-
if (serials.length > units.length) {
|
|
223
|
-
throw new PosHardwareReaderRefusal(`This sale has ${units.length} reader${units.length === 1 ? '' : 's'}.`, 400);
|
|
224
|
-
}
|
|
225
|
-
// Serials fill the readers not yet set up, in order; a registered one keeps its own.
|
|
226
|
-
const open = units.map((unit, index)=>({
|
|
227
|
-
unit,
|
|
228
|
-
index
|
|
229
|
-
})).filter(({ unit })=>!unit.readerId);
|
|
230
|
-
const next = [
|
|
231
|
-
...units
|
|
232
|
-
];
|
|
233
|
-
open.forEach(({ index }, position)=>{
|
|
234
|
-
var _serials_position;
|
|
235
|
-
next[index] = _extends({}, units[index], {
|
|
236
|
-
serialNumber: (_serials_position = serials[position]) != null ? _serials_position : null
|
|
237
|
-
});
|
|
238
|
-
});
|
|
223
|
+
const next = withPosHardwareSerials((_before_units = before.units) != null ? _before_units : [], serials);
|
|
239
224
|
transaction.update(ref, {
|
|
240
225
|
units: next,
|
|
241
226
|
serialNumbers: next.flatMap((unit)=>unit.serialNumber ? [
|
|
@@ -250,6 +235,193 @@ function firestore() {
|
|
|
250
235
|
};
|
|
251
236
|
});
|
|
252
237
|
}
|
|
238
|
+
/**
|
|
239
|
+
* The units with `serials` filling the readers not yet set up, in order; a
|
|
240
|
+
* registered reader keeps its own. Refuses more serials than readers.
|
|
241
|
+
*/ function withPosHardwareSerials(units, serials) {
|
|
242
|
+
if (serials.length > units.length) {
|
|
243
|
+
throw new PosHardwareReaderRefusal(`This order has ${units.length} reader${units.length === 1 ? '' : 's'}.`, 400);
|
|
244
|
+
}
|
|
245
|
+
const open = units.map((unit, index)=>({
|
|
246
|
+
unit,
|
|
247
|
+
index
|
|
248
|
+
})).filter(({ unit })=>!unit.readerId);
|
|
249
|
+
const next = [
|
|
250
|
+
...units
|
|
251
|
+
];
|
|
252
|
+
open.forEach(({ index }, position)=>{
|
|
253
|
+
var _serials_position;
|
|
254
|
+
next[index] = _extends({}, units[index], {
|
|
255
|
+
serialNumber: (_serials_position = serials[position]) != null ? _serials_position : null
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
return next;
|
|
259
|
+
}
|
|
260
|
+
/** Serial numbers as given: normalized, each once, none already on another order. */ async function checkedSerials(raw, orderId) {
|
|
261
|
+
const serials = (Array.isArray(raw) ? raw : []).map(normalizePosHardwareSerial).filter(Boolean);
|
|
262
|
+
if (new Set(serials).size !== serials.length) {
|
|
263
|
+
throw new PosHardwareReaderRefusal('A serial number is listed twice.', 400);
|
|
264
|
+
}
|
|
265
|
+
for (const serial of serials){
|
|
266
|
+
const elsewhere = await firestore().collectionGroup(POS_HARDWARE_ORDERS_COLLECTION).where('serialNumbers', 'array-contains', serial).limit(2).get();
|
|
267
|
+
if (elsewhere.docs.some((doc)=>String(doc.id) !== orderId)) {
|
|
268
|
+
throw new PosHardwareReaderRefusal(`Serial number ${serial} is already on another order.`, 409);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return serials;
|
|
272
|
+
}
|
|
273
|
+
/*==========================================
|
|
274
|
+
* SETTING AN ORDER UP BEFORE IT SHIPS (AGL-4038).
|
|
275
|
+
*
|
|
276
|
+
* The platform buys the readers in, receives them, sets them up and ships
|
|
277
|
+
* them to the buyer. Setting one up, on the staff Hardware orders page, is:
|
|
278
|
+
*
|
|
279
|
+
* - its serial number recorded on the order
|
|
280
|
+
* ({@link recordPosHardwareOrderSerials}), so the reader is matched to
|
|
281
|
+
* the order the moment the buyer pairs it on their store, and an order
|
|
282
|
+
* nobody is attached to yet joins the workspace that pairs it;
|
|
283
|
+
* - and, where the buyer's store can already take a reader (its plan
|
|
284
|
+
* includes the point of sale), the reader registered to that store by
|
|
285
|
+
* the code it shows ({@link registerPosHardwareOrderReader}), the same
|
|
286
|
+
* registration the booth and the POS devices card make.
|
|
287
|
+
*
|
|
288
|
+
* Both only while the order is still with the platform (paid, ordered or
|
|
289
|
+
* received), and shipping waits until every reader has its serial
|
|
290
|
+
* (`posHardwareReadyToShip`).
|
|
291
|
+
*=========================================*/ /** The statuses an order is still with the platform in, and can be set up. */ const BEFORE_SHIPPING = new Set([
|
|
292
|
+
'paid',
|
|
293
|
+
'ordered',
|
|
294
|
+
'received'
|
|
295
|
+
]);
|
|
296
|
+
/** Records the serial numbers of an order's readers, from the staff page. */ export async function recordPosHardwareOrderSerials(input) {
|
|
297
|
+
if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReaderRefusal('No such order.', 404);
|
|
298
|
+
const serials = await checkedSerials(input.serials, input.orderId);
|
|
299
|
+
const ref = hardwareOrdersRef(input.orgId).doc(input.orderId);
|
|
300
|
+
return firestore().runTransaction(async (transaction)=>{
|
|
301
|
+
const snapshot = await transaction.get(ref);
|
|
302
|
+
if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404);
|
|
303
|
+
const before = snapshot.data();
|
|
304
|
+
if (!BEFORE_SHIPPING.has(before.status)) {
|
|
305
|
+
throw new PosHardwareReaderRefusal('Serial numbers are recorded before the order ships.', 409);
|
|
306
|
+
}
|
|
307
|
+
const units = withPosHardwareSerials(posHardwareOrderUnits(before), serials);
|
|
308
|
+
const after = _extends({}, before, {
|
|
309
|
+
units,
|
|
310
|
+
serialNumbers: units.flatMap((unit)=>unit.serialNumber ? [
|
|
311
|
+
unit.serialNumber
|
|
312
|
+
] : []),
|
|
313
|
+
updatedAtMs: Date.now()
|
|
314
|
+
});
|
|
315
|
+
transaction.set(ref, after);
|
|
316
|
+
transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, after), posHardwareSaleSetOptions(after));
|
|
317
|
+
return after;
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Registers one of an order's readers to the buyer's store by the code it
|
|
322
|
+
* shows, from the staff page, before it ships. The order must name the
|
|
323
|
+
* buyer's store (an order from our own store is attached first, from the
|
|
324
|
+
* register's To attach list), and the store's plan must include the point of
|
|
325
|
+
* sale; a store with no reader Location yet is refused with
|
|
326
|
+
* `needs-address`, since only the buyer can say where it is, and the reader
|
|
327
|
+
* is then set up when they pair it.
|
|
328
|
+
*/ export async function registerPosHardwareOrderReader(input) {
|
|
329
|
+
var _order_attachment;
|
|
330
|
+
if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReaderRefusal('No such order.', 404);
|
|
331
|
+
const snapshot = await hardwareOrdersRef(input.orgId).doc(input.orderId).get();
|
|
332
|
+
const order = snapshot.data();
|
|
333
|
+
if (!order) throw new PosHardwareReaderRefusal('No such order.', 404);
|
|
334
|
+
if (!BEFORE_SHIPPING.has(order.status)) {
|
|
335
|
+
throw new PosHardwareReaderRefusal('A reader is registered here before the order ships.', 409);
|
|
336
|
+
}
|
|
337
|
+
if (isPosHardwareSellerStoreSale(order) && ((_order_attachment = order.attachment) == null ? void 0 : _order_attachment.state) !== 'attached') {
|
|
338
|
+
throw new PosHardwareReaderRefusal('Attach the order to the buyer’s workspace first, from To attach on our store’s register, or ship it and the reader joins their store when they pair it.', 409);
|
|
339
|
+
}
|
|
340
|
+
if (!order.hostId) throw new PosHardwareReaderRefusal('The buyer has not chosen a store for it yet.', 409);
|
|
341
|
+
if (!posHardwareOrderUnits(order).some((unit)=>!unit.readerId)) {
|
|
342
|
+
throw new PosHardwareReaderRefusal('Every reader on this order is registered.', 409);
|
|
343
|
+
}
|
|
344
|
+
return registerReaderOnOrder({
|
|
345
|
+
orgId: input.orgId,
|
|
346
|
+
orderId: input.orderId,
|
|
347
|
+
hostId: order.hostId,
|
|
348
|
+
registrationCode: input.registrationCode,
|
|
349
|
+
label: input.label,
|
|
350
|
+
uid: input.uid,
|
|
351
|
+
storeAddress: null
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* The registration itself, for the booth and the staff page: the store's
|
|
356
|
+
* plan and Location checked, the reader registered, and the order's first
|
|
357
|
+
* reader not yet set up (or the one with its serial) marked registered.
|
|
358
|
+
*/ async function registerReaderOnOrder(input) {
|
|
359
|
+
const { orgId, hostId } = input;
|
|
360
|
+
const readiness = await posHardwareStoreReadiness(hostId);
|
|
361
|
+
if (!readiness.posPlan) {
|
|
362
|
+
throw new PosHardwareReaderRefusal('Their workspace needs a plan with the point of sale before a reader can be added. They can add it, then set the reader up themselves.', 409);
|
|
363
|
+
}
|
|
364
|
+
if (!readiness.hasLocation && !input.storeAddress) {
|
|
365
|
+
throw new PosHardwareReaderRefusal('Their store has no address for card readers yet. Enter the store’s address to register the reader now, or they add it when they set the reader up on the POS devices card.', 409, 'needs-address');
|
|
366
|
+
}
|
|
367
|
+
const { registerPosTerminalReader } = await import("./pos-readers.js");
|
|
368
|
+
const registered = await registerPosTerminalReader(_extends({
|
|
369
|
+
hostId,
|
|
370
|
+
orgId,
|
|
371
|
+
uid: input.uid,
|
|
372
|
+
registrationCode: input.registrationCode,
|
|
373
|
+
label: input.label
|
|
374
|
+
}, input.storeAddress ? {
|
|
375
|
+
address: input.storeAddress
|
|
376
|
+
} : {}));
|
|
377
|
+
if ('error' in registered) throw new PosHardwareReaderRefusal(registered.error, registered.status);
|
|
378
|
+
// A reader with a serial matched its unit as it registered. One without
|
|
379
|
+
// (or not on the order) takes the first reader of the order not set up yet.
|
|
380
|
+
const ref = hardwareOrdersRef(orgId).doc(input.orderId);
|
|
381
|
+
const after = await firestore().runTransaction(async (transaction)=>{
|
|
382
|
+
const now = (await transaction.get(ref)).data();
|
|
383
|
+
const units = posHardwareOrderUnits(now);
|
|
384
|
+
if (units.some((unit)=>unit.readerId === registered.id)) return now;
|
|
385
|
+
const at = units.findIndex((unit)=>{
|
|
386
|
+
var _posHardwareSku;
|
|
387
|
+
return !unit.readerId && ((_posHardwareSku = posHardwareSku(unit.sku)) == null ? void 0 : _posHardwareSku.kind) === 'reader';
|
|
388
|
+
});
|
|
389
|
+
if (at < 0) return now;
|
|
390
|
+
const stamp = Date.now();
|
|
391
|
+
const next = units.map((unit, index)=>{
|
|
392
|
+
var _unit_serialNumber;
|
|
393
|
+
return index === at ? _extends({}, unit, {
|
|
394
|
+
serialNumber: (_unit_serialNumber = unit.serialNumber) != null ? _unit_serialNumber : registered.reader.serialNumber ? normalizePosHardwareSerial(registered.reader.serialNumber) : null,
|
|
395
|
+
readerId: registered.id,
|
|
396
|
+
hostId,
|
|
397
|
+
registeredAtMs: stamp
|
|
398
|
+
}) : unit;
|
|
399
|
+
});
|
|
400
|
+
const done = everyReaderRegistered(next);
|
|
401
|
+
const updated = _extends({}, now, {
|
|
402
|
+
units: next,
|
|
403
|
+
serialNumbers: next.flatMap((unit)=>unit.serialNumber ? [
|
|
404
|
+
unit.serialNumber
|
|
405
|
+
] : [])
|
|
406
|
+
}, done && now.status === 'delivered' ? {
|
|
407
|
+
status: 'registered',
|
|
408
|
+
registeredAtMs: stamp
|
|
409
|
+
} : {}, {
|
|
410
|
+
updatedAtMs: stamp
|
|
411
|
+
});
|
|
412
|
+
transaction.set(ref, updated);
|
|
413
|
+
transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, updated), posHardwareSaleSetOptions(updated));
|
|
414
|
+
return updated;
|
|
415
|
+
});
|
|
416
|
+
await fillPosHardwareBuyerAddress({
|
|
417
|
+
orgId,
|
|
418
|
+
orderId: input.orderId
|
|
419
|
+
});
|
|
420
|
+
return {
|
|
421
|
+
order: after,
|
|
422
|
+
readerId: registered.id
|
|
423
|
+
};
|
|
424
|
+
}
|
|
253
425
|
/** An in-person order of this workspace, for a change by its own people. */ function workspaceOrder(orgId, orderId) {
|
|
254
426
|
if (!POS_HARDWARE_ORDER_ID.test(orderId)) throw new PosHardwareReaderRefusal('No such order.', 404);
|
|
255
427
|
return {
|
|
@@ -265,7 +437,7 @@ function firestore() {
|
|
|
265
437
|
const snapshot = await transaction.get(ref);
|
|
266
438
|
if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404);
|
|
267
439
|
const before = snapshot.data();
|
|
268
|
-
if (before
|
|
440
|
+
if (!isPosHardwareSellerStoreSale(before)) throw new PosHardwareReaderRefusal('Only a reader bought from our store waits for a store.', 409);
|
|
269
441
|
const after = _extends({}, before, {
|
|
270
442
|
hostId: input.hostId
|
|
271
443
|
}, before.attachment ? {
|
|
@@ -295,7 +467,7 @@ function firestore() {
|
|
|
295
467
|
const snapshot = await transaction.get(ref);
|
|
296
468
|
if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404);
|
|
297
469
|
const before = snapshot.data();
|
|
298
|
-
if (before
|
|
470
|
+
if (!isPosHardwareSellerStoreSale(before)) throw new PosHardwareReaderRefusal('Only a reader bought from our store is marked set up here.', 409);
|
|
299
471
|
if (before.status === 'registered') return before;
|
|
300
472
|
if (before.status !== 'delivered') throw new PosHardwareReaderRefusal('This order can no longer be set up.', 409);
|
|
301
473
|
const now = Date.now();
|
|
@@ -344,7 +516,7 @@ function firestore() {
|
|
|
344
516
|
const orgId = String((_sale_get = sale.get('orgId')) != null ? _sale_get : '');
|
|
345
517
|
const snapshot = await hardwareOrdersRef(orgId).doc(input.orderId).get();
|
|
346
518
|
const order = snapshot.data();
|
|
347
|
-
if (!order || order
|
|
519
|
+
if (!order || !isPosHardwareSellerStoreSale(order) || ((_order_posSale = order.posSale) == null ? void 0 : _order_posSale.hostId) !== input.config.sellerHostId) {
|
|
348
520
|
throw new PosHardwareReaderRefusal('No such card reader sale.', 404);
|
|
349
521
|
}
|
|
350
522
|
if (((_order_attachment = order.attachment) == null ? void 0 : _order_attachment.state) !== 'attached' || !order.attachment.orgId) {
|
|
@@ -353,76 +525,25 @@ function firestore() {
|
|
|
353
525
|
const hostId = order.hostId;
|
|
354
526
|
if (!hostId) throw new PosHardwareReaderRefusal('Choose the buyer’s store first.', 409);
|
|
355
527
|
const readiness = await posHardwareStoreReadiness(hostId);
|
|
356
|
-
if (!readiness.posPlan) {
|
|
357
|
-
throw new PosHardwareReaderRefusal('Their workspace needs a plan with the point of sale before a reader can be added. They can add it, then set the reader up themselves.', 409);
|
|
358
|
-
}
|
|
359
528
|
// The store's address, only for a store with no Location: one that has
|
|
360
529
|
// its Location keeps it, whatever was sent.
|
|
361
530
|
const storeAddress = readiness.hasLocation ? null : boothStoreAddress(input.address);
|
|
362
|
-
if (
|
|
363
|
-
if (!storeAddress) {
|
|
364
|
-
throw new PosHardwareReaderRefusal('Their store has no address for card readers yet. Enter the store’s address to register the reader now, or they add it when they set the reader up on the POS devices card.', 409, 'needs-address');
|
|
365
|
-
}
|
|
531
|
+
if (storeAddress) {
|
|
366
532
|
const problem = (await import("./pos-terminal.js")).posTerminalAddressProblem(storeAddress);
|
|
367
533
|
if (problem) throw new PosHardwareReaderRefusal(problem, 400, 'needs-address');
|
|
368
534
|
}
|
|
369
|
-
const {
|
|
370
|
-
const registered = await registerPosTerminalReader(_extends({
|
|
371
|
-
hostId,
|
|
535
|
+
const { order: after, readerId } = await registerReaderOnOrder({
|
|
372
536
|
orgId,
|
|
373
|
-
|
|
537
|
+
orderId: input.orderId,
|
|
538
|
+
hostId,
|
|
374
539
|
registrationCode: input.registrationCode,
|
|
375
|
-
label: input.label
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
} : {}));
|
|
379
|
-
if ('error' in registered) throw new PosHardwareReaderRefusal(registered.error, registered.status);
|
|
380
|
-
// A reader with a serial matched its unit as it registered. One without
|
|
381
|
-
// (or not on the sale) takes the first reader of the sale not set up yet.
|
|
382
|
-
const ref = hardwareOrdersRef(orgId).doc(input.orderId);
|
|
383
|
-
const after = await firestore().runTransaction(async (transaction)=>{
|
|
384
|
-
var _now_units;
|
|
385
|
-
const now = (await transaction.get(ref)).data();
|
|
386
|
-
const units = (_now_units = now.units) != null ? _now_units : [];
|
|
387
|
-
if (units.some((unit)=>unit.readerId === registered.id)) return now;
|
|
388
|
-
const at = units.findIndex((unit)=>{
|
|
389
|
-
var _posHardwareSku;
|
|
390
|
-
return !unit.readerId && ((_posHardwareSku = posHardwareSku(unit.sku)) == null ? void 0 : _posHardwareSku.kind) === 'reader';
|
|
391
|
-
});
|
|
392
|
-
if (at < 0) return now;
|
|
393
|
-
const stamp = Date.now();
|
|
394
|
-
const next = units.map((unit, index)=>{
|
|
395
|
-
var _unit_serialNumber;
|
|
396
|
-
return index === at ? _extends({}, unit, {
|
|
397
|
-
serialNumber: (_unit_serialNumber = unit.serialNumber) != null ? _unit_serialNumber : registered.reader.serialNumber ? normalizePosHardwareSerial(registered.reader.serialNumber) : null,
|
|
398
|
-
readerId: registered.id,
|
|
399
|
-
hostId,
|
|
400
|
-
registeredAtMs: stamp
|
|
401
|
-
}) : unit;
|
|
402
|
-
});
|
|
403
|
-
const done = everyReaderRegistered(next);
|
|
404
|
-
const updated = _extends({}, now, {
|
|
405
|
-
units: next,
|
|
406
|
-
serialNumbers: next.flatMap((unit)=>unit.serialNumber ? [
|
|
407
|
-
unit.serialNumber
|
|
408
|
-
] : [])
|
|
409
|
-
}, done && now.status === 'delivered' ? {
|
|
410
|
-
status: 'registered',
|
|
411
|
-
registeredAtMs: stamp
|
|
412
|
-
} : {}, {
|
|
413
|
-
updatedAtMs: stamp
|
|
414
|
-
});
|
|
415
|
-
transaction.set(ref, updated);
|
|
416
|
-
transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, updated), posHardwareSaleSetOptions(updated));
|
|
417
|
-
return updated;
|
|
418
|
-
});
|
|
419
|
-
await fillPosHardwareBuyerAddress({
|
|
420
|
-
orgId,
|
|
421
|
-
orderId: input.orderId
|
|
540
|
+
label: input.label,
|
|
541
|
+
uid: input.uid,
|
|
542
|
+
storeAddress
|
|
422
543
|
});
|
|
423
544
|
return {
|
|
424
545
|
order: after,
|
|
425
|
-
readerId
|
|
546
|
+
readerId,
|
|
426
547
|
storeAddress
|
|
427
548
|
};
|
|
428
549
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-readers.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n normalizePosHardwareSerial,\n POS_HARDWARE_ORDER_ID,\n POS_HARDWARE_ORDERS_COLLECTION,\n posHardwareSaleRecord,\n posHardwareSaleSetOptions,\n posHardwareSku,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n type PosHardwareUnit,\n} from '../model/pos-hardware'\nimport { posHardwareAttachmentOf } from '../model/pos-hardware-in-person'\nimport { fillPosHardwareBuyerAddress } from './pos-hardware-buyer-record'\nimport { hardwareOrdersRef, posHardwareInPersonOrderId, posHardwareSaleRef } from './pos-hardware'\nimport type { PosTerminalAddress } from './pos-terminal'\n\n/*==========================================\n * A CARD READER SOLD IN PERSON, ONTO THE BUYER'S STORE (AGL-4038).\n *\n * Three ways, and every one ends with the order at Set up:\n *\n * 1. The serial number taken at the sale. Staff scan or type each reader's\n * serial on the sale; when the buyer registers a reader with that\n * serial (by its code, on the POS devices card), the reader is matched\n * to its unit here and the order moves to Set up once every reader on\n * it is — no step for the buyer. A sale nobody had attached yet is\n * attached to the workspace that registered its reader: only whoever\n * holds the reader can show its code.\n * 2. Registered at the booth. A register user registers the reader to the\n * store the buyer chose, by its code, while the buyer stands there:\n * the store's plan must include the point of sale and the store must\n * have a reader Location (its address), as for any registration.\n * 3. Paired later with no serial. The buyer registers it by code (or pairs\n * an M2 by Bluetooth, which no server sees) and says \"Mark set up\" on\n * the Hardware card; staff can mark it too.\n *=========================================*/\n\nexport class PosHardwareReaderRefusal extends Error {\n constructor(\n message: string,\n readonly status: number,\n /** A refusal the register answers with a step of its own: `needs-address` asks for the store's address. */\n readonly reason?: 'needs-address',\n ) {\n super(message)\n }\n}\n\n/**\n * A store address typed at the booth, read the way the POS devices card\n * sends it (AGL-4038): each field a trimmed string within the lengths the\n * reader registration keeps, the country as two capitals. Anything that is\n * not an object reads as no address.\n */\nexport function boothStoreAddress(raw: unknown): PosTerminalAddress | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null\n const field = (key: string, max: number) =>\n String((raw as Record<string, unknown>)[key] ?? '')\n .trim()\n .slice(0, max)\n const line2 = field('line2', 200)\n const state = field('state', 100)\n return {\n line1: field('line1', 200),\n ...(line2 ? { line2 } : {}),\n city: field('city', 100),\n ...(state ? { state } : {}),\n postalCode: field('postalCode', 20),\n country: field('country', 2).toUpperCase(),\n }\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\n/** Whether every reader on the order is registered: then it is Set up. */\nfunction everyReaderRegistered(units: readonly PosHardwareUnit[]): boolean {\n return units.length > 0 && units.every((unit) => Boolean(unit.readerId))\n}\n\n/** The order's units with `serial` registered as `readerId` on `hostId`, or null when no unit has it. */\nfunction withRegisteredUnit(\n units: readonly PosHardwareUnit[],\n serial: string,\n readerId: string,\n hostId: string,\n now: number,\n): PosHardwareUnit[] | null {\n const at = units.findIndex((unit) => unit.serialNumber === serial)\n if (at < 0) return null\n if (units[at].readerId === readerId) return [...units]\n return units.map((unit, index) =>\n index === at ? { ...unit, readerId, hostId, registeredAtMs: now } : unit,\n )\n}\n\n/**\n * A reader was just registered to a store: the in-person order that sold it\n * by this serial moves on. Attached to this workspace, or pending (then\n * attached to it now); an order attached to another workspace is left as it\n * is. Returns the orders it changed.\n */\nexport async function matchRegisteredPosHardwareReader(input: {\n hostId: string\n orgId: string\n uid: string\n readerId: string\n serialNumber: string\n now?: number\n}): Promise<{ matched: string[] }> {\n const serial = normalizePosHardwareSerial(input.serialNumber)\n if (!serial || !input.orgId) return { matched: [] }\n const found = await firestore()\n .collectionGroup(POS_HARDWARE_ORDERS_COLLECTION)\n .where('serialNumbers', 'array-contains', serial)\n .limit(5)\n .get()\n const matched: string[] = []\n for (const doc of found.docs as unknown as Array<{ id: string; data: () => PosHardwareOrder }>) {\n const orderId = String(doc.id)\n const now = input.now ?? Date.now()\n const changed = await firestore().runTransaction(async (transaction: any) => {\n const saleRef = posHardwareSaleRef(orderId)\n const sale = await transaction.get(saleRef)\n const fromOrgId = String(sale.get('orgId') ?? doc.data().orgId ?? '')\n const fromRef = hardwareOrdersRef(fromOrgId).doc(orderId)\n const from = await transaction.get(fromRef)\n if (!from.exists) return false\n const before = from.data() as PosHardwareOrder\n if (before.source !== 'in_person' || before.status === 'canceled' || before.status === 'refunded') return false\n const pending = before.attachment?.state !== 'attached'\n if (!pending && fromOrgId !== input.orgId) return false\n const units = withRegisteredUnit(before.units ?? [], serial, input.readerId, input.hostId, now)\n if (!units) return false\n const done = everyReaderRegistered(units)\n const after: PosHardwareOrder = {\n ...before,\n ...(pending\n ? {\n orgId: input.orgId,\n hostId: input.hostId,\n createdBy: input.uid,\n attachment: {\n ...posHardwareAttachmentOf({\n uid: input.uid,\n orgId: input.orgId,\n hostId: input.hostId,\n email: before.attachment?.email ?? null,\n attachedBy: '',\n attachedAtMs: now,\n // What the register typed of the buyer stays (AGL-4038).\n name: before.attachment?.name ?? null,\n address: before.attachment?.address ?? null,\n }),\n },\n }\n : { hostId: before.hostId || input.hostId }),\n units,\n ...(done && before.status === 'delivered' ? { status: 'registered' as const, registeredAtMs: now } : {}),\n updatedAtMs: now,\n }\n if (after.orgId === fromOrgId) {\n transaction.set(fromRef, after)\n } else {\n transaction.create(hardwareOrdersRef(after.orgId).doc(orderId), after)\n transaction.delete(fromRef)\n }\n transaction.set(saleRef, posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n return true\n })\n if (changed) matched.push(orderId)\n }\n // The buyer's address for the reseller's records, from the store the\n // reader is now on, where the sale has none yet.\n for (const orderId of matched) await fillPosHardwareBuyerAddress({ orgId: input.orgId, orderId })\n return { matched }\n}\n\n/**\n * The serial numbers of a sale's readers, taken at the sale: on the hardware\n * order once it is recorded, or on the register sale until it is (the\n * recorder takes them from there). Each is normalized, none may repeat, and\n * none may already be on another sale.\n */\nexport async function recordPosHardwareSerials(input: {\n config: PosHardwareInPersonConfig\n registerOrderId?: string | null\n orderId?: string | null\n serials: unknown\n}): Promise<{ orderId: string; serials: string[]; recorded: boolean }> {\n const serials = (Array.isArray(input.serials) ? input.serials : [])\n .map(normalizePosHardwareSerial)\n .filter(Boolean)\n if (new Set(serials).size !== serials.length) {\n throw new PosHardwareReaderRefusal('A serial number is listed twice.', 400)\n }\n const registerOrderId = String(input.registerOrderId ?? '')\n const orderId = registerOrderId\n ? posHardwareInPersonOrderId(input.config.sellerHostId, registerOrderId)\n : String(input.orderId ?? '')\n if (!POS_HARDWARE_ORDER_ID.test(orderId)) throw new PosHardwareReaderRefusal('Name the sale.', 400)\n for (const serial of serials) {\n const elsewhere = await firestore()\n .collectionGroup(POS_HARDWARE_ORDERS_COLLECTION)\n .where('serialNumbers', 'array-contains', serial)\n .limit(2)\n .get()\n if (elsewhere.docs.some((doc: any) => String(doc.id) !== orderId)) {\n throw new PosHardwareReaderRefusal(`Serial number ${serial} is already on another sale.`, 409)\n }\n }\n const saleRef = posHardwareSaleRef(orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const sale = await transaction.get(saleRef)\n if (!sale.exists) {\n if (!registerOrderId) throw new PosHardwareReaderRefusal('No such card reader sale.', 404)\n const registerRef = firestore()\n .collection('hosts')\n .doc(input.config.sellerHostId)\n .collection('orders')\n .doc(registerOrderId)\n const register = await transaction.get(registerRef)\n const status = String(register.get('status') ?? '')\n if (!register.exists || (status !== 'pending' && status !== 'paid')) {\n throw new PosHardwareReaderRefusal('No open or paid sale on this register by that number.', 404)\n }\n transaction.set(registerRef, { hardwareSerials: serials }, { merge: true })\n return { orderId, serials, recorded: false }\n }\n const ref = hardwareOrdersRef(String(sale.get('orgId') ?? '')).doc(orderId)\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such card reader sale.', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (before.source !== 'in_person' || before.posSale?.hostId !== input.config.sellerHostId) {\n throw new PosHardwareReaderRefusal('Only a card reader sold in person here takes serial numbers.', 409)\n }\n const units = before.units ?? []\n if (serials.length > units.length) {\n throw new PosHardwareReaderRefusal(`This sale has ${units.length} reader${units.length === 1 ? '' : 's'}.`, 400)\n }\n // Serials fill the readers not yet set up, in order; a registered one keeps its own.\n const open = units.map((unit, index) => ({ unit, index })).filter(({ unit }) => !unit.readerId)\n const next = [...units]\n open.forEach(({ index }, position) => {\n next[index] = { ...units[index], serialNumber: serials[position] ?? null }\n })\n transaction.update(ref, {\n units: next,\n serialNumbers: next.flatMap((unit) => (unit.serialNumber ? [unit.serialNumber] : [])),\n updatedAtMs: Date.now(),\n })\n return { orderId, serials, recorded: true }\n })\n}\n\n/** An in-person order of this workspace, for a change by its own people. */\nfunction workspaceOrder(orgId: string, orderId: string) {\n if (!POS_HARDWARE_ORDER_ID.test(orderId)) throw new PosHardwareReaderRefusal('No such order.', 404)\n return { ref: hardwareOrdersRef(orgId).doc(orderId) }\n}\n\n/**\n * The store a reader bought in person is for, chosen at setup by someone\n * who may set up devices there. The store must be the workspace's.\n */\nexport async function choosePosHardwareStore(input: {\n orgId: string\n orderId: string\n hostId: string\n}): Promise<PosHardwareOrder> {\n const { ref } = workspaceOrder(input.orgId, input.orderId)\n const chosen: PosHardwareOrder = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (before.source !== 'in_person') throw new PosHardwareReaderRefusal('Only a reader bought in person waits for a store.', 409)\n const after: PosHardwareOrder = {\n ...before,\n hostId: input.hostId,\n ...(before.attachment ? { attachment: { ...before.attachment, hostId: input.hostId } } : {}),\n updatedAtMs: Date.now(),\n }\n transaction.set(ref, after)\n transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, after), posHardwareSaleSetOptions(after))\n return after\n })\n await fillPosHardwareBuyerAddress({ orgId: input.orgId, orderId: input.orderId })\n return chosen\n}\n\n/**\n * \"Mark set up\": a reader bought in person was paired by its code or by\n * Bluetooth with no serial taken at the sale, so nothing matched it. The\n * workspace says so, and the order moves to Set up.\n */\nexport async function markPosHardwareSetUp(input: { orgId: string; orderId: string }): Promise<PosHardwareOrder> {\n const { ref } = workspaceOrder(input.orgId, input.orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (before.source !== 'in_person') throw new PosHardwareReaderRefusal('Only a reader bought in person is marked set up here.', 409)\n if (before.status === 'registered') return before\n if (before.status !== 'delivered') throw new PosHardwareReaderRefusal('This order can no longer be set up.', 409)\n const now = Date.now()\n const after: PosHardwareOrder = { ...before, status: 'registered', registeredAtMs: now, updatedAtMs: now }\n transaction.set(ref, after)\n transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, after), posHardwareSaleSetOptions(after))\n return after\n })\n}\n\n/** A store's readiness for a reader: its plan and its Location. */\nexport async function posHardwareStoreReadiness(hostId: string): Promise<{ posPlan: boolean; hasLocation: boolean }> {\n const [owner, config] = await Promise.all([\n getOrgForHost(hostId).catch(() => null),\n firestore().collection('hosts').doc(hostId).collection('terminal').doc('config').get(),\n ])\n return {\n posPlan: Aglyn.checkEntitlement(owner?.org as never, 'pos'),\n hasLocation: Boolean(config.exists && config.get('stripeLocationId')),\n }\n}\n\n/**\n * Registers a reader sold at the booth to the buyer's chosen store, by the\n * code it shows, while the buyer is there (AGL-4038). The sale must be\n * attached to them with a store chosen, and the store's plan must include\n * the point of sale.\n *\n * A store with no reader Location yet needs its address, which is where\n * Stripe sets the reader up for. Booth staff may type it with the buyer\n * (`address`): it goes exactly where the store's POS devices card would put\n * it, through the same registration, which creates the store's Location from\n * it and records it on the store's terminal settings. Without one the booth\n * refuses with `needs-address`, and the buyer can add it later on that card.\n * A store that already has its Location keeps it: an address sent for it is\n * never used.\n */\nexport async function registerPosHardwareAtBooth(input: {\n config: PosHardwareInPersonConfig\n orderId: string\n registrationCode: unknown\n label?: unknown\n address?: unknown\n uid: string\n}): Promise<{ order: PosHardwareOrder; readerId: string; storeAddress: PosTerminalAddress | null }> {\n if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReaderRefusal('Name the sale.', 400)\n const sale = await posHardwareSaleRef(input.orderId).get()\n if (!sale.exists) {\n throw new PosHardwareReaderRefusal('Take payment for the sale first, then register its reader.', 409)\n }\n const orgId = String(sale.get('orgId') ?? '')\n const snapshot = await hardwareOrdersRef(orgId).doc(input.orderId).get()\n const order = snapshot.data() as PosHardwareOrder | undefined\n if (!order || order.source !== 'in_person' || order.posSale?.hostId !== input.config.sellerHostId) {\n throw new PosHardwareReaderRefusal('No such card reader sale.', 404)\n }\n if (order.attachment?.state !== 'attached' || !order.attachment.orgId) {\n throw new PosHardwareReaderRefusal('Attach the sale to the buyer first.', 409)\n }\n const hostId = order.hostId\n if (!hostId) throw new PosHardwareReaderRefusal('Choose the buyer’s store first.', 409)\n const readiness = await posHardwareStoreReadiness(hostId)\n if (!readiness.posPlan) {\n throw new PosHardwareReaderRefusal(\n 'Their workspace needs a plan with the point of sale before a reader can be added. They can add it, then set the reader up themselves.',\n 409,\n )\n }\n // The store's address, only for a store with no Location: one that has\n // its Location keeps it, whatever was sent.\n const storeAddress = readiness.hasLocation ? null : boothStoreAddress(input.address)\n if (!readiness.hasLocation) {\n if (!storeAddress) {\n throw new PosHardwareReaderRefusal(\n 'Their store has no address for card readers yet. Enter the store’s address to register the reader now, or they add it when they set the reader up on the POS devices card.',\n 409,\n 'needs-address',\n )\n }\n const problem = (await import('./pos-terminal')).posTerminalAddressProblem(storeAddress)\n if (problem) throw new PosHardwareReaderRefusal(problem, 400, 'needs-address')\n }\n const { registerPosTerminalReader } = await import('./pos-readers')\n const registered = await registerPosTerminalReader({\n hostId,\n orgId,\n uid: input.uid,\n registrationCode: input.registrationCode,\n label: input.label,\n ...(storeAddress ? { address: storeAddress } : {}),\n })\n if ('error' in registered) throw new PosHardwareReaderRefusal(registered.error, registered.status)\n // A reader with a serial matched its unit as it registered. One without\n // (or not on the sale) takes the first reader of the sale not set up yet.\n const ref = hardwareOrdersRef(orgId).doc(input.orderId)\n const after = await firestore().runTransaction(async (transaction: any) => {\n const now = (await transaction.get(ref)).data() as PosHardwareOrder\n const units = now.units ?? []\n if (units.some((unit) => unit.readerId === registered.id)) return now\n const at = units.findIndex(\n (unit) => !unit.readerId && posHardwareSku(unit.sku)?.kind === 'reader',\n )\n if (at < 0) return now\n const stamp = Date.now()\n const next = units.map((unit, index) =>\n index === at\n ? {\n ...unit,\n serialNumber: unit.serialNumber ?? (registered.reader.serialNumber ? normalizePosHardwareSerial(registered.reader.serialNumber) : null),\n readerId: registered.id,\n hostId,\n registeredAtMs: stamp,\n }\n : unit,\n )\n const done = everyReaderRegistered(next)\n const updated: PosHardwareOrder = {\n ...now,\n units: next,\n serialNumbers: next.flatMap((unit) => (unit.serialNumber ? [unit.serialNumber] : [])),\n ...(done && now.status === 'delivered' ? { status: 'registered' as const, registeredAtMs: stamp } : {}),\n updatedAtMs: stamp,\n }\n transaction.set(ref, updated)\n transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, updated), posHardwareSaleSetOptions(updated))\n return updated\n })\n await fillPosHardwareBuyerAddress({ orgId, orderId: input.orderId })\n return { order: after, readerId: registered.id, storeAddress }\n}\n"],"names":["Aglyn","firebaseAdmin","getOrgForHost","normalizePosHardwareSerial","POS_HARDWARE_ORDER_ID","POS_HARDWARE_ORDERS_COLLECTION","posHardwareSaleRecord","posHardwareSaleSetOptions","posHardwareSku","posHardwareAttachmentOf","fillPosHardwareBuyerAddress","hardwareOrdersRef","posHardwareInPersonOrderId","posHardwareSaleRef","PosHardwareReaderRefusal","Error","message","status","reason","boothStoreAddress","raw","Array","isArray","field","key","max","String","trim","slice","line2","state","line1","city","postalCode","country","toUpperCase","firestore","app","everyReaderRegistered","units","length","every","unit","Boolean","readerId","withRegisteredUnit","serial","hostId","now","at","findIndex","serialNumber","map","index","registeredAtMs","matchRegisteredPosHardwareReader","input","orgId","matched","found","collectionGroup","where","limit","get","doc","docs","orderId","id","Date","changed","runTransaction","transaction","sale","before","saleRef","fromOrgId","data","fromRef","from","exists","source","pending","attachment","done","after","createdBy","uid","email","attachedBy","attachedAtMs","name","address","updatedAtMs","set","create","delete","push","recordPosHardwareSerials","serials","filter","Set","size","registerOrderId","config","sellerHostId","test","elsewhere","some","register","registerRef","collection","hardwareSerials","merge","recorded","ref","snapshot","posSale","open","next","forEach","position","update","serialNumbers","flatMap","workspaceOrder","choosePosHardwareStore","chosen","markPosHardwareSetUp","posHardwareStoreReadiness","owner","Promise","all","catch","posPlan","checkEntitlement","org","hasLocation","registerPosHardwareAtBooth","order","readiness","storeAddress","problem","posTerminalAddressProblem","registerPosTerminalReader","registered","registrationCode","label","error","sku","kind","stamp","reader","updated"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SACEC,0BAA0B,EAC1BC,qBAAqB,EACrBC,8BAA8B,EAC9BC,qBAAqB,EACrBC,yBAAyB,EACzBC,cAAc,QAIT,2BAAuB;AAC9B,SAASC,uBAAuB,QAAQ,qCAAiC;AACzE,SAASC,2BAA2B,QAAQ,iCAA6B;AACzE,SAASC,iBAAiB,EAAEC,0BAA0B,EAAEC,kBAAkB,QAAQ,oBAAgB;AAGlG;;;;;;;;;;;;;;;;;;;2CAmB2C,GAE3C,OAAO,MAAMC,iCAAiCC;IAC5C,YACEC,OAAe,EACf,AAASC,MAAc,EACvB,yGAAyG,GACzG,AAASC,MAAwB,CACjC;QACA,KAAK,CAACF,eAJGC,SAAAA,aAEAC,SAAAA;IAGX;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASC,kBAAkBC,GAAY;IAC5C,IAAI,CAACA,OAAO,OAAOA,QAAQ,YAAYC,MAAMC,OAAO,CAACF,MAAM,OAAO;IAClE,MAAMG,QAAQ,CAACC,KAAaC;YACnB;eAAPC,QAAO,WAAA,AAACN,GAA+B,CAACI,IAAI,YAArC,WAAyC,IAC7CG,IAAI,GACJC,KAAK,CAAC,GAAGH;;IACd,MAAMI,QAAQN,MAAM,SAAS;IAC7B,MAAMO,QAAQP,MAAM,SAAS;IAC7B,OAAO;QACLQ,OAAOR,MAAM,SAAS;OAClBM,QAAQ;QAAEA;IAAM,IAAI,CAAC;QACzBG,MAAMT,MAAM,QAAQ;OAChBO,QAAQ;QAAEA;IAAM,IAAI,CAAC;QACzBG,YAAYV,MAAM,cAAc;QAChCW,SAASX,MAAM,WAAW,GAAGY,WAAW;;AAE5C;AAEA,SAASC;IACP,OAAOnC,cAAcoC,GAAG,GAAGD,SAA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AAKpB,GAAG;QACtB,MAAMsE,OAAO/E,MAAMa,GAAG,CAAC,CAACV,MAAMW;gBAIRX;mBAHpBW,UAAUJ,KACN,aACKP;gBACHS,YAAY,GAAET,qBAAAA,KAAKS,YAAY,YAAjBT,qBAAsBsG,WAAWO,MAAM,CAACpG,YAAY,GAAGhD,2BAA2B6I,WAAWO,MAAM,CAACpG,YAAY,IAAI;gBAClIP,UAAUoG,WAAW7E,EAAE;gBACvBpB;gBACAO,gBAAgBgG;iBAElB5G;;QAEN,MAAMyC,OAAO7C,sBAAsBgF;QACnC,MAAMkC,UAA4B,aAC7BxG;YACHT,OAAO+E;YACPI,eAAeJ,KAAKK,OAAO,CAAC,CAACjF,OAAUA,KAAKS,YAAY,GAAG;oBAACT,KAAKS,YAAY;iBAAC,GAAG,EAAE;WAC/EgC,QAAQnC,IAAI/B,MAAM,KAAK,cAAc;YAAEA,QAAQ;YAAuBqC,gBAAgBgG;QAAM,IAAI,CAAC;YACrG1D,aAAa0D;;QAEf/E,YAAYsB,GAAG,CAACqB,KAAKsC;QACrBjF,YAAYsB,GAAG,CAAChF,mBAAmB2C,MAAMU,OAAO,GAAG5D,sBAAsBkD,MAAMU,OAAO,EAAEsF,UAAUjJ,0BAA0BiJ;QAC5H,OAAOA;IACT;IACA,MAAM9I,4BAA4B;QAAE+C;QAAOS,SAASV,MAAMU,OAAO;IAAC;IAClE,OAAO;QAAEwE,OAAOtD;QAAOxC,UAAUoG,WAAW7E,EAAE;QAAEyE;IAAa;AAC/D"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware-readers.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n isPosHardwareSellerStoreSale,\n normalizePosHardwareSerial,\n POS_HARDWARE_ORDER_ID,\n POS_HARDWARE_ORDERS_COLLECTION,\n posHardwareSaleRecord,\n posHardwareSaleSetOptions,\n posHardwareOrderUnits,\n posHardwareSku,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n type PosHardwareUnit,\n} from '../model/pos-hardware'\nimport { posHardwareAttachmentOf } from '../model/pos-hardware-in-person'\nimport { fillPosHardwareBuyerAddress } from './pos-hardware-buyer-record'\nimport { hardwareOrdersRef, posHardwareInPersonOrderId, posHardwareSaleRef } from './pos-hardware'\nimport type { PosTerminalAddress } from './pos-terminal'\n\n/*==========================================\n * A CARD READER SOLD IN PERSON, ONTO THE BUYER'S STORE (AGL-4038).\n *\n * Three ways, and every one ends with the order at Set up:\n *\n * 1. The serial number taken at the sale. Staff scan or type each reader's\n * serial on the sale; when the buyer registers a reader with that\n * serial (by its code, on the POS devices card), the reader is matched\n * to its unit here and the order moves to Set up once every reader on\n * it is — no step for the buyer. A sale nobody had attached yet is\n * attached to the workspace that registered its reader: only whoever\n * holds the reader can show its code.\n * 2. Registered at the booth. A register user registers the reader to the\n * store the buyer chose, by its code, while the buyer stands there:\n * the store's plan must include the point of sale and the store must\n * have a reader Location (its address), as for any registration.\n * 3. Paired later with no serial. The buyer registers it by code (or pairs\n * an M2 by Bluetooth, which no server sees) and says \"Mark set up\" on\n * the Hardware card; staff can mark it too.\n *=========================================*/\n\nexport class PosHardwareReaderRefusal extends Error {\n constructor(\n message: string,\n readonly status: number,\n /** A refusal the register answers with a step of its own: `needs-address` asks for the store's address. */\n readonly reason?: 'needs-address',\n ) {\n super(message)\n }\n}\n\n/**\n * A store address typed at the booth, read the way the POS devices card\n * sends it (AGL-4038): each field a trimmed string within the lengths the\n * reader registration keeps, the country as two capitals. Anything that is\n * not an object reads as no address.\n */\nexport function boothStoreAddress(raw: unknown): PosTerminalAddress | null {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null\n const field = (key: string, max: number) =>\n String((raw as Record<string, unknown>)[key] ?? '')\n .trim()\n .slice(0, max)\n const line2 = field('line2', 200)\n const state = field('state', 100)\n return {\n line1: field('line1', 200),\n ...(line2 ? { line2 } : {}),\n city: field('city', 100),\n ...(state ? { state } : {}),\n postalCode: field('postalCode', 20),\n country: field('country', 2).toUpperCase(),\n }\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\n/** Whether every reader on the order is registered: then it is Set up. */\nfunction everyReaderRegistered(units: readonly PosHardwareUnit[]): boolean {\n return units.length > 0 && units.every((unit) => Boolean(unit.readerId))\n}\n\n/** The order's units with `serial` registered as `readerId` on `hostId`, or null when no unit has it. */\nfunction withRegisteredUnit(\n units: readonly PosHardwareUnit[],\n serial: string,\n readerId: string,\n hostId: string,\n now: number,\n): PosHardwareUnit[] | null {\n const at = units.findIndex((unit) => unit.serialNumber === serial)\n if (at < 0) return null\n if (units[at].readerId === readerId) return [...units]\n return units.map((unit, index) =>\n index === at ? { ...unit, readerId, hostId, registeredAtMs: now } : unit,\n )\n}\n\n/**\n * A reader was just registered to a store: the in-person order that sold it\n * by this serial moves on. Attached to this workspace, or pending (then\n * attached to it now); an order attached to another workspace is left as it\n * is. Returns the orders it changed.\n */\nexport async function matchRegisteredPosHardwareReader(input: {\n hostId: string\n orgId: string\n uid: string\n readerId: string\n serialNumber: string\n now?: number\n}): Promise<{ matched: string[] }> {\n const serial = normalizePosHardwareSerial(input.serialNumber)\n if (!serial || !input.orgId) return { matched: [] }\n const found = await firestore()\n .collectionGroup(POS_HARDWARE_ORDERS_COLLECTION)\n .where('serialNumbers', 'array-contains', serial)\n .limit(5)\n .get()\n const matched: string[] = []\n for (const doc of found.docs as unknown as Array<{ id: string; data: () => PosHardwareOrder }>) {\n const orderId = String(doc.id)\n const now = input.now ?? Date.now()\n const changed = await firestore().runTransaction(async (transaction: any) => {\n const saleRef = posHardwareSaleRef(orderId)\n const sale = await transaction.get(saleRef)\n const fromOrgId = String(sale.get('orgId') ?? doc.data().orgId ?? '')\n const fromRef = hardwareOrdersRef(fromOrgId).doc(orderId)\n const from = await transaction.get(fromRef)\n if (!from.exists) return false\n const before = from.data() as PosHardwareOrder\n if (before.status === 'canceled' || before.status === 'refunded') return false\n // Only a sale of the platform's own store can be nobody's yet; any\n // other order is its workspace's (AGL-4038), set up before it shipped.\n const pending = isPosHardwareSellerStoreSale(before) && before.attachment?.state !== 'attached'\n if (!pending && fromOrgId !== input.orgId) return false\n const units = withRegisteredUnit(before.units ?? [], serial, input.readerId, input.hostId, now)\n if (!units) return false\n const done = everyReaderRegistered(units)\n const after: PosHardwareOrder = {\n ...before,\n ...(pending\n ? {\n orgId: input.orgId,\n hostId: input.hostId,\n createdBy: input.uid,\n attachment: {\n ...posHardwareAttachmentOf({\n uid: input.uid,\n orgId: input.orgId,\n hostId: input.hostId,\n email: before.attachment?.email ?? null,\n attachedBy: '',\n attachedAtMs: now,\n // What the register typed of the buyer stays (AGL-4038).\n name: before.attachment?.name ?? null,\n address: before.attachment?.address ?? null,\n }),\n },\n }\n : { hostId: before.hostId || input.hostId }),\n units,\n ...(done && before.status === 'delivered' ? { status: 'registered' as const, registeredAtMs: now } : {}),\n updatedAtMs: now,\n }\n if (after.orgId === fromOrgId) {\n transaction.set(fromRef, after)\n } else {\n transaction.create(hardwareOrdersRef(after.orgId).doc(orderId), after)\n transaction.delete(fromRef)\n }\n transaction.set(saleRef, posHardwareSaleRecord(orderId, after), posHardwareSaleSetOptions(after))\n return true\n })\n if (changed) matched.push(orderId)\n }\n // The buyer's address for the reseller's records, from the store the\n // reader is now on, where the sale has none yet.\n for (const orderId of matched) await fillPosHardwareBuyerAddress({ orgId: input.orgId, orderId })\n return { matched }\n}\n\n/**\n * The serial numbers of a sale's readers, taken at the sale: on the hardware\n * order once it is recorded, or on the register sale until it is (the\n * recorder takes them from there). Each is normalized, none may repeat, and\n * none may already be on another sale.\n */\nexport async function recordPosHardwareSerials(input: {\n config: PosHardwareInPersonConfig\n registerOrderId?: string | null\n orderId?: string | null\n serials: unknown\n}): Promise<{ orderId: string; serials: string[]; recorded: boolean }> {\n const serials = (Array.isArray(input.serials) ? input.serials : [])\n .map(normalizePosHardwareSerial)\n .filter(Boolean)\n if (new Set(serials).size !== serials.length) {\n throw new PosHardwareReaderRefusal('A serial number is listed twice.', 400)\n }\n const registerOrderId = String(input.registerOrderId ?? '')\n const orderId = registerOrderId\n ? posHardwareInPersonOrderId(input.config.sellerHostId, registerOrderId)\n : String(input.orderId ?? '')\n if (!POS_HARDWARE_ORDER_ID.test(orderId)) throw new PosHardwareReaderRefusal('Name the sale.', 400)\n for (const serial of serials) {\n const elsewhere = await firestore()\n .collectionGroup(POS_HARDWARE_ORDERS_COLLECTION)\n .where('serialNumbers', 'array-contains', serial)\n .limit(2)\n .get()\n if (elsewhere.docs.some((doc: any) => String(doc.id) !== orderId)) {\n throw new PosHardwareReaderRefusal(`Serial number ${serial} is already on another sale.`, 409)\n }\n }\n const saleRef = posHardwareSaleRef(orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const sale = await transaction.get(saleRef)\n if (!sale.exists) {\n if (!registerOrderId) throw new PosHardwareReaderRefusal('No such card reader sale.', 404)\n const registerRef = firestore()\n .collection('hosts')\n .doc(input.config.sellerHostId)\n .collection('orders')\n .doc(registerOrderId)\n const register = await transaction.get(registerRef)\n const status = String(register.get('status') ?? '')\n if (!register.exists || (status !== 'pending' && status !== 'paid')) {\n throw new PosHardwareReaderRefusal('No open or paid sale on this register by that number.', 404)\n }\n transaction.set(registerRef, { hardwareSerials: serials }, { merge: true })\n return { orderId, serials, recorded: false }\n }\n const ref = hardwareOrdersRef(String(sale.get('orgId') ?? '')).doc(orderId)\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such card reader sale.', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (!isPosHardwareSellerStoreSale(before) || before.posSale?.hostId !== input.config.sellerHostId) {\n throw new PosHardwareReaderRefusal('Only a card reader sold by this store takes serial numbers here.', 409)\n }\n const next = withPosHardwareSerials(before.units ?? [], serials)\n transaction.update(ref, {\n units: next,\n serialNumbers: next.flatMap((unit) => (unit.serialNumber ? [unit.serialNumber] : [])),\n updatedAtMs: Date.now(),\n })\n return { orderId, serials, recorded: true }\n })\n}\n\n/**\n * The units with `serials` filling the readers not yet set up, in order; a\n * registered reader keeps its own. Refuses more serials than readers.\n */\nfunction withPosHardwareSerials(units: readonly PosHardwareUnit[], serials: readonly string[]): PosHardwareUnit[] {\n if (serials.length > units.length) {\n throw new PosHardwareReaderRefusal(`This order has ${units.length} reader${units.length === 1 ? '' : 's'}.`, 400)\n }\n const open = units.map((unit, index) => ({ unit, index })).filter(({ unit }) => !unit.readerId)\n const next = [...units]\n open.forEach(({ index }, position) => {\n next[index] = { ...units[index], serialNumber: serials[position] ?? null }\n })\n return next\n}\n\n/** Serial numbers as given: normalized, each once, none already on another order. */\nasync function checkedSerials(raw: unknown, orderId: string): Promise<string[]> {\n const serials = (Array.isArray(raw) ? raw : []).map(normalizePosHardwareSerial).filter(Boolean)\n if (new Set(serials).size !== serials.length) {\n throw new PosHardwareReaderRefusal('A serial number is listed twice.', 400)\n }\n for (const serial of serials) {\n const elsewhere = await firestore()\n .collectionGroup(POS_HARDWARE_ORDERS_COLLECTION)\n .where('serialNumbers', 'array-contains', serial)\n .limit(2)\n .get()\n if (elsewhere.docs.some((doc: any) => String(doc.id) !== orderId)) {\n throw new PosHardwareReaderRefusal(`Serial number ${serial} is already on another order.`, 409)\n }\n }\n return serials\n}\n\n/*==========================================\n * SETTING AN ORDER UP BEFORE IT SHIPS (AGL-4038).\n *\n * The platform buys the readers in, receives them, sets them up and ships\n * them to the buyer. Setting one up, on the staff Hardware orders page, is:\n *\n * - its serial number recorded on the order\n * ({@link recordPosHardwareOrderSerials}), so the reader is matched to\n * the order the moment the buyer pairs it on their store, and an order\n * nobody is attached to yet joins the workspace that pairs it;\n * - and, where the buyer's store can already take a reader (its plan\n * includes the point of sale), the reader registered to that store by\n * the code it shows ({@link registerPosHardwareOrderReader}), the same\n * registration the booth and the POS devices card make.\n *\n * Both only while the order is still with the platform (paid, ordered or\n * received), and shipping waits until every reader has its serial\n * (`posHardwareReadyToShip`).\n *=========================================*/\n\n/** The statuses an order is still with the platform in, and can be set up. */\nconst BEFORE_SHIPPING = new Set(['paid', 'ordered', 'received'])\n\n/** Records the serial numbers of an order's readers, from the staff page. */\nexport async function recordPosHardwareOrderSerials(input: {\n orgId: string\n orderId: string\n serials: unknown\n}): Promise<PosHardwareOrder> {\n if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReaderRefusal('No such order.', 404)\n const serials = await checkedSerials(input.serials, input.orderId)\n const ref = hardwareOrdersRef(input.orgId).doc(input.orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (!BEFORE_SHIPPING.has(before.status)) {\n throw new PosHardwareReaderRefusal('Serial numbers are recorded before the order ships.', 409)\n }\n const units = withPosHardwareSerials(posHardwareOrderUnits(before), serials)\n const after: PosHardwareOrder = {\n ...before,\n units,\n serialNumbers: units.flatMap((unit) => (unit.serialNumber ? [unit.serialNumber] : [])),\n updatedAtMs: Date.now(),\n }\n transaction.set(ref, after)\n transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, after), posHardwareSaleSetOptions(after))\n return after\n })\n}\n\n/**\n * Registers one of an order's readers to the buyer's store by the code it\n * shows, from the staff page, before it ships. The order must name the\n * buyer's store (an order from our own store is attached first, from the\n * register's To attach list), and the store's plan must include the point of\n * sale; a store with no reader Location yet is refused with\n * `needs-address`, since only the buyer can say where it is, and the reader\n * is then set up when they pair it.\n */\nexport async function registerPosHardwareOrderReader(input: {\n orgId: string\n orderId: string\n registrationCode: unknown\n label?: unknown\n uid: string\n}): Promise<{ order: PosHardwareOrder; readerId: string }> {\n if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReaderRefusal('No such order.', 404)\n const snapshot = await hardwareOrdersRef(input.orgId).doc(input.orderId).get()\n const order = snapshot.data() as PosHardwareOrder | undefined\n if (!order) throw new PosHardwareReaderRefusal('No such order.', 404)\n if (!BEFORE_SHIPPING.has(order.status)) {\n throw new PosHardwareReaderRefusal('A reader is registered here before the order ships.', 409)\n }\n if (isPosHardwareSellerStoreSale(order) && order.attachment?.state !== 'attached') {\n throw new PosHardwareReaderRefusal(\n 'Attach the order to the buyer’s workspace first, from To attach on our store’s register, or ship it and the reader joins their store when they pair it.',\n 409,\n )\n }\n if (!order.hostId) throw new PosHardwareReaderRefusal('The buyer has not chosen a store for it yet.', 409)\n if (!posHardwareOrderUnits(order).some((unit) => !unit.readerId)) {\n throw new PosHardwareReaderRefusal('Every reader on this order is registered.', 409)\n }\n return registerReaderOnOrder({\n orgId: input.orgId,\n orderId: input.orderId,\n hostId: order.hostId,\n registrationCode: input.registrationCode,\n label: input.label,\n uid: input.uid,\n storeAddress: null,\n })\n}\n\n/**\n * The registration itself, for the booth and the staff page: the store's\n * plan and Location checked, the reader registered, and the order's first\n * reader not yet set up (or the one with its serial) marked registered.\n */\nasync function registerReaderOnOrder(input: {\n orgId: string\n orderId: string\n hostId: string\n registrationCode: unknown\n label?: unknown\n uid: string\n storeAddress: PosTerminalAddress | null\n}): Promise<{ order: PosHardwareOrder; readerId: string }> {\n const { orgId, hostId } = input\n const readiness = await posHardwareStoreReadiness(hostId)\n if (!readiness.posPlan) {\n throw new PosHardwareReaderRefusal(\n 'Their workspace needs a plan with the point of sale before a reader can be added. They can add it, then set the reader up themselves.',\n 409,\n )\n }\n if (!readiness.hasLocation && !input.storeAddress) {\n throw new PosHardwareReaderRefusal(\n 'Their store has no address for card readers yet. Enter the store’s address to register the reader now, or they add it when they set the reader up on the POS devices card.',\n 409,\n 'needs-address',\n )\n }\n const { registerPosTerminalReader } = await import('./pos-readers')\n const registered = await registerPosTerminalReader({\n hostId,\n orgId,\n uid: input.uid,\n registrationCode: input.registrationCode,\n label: input.label,\n ...(input.storeAddress ? { address: input.storeAddress } : {}),\n })\n if ('error' in registered) throw new PosHardwareReaderRefusal(registered.error, registered.status)\n // A reader with a serial matched its unit as it registered. One without\n // (or not on the order) takes the first reader of the order not set up yet.\n const ref = hardwareOrdersRef(orgId).doc(input.orderId)\n const after = await firestore().runTransaction(async (transaction: any) => {\n const now = (await transaction.get(ref)).data() as PosHardwareOrder\n const units = posHardwareOrderUnits(now)\n if (units.some((unit) => unit.readerId === registered.id)) return now\n const at = units.findIndex((unit) => !unit.readerId && posHardwareSku(unit.sku)?.kind === 'reader')\n if (at < 0) return now\n const stamp = Date.now()\n const next = units.map((unit, index) =>\n index === at\n ? {\n ...unit,\n serialNumber:\n unit.serialNumber ??\n (registered.reader.serialNumber ? normalizePosHardwareSerial(registered.reader.serialNumber) : null),\n readerId: registered.id,\n hostId,\n registeredAtMs: stamp,\n }\n : unit,\n )\n const done = everyReaderRegistered(next)\n const updated: PosHardwareOrder = {\n ...now,\n units: next,\n serialNumbers: next.flatMap((unit) => (unit.serialNumber ? [unit.serialNumber] : [])),\n ...(done && now.status === 'delivered' ? { status: 'registered' as const, registeredAtMs: stamp } : {}),\n updatedAtMs: stamp,\n }\n transaction.set(ref, updated)\n transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, updated), posHardwareSaleSetOptions(updated))\n return updated\n })\n await fillPosHardwareBuyerAddress({ orgId, orderId: input.orderId })\n return { order: after, readerId: registered.id }\n}\n\n/** An in-person order of this workspace, for a change by its own people. */\nfunction workspaceOrder(orgId: string, orderId: string) {\n if (!POS_HARDWARE_ORDER_ID.test(orderId)) throw new PosHardwareReaderRefusal('No such order.', 404)\n return { ref: hardwareOrdersRef(orgId).doc(orderId) }\n}\n\n/**\n * The store a reader bought in person is for, chosen at setup by someone\n * who may set up devices there. The store must be the workspace's.\n */\nexport async function choosePosHardwareStore(input: {\n orgId: string\n orderId: string\n hostId: string\n}): Promise<PosHardwareOrder> {\n const { ref } = workspaceOrder(input.orgId, input.orderId)\n const chosen: PosHardwareOrder = await firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (!isPosHardwareSellerStoreSale(before)) throw new PosHardwareReaderRefusal('Only a reader bought from our store waits for a store.', 409)\n const after: PosHardwareOrder = {\n ...before,\n hostId: input.hostId,\n ...(before.attachment ? { attachment: { ...before.attachment, hostId: input.hostId } } : {}),\n updatedAtMs: Date.now(),\n }\n transaction.set(ref, after)\n transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, after), posHardwareSaleSetOptions(after))\n return after\n })\n await fillPosHardwareBuyerAddress({ orgId: input.orgId, orderId: input.orderId })\n return chosen\n}\n\n/**\n * \"Mark set up\": a reader bought in person was paired by its code or by\n * Bluetooth with no serial taken at the sale, so nothing matched it. The\n * workspace says so, and the order moves to Set up.\n */\nexport async function markPosHardwareSetUp(input: { orgId: string; orderId: string }): Promise<PosHardwareOrder> {\n const { ref } = workspaceOrder(input.orgId, input.orderId)\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new PosHardwareReaderRefusal('No such order.', 404)\n const before = snapshot.data() as PosHardwareOrder\n if (!isPosHardwareSellerStoreSale(before)) throw new PosHardwareReaderRefusal('Only a reader bought from our store is marked set up here.', 409)\n if (before.status === 'registered') return before\n if (before.status !== 'delivered') throw new PosHardwareReaderRefusal('This order can no longer be set up.', 409)\n const now = Date.now()\n const after: PosHardwareOrder = { ...before, status: 'registered', registeredAtMs: now, updatedAtMs: now }\n transaction.set(ref, after)\n transaction.set(posHardwareSaleRef(input.orderId), posHardwareSaleRecord(input.orderId, after), posHardwareSaleSetOptions(after))\n return after\n })\n}\n\n/** A store's readiness for a reader: its plan and its Location. */\nexport async function posHardwareStoreReadiness(hostId: string): Promise<{ posPlan: boolean; hasLocation: boolean }> {\n const [owner, config] = await Promise.all([\n getOrgForHost(hostId).catch(() => null),\n firestore().collection('hosts').doc(hostId).collection('terminal').doc('config').get(),\n ])\n return {\n posPlan: Aglyn.checkEntitlement(owner?.org as never, 'pos'),\n hasLocation: Boolean(config.exists && config.get('stripeLocationId')),\n }\n}\n\n/**\n * Registers a reader sold at the booth to the buyer's chosen store, by the\n * code it shows, while the buyer is there (AGL-4038). The sale must be\n * attached to them with a store chosen, and the store's plan must include\n * the point of sale.\n *\n * A store with no reader Location yet needs its address, which is where\n * Stripe sets the reader up for. Booth staff may type it with the buyer\n * (`address`): it goes exactly where the store's POS devices card would put\n * it, through the same registration, which creates the store's Location from\n * it and records it on the store's terminal settings. Without one the booth\n * refuses with `needs-address`, and the buyer can add it later on that card.\n * A store that already has its Location keeps it: an address sent for it is\n * never used.\n */\nexport async function registerPosHardwareAtBooth(input: {\n config: PosHardwareInPersonConfig\n orderId: string\n registrationCode: unknown\n label?: unknown\n address?: unknown\n uid: string\n}): Promise<{ order: PosHardwareOrder; readerId: string; storeAddress: PosTerminalAddress | null }> {\n if (!POS_HARDWARE_ORDER_ID.test(input.orderId)) throw new PosHardwareReaderRefusal('Name the sale.', 400)\n const sale = await posHardwareSaleRef(input.orderId).get()\n if (!sale.exists) {\n throw new PosHardwareReaderRefusal('Take payment for the sale first, then register its reader.', 409)\n }\n const orgId = String(sale.get('orgId') ?? '')\n const snapshot = await hardwareOrdersRef(orgId).doc(input.orderId).get()\n const order = snapshot.data() as PosHardwareOrder | undefined\n if (!order || !isPosHardwareSellerStoreSale(order) || order.posSale?.hostId !== input.config.sellerHostId) {\n throw new PosHardwareReaderRefusal('No such card reader sale.', 404)\n }\n if (order.attachment?.state !== 'attached' || !order.attachment.orgId) {\n throw new PosHardwareReaderRefusal('Attach the sale to the buyer first.', 409)\n }\n const hostId = order.hostId\n if (!hostId) throw new PosHardwareReaderRefusal('Choose the buyer’s store first.', 409)\n const readiness = await posHardwareStoreReadiness(hostId)\n // The store's address, only for a store with no Location: one that has\n // its Location keeps it, whatever was sent.\n const storeAddress = readiness.hasLocation ? null : boothStoreAddress(input.address)\n if (storeAddress) {\n const problem = (await import('./pos-terminal')).posTerminalAddressProblem(storeAddress)\n if (problem) throw new PosHardwareReaderRefusal(problem, 400, 'needs-address')\n }\n const { order: after, readerId } = await registerReaderOnOrder({\n orgId,\n orderId: input.orderId,\n hostId,\n registrationCode: input.registrationCode,\n label: input.label,\n uid: input.uid,\n storeAddress,\n })\n return { order: after, readerId, storeAddress }\n}\n"],"names":["Aglyn","firebaseAdmin","getOrgForHost","isPosHardwareSellerStoreSale","normalizePosHardwareSerial","POS_HARDWARE_ORDER_ID","POS_HARDWARE_ORDERS_COLLECTION","posHardwareSaleRecord","posHardwareSaleSetOptions","posHardwareOrderUnits","posHardwareSku","posHardwareAttachmentOf","fillPosHardwareBuyerAddress","hardwareOrdersRef","posHardwareInPersonOrderId","posHardwareSaleRef","PosHardwareReaderRefusal","Error","message","status","reason","boothStoreAddress","raw","Array","isArray","field","key","max","String","trim","slice","line2","state","line1","city","postalCode","country","toUpperCase","firestore","app","everyReaderRegistered","units","length","every","unit","Boolean","readerId","withRegisteredUnit","serial","hostId","now","at","findIndex","serialNumber","map","index","registeredAtMs","matchRegisteredPosHardwareReader","input","orgId","matched","found","collectionGroup","where","limit","get","doc","docs","orderId","id","Date","changed","runTransaction","transaction","sale","before","saleRef","fromOrgId","data","fromRef","from","exists","pending","attachment","done","after","createdBy","uid","email","attachedBy","attachedAtMs","name","address","updatedAtMs","set","create","delete","push","recordPosHardwareSerials","serials","filter","Set","size","registerOrderId","config","sellerHostId","test","elsewhere","some","register","registerRef","collection","hardwareSerials","merge","recorded","ref","snapshot","posSale","next","withPosHardwareSerials","update","serialNumbers","flatMap","open","forEach","position","checkedSerials","BEFORE_SHIPPING","recordPosHardwareOrderSerials","has","registerPosHardwareOrderReader","order","registerReaderOnOrder","registrationCode","label","storeAddress","readiness","posHardwareStoreReadiness","posPlan","hasLocation","registerPosTerminalReader","registered","error","sku","kind","stamp","reader","updated","workspaceOrder","choosePosHardwareStore","chosen","markPosHardwareSetUp","owner","Promise","all","catch","checkEntitlement","org","registerPosHardwareAtBooth","problem","posTerminalAddressProblem"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAC5C,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SACEC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,qBAAqB,EACrBC,8BAA8B,EAC9BC,qBAAqB,EACrBC,yBAAyB,EACzBC,qBAAqB,EACrBC,cAAc,QAIT,2BAAuB;AAC9B,SAASC,uBAAuB,QAAQ,qCAAiC;AACzE,SAASC,2BAA2B,QAAQ,iCAA6B;AACzE,SAASC,iBAAiB,EAAEC,0BAA0B,EAAEC,kBAAkB,QAAQ,oBAAgB;AAGlG;;;;;;;;;;;;;;;;;;;2CAmB2C,GAE3C,OAAO,MAAMC,iCAAiCC;IAC5C,YACEC,OAAe,EACf,AAASC,MAAc,EACvB,yGAAyG,GACzG,AAASC,MAAwB,CACjC;QACA,KAAK,CAACF,eAJGC,SAAAA,aAEAC,SAAAA;IAGX;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASC,kBAAkBC,GAAY;IAC5C,IAAI,CAACA,OAAO,OAAOA,QAAQ,YAAYC,MAAMC,OAAO,CAACF,MAAM,OAAO;IAClE,MAAMG,QAAQ,CAACC,KAAaC;YACnB;eAAPC,QAAO,WAAA,AAACN,GAA+B,CAACI,IAAI,YAArC,WAAyC,IAC7CG,IAAI,GACJC,KAAK,CAAC,GAAGH;;IACd,MAAM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EAAE;QACzG,MAAM,IAAIzF,yBAAyB,6BAA6B;IAClE;IACA,IAAImH,EAAAA,oBAAAA,MAAMhD,UAAU,qBAAhBgD,kBAAkBnG,KAAK,MAAK,cAAc,CAACmG,MAAMhD,UAAU,CAACxB,KAAK,EAAE;QACrE,MAAM,IAAI3C,yBAAyB,uCAAuC;IAC5E;IACA,MAAMiC,SAASkF,MAAMlF,MAAM;IAC3B,IAAI,CAACA,QAAQ,MAAM,IAAIjC,yBAAyB,mCAAmC;IACnF,MAAMwH,YAAY,MAAMC,0BAA0BxF;IAClD,uEAAuE;IACvE,4CAA4C;IAC5C,MAAMsF,eAAeC,UAAUG,WAAW,GAAG,OAAOtH,kBAAkBqC,MAAMkC,OAAO;IACnF,IAAI2C,cAAc;QAChB,MAAMwB,UAAU,AAAC,CAAA,MAAM,MAAM,CAAC,oBAAgB,EAAGC,yBAAyB,CAACzB;QAC3E,IAAIwB,SAAS,MAAM,IAAI/I,yBAAyB+I,SAAS,KAAK;IAChE;IACA,MAAM,EAAE5B,OAAO9C,KAAK,EAAEvC,QAAQ,EAAE,GAAG,MAAMsF,sBAAsB;QAC7DzE;QACAS,SAASV,MAAMU,OAAO;QACtBnB;QACAoF,kBAAkB3E,MAAM2E,gBAAgB;QACxCC,OAAO5E,MAAM4E,KAAK;QAClB/C,KAAK7B,MAAM6B,GAAG;QACdgD;IACF;IACA,OAAO;QAAEJ,OAAO9C;QAAOvC;QAAUyF;IAAa;AAChD"}
|
|
@@ -40,15 +40,20 @@ export declare function recordRegisterHardwareReturn(input: {
|
|
|
40
40
|
now?: number;
|
|
41
41
|
}): Promise<PosHardwareOrder | null>;
|
|
42
42
|
/**
|
|
43
|
-
* Refunds what is left of an
|
|
44
|
-
* through the
|
|
45
|
-
*
|
|
43
|
+
* Refunds what is left of an order sold by the platform's own store from the
|
|
44
|
+
* staff page (way 2), through the store order's own card refund: an
|
|
45
|
+
* in-person sale's register sale, or an online order's Checkout payment
|
|
46
|
+
* (AGL-4038), both destination charges into the store's account. Refused
|
|
47
|
+
* for a sale paid by anything Stripe cannot refund, which goes back at the
|
|
48
|
+
* register instead. `amountCents` refunds less than what is left: a return
|
|
49
|
+
* of an online order keeps the original shipping and any restocking fee.
|
|
46
50
|
*/
|
|
47
51
|
export declare function refundInPersonPosHardwareOrder(input: {
|
|
48
52
|
config: PosHardwareInPersonConfig | null;
|
|
49
53
|
orgId: string;
|
|
50
54
|
orderId: string;
|
|
51
55
|
actorUid: string;
|
|
56
|
+
amountCents?: number;
|
|
52
57
|
now?: number;
|
|
53
58
|
}): Promise<{
|
|
54
59
|
before: PosHardwareOrder;
|