@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.
Files changed (152) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/account-subscriptions.d.ts +51 -0
  3. package/src/lib/components/account-subscriptions.js +168 -0
  4. package/src/lib/components/account-subscriptions.js.map +1 -0
  5. package/src/lib/components/account.js +12 -48
  6. package/src/lib/components/account.js.map +1 -1
  7. package/src/lib/components/cart.js +30 -6
  8. package/src/lib/components/cart.js.map +1 -1
  9. package/src/lib/components/commerce-console-page.js +6 -0
  10. package/src/lib/components/commerce-console-page.js.map +1 -1
  11. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  12. package/src/lib/components/commerce-console-sections.js +5 -0
  13. package/src/lib/components/commerce-console-sections.js.map +1 -1
  14. package/src/lib/components/console/paid-media.d.ts +1 -0
  15. package/src/lib/components/console/paid-media.js +15 -4
  16. package/src/lib/components/console/paid-media.js.map +1 -1
  17. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  18. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  19. package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
  20. package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
  21. package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
  22. package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
  23. package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
  24. package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
  25. package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
  26. package/src/lib/components/console/pos-cellular-control.component.js +5 -5
  27. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  28. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  29. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  30. package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
  31. package/src/lib/components/console/pos-hardware-card.component.js +77 -8
  32. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
  33. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
  34. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
  35. package/src/lib/components/console/pos-page.component.js +19 -2
  36. package/src/lib/components/console/pos-page.component.js.map +1 -1
  37. package/src/lib/components/console/product-editor-dialog.component.js +21 -2
  38. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  39. package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
  40. package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
  41. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
  42. package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
  43. package/src/lib/components/console/subscriptions-card.component.js +280 -0
  44. package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
  45. package/src/lib/components/hardware-terms-consent.d.ts +22 -0
  46. package/src/lib/components/hardware-terms-consent.js +85 -0
  47. package/src/lib/components/hardware-terms-consent.js.map +1 -0
  48. package/src/lib/components/product-detail.js +25 -5
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/constants/operator-alerts.d.ts +1 -1
  51. package/src/lib/constants/operator-alerts.js +4 -4
  52. package/src/lib/constants/operator-alerts.js.map +1 -1
  53. package/src/lib/model/commerce-orders.d.ts +6 -2
  54. package/src/lib/model/commerce-orders.js.map +1 -1
  55. package/src/lib/model/commerce-payment-methods.d.ts +24 -0
  56. package/src/lib/model/commerce-payment-methods.js +35 -0
  57. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  58. package/src/lib/model/commerce.d.ts +6 -0
  59. package/src/lib/model/commerce.js.map +1 -1
  60. package/src/lib/model/index.d.ts +1 -0
  61. package/src/lib/model/index.js +1 -0
  62. package/src/lib/model/index.js.map +1 -1
  63. package/src/lib/model/paid-media.d.ts +8 -0
  64. package/src/lib/model/paid-media.js +13 -0
  65. package/src/lib/model/paid-media.js.map +1 -1
  66. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  67. package/src/lib/model/pos-hardware-in-person.js +52 -20
  68. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  69. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  70. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  71. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  72. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  73. package/src/lib/model/pos-hardware-terms.js +68 -3
  74. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  75. package/src/lib/model/pos-hardware.d.ts +101 -15
  76. package/src/lib/model/pos-hardware.js +128 -18
  77. package/src/lib/model/pos-hardware.js.map +1 -1
  78. package/src/lib/model/pos-reader-splash.js +2 -2
  79. package/src/lib/model/pos-reader-splash.js.map +1 -1
  80. package/src/lib/model/product-write.d.ts +3 -0
  81. package/src/lib/model/subscription-view.d.ts +90 -0
  82. package/src/lib/model/subscription-view.js +176 -0
  83. package/src/lib/model/subscription-view.js.map +1 -0
  84. package/src/lib/server/billing-webhook.d.ts +4 -6
  85. package/src/lib/server/billing-webhook.js +109 -51
  86. package/src/lib/server/billing-webhook.js.map +1 -1
  87. package/src/lib/server/cart-checkout.js +45 -10
  88. package/src/lib/server/cart-checkout.js.map +1 -1
  89. package/src/lib/server/cart.js +15 -3
  90. package/src/lib/server/cart.js.map +1 -1
  91. package/src/lib/server/checkout.js +58 -16
  92. package/src/lib/server/checkout.js.map +1 -1
  93. package/src/lib/server/draft-order.js +7 -3
  94. package/src/lib/server/draft-order.js.map +1 -1
  95. package/src/lib/server/membership-account.d.ts +22 -0
  96. package/src/lib/server/membership-account.js +52 -8
  97. package/src/lib/server/membership-account.js.map +1 -1
  98. package/src/lib/server/pos-auth.d.ts +3 -3
  99. package/src/lib/server/pos-auth.js +3 -3
  100. package/src/lib/server/pos-auth.js.map +1 -1
  101. package/src/lib/server/pos-cellular-billing.js +1 -1
  102. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  103. package/src/lib/server/pos-cellular-notify.js +1 -1
  104. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  105. package/src/lib/server/pos-cellular.js +1 -1
  106. package/src/lib/server/pos-cellular.js.map +1 -1
  107. package/src/lib/server/pos-hardware-admin.js +86 -13
  108. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  109. package/src/lib/server/pos-hardware-attach.js +5 -5
  110. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  111. package/src/lib/server/pos-hardware-cancel.js +65 -0
  112. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  113. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  114. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  115. package/src/lib/server/pos-hardware-closure.js +5 -8
  116. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  117. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  118. package/src/lib/server/pos-hardware-in-person.js +72 -17
  119. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  120. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  121. package/src/lib/server/pos-hardware-notify.js +30 -5
  122. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  123. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  124. package/src/lib/server/pos-hardware-readers.js +206 -85
  125. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  126. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  127. package/src/lib/server/pos-hardware-returns.js +39 -7
  128. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  129. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  130. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  131. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  132. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  133. package/src/lib/server/pos-hardware-sale.js +1 -0
  134. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  135. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  136. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  137. package/src/lib/server/pos-hardware-webhook.js +16 -3
  138. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  139. package/src/lib/server/pos-hardware.d.ts +14 -3
  140. package/src/lib/server/pos-hardware.js +83 -18
  141. package/src/lib/server/pos-hardware.js.map +1 -1
  142. package/src/lib/server/pos-ops-routes.js +2 -10
  143. package/src/lib/server/pos-ops-routes.js.map +1 -1
  144. package/src/lib/server/quote-pay.js +8 -4
  145. package/src/lib/server/quote-pay.js.map +1 -1
  146. package/src/lib/server/stream.d.ts +2 -0
  147. package/src/lib/server/stream.js +22 -2
  148. package/src/lib/server/stream.js.map +1 -1
  149. package/src/lib/server/tax-return-source.js +5 -1
  150. package/src/lib/server/tax-return-source.js.map +1 -1
  151. package/src/lib/server.js +2 -2
  152. package/src/lib/server.js.map +1 -1
