@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
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -13,7 +14,7 @@
13
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
15
  * See the License for the specific language governing permissions and
15
16
  * limitations under the License.
16
- */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
+ */ import { isPosHardwareSkuId, parsePosHardwareInPersonConfig } from "../model/pos-hardware.js";
17
18
  import * as CommerceModel from "../model/index.js";
18
19
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
19
20
  import { isDocumentId } from "@aglyn/tenant-data-admin/server/document-id";
@@ -63,6 +64,7 @@ import { readStoreDay } from "./store-day.js";
63
64
  const hostRef = firestore.collection('hosts').doc(hostId);
64
65
  try {
65
66
  var _cartSnapshot_data;
67
+ var _parsePosHardwareInPersonConfig;
66
68
  if (!cartId) {
67
69
  if (!isPost) return res.status(200).json({
68
70
  lines: [],
@@ -242,11 +244,21 @@ import { readStoreDay } from "./store-day.js";
242
244
  });
243
245
  });
244
246
  const subtotalCents = lines.filter((line)=>!line.unavailable).reduce((sum, line)=>sum + line.unitAmountCents * line.quantity, 0);
245
- return res.status(200).json({
247
+ // Card reader hardware the platform's own store sells (AGL-4038): the
248
+ // cart asks for the terms of sale before checkout. Read from the
249
+ // environment first, so no other store reads anything more.
250
+ const sellerHostId = (_parsePosHardwareInPersonConfig = parsePosHardwareInPersonConfig(process.env)) == null ? void 0 : _parsePosHardwareInPersonConfig.sellerHostId;
251
+ const hardwareTerms = sellerHostId === hostId && cart.lines.some((line)=>{
252
+ var _productsById_get;
253
+ return isPosHardwareSkuId((_productsById_get = productsById.get(line.productId)) == null ? void 0 : _productsById_get.hardwareSku);
254
+ });
255
+ return res.status(200).json(_extends({
246
256
  lines,
247
257
  count: CommerceModel.cartCount(cart),
248
258
  subtotalCents
249
- });
259
+ }, hardwareTerms ? {
260
+ hardwareTerms: true
261
+ } : {}));
250
262
  } catch (error) {
251
263
  console.error(error);
252
264
  return res.status(500).json({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/cart.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 type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { cartCookieName, mintCartId, readCartId } from './cart-cookie'\nimport { readStoreDay } from './store-day'\n\nexport interface ResolvedCartLine extends CommerceModel.CartLine {\n name: string\n variantLabel?: string\n unitAmountCents: number\n imageUrl?: string\n /** Line no longer purchasable (deleted/draft/sold out). */\n unavailable?: boolean\n /**\n * What the shopper must do about an unavailable line, when the cart can say\n * (AGL-4100): its add-ons no longer answer the product's choices.\n */\n problem?: string\n}\n\n/**\n * Server-backed cart (AGL-293): cookie-keyed doc under\n * `hosts/{hostId}/carts`. GET returns the resolved cart; POST mutates\n * with {action: add|set|remove|clear}. Lines resolve against product\n * docs on every read so prices/names never go stale, and unavailable\n * lines surface instead of silently charging.\n */\nexport const cartHandler: PluginApiHandler = async (req, res) => {\n const isPost = req.method === 'POST'\n if (!isPost && req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const body = isPost\n ? typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n : {}\n // AGL-1769: BOTH components of the path this handler writes come from the\n // caller — `hostId` off the body, `cartId` off a cookie whose name embeds\n // `hostId` — and `.doc()` appends a slash-separated PATH rather than taking\n // one opaque id. So an unvalidated pair named the nesting as well as the\n // document: a `hostId` of `a/b/c` wrote under `hosts/a/b/c`, invisible to\n // every console list because they resolve the host doc first.\n //\n // This handler is the one visitor-facing write in the AGL-1763 sweep that\n // needs NO credentials — no session, no member gate, no signature — so it is\n // the one place the id rule has to hold on its own.\n const hostId = String((isPost ? body.hostId : req.query.hostId) ?? '')\n // The message names BOTH causes it now covers (`762621581`): the guard reads\n // as \"absent\" but also refuses a hostId that is a path rather than an id, and\n // a caller told only \"missing\" would go looking for the wrong mistake.\n // AGL-1771: `isDocumentId`, not the cart module's old `isCartId` alias — this\n // value is a HOST id, and the rule it has to satisfy was never about carts.\n if (!isDocumentId(hostId))\n return res.status(400).json({ error: 'Missing or invalid hostId' })\n\n const cookieName = cartCookieName(hostId)\n // A cookie that is not a single document id reads as NO cart: a GET returns\n // an empty one and a POST mints a fresh id below, exactly as for a first-time\n // visitor. Nothing is stranded — a path that was never a cart id was never a\n // basket anyone filled.\n let cartId = readCartId(req.cookies, hostId)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n\n try {\n if (!cartId) {\n if (!isPost) return res.status(200).json({ lines: [], count: 0 })\n cartId = mintCartId()\n res.setHeader(\n 'Set-Cookie',\n `${cookieName}=${cartId}; Path=/; Max-Age=${60 * 60 * 24 * 90}; ` +\n 'HttpOnly; SameSite=Lax; Secure',\n )\n }\n const cartRef = hostRef.collection('carts').doc(cartId)\n const cartSnapshot = await cartRef.get()\n const cart: CommerceModel.HostCart = (cartSnapshot.data() as any) ?? { lines: [] }\n\n if (isPost) {\n const action = String(body.action ?? 'add')\n // The day the shopper chose to use a check-in item (AGL-4043): part of\n // the line's identity, so two days of one pass are two lines.\n const useDayKey = typeof body.useDayKey === 'string' ? body.useDayKey.trim() : ''\n // The add-ons chosen on the product's page (AGL-4100), ids only: part\n // of the line's identity, priced from the product, never from here.\n const requestedModifiers = CommerceModel.modifierSelectionFrom(body.modifiers)\n const line: CommerceModel.CartLine = {\n productId: String(body.productId ?? ''),\n ...(body.variantId ? { variantId: String(body.variantId) } : {}),\n ...(useDayKey ? { useDayKey } : {}),\n ...(requestedModifiers.length ? { modifiers: requestedModifiers } : {}),\n // Clamped at the door as well as in the model (AGL-2285): the route\n // used `Math.round(Number(...))` alone, which yields `NaN` for\n // `{\"quantity\":\"x\"}` and slipped past `upsertCartLine`'s `<= 0` guard.\n quantity: Math.min(\n CommerceModel.CART_MAX_QUANTITY,\n Math.max(\n -CommerceModel.CART_MAX_QUANTITY,\n Number.isFinite(Number(body.quantity ?? 1))\n ? Math.round(Number(body.quantity ?? 1))\n : 0,\n ),\n ),\n }\n if (useDayKey && !CommerceModel.isCheckInDayKey(useDayKey)) {\n return res.status(400).json({ error: 'Choose the day as a date.' })\n }\n if (action === 'clear') {\n cart.lines = []\n } else if (!line.productId) {\n return res.status(400).json({ error: 'Missing productId' })\n } else if (action === 'remove') {\n cart.lines = CommerceModel.removeCartLine(cart, line)\n } else {\n // A product sold in person only (AGL-4060) never enters a basket: it\n // answers as no product at all, as its page does. A line already in\n // the cart stays removable and resolves as unavailable below.\n if (line.quantity > 0 && isDocumentId(line.productId)) {\n const productSnapshot = await hostRef.collection('products').doc(line.productId).get()\n if (productSnapshot.exists && !CommerceModel.productSellsOnline(productSnapshot.data())) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n // A use day is asked only by an item that asks for one, and is a\n // day that has not passed on the store's calendar (AGL-4043).\n const isNewLine = !cart.lines.some(\n (held) => CommerceModel.cartLineKey(held) === CommerceModel.cartLineKey(line),\n )\n const product = productSnapshot.exists ? CommerceModel.liftLegacyProduct(productSnapshot.data() as any) : null\n if (useDayKey && (action === 'add' || isNewLine)) {\n const variantId = line.variantId ?? product?.variants[0]?.id\n if (!product || !CommerceModel.productAsksUseDate(product, variantId)) {\n return res.status(400).json({ error: 'This item has no day to choose.' })\n }\n const problem = CommerceModel.checkInUseDayProblem(useDayKey, (await readStoreDay(hostRef)).todayKey)\n if (problem) return res.status(400).json({ error: problem })\n }\n // Add-ons (AGL-4100): asked of the groups the website shows, every\n // required one answered, and kept as ids in the product's order. A\n // required group left unanswered is refused here, so no line goes\n // in a basket that checkout would have to turn away.\n if (product && (action === 'add' || isNewLine)) {\n const chosen = CommerceModel.resolveWebsiteLineModifiers(\n product,\n line.modifiers,\n line.variantId ?? product.variants[0]?.id,\n )\n if (!chosen.ok) return res.status(400).json({ error: chosen.error })\n const selection = CommerceModel.modifierSelectionOf(chosen.modifiers)\n if (selection.length) line.modifiers = selection\n else delete line.modifiers\n }\n }\n cart.lines = CommerceModel.upsertCartLine(\n cart,\n line,\n action === 'set' ? 'set' : 'add',\n )\n }\n // AGL-1769: never mint an EMPTY cart. `clear` returns above before the\n // `!line.productId` check, so `{ hostId, action: 'clear' }` — no\n // product, valid or otherwise, and no credentials — used to create a\n // document per request holding `lines: []` and two timestamps. A `remove`\n // or a `set 0` that empties an absent basket is the same request wearing\n // a productId. A cart that would store no lines is not a cart.\n //\n // AGL-1760's test — does refusing discard money or work that already\n // occurred — is passed trivially here: there is no basket to strand. The\n // caller still gets its cookie and its empty-cart response, so the next\n // add lands on this id and creates the document properly.\n if (cartSnapshot.exists || cart.lines.length > 0) {\n await cartRef.set(\n {\n lines: cart.lines,\n updatedAtMs: Date.now(),\n ...(cartSnapshot.exists ? {} : { createdAtMs: Date.now() }),\n },\n { merge: true },\n )\n }\n }\n\n // Resolve display lines from product docs — never trust stored data.\n const uniqueProductIds = [...new Set(cart.lines.map((l) => l.productId))]\n const productSnapshots = await Promise.all(\n uniqueProductIds.map((id) =>\n hostRef.collection('products').doc(id).get(),\n ),\n )\n const productsById = new Map(\n productSnapshots.map((snapshot) => [\n snapshot.id,\n snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data() as any) : null,\n ]),\n )\n const lines: ResolvedCartLine[] = cart.lines.map((line) => {\n const product = productsById.get(line.productId)\n if (!product || !CommerceModel.productListedOnline(product)) {\n return {\n ...line,\n name: product?.name ?? 'Unavailable product',\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n // A variant with no price yet (AGL-2916) is not for sale, and never a\n // line worth nothing.\n if (!variant || !CommerceModel.variantHasPrice(variant)) {\n return {\n ...line,\n name: product.name,\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variantLabel = Object.keys(variant.options ?? {}).length\n ? Object.values(variant.options ?? {}).join(' / ')\n : undefined\n // Add-ons priced from the product on every read (AGL-4100), on this\n // variant. Choices the product no longer offers, or a required one\n // now unanswered, make the line unavailable with what to do.\n const chosen = CommerceModel.resolveWebsiteLineModifiers(product, line.modifiers, variant.id)\n if (!chosen.ok) {\n return {\n ...line,\n name: product.name,\n ...(variantLabel ? { variantLabel } : {}),\n unitAmountCents: 0,\n unavailable: true,\n problem: CommerceModel.cartLineModifierProblem(chosen.error),\n }\n }\n const label = CommerceModel.lineLabelWithModifiers(variantLabel, chosen.modifiers)\n return {\n ...line,\n name: product.name,\n ...(label ? { variantLabel: label } : {}),\n unitAmountCents: Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents,\n ...(variant.imageUrl || product.mediaUrls?.[0] || product.imageUrl\n ? {\n imageUrl:\n variant.imageUrl ??\n product.mediaUrls?.[0] ??\n product.imageUrl,\n }\n : {}),\n ...(CommerceModel.canPurchase(product, variant.id, line.quantity)\n ? {}\n : { unavailable: true }),\n }\n })\n const subtotalCents = lines\n .filter((line) => !line.unavailable)\n .reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n return res.status(200).json({\n lines,\n count: CommerceModel.cartCount(cart),\n subtotalCents,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Cart unavailable' })\n }\n}\n"],"names":["CommerceModel","firebaseAdmin","isDocumentId","cartCookieName","mintCartId","readCartId","readStoreDay","cartHandler","req","res","isPost","method","status","json","error","body","JSON","parse","hostId","String","query","cookieName","cartId","cookies","firestore","app","hostRef","collection","doc","cartSnapshot","lines","count","setHeader","cartRef","get","cart","data","action","useDayKey","trim","requestedModifiers","modifierSelectionFrom","modifiers","line","productId","variantId","length","quantity","Math","min","CART_MAX_QUANTITY","max","Number","isFinite","round","isCheckInDayKey","removeCartLine","productSnapshot","exists","productSellsOnline","isNewLine","some","held","cartLineKey","product","liftLegacyProduct","variants","id","productAsksUseDate","problem","checkInUseDayProblem","todayKey","chosen","resolveWebsiteLineModifiers","ok","selection","modifierSelectionOf","upsertCartLine","set","updatedAtMs","Date","now","createdAtMs","merge","uniqueProductIds","Set","map","l","productSnapshots","Promise","all","productsById","Map","snapshot","variant","productListedOnline","name","unitAmountCents","unavailable","find","item","variantHasPrice","variantLabel","Object","keys","options","values","join","undefined","cartLineModifierProblem","label","lineLabelWithModifiers","priceUsd","extraCents","imageUrl","mediaUrls","canPurchase","subtotalCents","filter","reduce","sum","cartCount","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CA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eAC3EnB,QAAQoB,QAAQ,MAAIlD,qBAAAA,QAAQmD,SAAS,qBAAjBnD,kBAAmB,CAAC,EAAE,KAAIA,QAAQkD,QAAQ,GAC9D;gBACEA,QAAQ,GACNpB,QAAAA,oBAAAA,QAAQoB,QAAQ,YAAhBpB,qBACA9B,sBAAAA,QAAQmD,SAAS,qBAAjBnD,mBAAmB,CAAC,EAAE,YADtB8B,OAEA9B,QAAQkD,QAAQ;YACpB,IACA,CAAC,GACDlH,cAAcoH,WAAW,CAACpD,SAAS8B,QAAQ3B,EAAE,EAAExB,KAAKI,QAAQ,IAC5D,CAAC,IACD;gBAAEmD,aAAa;YAAK;QAE5B;QACA,MAAMmB,gBAAgBvF,MACnBwF,MAAM,CAAC,CAAC3E,OAAS,CAACA,KAAKuD,WAAW,EAClCqB,MAAM,CAAC,CAACC,KAAK7E,OAAS6E,MAAM7E,KAAKsD,eAAe,GAAGtD,KAAKI,QAAQ,EAAE;QACrE,OAAOtC,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1BiB;YACAC,OAAO/B,cAAcyH,SAAS,CAACtF;YAC/BkF;QACF;IACF,EAAE,OAAOvG,OAAO;QACd4G,QAAQ5G,KAAK,CAACA;QACd,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAmB;IAC1D;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/cart.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 { isPosHardwareSkuId, parsePosHardwareInPersonConfig } from '../model/pos-hardware'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { cartCookieName, mintCartId, readCartId } from './cart-cookie'\nimport { readStoreDay } from './store-day'\n\nexport interface ResolvedCartLine extends CommerceModel.CartLine {\n name: string\n variantLabel?: string\n unitAmountCents: number\n imageUrl?: string\n /** Line no longer purchasable (deleted/draft/sold out). */\n unavailable?: boolean\n /**\n * What the shopper must do about an unavailable line, when the cart can say\n * (AGL-4100): its add-ons no longer answer the product's choices.\n */\n problem?: string\n}\n\n/**\n * Server-backed cart (AGL-293): cookie-keyed doc under\n * `hosts/{hostId}/carts`. GET returns the resolved cart; POST mutates\n * with {action: add|set|remove|clear}. Lines resolve against product\n * docs on every read so prices/names never go stale, and unavailable\n * lines surface instead of silently charging.\n */\nexport const cartHandler: PluginApiHandler = async (req, res) => {\n const isPost = req.method === 'POST'\n if (!isPost && req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const body = isPost\n ? typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n : {}\n // AGL-1769: BOTH components of the path this handler writes come from the\n // caller — `hostId` off the body, `cartId` off a cookie whose name embeds\n // `hostId` — and `.doc()` appends a slash-separated PATH rather than taking\n // one opaque id. So an unvalidated pair named the nesting as well as the\n // document: a `hostId` of `a/b/c` wrote under `hosts/a/b/c`, invisible to\n // every console list because they resolve the host doc first.\n //\n // This handler is the one visitor-facing write in the AGL-1763 sweep that\n // needs NO credentials — no session, no member gate, no signature — so it is\n // the one place the id rule has to hold on its own.\n const hostId = String((isPost ? body.hostId : req.query.hostId) ?? '')\n // The message names BOTH causes it now covers (`762621581`): the guard reads\n // as \"absent\" but also refuses a hostId that is a path rather than an id, and\n // a caller told only \"missing\" would go looking for the wrong mistake.\n // AGL-1771: `isDocumentId`, not the cart module's old `isCartId` alias — this\n // value is a HOST id, and the rule it has to satisfy was never about carts.\n if (!isDocumentId(hostId))\n return res.status(400).json({ error: 'Missing or invalid hostId' })\n\n const cookieName = cartCookieName(hostId)\n // A cookie that is not a single document id reads as NO cart: a GET returns\n // an empty one and a POST mints a fresh id below, exactly as for a first-time\n // visitor. Nothing is stranded — a path that was never a cart id was never a\n // basket anyone filled.\n let cartId = readCartId(req.cookies, hostId)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n\n try {\n if (!cartId) {\n if (!isPost) return res.status(200).json({ lines: [], count: 0 })\n cartId = mintCartId()\n res.setHeader(\n 'Set-Cookie',\n `${cookieName}=${cartId}; Path=/; Max-Age=${60 * 60 * 24 * 90}; ` +\n 'HttpOnly; SameSite=Lax; Secure',\n )\n }\n const cartRef = hostRef.collection('carts').doc(cartId)\n const cartSnapshot = await cartRef.get()\n const cart: CommerceModel.HostCart = (cartSnapshot.data() as any) ?? { lines: [] }\n\n if (isPost) {\n const action = String(body.action ?? 'add')\n // The day the shopper chose to use a check-in item (AGL-4043): part of\n // the line's identity, so two days of one pass are two lines.\n const useDayKey = typeof body.useDayKey === 'string' ? body.useDayKey.trim() : ''\n // The add-ons chosen on the product's page (AGL-4100), ids only: part\n // of the line's identity, priced from the product, never from here.\n const requestedModifiers = CommerceModel.modifierSelectionFrom(body.modifiers)\n const line: CommerceModel.CartLine = {\n productId: String(body.productId ?? ''),\n ...(body.variantId ? { variantId: String(body.variantId) } : {}),\n ...(useDayKey ? { useDayKey } : {}),\n ...(requestedModifiers.length ? { modifiers: requestedModifiers } : {}),\n // Clamped at the door as well as in the model (AGL-2285): the route\n // used `Math.round(Number(...))` alone, which yields `NaN` for\n // `{\"quantity\":\"x\"}` and slipped past `upsertCartLine`'s `<= 0` guard.\n quantity: Math.min(\n CommerceModel.CART_MAX_QUANTITY,\n Math.max(\n -CommerceModel.CART_MAX_QUANTITY,\n Number.isFinite(Number(body.quantity ?? 1))\n ? Math.round(Number(body.quantity ?? 1))\n : 0,\n ),\n ),\n }\n if (useDayKey && !CommerceModel.isCheckInDayKey(useDayKey)) {\n return res.status(400).json({ error: 'Choose the day as a date.' })\n }\n if (action === 'clear') {\n cart.lines = []\n } else if (!line.productId) {\n return res.status(400).json({ error: 'Missing productId' })\n } else if (action === 'remove') {\n cart.lines = CommerceModel.removeCartLine(cart, line)\n } else {\n // A product sold in person only (AGL-4060) never enters a basket: it\n // answers as no product at all, as its page does. A line already in\n // the cart stays removable and resolves as unavailable below.\n if (line.quantity > 0 && isDocumentId(line.productId)) {\n const productSnapshot = await hostRef.collection('products').doc(line.productId).get()\n if (productSnapshot.exists && !CommerceModel.productSellsOnline(productSnapshot.data())) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n // A use day is asked only by an item that asks for one, and is a\n // day that has not passed on the store's calendar (AGL-4043).\n const isNewLine = !cart.lines.some(\n (held) => CommerceModel.cartLineKey(held) === CommerceModel.cartLineKey(line),\n )\n const product = productSnapshot.exists ? CommerceModel.liftLegacyProduct(productSnapshot.data() as any) : null\n if (useDayKey && (action === 'add' || isNewLine)) {\n const variantId = line.variantId ?? product?.variants[0]?.id\n if (!product || !CommerceModel.productAsksUseDate(product, variantId)) {\n return res.status(400).json({ error: 'This item has no day to choose.' })\n }\n const problem = CommerceModel.checkInUseDayProblem(useDayKey, (await readStoreDay(hostRef)).todayKey)\n if (problem) return res.status(400).json({ error: problem })\n }\n // Add-ons (AGL-4100): asked of the groups the website shows, every\n // required one answered, and kept as ids in the product's order. A\n // required group left unanswered is refused here, so no line goes\n // in a basket that checkout would have to turn away.\n if (product && (action === 'add' || isNewLine)) {\n const chosen = CommerceModel.resolveWebsiteLineModifiers(\n product,\n line.modifiers,\n line.variantId ?? product.variants[0]?.id,\n )\n if (!chosen.ok) return res.status(400).json({ error: chosen.error })\n const selection = CommerceModel.modifierSelectionOf(chosen.modifiers)\n if (selection.length) line.modifiers = selection\n else delete line.modifiers\n }\n }\n cart.lines = CommerceModel.upsertCartLine(\n cart,\n line,\n action === 'set' ? 'set' : 'add',\n )\n }\n // AGL-1769: never mint an EMPTY cart. `clear` returns above before the\n // `!line.productId` check, so `{ hostId, action: 'clear' }` — no\n // product, valid or otherwise, and no credentials — used to create a\n // document per request holding `lines: []` and two timestamps. A `remove`\n // or a `set 0` that empties an absent basket is the same request wearing\n // a productId. A cart that would store no lines is not a cart.\n //\n // AGL-1760's test — does refusing discard money or work that already\n // occurred — is passed trivially here: there is no basket to strand. The\n // caller still gets its cookie and its empty-cart response, so the next\n // add lands on this id and creates the document properly.\n if (cartSnapshot.exists || cart.lines.length > 0) {\n await cartRef.set(\n {\n lines: cart.lines,\n updatedAtMs: Date.now(),\n ...(cartSnapshot.exists ? {} : { createdAtMs: Date.now() }),\n },\n { merge: true },\n )\n }\n }\n\n // Resolve display lines from product docs — never trust stored data.\n const uniqueProductIds = [...new Set(cart.lines.map((l) => l.productId))]\n const productSnapshots = await Promise.all(\n uniqueProductIds.map((id) =>\n hostRef.collection('products').doc(id).get(),\n ),\n )\n const productsById = new Map(\n productSnapshots.map((snapshot) => [\n snapshot.id,\n snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data() as any) : null,\n ]),\n )\n const lines: ResolvedCartLine[] = cart.lines.map((line) => {\n const product = productsById.get(line.productId)\n if (!product || !CommerceModel.productListedOnline(product)) {\n return {\n ...line,\n name: product?.name ?? 'Unavailable product',\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n // A variant with no price yet (AGL-2916) is not for sale, and never a\n // line worth nothing.\n if (!variant || !CommerceModel.variantHasPrice(variant)) {\n return {\n ...line,\n name: product.name,\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variantLabel = Object.keys(variant.options ?? {}).length\n ? Object.values(variant.options ?? {}).join(' / ')\n : undefined\n // Add-ons priced from the product on every read (AGL-4100), on this\n // variant. Choices the product no longer offers, or a required one\n // now unanswered, make the line unavailable with what to do.\n const chosen = CommerceModel.resolveWebsiteLineModifiers(product, line.modifiers, variant.id)\n if (!chosen.ok) {\n return {\n ...line,\n name: product.name,\n ...(variantLabel ? { variantLabel } : {}),\n unitAmountCents: 0,\n unavailable: true,\n problem: CommerceModel.cartLineModifierProblem(chosen.error),\n }\n }\n const label = CommerceModel.lineLabelWithModifiers(variantLabel, chosen.modifiers)\n return {\n ...line,\n name: product.name,\n ...(label ? { variantLabel: label } : {}),\n unitAmountCents: Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents,\n ...(variant.imageUrl || product.mediaUrls?.[0] || product.imageUrl\n ? {\n imageUrl:\n variant.imageUrl ??\n product.mediaUrls?.[0] ??\n product.imageUrl,\n }\n : {}),\n ...(CommerceModel.canPurchase(product, variant.id, line.quantity)\n ? {}\n : { unavailable: true }),\n }\n })\n const subtotalCents = lines\n .filter((line) => !line.unavailable)\n .reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n // Card reader hardware the platform's own store sells (AGL-4038): the\n // cart asks for the terms of sale before checkout. Read from the\n // environment first, so no other store reads anything more.\n const sellerHostId = parsePosHardwareInPersonConfig(process.env)?.sellerHostId\n const hardwareTerms =\n sellerHostId === hostId &&\n cart.lines.some((line) => isPosHardwareSkuId(productsById.get(line.productId)?.hardwareSku))\n return res.status(200).json({\n lines,\n count: CommerceModel.cartCount(cart),\n subtotalCents,\n ...(hardwareTerms ? { hardwareTerms: true } : {}),\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Cart unavailable' })\n }\n}\n"],"names":["isPosHardwareSkuId","parsePosHardwareInPersonConfig","CommerceModel","firebaseAdmin","isDocumentId","cartCookieName","mintCartId","readCartId","readStoreDay","cartHandler","req","res","isPost","method","status","json","error","body","JSON","parse","hostId","String","query","cookieName","cartId","cookies","firestore","app","hostRef","collection","doc","cartSnapshot","lines","count","setHeader","cartRef","get","cart","data","action","useDayKey","trim","requestedModifiers","modifierSelectionFrom","modifiers","line","productId","variantId","length","quantity","Math","min","CART_MAX_QUANTITY","max","Number","isFinite","round","isCheckInDayKey","removeCartLine","productSnapshot","exists","productSellsOnline","isNewLine","some","held","cartLineKey","product","liftLegacyProduct","variants","id","productAsksUseDate","problem","checkInUseDayProblem","todayKey","chosen","resolveWebsiteLineModifiers","ok","selection","modifierSelectionOf","upsertCartLine","set","updatedAtMs","Date","now","createdAtMs","merge","uniqueProductIds","Set","map","l","productSnapshots","Promise","all","productsById","Map","snapshot","variant","productListedOnline","name","unitAmountCents","unavailable","find","item","variantHasPrice","variantLabel","Object","keys","options","values","join","undefined","cartLineModifierProblem","label","lineLabelWithModifiers","priceUsd","extraCents","imageUrl","mediaUrls","canPurchase","subtotalCents","filter","reduce","sum","sellerHostId","process","env","hardwareTerms","hardwareSku","cartCount","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,8BAA8B,QAAQ,2BAAuB;AAG1F,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,EAAEC,UAAU,EAAEC,UAAU,QAAQ,mBAAe;AACtE,SAASC,YAAY,QAAQ,iBAAa;AAgB1C;;;;;;CAMC,GACD,OAAO,MAAMC,cAAgC,OAAOC,KAAKC;QAQhDD,WAYgBE;IAnBvB,MAAMA,SAASF,IAAIG,MAAM,KAAK;IAC9B,IAAI,CAACD,UAAUF,IAAIG,MAAM,KAAK,OAAO;QACnC,OAAOF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,OAAOL,SACT,OAAOF,IAAIO,IAAI,KAAK,WAClBC,KAAKC,KAAK,CAACT,IAAIO,IAAI,IAAI,SACtBP,YAAAA,IAAIO,IAAI,YAARP,YAAY,CAAC,IAChB,CAAC;IACL,0EAA0E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,sEAAsE;QACtE,iEAAiE;QACjE,4DAA4D;QAC5D,MAAM0E,gBAAe1H,kCAAAA,+BAA+B2H,QAAQC,GAAG,sBAA1C5H,gCAA6C0H,YAAY;QAC9E,MAAMG,gBACJH,iBAAiBvG,UACjBiB,KAAKL,KAAK,CAAC+B,IAAI,CAAC,CAAClB;gBAA4BgD;mBAAnB7F,oBAAmB6F,oBAAAA,aAAazD,GAAG,CAACS,KAAKC,SAAS,sBAA/B+C,kBAAkCkC,WAAW;;QAC5F,OAAOpH,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1BiB;YACAC,OAAO/B,cAAc8H,SAAS,CAAC3F;YAC/BkF;WACIO,gBAAgB;YAAEA,eAAe;QAAK,IAAI,CAAC;IAEnD,EAAE,OAAO9G,OAAO;QACdiH,QAAQjH,KAAK,CAACA;QACd,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAmB;IAC1D;AACF,EAAC"}
@@ -1,4 +1,5 @@
1
1
  import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
2
3
  /**
3
4
  * @license
4
5
  * Copyright 2026 Aglyn LLC
@@ -26,6 +27,10 @@ import { checkoutSessionCardAuthenticationParams } from "@aglyn/tenant-data-admi
26
27
  import { CARRIER_POSTAL_CODE_MESSAGE, planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
27
28
  import { readActiveMemberSession } from "./membership.js";
28
29
  import { readStoreDay } from "./store-day.js";
30
+ import { readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
31
+ import { POS_HARDWARE_TAX_CODE } from "../model/pos-hardware.js";
32
+ import { posHardwareTermsMetadata } from "../model/pos-hardware-terms.js";
33
+ import { sellerStoreHardwareCheckout } from "./pos-hardware-sale-fields.js";
29
34
  import { resolveManualTaxRateId } from "./manual-tax-rate.js";
30
35
  import { taxEngineSessionMetadata } from "../model/commerce-tax-engine.js";
31
36
  import { quoteSaleTaxWithEngine } from "./tax-engine-quote.js";
@@ -125,8 +130,8 @@ export const checkoutHandler = async (req, res)=>{
125
130
  if (held) await held.release();
126
131
  };
127
132
  try {
128
- var _variant_priceUsd, _variant_options, _variant_options1, _req_headers_referer, _req_headers_host, _storeSettings_get, _lifted_type, _ref1, _ref2, _lifted_name, _ref3, _lifted_type1, _variant_weightGrams, _lifted_type2, _lifted_type3, _product_name, _ref4, _session_id;
129
- var _ownerOrg_org, _ownerOrg_org1, _ownerOrg_org2;
133
+ var _variant_priceUsd, _variant_options, _variant_options1, _ref1, _ref2, _readClientIp, _ref3, _req_headers_referer, _req_headers_host, _storeSettings_get, _lifted_type, _ref4, _ref5, _lifted_name, _ref6, _lifted_type1, _variant_weightGrams, _lifted_type2, _lifted_type3, _product_name, _ref7, _session_id;
134
+ var _ownerOrg_org, _ownerOrg_org1, _req_headers, _ownerOrg_org2, _ownerOrg_org3;
130
135
  const firestore = firebaseAdmin.app().firestore();
131
136
  const hostRef = firestore.collection('hosts').doc(hostId);
132
137
  const [hostSnapshot, productSnapshot] = await Promise.all([
@@ -211,14 +216,14 @@ export const checkoutHandler = async (req, res)=>{
211
216
  // that has not passed on the store's calendar. Refused before anything
212
217
  // is held, so a wrong day costs the buyer nothing.
213
218
  if (useDayKey) {
214
- var _ref5, _hostSnapshot_data;
219
+ var _ref8, _hostSnapshot_data;
215
220
  if (!CommerceModel.productAsksUseDate(lifted, variant.id)) {
216
221
  return res.status(400).json({
217
222
  error: 'This item has no day to choose.'
218
223
  });
219
224
  }
220
225
  const storeDay = await readStoreDay(hostRef, {
221
- org: (_ref5 = ownerOrg == null ? void 0 : ownerOrg.org) != null ? _ref5 : null,
226
+ org: (_ref8 = ownerOrg == null ? void 0 : ownerOrg.org) != null ? _ref8 : null,
222
227
  host: (_hostSnapshot_data = hostSnapshot.data()) != null ? _hostSnapshot_data : null
223
228
  });
224
229
  const problem = CommerceModel.checkInUseDayProblem(useDayKey, storeDay.todayKey);
@@ -256,6 +261,43 @@ export const checkoutHandler = async (req, res)=>{
256
261
  error: planRequiredMessage('Subscription products', 'storefrontSubscriptions')
257
262
  });
258
263
  }
264
+ // CARD READER HARDWARE ON THE PLATFORM'S OWN STORE (AGL-4038), as the
265
+ // cart reads it: the terms of sale and business use ticked, the online
266
+ // order limits held, never by subscription, taxed as goods, and the
267
+ // acceptance carried for the order. Before anything is held or claimed.
268
+ const hardware = sellerStoreHardwareCheckout({
269
+ hostId,
270
+ orgId: String((_ref1 = (_ref2 = ownerOrg == null ? void 0 : (_ownerOrg_org1 = ownerOrg.org) == null ? void 0 : _ownerOrg_org1.id) != null ? _ref2 : ownerOrg == null ? void 0 : ownerOrg.orgId) != null ? _ref1 : ''),
271
+ lines: [
272
+ {
273
+ productId: String(productId),
274
+ quantity
275
+ }
276
+ ],
277
+ products: new Map([
278
+ [
279
+ String(productId),
280
+ lifted
281
+ ]
282
+ ]),
283
+ hardwareTerms: body.hardwareTerms,
284
+ subscription: isSubscription
285
+ });
286
+ if (hardware.refusal) {
287
+ const _hardware_refusal = hardware.refusal, { status: refusedStatus } = _hardware_refusal, refusal = _object_without_properties_loose(_hardware_refusal, [
288
+ "status"
289
+ ]);
290
+ return res.status(refusedStatus).json(refusal);
291
+ }
292
+ const hardwareParams = hardware.hardware ? _extends({
293
+ 'line_items[0][price_data][product_data][tax_code]': POS_HARDWARE_TAX_CODE
294
+ }, Object.fromEntries(Object.entries(posHardwareTermsMetadata({
295
+ ip: (_readClientIp = readClientIp(req.headers)) != null ? _readClientIp : null,
296
+ userAgent: String((_ref3 = (_req_headers = req.headers) == null ? void 0 : _req_headers['user-agent']) != null ? _ref3 : '') || null
297
+ })).map(([key, value])=>[
298
+ `metadata[${key}]`,
299
+ value
300
+ ]))) : {};
259
301
  // ALREADY SUBSCRIBED? (AGL-1849)
260
302
  //
261
303
  // The idempotency key closes the RETRY shape: one attempt, one key, one
@@ -393,10 +435,10 @@ export const checkoutHandler = async (req, res)=>{
393
435
  // hub did not already answer for this code.
394
436
  let appliedCoupon = '';
395
437
  if (couponCode && !resolvedDiscount) {
396
- var _ref6;
438
+ var _ref9;
397
439
  const couponSnapshot = await hostRef.collection('coupons').doc(couponCode).get();
398
440
  const coupon = couponSnapshot.data();
399
- const percentOff = Number((_ref6 = coupon == null ? void 0 : coupon.percentOff) != null ? _ref6 : 0);
441
+ const percentOff = Number((_ref9 = coupon == null ? void 0 : coupon.percentOff) != null ? _ref9 : 0);
400
442
  const expired = (coupon == null ? void 0 : coupon.expiresAtMs) != null && Number(coupon.expiresAtMs) < Date.now();
401
443
  // A PRE-FILTER, no longer the enforcement (AGL-2453). It answers early so
402
444
  // an obviously spent code 400s before a claim is minted, and it counts
@@ -461,9 +503,9 @@ export const checkoutHandler = async (req, res)=>{
461
503
  hasPhysicalLine: true,
462
504
  store: await readLocalFulfillmentStore({
463
505
  hostRef,
464
- storeSettings: (_ref1 = storeSettings.data == null ? void 0 : storeSettings.data.call(storeSettings)) != null ? _ref1 : null,
506
+ storeSettings: (_ref4 = storeSettings.data == null ? void 0 : storeSettings.data.call(storeSettings)) != null ? _ref4 : null,
465
507
  org: ownerOrg.org,
466
- host: (_ref2 = hostSnapshot.data == null ? void 0 : hostSnapshot.data.call(hostSnapshot)) != null ? _ref2 : null
508
+ host: (_ref5 = hostSnapshot.data == null ? void 0 : hostSnapshot.data.call(hostSnapshot)) != null ? _ref5 : null
467
509
  })
468
510
  }) : {
469
511
  kind: 'shipping'
@@ -582,7 +624,7 @@ export const checkoutHandler = async (req, res)=>{
582
624
  const claimed = await claimAttempt(firestore, {
583
625
  kind: 'commerce-checkout',
584
626
  scopeId: hostId,
585
- orgId: String((_ref3 = ownerOrg == null ? void 0 : (_ownerOrg_org1 = ownerOrg.org) == null ? void 0 : _ownerOrg_org1.id) != null ? _ref3 : ''),
627
+ orgId: String((_ref6 = ownerOrg == null ? void 0 : (_ownerOrg_org2 = ownerOrg.org) == null ? void 0 : _ownerOrg_org2.id) != null ? _ref6 : ''),
586
628
  key: idempotencyKey,
587
629
  busyMessage: 'This checkout is already being processed'
588
630
  });
@@ -693,13 +735,13 @@ export const checkoutHandler = async (req, res)=>{
693
735
  // paths quietly diverge. Behaviour here is unchanged.
694
736
  let recurringTaxRateId = '';
695
737
  if (isSubscription && taxCents > 0) {
696
- var _ref7;
697
- recurringTaxRateId = (_ref7 = await resolveManualTaxRateId({
738
+ var _ref10;
739
+ recurringTaxRateId = (_ref10 = await resolveManualTaxRateId({
698
740
  hostRef,
699
741
  taxPct,
700
742
  taxLabel,
701
743
  headers: stripeKeyHeader('tax-rate')
702
- })) != null ? _ref7 : '';
744
+ })) != null ? _ref10 : '';
703
745
  if (!recurringTaxRateId) {
704
746
  // Nothing was sold — hand the key back so the same button works
705
747
  // once Stripe does (AGL-1697).
@@ -792,10 +834,10 @@ export const checkoutHandler = async (req, res)=>{
792
834
  // The unnamed `Local pickup` rate gives way to the store's pickup
793
835
  // locations, which the shopper chooses before checkout (AGL-3624).
794
836
  if (localPlan.kind === 'shipping' && (shippingSettings == null ? void 0 : shippingSettings.localPickup) && shippingPlan.options.some((option)=>option.rateId === CommerceModel.LOCAL_PICKUP_RATE_ID)) {
795
- var _ref8;
837
+ var _ref11;
796
838
  const { pickupLocations } = await readLocalFulfillmentStore({
797
839
  hostRef,
798
- storeSettings: (_ref8 = storeSettings.data == null ? void 0 : storeSettings.data.call(storeSettings)) != null ? _ref8 : null,
840
+ storeSettings: (_ref11 = storeSettings.data == null ? void 0 : storeSettings.data.call(storeSettings)) != null ? _ref11 : null,
799
841
  host: null
800
842
  });
801
843
  if (pickupLocations.length) {
@@ -991,7 +1033,7 @@ export const checkoutHandler = async (req, res)=>{
991
1033
  } : {}, {
992
1034
  'metadata[quantity]': String(quantity),
993
1035
  'metadata[feeCents]': String(feeCents)
994
- }, shippingPlan.quotedPostalCode ? {
1036
+ }, hardwareParams, shippingPlan.quotedPostalCode ? {
995
1037
  'metadata[shippingQuotePostalCode]': shippingPlan.quotedPostalCode
996
1038
  } : {}, useStripeTax && !isSubscription ? {
997
1039
  'metadata[transferCents]': String(CommerceModel.platformLiableTransferCents({
@@ -1077,7 +1119,7 @@ export const checkoutHandler = async (req, res)=>{
1077
1119
  //
1078
1120
  // Off unless the flag is on for this org AND a publishable key exists, so
1079
1121
  // the default remains the redirect — see `resolveNativeCheckoutMode`.
1080
- const nativeMode = await resolveNativeCheckoutMode(String((_ref4 = ownerOrg == null ? void 0 : (_ownerOrg_org2 = ownerOrg.org) == null ? void 0 : _ownerOrg_org2.id) != null ? _ref4 : ''));
1122
+ const nativeMode = await resolveNativeCheckoutMode(String((_ref7 = ownerOrg == null ? void 0 : (_ownerOrg_org3 = ownerOrg.org) == null ? void 0 : _ownerOrg_org3.id) != null ? _ref7 : ''));
1081
1123
  if (nativeMode.native) {
1082
1124
  applyNativeCheckoutParams(params, `${backUrl}${separator}order=success&session_id={CHECKOUT_SESSION_ID}`);
1083
1125
  }