@@ -15,10 +15,12 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import { createHash } from "crypto";
18
+ import { readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
18
19
  import * as Aglyn from "@aglyn/aglyn/server";
19
20
  import { firebaseAdmin, readOrgBilling } from "@aglyn/tenant-data-admin";
20
21
  import { hostConsoleUrl } from "@aglyn/tenant-data-admin/server/host-console-link";
21
- import { encodePosHardwareLines, isPosHardwareShippingMethod, POS_HARDWARE_ANCHOR, parsePosHardwareConfig, parsePosHardwareInPersonConfig, POS_HARDWARE_CURRENCY, POS_HARDWARE_METADATA_TYPE, POS_HARDWARE_ORDERS_COLLECTION, POS_HARDWARE_SALES_COLLECTION, POS_HARDWARE_SHIP_COUNTRIES, POS_HARDWARE_SHIPPING_LABELS, posHardwareOffers, posHardwareOrderSource, posHardwareSku, pricePosHardwareCart } from "../model/pos-hardware.js";
22
+ import { isPosHardwareSellerStoreSale, encodePosHardwareLines, isPosHardwareShippingMethod, POS_HARDWARE_ANCHOR, parsePosHardwareConfig, parsePosHardwareInPersonConfig, POS_HARDWARE_CURRENCY, POS_HARDWARE_METADATA_TYPE, POS_HARDWARE_ORDERS_COLLECTION, POS_HARDWARE_SALES_COLLECTION, POS_HARDWARE_SHIP_COUNTRIES, POS_HARDWARE_SHIPPING_LABELS, POS_HARDWARE_SKUS, POS_HARDWARE_TAX_CODE, posHardwareOffers, posHardwareOrderSource, posHardwareSku, pricePosHardwareCart } from "../model/pos-hardware.js";
23
+ import { POS_HARDWARE_TERMS_REQUIRED, posHardwareTermsConfirmed, posHardwareTermsMetadata } from "../model/pos-hardware-terms.js";
22
24
  import { mayVisitPosHardwareShop } from "../model/plugin-permissions.js";
23
25
  import { authorizePosStaff, posIdempotencyKey, posRequestBody } from "./pos-auth.js";
24
26
  import { posStripe, posTerminalAvailable } from "./pos-stripe.js";
@@ -30,8 +32,9 @@ import { posStripe, posTerminalAvailable } from "./pos-stripe.js";
30
32
  * checkout a Stripe Checkout Session for the basket, on the PLATFORM
31
33
  * orders this site's hardware orders, newest first
32
34
  *
33
- * Gated like the register (`authorizePosStaff`, on a plan with POS), because
34
- * the readers it sells are the register's, with one difference (AGL-4047):
35
+ * Gated like the register (`authorizePosStaff`) but on ANY plan (AGL-4038):
36
+ * a workspace buys its readers first and adds the point of sale when it sets
37
+ * them up. The readers it sells are the register's, with one difference (AGL-4047):
35
38
  * the shop admits whoever works the register (`managePos`) AND whoever may
36
39
  * buy hardware (`posBuyHardware`), which stands on its own — a bookkeeper
37
40
  * with no register orders the store's readers. A checkout needs
@@ -56,6 +59,38 @@ import { posStripe, posTerminalAvailable } from "./pos-stripe.js";
56
59
  */ export function posHardwareInPersonConfig(env = process.env) {
57
60
  return parsePosHardwareInPersonConfig(env);
58
61
  }
62
+ /**
63
+ * The price each hardware item is listed at in the platform's own store
64
+ * (AGL-4038), in cents: an active product there whose `hardwareSku` names
65
+ * the item, at its first variant's price. Where two products name one item,
66
+ * the lower price, so no page the store shows quotes less than the shop
67
+ * charges. Empty while no seller store is configured. A failed read throws:
68
+ * the shop does not quote a price it cannot check against the store's.
69
+ */ export async function posHardwareListedCents(inPerson = posHardwareInPersonConfig()) {
70
+ if (!inPerson) return {};
71
+ const snapshot = await firebaseAdmin.app().firestore().collection('hosts').doc(inPerson.sellerHostId).collection('products').where('hardwareSku', 'in', POS_HARDWARE_SKUS.map((sku)=>sku.id)).get();
72
+ const listed = {};
73
+ for (const doc of snapshot.docs){
74
+ var _product_hardwareSku, _product_status, _listed_sku_id;
75
+ var _variants_;
76
+ const product = doc.data();
77
+ const sku = posHardwareSku(String((_product_hardwareSku = product['hardwareSku']) != null ? _product_hardwareSku : ''));
78
+ if (!sku || ((_product_status = product['status']) != null ? _product_status : 'active') !== 'active') continue;
79
+ const variants = Array.isArray(product['variants']) ? product['variants'] : [];
80
+ const priceUsd = Number(variants.length ? (_variants_ = variants[0]) == null ? void 0 : _variants_.priceUsd : product['priceUsd']);
81
+ if (!Number.isFinite(priceUsd) || priceUsd <= 0) continue;
82
+ const cents = Math.round(priceUsd * 100);
83
+ listed[sku.id] = Math.min((_listed_sku_id = listed[sku.id]) != null ? _listed_sku_id : cents, cents);
84
+ }
85
+ return listed;
86
+ }
87
+ /** The shop's config with the platform's own store's listed prices, or `null` while it is hidden. */ export async function posHardwarePricedConfig() {
88
+ const config = posHardwareConfig();
89
+ if (!config) return null;
90
+ return _extends({}, config, {
91
+ listedCents: await posHardwareListedCents()
92
+ });
93
+ }
59
94
  /** Whether a store, owned by `orgId`, is the platform's own hardware seller. */ export function isPosHardwareSellerStore(config, hostId, orgId) {
60
95
  return Boolean(config) && (config == null ? void 0 : config.sellerHostId) === hostId && (config == null ? void 0 : config.sellerOrgId) === orgId;
61
96
  }
@@ -167,7 +202,8 @@ export function hardwareOrdersRef(orgId) {
167
202
  orders: orders.docs.map((doc)=>({
168
203
  id: String(doc.id),
169
204
  order: doc.data()
170
- })).filter(({ order })=>order.source === 'in_person').sort((a, b)=>Number(b.order.hostId === hostId) - Number(a.order.hostId === hostId)).map(({ id, order })=>{
205
+ }))// Bought from the platform's own store, at an event or online (AGL-4038).
206
+ .filter(({ order })=>isPosHardwareSellerStoreSale(order)).sort((a, b)=>Number(b.order.hostId === hostId) - Number(a.order.hostId === hostId)).map(({ id, order })=>{
171
207
  var _order_units;
172
208
  return _extends({}, merchantHardwareOrderView(id, order), {
173
209
  hostId: order.hostId,
@@ -176,6 +212,11 @@ export function hardwareOrdersRef(orgId) {
176
212
  })
177
213
  };
178
214
  }
215
+ const LISTED_READ_FAILED = Symbol('listed-read-failed');
216
+ function listedReadFailed(error) {
217
+ console.error('[pos-hardware] the store\'s listed prices could not be read', error);
218
+ return LISTED_READ_FAILED;
219
+ }
179
220
  export const posHardwareHandler = async (req, res)=>{
180
221
  var _body_hostId, _body_action;
181
222
  if (req.method !== 'POST') return res.status(405).json({
@@ -190,21 +231,28 @@ export const posHardwareHandler = async (req, res)=>{
190
231
  // `managePos` until a role or the member sets it, and may be granted
191
232
  // without it — starts a checkout that the workspace pays for.
192
233
  //
193
- // A READER BOUGHT IN PERSON (AGL-4038): `waiting` is read without the
194
- // point of sale plan, because a workspace without it is exactly the one
195
- // that must be told to add it first; choosing its store and marking it set
196
- // up are setting up devices (`posDevices`) on the store named.
234
+ // ANYONE CAN BUY (AGL-4038): browsing, checking out, the orders, a return
235
+ // request and the readers waiting to be set up are open whatever the
236
+ // workspace's plan. A reader takes payments at the register, which comes
237
+ // with the point of sale, so the card, a delivered order and the register
238
+ // prompt to add it; the key above still decides who may buy. Setting a
239
+ // reader up — choosing its store, marking it set up — is setting up
240
+ // devices (`posDevices`) on the store named, and asks the plan.
197
241
  const settingUp = action === 'choose-store' || action === 'mark-set-up';
198
- const gate = await authorizePosStaff(req, hostId, action === 'checkout' ? 'posBuyHardware' : settingUp ? 'posDevices' : undefined, mayVisitPosHardwareShop, // A workspace whose plan lost the point of sale still sees what it bought
199
- // and may ask to return a reader bought in person.
200
- action === 'waiting' || action === 'orders' || action === 'request-return' ? {
201
- planRequired: false
202
- } : {});
242
+ const gate = await authorizePosStaff(req, hostId, action === 'checkout' ? 'posBuyHardware' : settingUp ? 'posDevices' : undefined, mayVisitPosHardwareShop, {
243
+ planRequired: settingUp
244
+ });
203
245
  if ('error' in gate) return res.status(gate.status).json({
204
246
  error: gate.error
205
247
  });
206
248
  const staff = gate.staff;
207
- const config = posHardwareConfig();
249
+ // Priced by the store's listed prices only where a price is quoted or charged.
250
+ const config = action === 'catalog' || action === 'checkout' ? await posHardwarePricedConfig().catch(listedReadFailed) : posHardwareConfig();
251
+ if (config === LISTED_READ_FAILED) {
252
+ return res.status(503).json({
253
+ error: 'The hardware shop could not check its prices. Try again in a moment.'
254
+ });
255
+ }
208
256
  try {
209
257
  switch(action){
210
258
  case 'waiting':
@@ -296,8 +344,8 @@ export const posHardwareHandler = async (req, res)=>{
296
344
  }
297
345
  case 'checkout':
298
346
  {
299
- var _billing_stripeCustomerId, _ref;
300
- var _created_body;
347
+ var _readClientIp, _ref, _billing_stripeCustomerId, _ref1;
348
+ var _req_headers, _created_body;
301
349
  if (!config) return res.status(404).json({
302
350
  error: 'The hardware shop is not available.'
303
351
  });
@@ -317,6 +365,17 @@ export const posHardwareHandler = async (req, res)=>{
317
365
  if (!shipping) return res.status(400).json({
318
366
  error: 'Choose a shipping speed.'
319
367
  });
368
+ // The terms of sale and business use, both ticked (AGL-4038).
369
+ if (!posHardwareTermsConfirmed(body['hardwareTerms'])) {
370
+ return res.status(400).json({
371
+ error: POS_HARDWARE_TERMS_REQUIRED,
372
+ needsHardwareTerms: true
373
+ });
374
+ }
375
+ const terms = posHardwareTermsMetadata({
376
+ ip: (_readClientIp = readClientIp(req.headers)) != null ? _readClientIp : null,
377
+ userAgent: String((_ref = (_req_headers = req.headers) == null ? void 0 : _req_headers['user-agent']) != null ? _ref : '') || null
378
+ });
320
379
  const orderId = posHardwareOrderId(staff.orgId, staff.hostId, attemptKey);
321
380
  const billing = await readOrgBilling(staff.orgId).catch(()=>({}));
322
381
  const customer = String((_billing_stripeCustomerId = billing.stripeCustomerId) != null ? _billing_stripeCustomerId : '').trim();
@@ -341,7 +400,11 @@ export const posHardwareHandler = async (req, res)=>{
341
400
  'metadata[lines]': encodePosHardwareLines(priced.lines),
342
401
  'metadata[shippingMethod]': shipping.method,
343
402
  'metadata[shippingCents]': shipping.cents,
344
- 'metadata[subtotalCents]': priced.subtotalCents,
403
+ 'metadata[subtotalCents]': priced.subtotalCents
404
+ }, Object.fromEntries(Object.entries(terms).map(([key, value])=>[
405
+ `metadata[${key}]`,
406
+ value
407
+ ])), {
345
408
  'payment_intent_data[description]': `Card reader order ${posHardwareOrderNumber(orderId)}`,
346
409
  'payment_intent_data[metadata][type]': POS_HARDWARE_METADATA_TYPE,
347
410
  'payment_intent_data[metadata][orderId]': orderId,
@@ -364,13 +427,15 @@ export const posHardwareHandler = async (req, res)=>{
364
427
  params[`line_items[${index}][price_data][product_data][name]`] = line.name;
365
428
  if (sku) params[`line_items[${index}][price_data][product_data][description]`] = sku.use;
366
429
  params[`line_items[${index}][price_data][product_data][metadata][sku]`] = line.sku;
430
+ // Taxed as the physical good it is, never as the account's default (software).
431
+ params[`line_items[${index}][price_data][product_data][tax_code]`] = POS_HARDWARE_TAX_CODE;
367
432
  if (config.automaticTax) params[`line_items[${index}][price_data][tax_behavior]`] = 'exclusive';
368
433
  });
369
434
  const created = await posStripe('POST', 'checkout/sessions', {
370
435
  params,
371
436
  idempotencyKey: `pos-hw-checkout-${orderId}`
372
437
  });
373
- const url = String((_ref = (_created_body = created.body) == null ? void 0 : _created_body.url) != null ? _ref : '');
438
+ const url = String((_ref1 = (_created_body = created.body) == null ? void 0 : _created_body.url) != null ? _ref1 : '');
374
439
  if (!created.ok || !url) {
375
440
  var _created_body_error, _created_body1;
376
441
  console.error('[pos-hardware] checkout refused', created.status, (_created_body1 = created.body) == null ? void 0 : (_created_body_error = _created_body1.error) == null ? void 0 : _created_body_error.code);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware.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 { createHash } from 'crypto'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport { hostConsoleUrl } from '@aglyn/tenant-data-admin/server/host-console-link'\nimport {\n encodePosHardwareLines,\n isPosHardwareShippingMethod,\n POS_HARDWARE_ANCHOR,\n parsePosHardwareConfig,\n parsePosHardwareInPersonConfig,\n POS_HARDWARE_CURRENCY,\n POS_HARDWARE_METADATA_TYPE,\n POS_HARDWARE_ORDERS_COLLECTION,\n POS_HARDWARE_SALES_COLLECTION,\n POS_HARDWARE_SHIP_COUNTRIES,\n POS_HARDWARE_SHIPPING_LABELS,\n posHardwareOffers,\n posHardwareOrderSource,\n posHardwareSku,\n pricePosHardwareCart,\n type PosHardwareConfig,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n} from '../model/pos-hardware'\nimport { mayVisitPosHardwareShop } from '../model/plugin-permissions'\nimport { authorizePosStaff, posIdempotencyKey, posRequestBody } from './pos-auth'\nimport { posStripe, posTerminalAvailable } from './pos-stripe'\n\n/*==========================================\n * `POST /api/commerce/pos-hardware` (AGL-4038): the merchant's half of the\n * POS hardware shop, behind the Hardware card on Products → Point of sale.\n *\n * catalog what is on offer and at what price, or `available: false`\n * checkout a Stripe Checkout Session for the basket, on the PLATFORM\n * orders this site's hardware orders, newest first\n *\n * Gated like the register (`authorizePosStaff`, on a plan with POS), because\n * the readers it sells are the register's, with one difference (AGL-4047):\n * the shop admits whoever works the register (`managePos`) AND whoever may\n * buy hardware (`posBuyHardware`), which stands on its own — a bookkeeper\n * with no register orders the store's readers. A checkout needs\n * `posBuyHardware`; seeing the catalog and the site's orders needs either.\n *\n * THE SALE IS THE PLATFORM'S. The session is created with the platform key\n * and NO connected account, `transfer_data` or application fee: the merchant\n * is the buyer here, and the platform is the seller of record that places\n * the order with Stripe. The order document is written by the webhook once\n * Stripe says the session is paid (`pos-hardware-webhook.ts`), never here.\n *=========================================*/\n\n/** The shop's config from this deployment, or `null` while it is hidden. */\nexport function posHardwareConfig(\n env: Record<string, string | undefined> = process.env,\n): PosHardwareConfig | null {\n // A reader the platform cannot yet take payments on is not for sale: the\n // shop opens only where the register offers card readers at all.\n if (!posTerminalAvailable()) return null\n return parsePosHardwareConfig(env)\n}\n\n/**\n * The platform's own store that sells hardware in person (AGL-4038), or\n * `null` while that is off. Read like the shop's other figures; a store is\n * the seller only when BOTH its id and its workspace's match, so a site moved\n * to another workspace stops selling hardware rather than selling it for them.\n */\nexport function posHardwareInPersonConfig(\n env: Record<string, string | undefined> = process.env,\n): PosHardwareInPersonConfig | null {\n return parsePosHardwareInPersonConfig(env)\n}\n\n/** Whether a store, owned by `orgId`, is the platform's own hardware seller. */\nexport function isPosHardwareSellerStore(\n config: PosHardwareInPersonConfig | null,\n hostId: string,\n orgId: string,\n): config is PosHardwareInPersonConfig {\n return Boolean(config) && config?.sellerHostId === hostId && config?.sellerOrgId === orgId\n}\n\n/**\n * An in-person order's id, from the register sale it came from: one register\n * sale is one hardware order however often its completion is told.\n */\nexport function posHardwareInPersonOrderId(hostId: string, registerOrderId: string): string {\n return `hw_${createHash('sha256').update(`pos:${hostId}:${registerOrderId}`).digest('hex').slice(0, 20)}`\n}\n\n/** The order's id, derived from the attempt so a repeated press is one order. */\nexport function posHardwareOrderId(orgId: string, hostId: string, attemptKey: string): string {\n return `hw_${createHash('sha256').update(`${orgId}:${hostId}:${attemptKey}`).digest('hex').slice(0, 20)}`\n}\n\n/** The number a person reads: `HW-` and six characters of the id. */\nexport function posHardwareOrderNumber(orderId: string): string {\n return `HW-${orderId.replace(/^hw_/, '').slice(0, 6).toUpperCase()}`\n}\n\nexport function hardwareOrdersRef(orgId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection(POS_HARDWARE_ORDERS_COLLECTION)\n}\n\n/**\n * `posHardwareSales/{orderId}`, the retained sale record beside each order\n * (see `PosHardwareSaleRecord`). Top-level on purpose: the workspace erasure\n * cannot reach it.\n */\nexport function posHardwareSaleRef(orderId: string) {\n return firebaseAdmin.app().firestore().collection(POS_HARDWARE_SALES_COLLECTION).doc(orderId)\n}\n\n/** An order as the merchant's card shows it: no Stripe ids, no staff notes. */\nexport function merchantHardwareOrderView(id: string, order: PosHardwareOrder) {\n return {\n id,\n number: posHardwareOrderNumber(id),\n status: order.status,\n lines: (order.lines ?? []).map((line) => ({\n sku: line.sku,\n name: line.name,\n quantity: line.quantity,\n unitCents: line.unitCents,\n lineCents: line.lineCents,\n })),\n subtotalCents: order.subtotalCents ?? 0,\n shippingCents: order.shipping?.cents ?? 0,\n shippingLabel: order.shipping?.label ?? '',\n taxCents: order.taxCents ?? 0,\n totalCents: order.totalCents ?? 0,\n tracking: order.tracking ?? null,\n createdAtMs: order.createdAtMs ?? 0,\n updatedAtMs: order.updatedAtMs ?? order.createdAtMs ?? 0,\n // Bought in person (AGL-4038): handed over at the sale, no parcel.\n source: posHardwareOrderSource(order),\n discountCents: order.discountCents ?? 0,\n /** Readers still to set up, for an in-person order that took serials. */\n readersToSetUp: (order.units ?? []).filter((unit) => !unit.readerId).length,\n refundedCents: order.refundedCents ?? 0,\n /** The buyer's return request and what was decided, without who asked. */\n returnRequest: order.returnRequest\n ? { state: order.returnRequest.state, requestedAtMs: order.returnRequest.requestedAtMs, note: order.returnRequest.note }\n : null,\n }\n}\n\nexport type MerchantHardwareOrderView = ReturnType<typeof merchantHardwareOrderView>\n\n/** The POS settings page of a site, as an absolute console URL. */\nexport async function posSettingsUrl(hostId: string): Promise<string> {\n return hostConsoleUrl(hostId, `/${hostId}/products/pos`)\n}\n\n/** `base` with `query` added before any `#fragment`, then `#hash`. */\nexport function withQueryAndHash(base: string, query: string, hash: string): string {\n const [path] = base.split('#')\n const joiner = path.includes('?') ? '&' : '?'\n return `${path}${joiner}${query}#${hash}`\n}\n\n\n/**\n * The readers this workspace bought in person that are not set up yet\n * (AGL-4038): whether its plan includes the point of sale, its stores and\n * whether each can take a reader, and each order with what it waits for.\n * Nothing at all while the in-person sale is off.\n */\nexport async function waitingInPersonReaders(orgId: string, hostId: string) {\n if (!posHardwareInPersonConfig() || !orgId) return { posPlan: false, stores: [], orders: [] }\n const firestore = firebaseAdmin.app().firestore()\n const [orders, org, hosts] = await Promise.all([\n hardwareOrdersRef(orgId)\n .where('attachment.state', '==', 'attached')\n .where('status', '==', 'delivered')\n .limit(20)\n .get(),\n firestore.collection('orgs').doc(orgId).get(),\n firestore.collection('hosts').where('orgId', '==', orgId).limit(20).get(),\n ])\n if (!orders.docs.length) return { posPlan: false, stores: [], orders: [] }\n const stores = await Promise.all(\n hosts.docs.map(async (doc: any) => {\n const id = String(doc.id)\n const [terminal, setupUrl] = await Promise.all([\n firestore.collection('hosts').doc(id).collection('terminal').doc('config').get(),\n posSettingsUrl(id),\n ])\n return {\n hostId: id,\n name: String(doc.get('name') ?? doc.get('title') ?? id),\n hasLocation: Boolean(terminal.exists && terminal.get('stripeLocationId')),\n setupUrl: `${setupUrl.split('#')[0]}#pos-devices`,\n }\n }),\n )\n return {\n posPlan: Aglyn.checkEntitlement(org.data() as never, 'pos'),\n stores,\n // Every store's, this store's first: a reader waits wherever the\n // workspace's people look.\n orders: orders.docs\n .map((doc: any) => ({ id: String(doc.id), order: doc.data() as PosHardwareOrder }))\n .filter(({ order }) => order.source === 'in_person')\n .sort((a, b) => Number(b.order.hostId === hostId) - Number(a.order.hostId === hostId))\n .map(({ id, order }) => ({\n ...merchantHardwareOrderView(id, order),\n hostId: order.hostId,\n serialsTaken: (order.units ?? []).filter((unit) => unit.serialNumber && !unit.readerId).length,\n })),\n }\n}\n\nexport const posHardwareHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = posRequestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const action = String(body['action'] ?? '')\n // BUYING IS ITS OWN KEY (AGL-4047): anyone who works the register or may\n // buy hardware sees what the shop offers and what this site ordered, and\n // only a member holding \"Buy point of sale hardware\" — which follows\n // `managePos` until a role or the member sets it, and may be granted\n // without it — starts a checkout that the workspace pays for.\n //\n // A READER BOUGHT IN PERSON (AGL-4038): `waiting` is read without the\n // point of sale plan, because a workspace without it is exactly the one\n // that must be told to add it first; choosing its store and marking it set\n // up are setting up devices (`posDevices`) on the store named.\n const settingUp = action === 'choose-store' || action === 'mark-set-up'\n const gate = await authorizePosStaff(\n req,\n hostId,\n action === 'checkout' ? 'posBuyHardware' : settingUp ? 'posDevices' : undefined,\n mayVisitPosHardwareShop,\n // A workspace whose plan lost the point of sale still sees what it bought\n // and may ask to return a reader bought in person.\n action === 'waiting' || action === 'orders' || action === 'request-return' ? { planRequired: false } : {},\n )\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n const staff = gate.staff\n const config = posHardwareConfig()\n try {\n switch (action) {\n case 'waiting':\n return res.status(200).json(await waitingInPersonReaders(staff.orgId, staff.hostId))\n case 'request-return': {\n const returns = await import('./pos-hardware-returns')\n const orderId = String(body['orderId'] ?? '')\n try {\n const order = await returns.requestPosHardwareReturn({\n orgId: staff.orgId,\n orderId,\n uid: staff.uid,\n reason: body['reason'],\n })\n return res.status(200).json({ ok: true, order: merchantHardwareOrderView(orderId, order) })\n } catch (error) {\n if (error instanceof returns.PosHardwareReturnRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'choose-store':\n case 'mark-set-up': {\n const readers = await import('./pos-hardware-readers')\n const orderId = String(body['orderId'] ?? '')\n try {\n const order =\n action === 'choose-store'\n ? await readers.choosePosHardwareStore({ orgId: staff.orgId, orderId, hostId: staff.hostId })\n : await readers.markPosHardwareSetUp({ orgId: staff.orgId, orderId })\n return res.status(200).json({ ok: true, order: merchantHardwareOrderView(orderId, order) })\n } catch (error) {\n if (error instanceof readers.PosHardwareReaderRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'catalog':\n if (!config) return res.status(200).json({ available: false })\n return res.status(200).json({\n available: true,\n offers: posHardwareOffers(config),\n shipping: config.shipping.map((option) => ({\n method: option.method,\n label: POS_HARDWARE_SHIPPING_LABELS[option.method],\n cents: option.cents,\n })),\n automaticTax: config.automaticTax,\n shipCountries: POS_HARDWARE_SHIP_COUNTRIES,\n })\n case 'orders': {\n // This site's orders, and the readers bought in person for the\n // workspace that wait for a store to be chosen at setup (AGL-4038).\n // A sale on the selling workspace's own To attach list is never one.\n const [site, workspace] = await Promise.all([\n hardwareOrdersRef(staff.orgId).where('hostId', '==', staff.hostId).orderBy('createdAtMs', 'desc').limit(50).get(),\n hardwareOrdersRef(staff.orgId)\n .where('hostId', '==', '')\n .where('attachment.state', '==', 'attached')\n .orderBy('createdAtMs', 'desc')\n .limit(50)\n .get(),\n ])\n const orders = [...site.docs, ...workspace.docs]\n .map((doc: any) => merchantHardwareOrderView(String(doc.id), doc.data() as PosHardwareOrder))\n .sort((a, b) => b.createdAtMs - a.createdAtMs)\n .slice(0, 50)\n return res.status(200).json({ orders })\n }\n case 'checkout': {\n if (!config) return res.status(404).json({ error: 'The hardware shop is not available.' })\n const attemptKey = posIdempotencyKey(req)\n if (!attemptKey) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n if (!staff.orgId) return res.status(409).json({ error: 'This site has no workspace.' })\n const priced = pricePosHardwareCart(config, body['lines'])\n if ('error' in priced) return res.status(400).json({ error: priced.error })\n const method = body['shippingMethod']\n const shipping = isPosHardwareShippingMethod(method)\n ? config.shipping.find((option) => option.method === method)\n : undefined\n if (!shipping) return res.status(400).json({ error: 'Choose a shipping speed.' })\n\n const orderId = posHardwareOrderId(staff.orgId, staff.hostId, attemptKey)\n const billing = await readOrgBilling(staff.orgId).catch(() => ({}))\n const customer = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '').trim()\n const base = await posSettingsUrl(staff.hostId)\n const params: Record<string, string | number | boolean> = {\n mode: 'payment',\n client_reference_id: orderId,\n success_url: withQueryAndHash(base, 'hardwareOrder=placed', POS_HARDWARE_ANCHOR),\n cancel_url: withQueryAndHash(base, 'hardwareOrder=canceled', POS_HARDWARE_ANCHOR),\n 'payment_method_types[0]': 'card',\n 'shipping_address_collection[allowed_countries][0]': POS_HARDWARE_SHIP_COUNTRIES[0],\n 'phone_number_collection[enabled]': true,\n 'shipping_options[0][shipping_rate_data][type]': 'fixed_amount',\n 'shipping_options[0][shipping_rate_data][display_name]': POS_HARDWARE_SHIPPING_LABELS[shipping.method],\n 'shipping_options[0][shipping_rate_data][fixed_amount][amount]': shipping.cents,\n 'shipping_options[0][shipping_rate_data][fixed_amount][currency]': POS_HARDWARE_CURRENCY,\n 'metadata[type]': POS_HARDWARE_METADATA_TYPE,\n 'metadata[orderId]': orderId,\n 'metadata[orgId]': staff.orgId,\n 'metadata[hostId]': staff.hostId,\n 'metadata[uid]': staff.uid,\n 'metadata[lines]': encodePosHardwareLines(priced.lines),\n 'metadata[shippingMethod]': shipping.method,\n 'metadata[shippingCents]': shipping.cents,\n 'metadata[subtotalCents]': priced.subtotalCents,\n 'payment_intent_data[description]': `Card reader order ${posHardwareOrderNumber(orderId)}`,\n 'payment_intent_data[metadata][type]': POS_HARDWARE_METADATA_TYPE,\n 'payment_intent_data[metadata][orderId]': orderId,\n 'payment_intent_data[metadata][orgId]': staff.orgId,\n ...(customer ? { customer } : {}),\n ...(config.automaticTax\n ? {\n 'automatic_tax[enabled]': true,\n 'shipping_options[0][shipping_rate_data][tax_behavior]': 'exclusive',\n // A returning workspace's saved address is kept up to date\n // from what Checkout collects, which automatic tax requires.\n ...(customer ? { 'customer_update[shipping]': 'auto' } : {}),\n }\n : {}),\n }\n priced.lines.forEach((line, index) => {\n const sku = posHardwareSku(line.sku)\n params[`line_items[${index}][quantity]`] = line.quantity\n // A literal, not POS_HARDWARE_CURRENCY: check:facilitator-charge-shape\n // reads Stripe Tax beside a usd line item only when it says so (AGL-1956).\n params[`line_items[${index}][price_data][currency]`] = 'usd'\n params[`line_items[${index}][price_data][unit_amount]`] = line.unitCents\n params[`line_items[${index}][price_data][product_data][name]`] = line.name\n if (sku) params[`line_items[${index}][price_data][product_data][description]`] = sku.use\n params[`line_items[${index}][price_data][product_data][metadata][sku]`] = line.sku\n if (config.automaticTax) params[`line_items[${index}][price_data][tax_behavior]`] = 'exclusive'\n })\n const created = await posStripe('POST', 'checkout/sessions', {\n params,\n idempotencyKey: `pos-hw-checkout-${orderId}`,\n })\n const url = String(created.body?.url ?? '')\n if (!created.ok || !url) {\n console.error('[pos-hardware] checkout refused', created.status, created.body?.error?.code)\n return res.status(502).json({ error: 'Checkout could not be started. Try again in a moment.' })\n }\n return res.status(200).json({ url, orderId })\n }\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[pos-hardware]', action, error)\n return res.status(500).json({ error: 'The hardware shop could not answer' })\n }\n}\n"],"names":["createHash","Aglyn","firebaseAdmin","readOrgBilling","hostConsoleUrl","encodePosHardwareLines","isPosHardwareShippingMethod","POS_HARDWARE_ANCHOR","parsePosHardwareConfig","parsePosHardwareInPersonConfig","POS_HARDWARE_CURRENCY","POS_HARDWARE_METADATA_TYPE","POS_HARDWARE_ORDERS_COLLECTION","POS_HARDWARE_SALES_COLLECTION","POS_HARDWARE_SHIP_COUNTRIES","POS_HARDWARE_SHIPPING_LABELS","posHardwareOffers","posHardwareOrderSource","posHardwareSku","pricePosHardwareCart","mayVisitPosHardwareShop","authorizePosStaff","posIdempotencyKey","posRequestBody","posStripe","posTerminalAvailable","posHardwareConfig","env","process","posHardwareInPersonConfig","isPosHardwareSellerStore","config","hostId","orgId","Boolean","sellerHostId","sellerOrgId","posHardwareInPersonOrderId","registerOrderId","update","digest","slice","posHardwareOrderId","attemptKey","posHardwareOrderNumber","orderId","replace","toUpperCase","hardwareOrdersRef","app","firestore","collection","doc","posHardwareSaleRef","merchantHardwareOrderView","id","order","number","status","lines","map","line","sku","name","quantity","unitCents","lineCents","subtotalCents","shippingCents","shipping","cents","shippingLabel","label","taxCents","totalCents","tracking","createdAtMs","updatedAtMs","source","discountCents","readersToSetUp","units","filter","unit","readerId","length","refundedCents","returnRequest","state","requestedAtMs","note","posSettingsUrl","withQueryAndHash","base","query","hash","path","split","joiner","includes","waitingInPersonReaders","posPlan","stores","orders","org","hosts","Promise","all","where","limit","get","docs","String","terminal","setupUrl","hasLocation","exists","checkEntitlement","data","sort","a","b","Number","serialsTaken","serialNumber","posHardwareHandler","req","res","body","method","json","error","action","settingUp","gate","undefined","planRequired","staff","returns","requestPosHardwareReturn","uid","reason","ok","PosHardwareReturnRefusal","message","readers","choosePosHardwareStore","markPosHardwareSetUp","PosHardwareReaderRefusal","available","offers","option","automaticTax","shipCountries","site","workspace","orderBy","created","priced","find","billing","catch","customer","stripeCustomerId","trim","params","mode","client_reference_id","success_url","cancel_url","forEach","index","use","idempotencyKey","url","console","code"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,YAAYC,WAAW,sBAAqB;AAE5C,SAASC,aAAa,EAAEC,cAAc,QAAQ,2BAA0B;AACxE,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SACEC,sBAAsB,EACtBC,2BAA2B,EAC3BC,mBAAmB,EACnBC,sBAAsB,EACtBC,8BAA8B,EAC9BC,qBAAqB,EACrBC,0BAA0B,EAC1BC,8BAA8B,EAC9BC,6BAA6B,EAC7BC,2BAA2B,EAC3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Z6B,cAAciB,GAAG,mBAAI;oBACxC,IAAI,CAACjB,QAAQf,EAAE,IAAI,CAACgC,KAAK;4BAC0CjB,qBAAAA;wBAAjEkB,QAAQ5C,KAAK,CAAC,mCAAmC0B,QAAQnG,MAAM,GAAEmG,iBAAAA,QAAQ7B,IAAI,sBAAZ6B,sBAAAA,eAAc1B,KAAK,qBAAnB0B,oBAAqBmB,IAAI;wBAC1F,OAAOjD,IAAIrE,MAAM,CAAC,KAAKwE,IAAI,CAAC;4BAAEC,OAAO;wBAAwD;oBAC/F;oBACA,OAAOJ,IAAIrE,MAAM,CAAC,KAAKwE,IAAI,CAAC;wBAAE4C;wBAAKjI;oBAAQ;gBAC7C;YACA;gBACE,OAAOkF,IAAIrE,MAAM,CAAC,KAAKwE,IAAI,CAAC;oBAAEC,OAAO;gBAAiB;QAC1D;IACF,EAAE,OAAOA,OAAO;QACd4C,QAAQ5C,KAAK,CAAC,kBAAkBC,QAAQD;QACxC,OAAOJ,IAAIrE,MAAM,CAAC,KAAKwE,IAAI,CAAC;YAAEC,OAAO;QAAqC;IAC5E;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-hardware.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 { createHash } from 'crypto'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport { hostConsoleUrl } from '@aglyn/tenant-data-admin/server/host-console-link'\nimport {\n isPosHardwareSellerStoreSale,\n encodePosHardwareLines,\n isPosHardwareShippingMethod,\n POS_HARDWARE_ANCHOR,\n parsePosHardwareConfig,\n parsePosHardwareInPersonConfig,\n POS_HARDWARE_CURRENCY,\n POS_HARDWARE_METADATA_TYPE,\n POS_HARDWARE_ORDERS_COLLECTION,\n POS_HARDWARE_SALES_COLLECTION,\n POS_HARDWARE_SHIP_COUNTRIES,\n POS_HARDWARE_SHIPPING_LABELS,\n POS_HARDWARE_SKUS,\n POS_HARDWARE_TAX_CODE,\n posHardwareOffers,\n posHardwareOrderSource,\n posHardwareSku,\n pricePosHardwareCart,\n type PosHardwareConfig,\n type PosHardwareInPersonConfig,\n type PosHardwareOrder,\n type PosHardwareSkuId,\n} from '../model/pos-hardware'\nimport {\n POS_HARDWARE_TERMS_REQUIRED,\n posHardwareTermsConfirmed,\n posHardwareTermsMetadata,\n} from '../model/pos-hardware-terms'\nimport { mayVisitPosHardwareShop } from '../model/plugin-permissions'\nimport { authorizePosStaff, posIdempotencyKey, posRequestBody } from './pos-auth'\nimport { posStripe, posTerminalAvailable } from './pos-stripe'\n\n/*==========================================\n * `POST /api/commerce/pos-hardware` (AGL-4038): the merchant's half of the\n * POS hardware shop, behind the Hardware card on Products → Point of sale.\n *\n * catalog what is on offer and at what price, or `available: false`\n * checkout a Stripe Checkout Session for the basket, on the PLATFORM\n * orders this site's hardware orders, newest first\n *\n * Gated like the register (`authorizePosStaff`) but on ANY plan (AGL-4038):\n * a workspace buys its readers first and adds the point of sale when it sets\n * them up. The readers it sells are the register's, with one difference (AGL-4047):\n * the shop admits whoever works the register (`managePos`) AND whoever may\n * buy hardware (`posBuyHardware`), which stands on its own — a bookkeeper\n * with no register orders the store's readers. A checkout needs\n * `posBuyHardware`; seeing the catalog and the site's orders needs either.\n *\n * THE SALE IS THE PLATFORM'S. The session is created with the platform key\n * and NO connected account, `transfer_data` or application fee: the merchant\n * is the buyer here, and the platform is the seller of record that places\n * the order with Stripe. The order document is written by the webhook once\n * Stripe says the session is paid (`pos-hardware-webhook.ts`), never here.\n *=========================================*/\n\n/** The shop's config from this deployment, or `null` while it is hidden. */\nexport function posHardwareConfig(\n env: Record<string, string | undefined> = process.env,\n): PosHardwareConfig | null {\n // A reader the platform cannot yet take payments on is not for sale: the\n // shop opens only where the register offers card readers at all.\n if (!posTerminalAvailable()) return null\n return parsePosHardwareConfig(env)\n}\n\n/**\n * The platform's own store that sells hardware in person (AGL-4038), or\n * `null` while that is off. Read like the shop's other figures; a store is\n * the seller only when BOTH its id and its workspace's match, so a site moved\n * to another workspace stops selling hardware rather than selling it for them.\n */\nexport function posHardwareInPersonConfig(\n env: Record<string, string | undefined> = process.env,\n): PosHardwareInPersonConfig | null {\n return parsePosHardwareInPersonConfig(env)\n}\n\n/**\n * The price each hardware item is listed at in the platform's own store\n * (AGL-4038), in cents: an active product there whose `hardwareSku` names\n * the item, at its first variant's price. Where two products name one item,\n * the lower price, so no page the store shows quotes less than the shop\n * charges. Empty while no seller store is configured. A failed read throws:\n * the shop does not quote a price it cannot check against the store's.\n */\nexport async function posHardwareListedCents(\n inPerson: PosHardwareInPersonConfig | null = posHardwareInPersonConfig(),\n): Promise<Partial<Record<PosHardwareSkuId, number>>> {\n if (!inPerson) return {}\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(inPerson.sellerHostId)\n .collection('products')\n .where(\n 'hardwareSku',\n 'in',\n POS_HARDWARE_SKUS.map((sku) => sku.id),\n )\n .get()\n const listed: Partial<Record<PosHardwareSkuId, number>> = {}\n for (const doc of snapshot.docs as Array<{ data: () => Record<string, unknown> }>) {\n const product = doc.data()\n const sku = posHardwareSku(String(product['hardwareSku'] ?? ''))\n if (!sku || (product['status'] ?? 'active') !== 'active') continue\n const variants = Array.isArray(product['variants']) ? (product['variants'] as Array<{ priceUsd?: unknown }>) : []\n const priceUsd = Number(variants.length ? variants[0]?.priceUsd : product['priceUsd'])\n if (!Number.isFinite(priceUsd) || priceUsd <= 0) continue\n const cents = Math.round(priceUsd * 100)\n listed[sku.id] = Math.min(listed[sku.id] ?? cents, cents)\n }\n return listed\n}\n\n/** The shop's config with the platform's own store's listed prices, or `null` while it is hidden. */\nexport async function posHardwarePricedConfig(): Promise<PosHardwareConfig | null> {\n const config = posHardwareConfig()\n if (!config) return null\n return { ...config, listedCents: await posHardwareListedCents() }\n}\n\n/** Whether a store, owned by `orgId`, is the platform's own hardware seller. */\nexport function isPosHardwareSellerStore(\n config: PosHardwareInPersonConfig | null,\n hostId: string,\n orgId: string,\n): config is PosHardwareInPersonConfig {\n return Boolean(config) && config?.sellerHostId === hostId && config?.sellerOrgId === orgId\n}\n\n/**\n * An in-person order's id, from the register sale it came from: one register\n * sale is one hardware order however often its completion is told.\n */\nexport function posHardwareInPersonOrderId(hostId: string, registerOrderId: string): string {\n return `hw_${createHash('sha256').update(`pos:${hostId}:${registerOrderId}`).digest('hex').slice(0, 20)}`\n}\n\n/** The order's id, derived from the attempt so a repeated press is one order. */\nexport function posHardwareOrderId(orgId: string, hostId: string, attemptKey: string): string {\n return `hw_${createHash('sha256').update(`${orgId}:${hostId}:${attemptKey}`).digest('hex').slice(0, 20)}`\n}\n\n/** The number a person reads: `HW-` and six characters of the id. */\nexport function posHardwareOrderNumber(orderId: string): string {\n return `HW-${orderId.replace(/^hw_/, '').slice(0, 6).toUpperCase()}`\n}\n\nexport function hardwareOrdersRef(orgId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .collection(POS_HARDWARE_ORDERS_COLLECTION)\n}\n\n/**\n * `posHardwareSales/{orderId}`, the retained sale record beside each order\n * (see `PosHardwareSaleRecord`). Top-level on purpose: the workspace erasure\n * cannot reach it.\n */\nexport function posHardwareSaleRef(orderId: string) {\n return firebaseAdmin.app().firestore().collection(POS_HARDWARE_SALES_COLLECTION).doc(orderId)\n}\n\n/** An order as the merchant's card shows it: no Stripe ids, no staff notes. */\nexport function merchantHardwareOrderView(id: string, order: PosHardwareOrder) {\n return {\n id,\n number: posHardwareOrderNumber(id),\n status: order.status,\n lines: (order.lines ?? []).map((line) => ({\n sku: line.sku,\n name: line.name,\n quantity: line.quantity,\n unitCents: line.unitCents,\n lineCents: line.lineCents,\n })),\n subtotalCents: order.subtotalCents ?? 0,\n shippingCents: order.shipping?.cents ?? 0,\n shippingLabel: order.shipping?.label ?? '',\n taxCents: order.taxCents ?? 0,\n totalCents: order.totalCents ?? 0,\n tracking: order.tracking ?? null,\n createdAtMs: order.createdAtMs ?? 0,\n updatedAtMs: order.updatedAtMs ?? order.createdAtMs ?? 0,\n // Bought in person (AGL-4038): handed over at the sale, no parcel.\n source: posHardwareOrderSource(order),\n discountCents: order.discountCents ?? 0,\n /** Readers still to set up, for an in-person order that took serials. */\n readersToSetUp: (order.units ?? []).filter((unit) => !unit.readerId).length,\n refundedCents: order.refundedCents ?? 0,\n /** The buyer's return request and what was decided, without who asked. */\n returnRequest: order.returnRequest\n ? { state: order.returnRequest.state, requestedAtMs: order.returnRequest.requestedAtMs, note: order.returnRequest.note }\n : null,\n }\n}\n\nexport type MerchantHardwareOrderView = ReturnType<typeof merchantHardwareOrderView>\n\n/** The POS settings page of a site, as an absolute console URL. */\nexport async function posSettingsUrl(hostId: string): Promise<string> {\n return hostConsoleUrl(hostId, `/${hostId}/products/pos`)\n}\n\n/** `base` with `query` added before any `#fragment`, then `#hash`. */\nexport function withQueryAndHash(base: string, query: string, hash: string): string {\n const [path] = base.split('#')\n const joiner = path.includes('?') ? '&' : '?'\n return `${path}${joiner}${query}#${hash}`\n}\n\n\n/**\n * The readers this workspace bought in person that are not set up yet\n * (AGL-4038): whether its plan includes the point of sale, its stores and\n * whether each can take a reader, and each order with what it waits for.\n * Nothing at all while the in-person sale is off.\n */\nexport async function waitingInPersonReaders(orgId: string, hostId: string) {\n if (!posHardwareInPersonConfig() || !orgId) return { posPlan: false, stores: [], orders: [] }\n const firestore = firebaseAdmin.app().firestore()\n const [orders, org, hosts] = await Promise.all([\n hardwareOrdersRef(orgId)\n .where('attachment.state', '==', 'attached')\n .where('status', '==', 'delivered')\n .limit(20)\n .get(),\n firestore.collection('orgs').doc(orgId).get(),\n firestore.collection('hosts').where('orgId', '==', orgId).limit(20).get(),\n ])\n if (!orders.docs.length) return { posPlan: false, stores: [], orders: [] }\n const stores = await Promise.all(\n hosts.docs.map(async (doc: any) => {\n const id = String(doc.id)\n const [terminal, setupUrl] = await Promise.all([\n firestore.collection('hosts').doc(id).collection('terminal').doc('config').get(),\n posSettingsUrl(id),\n ])\n return {\n hostId: id,\n name: String(doc.get('name') ?? doc.get('title') ?? id),\n hasLocation: Boolean(terminal.exists && terminal.get('stripeLocationId')),\n setupUrl: `${setupUrl.split('#')[0]}#pos-devices`,\n }\n }),\n )\n return {\n posPlan: Aglyn.checkEntitlement(org.data() as never, 'pos'),\n stores,\n // Every store's, this store's first: a reader waits wherever the\n // workspace's people look.\n orders: orders.docs\n .map((doc: any) => ({ id: String(doc.id), order: doc.data() as PosHardwareOrder }))\n // Bought from the platform's own store, at an event or online (AGL-4038).\n .filter(({ order }) => isPosHardwareSellerStoreSale(order))\n .sort((a, b) => Number(b.order.hostId === hostId) - Number(a.order.hostId === hostId))\n .map(({ id, order }) => ({\n ...merchantHardwareOrderView(id, order),\n hostId: order.hostId,\n serialsTaken: (order.units ?? []).filter((unit) => unit.serialNumber && !unit.readerId).length,\n })),\n }\n}\n\nconst LISTED_READ_FAILED = Symbol('listed-read-failed')\n\nfunction listedReadFailed(error: unknown): typeof LISTED_READ_FAILED {\n console.error('[pos-hardware] the store\\'s listed prices could not be read', error)\n return LISTED_READ_FAILED\n}\n\nexport const posHardwareHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = posRequestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const action = String(body['action'] ?? '')\n // BUYING IS ITS OWN KEY (AGL-4047): anyone who works the register or may\n // buy hardware sees what the shop offers and what this site ordered, and\n // only a member holding \"Buy point of sale hardware\" — which follows\n // `managePos` until a role or the member sets it, and may be granted\n // without it — starts a checkout that the workspace pays for.\n //\n // ANYONE CAN BUY (AGL-4038): browsing, checking out, the orders, a return\n // request and the readers waiting to be set up are open whatever the\n // workspace's plan. A reader takes payments at the register, which comes\n // with the point of sale, so the card, a delivered order and the register\n // prompt to add it; the key above still decides who may buy. Setting a\n // reader up — choosing its store, marking it set up — is setting up\n // devices (`posDevices`) on the store named, and asks the plan.\n const settingUp = action === 'choose-store' || action === 'mark-set-up'\n const gate = await authorizePosStaff(\n req,\n hostId,\n action === 'checkout' ? 'posBuyHardware' : settingUp ? 'posDevices' : undefined,\n mayVisitPosHardwareShop,\n { planRequired: settingUp },\n )\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n const staff = gate.staff\n // Priced by the store's listed prices only where a price is quoted or charged.\n const config = action === 'catalog' || action === 'checkout' ? await posHardwarePricedConfig().catch(listedReadFailed) : posHardwareConfig()\n if (config === LISTED_READ_FAILED) {\n return res.status(503).json({ error: 'The hardware shop could not check its prices. Try again in a moment.' })\n }\n try {\n switch (action) {\n case 'waiting':\n return res.status(200).json(await waitingInPersonReaders(staff.orgId, staff.hostId))\n case 'request-return': {\n const returns = await import('./pos-hardware-returns')\n const orderId = String(body['orderId'] ?? '')\n try {\n const order = await returns.requestPosHardwareReturn({\n orgId: staff.orgId,\n orderId,\n uid: staff.uid,\n reason: body['reason'],\n })\n return res.status(200).json({ ok: true, order: merchantHardwareOrderView(orderId, order) })\n } catch (error) {\n if (error instanceof returns.PosHardwareReturnRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'choose-store':\n case 'mark-set-up': {\n const readers = await import('./pos-hardware-readers')\n const orderId = String(body['orderId'] ?? '')\n try {\n const order =\n action === 'choose-store'\n ? await readers.choosePosHardwareStore({ orgId: staff.orgId, orderId, hostId: staff.hostId })\n : await readers.markPosHardwareSetUp({ orgId: staff.orgId, orderId })\n return res.status(200).json({ ok: true, order: merchantHardwareOrderView(orderId, order) })\n } catch (error) {\n if (error instanceof readers.PosHardwareReaderRefusal) {\n return res.status(error.status).json({ error: error.message })\n }\n throw error\n }\n }\n case 'catalog':\n if (!config) return res.status(200).json({ available: false })\n return res.status(200).json({\n available: true,\n offers: posHardwareOffers(config),\n shipping: config.shipping.map((option) => ({\n method: option.method,\n label: POS_HARDWARE_SHIPPING_LABELS[option.method],\n cents: option.cents,\n })),\n automaticTax: config.automaticTax,\n shipCountries: POS_HARDWARE_SHIP_COUNTRIES,\n })\n case 'orders': {\n // This site's orders, and the readers bought in person for the\n // workspace that wait for a store to be chosen at setup (AGL-4038).\n // A sale on the selling workspace's own To attach list is never one.\n const [site, workspace] = await Promise.all([\n hardwareOrdersRef(staff.orgId).where('hostId', '==', staff.hostId).orderBy('createdAtMs', 'desc').limit(50).get(),\n hardwareOrdersRef(staff.orgId)\n .where('hostId', '==', '')\n .where('attachment.state', '==', 'attached')\n .orderBy('createdAtMs', 'desc')\n .limit(50)\n .get(),\n ])\n const orders = [...site.docs, ...workspace.docs]\n .map((doc: any) => merchantHardwareOrderView(String(doc.id), doc.data() as PosHardwareOrder))\n .sort((a, b) => b.createdAtMs - a.createdAtMs)\n .slice(0, 50)\n return res.status(200).json({ orders })\n }\n case 'checkout': {\n if (!config) return res.status(404).json({ error: 'The hardware shop is not available.' })\n const attemptKey = posIdempotencyKey(req)\n if (!attemptKey) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n if (!staff.orgId) return res.status(409).json({ error: 'This site has no workspace.' })\n const priced = pricePosHardwareCart(config, body['lines'])\n if ('error' in priced) return res.status(400).json({ error: priced.error })\n const method = body['shippingMethod']\n const shipping = isPosHardwareShippingMethod(method)\n ? config.shipping.find((option) => option.method === method)\n : undefined\n if (!shipping) return res.status(400).json({ error: 'Choose a shipping speed.' })\n // The terms of sale and business use, both ticked (AGL-4038).\n if (!posHardwareTermsConfirmed(body['hardwareTerms'])) {\n return res.status(400).json({ error: POS_HARDWARE_TERMS_REQUIRED, needsHardwareTerms: true })\n }\n const terms = posHardwareTermsMetadata({\n ip: readClientIp(req.headers as never) ?? null,\n userAgent: String(req.headers?.['user-agent'] ?? '') || null,\n })\n\n const orderId = posHardwareOrderId(staff.orgId, staff.hostId, attemptKey)\n const billing = await readOrgBilling(staff.orgId).catch(() => ({}))\n const customer = String((billing as { stripeCustomerId?: unknown }).stripeCustomerId ?? '').trim()\n const base = await posSettingsUrl(staff.hostId)\n const params: Record<string, string | number | boolean> = {\n mode: 'payment',\n client_reference_id: orderId,\n success_url: withQueryAndHash(base, 'hardwareOrder=placed', POS_HARDWARE_ANCHOR),\n cancel_url: withQueryAndHash(base, 'hardwareOrder=canceled', POS_HARDWARE_ANCHOR),\n 'payment_method_types[0]': 'card',\n 'shipping_address_collection[allowed_countries][0]': POS_HARDWARE_SHIP_COUNTRIES[0],\n 'phone_number_collection[enabled]': true,\n 'shipping_options[0][shipping_rate_data][type]': 'fixed_amount',\n 'shipping_options[0][shipping_rate_data][display_name]': POS_HARDWARE_SHIPPING_LABELS[shipping.method],\n 'shipping_options[0][shipping_rate_data][fixed_amount][amount]': shipping.cents,\n 'shipping_options[0][shipping_rate_data][fixed_amount][currency]': POS_HARDWARE_CURRENCY,\n 'metadata[type]': POS_HARDWARE_METADATA_TYPE,\n 'metadata[orderId]': orderId,\n 'metadata[orgId]': staff.orgId,\n 'metadata[hostId]': staff.hostId,\n 'metadata[uid]': staff.uid,\n 'metadata[lines]': encodePosHardwareLines(priced.lines),\n 'metadata[shippingMethod]': shipping.method,\n 'metadata[shippingCents]': shipping.cents,\n 'metadata[subtotalCents]': priced.subtotalCents,\n ...Object.fromEntries(Object.entries(terms).map(([key, value]) => [`metadata[${key}]`, value])),\n 'payment_intent_data[description]': `Card reader order ${posHardwareOrderNumber(orderId)}`,\n 'payment_intent_data[metadata][type]': POS_HARDWARE_METADATA_TYPE,\n 'payment_intent_data[metadata][orderId]': orderId,\n 'payment_intent_data[metadata][orgId]': staff.orgId,\n ...(customer ? { customer } : {}),\n ...(config.automaticTax\n ? {\n 'automatic_tax[enabled]': true,\n 'shipping_options[0][shipping_rate_data][tax_behavior]': 'exclusive',\n // A returning workspace's saved address is kept up to date\n // from what Checkout collects, which automatic tax requires.\n ...(customer ? { 'customer_update[shipping]': 'auto' } : {}),\n }\n : {}),\n }\n priced.lines.forEach((line, index) => {\n const sku = posHardwareSku(line.sku)\n params[`line_items[${index}][quantity]`] = line.quantity\n // A literal, not POS_HARDWARE_CURRENCY: check:facilitator-charge-shape\n // reads Stripe Tax beside a usd line item only when it says so (AGL-1956).\n params[`line_items[${index}][price_data][currency]`] = 'usd'\n params[`line_items[${index}][price_data][unit_amount]`] = line.unitCents\n params[`line_items[${index}][price_data][product_data][name]`] = line.name\n if (sku) params[`line_items[${index}][price_data][product_data][description]`] = sku.use\n params[`line_items[${index}][price_data][product_data][metadata][sku]`] = line.sku\n // Taxed as the physical good it is, never as the account's default (software).\n params[`line_items[${index}][price_data][product_data][tax_code]`] = POS_HARDWARE_TAX_CODE\n if (config.automaticTax) params[`line_items[${index}][price_data][tax_behavior]`] = 'exclusive'\n })\n const created = await posStripe('POST', 'checkout/sessions', {\n params,\n idempotencyKey: `pos-hw-checkout-${orderId}`,\n })\n const url = String(created.body?.url ?? '')\n if (!created.ok || !url) {\n console.error('[pos-hardware] checkout refused', created.status, created.body?.error?.code)\n return res.status(502).json({ error: 'Checkout could not be started. Try again in a moment.' })\n }\n return res.status(200).json({ url, orderId })\n }\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[pos-hardware]', action, error)\n return res.status(500).json({ error: 'The hardware shop could not answer' })\n }\n}\n"],"names":["createHash","readClientIp","Aglyn","firebaseAdmin","readOrgBilling","hostConsoleUrl","isPosHardwareSellerStoreSale","encodePosHardwareLines","isPosHardwareShippingMethod","POS_HARDWARE_ANCHOR","parsePosHardwareConfig","parsePosHardwareInPersonConfig","POS_HARDWARE_CURRENCY","POS_HARDWARE_METADATA_TYPE","POS_HARDWARE_ORDERS_COLLECTION","POS_HARDWARE_SALES_COLLECTION","POS_HARDWARE_SHIP_COUNTRIES","POS_HARDWARE_SHIPPING_LABELS","POS_HARDWARE_SKUS","POS_HARDWARE_TAX_CODE","posHardwareOffers","posHardwareOrderSource","posHardwareSku","pricePosHardwareCart","POS_HARDWARE_TERMS_REQUIRED","posHardwareTermsConfirmed","posHardwareTermsMetadata","mayVisitPosHardwareShop","authorizePosStaff","posIdempotencyKey","posRequestBody","posStripe","posTerminalAvailable","posHardwareConfig","env","process","posHardwareInPersonConfig","posHardwareListedCents","inPerson","snapshot","app","firestore","collection","doc","sellerHostId","where","map","sku","id","get","listed","docs","product","variants","data","String","Array","isArray","priceUsd","Number","length","isFinite","cents","Math","round","min","posHardwarePricedConfig","config","listedCents","isPosHardwareSellerStore","hostId","orgId","Boolean","sellerOrgId","posHardwareInPersonOrderId","registerOrderId","update","digest","slice","posHardwareOrderId","attemptKey","posHardwareOrderNumber","orderId","replace","toUpperCase","hardwareOrdersRef","posHardwareSaleRef","merchantHardwareOrderView","order","number","status","lines","line","name","quantity","unitCents","lineCents","subtotalCents","shippingCents","shipping","shippingLabel","label","taxCents","totalCents","tracking","createdAtMs","updatedAtMs","source","discountCents","readersToSetUp","units","filter","unit","readerId","refundedCents","returnRequest","state","requestedAtMs","note","posSettingsUrl","withQueryAndHash","base","query","hash","path","split","joiner","includes","waitingInPersonReaders","posPlan","stores","orders","org","hosts","Promise","all","limit","terminal","setupUrl","hasLocation","exists","checkEntitlement","sort","a","b","serialsTaken","serialNumber","LISTED_READ_FAILED","Symbol","listedReadFailed","error","console","posHardwareHandler","req","res","body","method","json","action","settingUp","gate","undefined","planRequired","staff","catch","returns","requestPosHardwareReturn","uid","reason","ok","PosHardwareReturnRefusal","message","readers","choosePosHardwareStore","markPosHardwareSetUp","PosHardwareReaderRefusal","available","offers","option","automaticTax","shipCountries","site","workspace","orderBy","created","priced","find","needsHardwareTerms","terms","ip","headers","userAgent","billing","customer","stripeCustomerId","trim","params","mode","client_reference_id","success_url","cancel_url","Object","fromEntries","entries","key","value","forEach","index","use","idempotencyKey","url","code"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,YAAY,QAAQ,oCAAmC;AAChE,YAAYC,WAAW,sBAAqB;AAE5C,SAASC,aAAa,EAAEC,cAAc,QAAQ,2BAA0B;AACxE,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SACEC,4BAA4B,EAC5BC,sBAAsB,EACtBC,2BAA2B,EAC3BC,mBAAmB,EACnBC,sBAAsB,EACtBC,8BAA8B,EAC9BC,qBAAqB,EACrBC,0BAA0B,EAC1BC,8BAA8B,EAC9BC,6BAA6B,EAC7BC,2BAA2B,EAC3BC,4BAA4B,EAC5BC,iBAAiB,EACjBC,qBAAqB,EACrBC,iBAAiB,EACjBC,sBAAsB,EACtBC,cAAc,EACdC,oBAAoB,QAKf,2BAAuB;AAC9B,SACEC,2BAA2B,EAC3BC,yBAAyB,EACzBC,wBAAwB,QACnB,iCAA6B;AACpC,SAASC,uBAAuB,QAAQ,iCAA6B;AACrE,SAASC,iBAAiB,EAAEC,iBAAiB,EAAEC,cAAc,QAAQ,gBAAY;AACjF,SAASC,SAAS,EAAEC,oBAAoB,QAAQ,kBAAc;AAE9D;;;;;;;;;;;;;;;;;;;;;2CAqB2C,GAE3C,0EAA0E,GAC1E,OAAO,SAASC,kBACdC,MAA0CC,QAAQD,GAAG;IAErD,yEAAyE;IACzE,iEAAiE;IACjE,IAAI,CAACF,wBAAwB,OAAO;IACpC,OAAOtB,uBAAuBwB;AAChC;AAEA;;;;;CAKC,GACD,OAAO,SAASE,0BACdF,MAA0CC,QAAQD,GAAG;IAErD,OAAOvB,+BAA+BuB;AACxC;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeG,uBACpBC,WAA6CF,2BAA2B;IAExE,IAAI,CAAC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wBAClF,+EAA+E;wBAC/EqJ,MAAM,CAAC,CAAC,WAAW,EAAEW,MAAM,qCAAqC,CAAC,CAAC,GAAG5L;wBACrE,IAAIgD,OAAOgH,YAAY,EAAEiB,MAAM,CAAC,CAAC,WAAW,EAAEW,MAAM,2BAA2B,CAAC,CAAC,GAAG;oBACtF;oBACA,MAAMvB,UAAU,MAAMzJ,UAAU,QAAQ,qBAAqB;wBAC3DqK;wBACAa,gBAAgB,CAAC,gBAAgB,EAAE/H,SAAS;oBAC9C;oBACA,MAAMgI,MAAM3J,iBAAOiI,gBAAAA,QAAQ7B,IAAI,qBAAZ6B,cAAc0B,GAAG,oBAAI;oBACxC,IAAI,CAAC1B,QAAQf,EAAE,IAAI,CAACyC,KAAK;4BAC0C1B,qBAAAA;wBAAjEjC,QAAQD,KAAK,CAAC,mCAAmCkC,QAAQ9F,MAAM,GAAE8F,iBAAAA,QAAQ7B,IAAI,sBAAZ6B,sBAAAA,eAAclC,KAAK,qBAAnBkC,oBAAqB2B,IAAI;wBAC1F,OAAOzD,IAAIhE,MAAM,CAAC,KAAKmE,IAAI,CAAC;4BAAEP,OAAO;wBAAwD;oBAC/F;oBACA,OAAOI,IAAIhE,MAAM,CAAC,KAAKmE,IAAI,CAAC;wBAAEqD;wBAAKhI;oBAAQ;gBAC7C;YACA;gBACE,OAAOwE,IAAIhE,MAAM,CAAC,KAAKmE,IAAI,CAAC;oBAAEP,OAAO;gBAAiB;QAC1D;IACF,EAAE,OAAOA,OAAO;QACdC,QAAQD,KAAK,CAAC,kBAAkBQ,QAAQR;QACxC,OAAOI,IAAIhE,MAAM,CAAC,KAAKmE,IAAI,CAAC;YAAEP,OAAO;QAAqC;IAC5E;AACF,EAAC"}
@@ -19,7 +19,7 @@ import { posCustomerHandler } from "./pos-customer.js";
19
19
  import { posDayReportHandler } from "./pos-day-report.js";
20
20
  import { registerPosSalePrinting } from "./pos-print.js";
21
21
  import { onPosSaleCompleted } from "./pos-sale.js";
22
- import { parsePosHardwareInPersonConfig } from "../model/pos-hardware.js";
22
+ import { recordSellerStoreSaleHardware } from "./pos-hardware-sale-fields.js";
23
23
  import { posReturnHandler } from "./pos-return.js";
24
24
  import { posShiftHandler } from "./pos-shift.js";
25
25
  import { posStaffPinHandler } from "./pos-staff-pin.js";
@@ -58,15 +58,7 @@ let hardwareSubscribed = false;
58
58
  */ function registerPosSaleHardware() {
59
59
  if (hardwareSubscribed) return;
60
60
  hardwareSubscribed = true;
61
- onPosSaleCompleted(async (event)=>{
62
- var _parsePosHardwareInPersonConfig;
63
- if (((_parsePosHardwareInPersonConfig = parsePosHardwareInPersonConfig(process.env)) == null ? void 0 : _parsePosHardwareInPersonConfig.sellerHostId) !== event.hostId) return;
64
- try {
65
- await (await import("./pos-hardware-in-person.js")).recordCompletedSaleHardware(event);
66
- } catch (error) {
67
- console.error('[pos-hardware-in-person] recorder not loaded', event.orderId, error);
68
- }
69
- });
61
+ onPosSaleCompleted((event)=>recordSellerStoreSaleHardware(event));
70
62
  }
71
63
 
72
64
  //# sourceMappingURL=pos-ops-routes.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-ops-routes.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 { registerPluginApiRoute } from '@aglyn/aglyn/server'\nimport { posCheckInHandler, registerPosSaleCheckIns } from './pos-check-in'\nimport { posCustomerHandler } from './pos-customer'\nimport { posDayReportHandler } from './pos-day-report'\nimport { registerPosSalePrinting } from './pos-print'\nimport { onPosSaleCompleted } from './pos-sale'\nimport { parsePosHardwareInPersonConfig } from '../model/pos-hardware'\nimport { posReturnHandler } from './pos-return'\nimport { posShiftHandler } from './pos-shift'\nimport { posStaffPinHandler } from './pos-staff-pin'\n\n/**\n * The register's operations routes (AGL-3609): shifts and the drawer, staff\n * PINs, the customer lookup and returns, the day totals (AGL-4037), the\n * check-in (AGL-4043), plus the\n * sale printing. Console-auth, so they register on the console surface with\n * the sale route itself.\n */\nexport function registerPosOpsRoutes(): void {\n registerPluginApiRoute('commerce/pos-shift', posShiftHandler)\n registerPluginApiRoute('commerce/pos-staff-pin', posStaffPinHandler)\n registerPluginApiRoute('commerce/pos-customer', posCustomerHandler)\n registerPluginApiRoute('commerce/pos-return', posReturnHandler)\n // One day's or one event's totals across every register, shift and cashier\n // (AGL-4037): a GET, read with the same gate as the shift reports.\n registerPluginApiRoute('commerce/pos-day-report', posDayReportHandler)\n // Check-in at the window (AGL-4043): who is due today, checking them in\n // with a wristband, and the day's list; a register sale's check-ins are\n // written the moment it completes, through the same seam as its printing.\n registerPluginApiRoute('commerce/pos-check-in', posCheckInHandler)\n registerPosSaleCheckIns()\n // A completed sale's receipt and drawer kick on the register's cloud\n // printers (AGL-3619), through the sale-completed seam every path fires.\n registerPosSalePrinting()\n // A card reader sold at the platform's own store's register becomes a\n // hardware order for the buyer's workspace (AGL-4038).\n registerPosSaleHardware()\n}\n\nlet hardwareSubscribed = false\n\n/**\n * Records the hardware order of a completed sale on the platform's own\n * store. Every other store's sale is answered from the environment alone,\n * without loading the recorder. Never throws into a sale; a sale this misses\n * stays marked and the To attach list's sweep records it.\n */\nfunction registerPosSaleHardware(): void {\n if (hardwareSubscribed) return\n hardwareSubscribed = true\n onPosSaleCompleted(async (event) => {\n if (parsePosHardwareInPersonConfig(process.env)?.sellerHostId !== event.hostId) return\n try {\n await (await import('./pos-hardware-in-person')).recordCompletedSaleHardware(event)\n } catch (error) {\n console.error('[pos-hardware-in-person] recorder not loaded', event.orderId, error)\n }\n })\n}\n"],"names":["registerPluginApiRoute","posCheckInHandler","registerPosSaleCheckIns","posCustomerHandler","posDayReportHandler","registerPosSalePrinting","onPosSaleCompleted","parsePosHardwareInPersonConfig","posReturnHandler","posShiftHandler","posStaffPinHandler","registerPosOpsRoutes","registerPosSaleHardware","hardwareSubscribed","event","process","env","sellerHostId","hostId","recordCompletedSaleHardware","error","console","orderId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,sBAAqB;AAC5D,SAASC,iBAAiB,EAAEC,uBAAuB,QAAQ,oBAAgB;AAC3E,SAASC,kBAAkB,QAAQ,oBAAgB;AACnD,SAASC,mBAAmB,QAAQ,sBAAkB;AACtD,SAASC,uBAAuB,QAAQ,iBAAa;AACrD,SAASC,kBAAkB,QAAQ,gBAAY;AAC/C,SAASC,8BAA8B,QAAQ,2BAAuB;AACtE,SAASC,gBAAgB,QAAQ,kBAAc;AAC/C,SAASC,eAAe,QAAQ,iBAAa;AAC7C,SAASC,kBAAkB,QAAQ,qBAAiB;AAEpD;;;;;;CAMC,GACD,OAAO,SAASC;IACdX,uBAAuB,sBAAsBS;IAC7CT,uBAAuB,0BAA0BU;IACjDV,uBAAuB,yBAAyBG;IAChDH,uBAAuB,uBAAuBQ;IAC9C,2EAA2E;IAC3E,mEAAmE;IACnER,uBAAuB,2BAA2BI;IAClD,wEAAwE;IACxE,wEAAwE;IACxE,0EAA0E;IAC1EJ,uBAAuB,yBAAyBC;IAChDC;IACA,qEAAqE;IACrE,yEAAyE;IACzEG;IACA,sEAAsE;IACtE,uDAAuD;IACvDO;AACF;AAEA,IAAIC,qBAAqB;AAEzB;;;;;CAKC,GACD,SAASD;IACP,IAAIC,oBAAoB;IACxBA,qBAAqB;IACrBP,mBAAmB,OAAOQ;YACpBP;QAAJ,IAAIA,EAAAA,kCAAAA,+BAA+BQ,QAAQC,GAAG,sBAA1CT,gCAA6CU,YAAY,MAAKH,MAAMI,MAAM,EAAE;QAChF,IAAI;YACF,MAAM,AAAC,CAAA,MAAM,MAAM,CAAC,8BAA0B,EAAGC,2BAA2B,CAACL;QAC/E,EAAE,OAAOM,OAAO;YACdC,QAAQD,KAAK,CAAC,gDAAgDN,MAAMQ,OAAO,EAAEF;QAC/E;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-ops-routes.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 { registerPluginApiRoute } from '@aglyn/aglyn/server'\nimport { posCheckInHandler, registerPosSaleCheckIns } from './pos-check-in'\nimport { posCustomerHandler } from './pos-customer'\nimport { posDayReportHandler } from './pos-day-report'\nimport { registerPosSalePrinting } from './pos-print'\nimport { onPosSaleCompleted } from './pos-sale'\nimport { recordSellerStoreSaleHardware } from './pos-hardware-sale-fields'\nimport { posReturnHandler } from './pos-return'\nimport { posShiftHandler } from './pos-shift'\nimport { posStaffPinHandler } from './pos-staff-pin'\n\n/**\n * The register's operations routes (AGL-3609): shifts and the drawer, staff\n * PINs, the customer lookup and returns, the day totals (AGL-4037), the\n * check-in (AGL-4043), plus the\n * sale printing. Console-auth, so they register on the console surface with\n * the sale route itself.\n */\nexport function registerPosOpsRoutes(): void {\n registerPluginApiRoute('commerce/pos-shift', posShiftHandler)\n registerPluginApiRoute('commerce/pos-staff-pin', posStaffPinHandler)\n registerPluginApiRoute('commerce/pos-customer', posCustomerHandler)\n registerPluginApiRoute('commerce/pos-return', posReturnHandler)\n // One day's or one event's totals across every register, shift and cashier\n // (AGL-4037): a GET, read with the same gate as the shift reports.\n registerPluginApiRoute('commerce/pos-day-report', posDayReportHandler)\n // Check-in at the window (AGL-4043): who is due today, checking them in\n // with a wristband, and the day's list; a register sale's check-ins are\n // written the moment it completes, through the same seam as its printing.\n registerPluginApiRoute('commerce/pos-check-in', posCheckInHandler)\n registerPosSaleCheckIns()\n // A completed sale's receipt and drawer kick on the register's cloud\n // printers (AGL-3619), through the sale-completed seam every path fires.\n registerPosSalePrinting()\n // A card reader sold at the platform's own store's register becomes a\n // hardware order for the buyer's workspace (AGL-4038).\n registerPosSaleHardware()\n}\n\nlet hardwareSubscribed = false\n\n/**\n * Records the hardware order of a completed sale on the platform's own\n * store. Every other store's sale is answered from the environment alone,\n * without loading the recorder. Never throws into a sale; a sale this misses\n * stays marked and the To attach list's sweep records it.\n */\nfunction registerPosSaleHardware(): void {\n if (hardwareSubscribed) return\n hardwareSubscribed = true\n onPosSaleCompleted((event) => recordSellerStoreSaleHardware(event))\n}\n"],"names":["registerPluginApiRoute","posCheckInHandler","registerPosSaleCheckIns","posCustomerHandler","posDayReportHandler","registerPosSalePrinting","onPosSaleCompleted","recordSellerStoreSaleHardware","posReturnHandler","posShiftHandler","posStaffPinHandler","registerPosOpsRoutes","registerPosSaleHardware","hardwareSubscribed","event"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,sBAAqB;AAC5D,SAASC,iBAAiB,EAAEC,uBAAuB,QAAQ,oBAAgB;AAC3E,SAASC,kBAAkB,QAAQ,oBAAgB;AACnD,SAASC,mBAAmB,QAAQ,sBAAkB;AACtD,SAASC,uBAAuB,QAAQ,iBAAa;AACrD,SAASC,kBAAkB,QAAQ,gBAAY;AAC/C,SAASC,6BAA6B,QAAQ,gCAA4B;AAC1E,SAASC,gBAAgB,QAAQ,kBAAc;AAC/C,SAASC,eAAe,QAAQ,iBAAa;AAC7C,SAASC,kBAAkB,QAAQ,qBAAiB;AAEpD;;;;;;CAMC,GACD,OAAO,SAASC;IACdX,uBAAuB,sBAAsBS;IAC7CT,uBAAuB,0BAA0BU;IACjDV,uBAAuB,yBAAyBG;IAChDH,uBAAuB,uBAAuBQ;IAC9C,2EAA2E;IAC3E,mEAAmE;IACnER,uBAAuB,2BAA2BI;IAClD,wEAAwE;IACxE,wEAAwE;IACxE,0EAA0E;IAC1EJ,uBAAuB,yBAAyBC;IAChDC;IACA,qEAAqE;IACrE,yEAAyE;IACzEG;IACA,sEAAsE;IACtE,uDAAuD;IACvDO;AACF;AAEA,IAAIC,qBAAqB;AAEzB;;;;;CAKC,GACD,SAASD;IACP,IAAIC,oBAAoB;IACxBA,qBAAqB;IACrBP,mBAAmB,CAACQ,QAAUP,8BAA8BO;AAC9D"}
@@ -14,7 +14,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { checkEntitlement, claimAttempt, deriveStripeObjectKey, resolveTransactionFeeCents } from "@aglyn/aglyn/server";
17
+ */ import { checkEntitlement, claimAttempt, deriveStripeObjectKey, PAY_LINK_PROCESSING_PERCENT, resolveTransactionFeeCents } from "@aglyn/aglyn/server";
18
18
  import { resolveHostToken } from "@aglyn/aglyn/app-utils/host-tokens";
19
19
  import { readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
20
20
  import { siteReturnOrigin } from "@aglyn/aglyn/app-utils/site-return-url";
@@ -434,7 +434,10 @@ function headerOf(req, name) {
434
434
  })));
435
435
  params.set('metadata[transferShippingCents]', String(shippingFloorCents));
436
436
  }
437
- CommerceModel.appendStorefrontPaymentMethodParams(params, input.paymentMethods);
437
+ // A quote or an invoice pays by card or a card-rate wallet, never by
438
+ // buy-now-pay-later, whatever the store offers on its storefront: its fee is
439
+ // priced at the card rate (`PAY_LINK_PROCESSING_PERCENT`).
440
+ CommerceModel.appendStorefrontPaymentMethodParams(params, CommerceModel.payLinkPaymentMethodControls(input.paymentMethods));
438
441
  return params;
439
442
  }
440
443
  const QUOTE_UPDATED_MESSAGE = 'This quote was updated since you opened it. Reload the page to see it before you pay.';
@@ -518,9 +521,10 @@ const refusal = (status, reason, error, extra = {})=>({
518
521
  const { owner, accountId } = payments;
519
522
  const charge = CommerceModel.invoiceCheckoutCharge(order, quoteId, payStore);
520
523
  // The fee is sized on the most the buyer can pay, as a draft's first link
521
- // sized it on its dearest rate.
524
+ // sized it on its dearest rate, and its processing half at the card rate:
525
+ // the session below excludes every buy-now-pay-later method.
522
526
  const dearestRateCents = charge.shippingOptions.reduce((most, rate)=>Math.max(most, rate.amountCents), 0);
523
- const feeCents = resolveTransactionFeeCents(owner == null ? void 0 : owner.org, charge.feeProductType, charge.goodsCents, charge.totalCents + dearestRateCents);
527
+ const feeCents = resolveTransactionFeeCents(owner == null ? void 0 : owner.org, charge.feeProductType, charge.goodsCents, charge.totalCents + dearestRateCents, PAY_LINK_PROCESSING_PERCENT);
524
528
  const nativeMode = await deps.nativeMode(String((_ref = owner == null ? void 0 : owner.id) != null ? _ref : ''));
525
529
  const site = host;
526
530
  const origin = siteReturnOrigin({