@aglyn/plugins-commerce 1.14.0 → 1.15.1

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 (214) 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 +38 -9
  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 +282 -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 +32 -8
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/components/quote-page-body.js +7 -3
  51. package/src/lib/components/quote-page-body.js.map +1 -1
  52. package/src/lib/components/related-products.js +6 -3
  53. package/src/lib/components/related-products.js.map +1 -1
  54. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  55. package/src/lib/components/storefront-payment-element.js +11 -7
  56. package/src/lib/components/storefront-payment-element.js.map +1 -1
  57. package/src/lib/constants/operator-alerts.d.ts +1 -1
  58. package/src/lib/constants/operator-alerts.js +4 -4
  59. package/src/lib/constants/operator-alerts.js.map +1 -1
  60. package/src/lib/model/commerce-orders.d.ts +6 -2
  61. package/src/lib/model/commerce-orders.js.map +1 -1
  62. package/src/lib/model/commerce-payment-methods.d.ts +27 -16
  63. package/src/lib/model/commerce-payment-methods.js +11 -83
  64. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  65. package/src/lib/model/commerce.d.ts +6 -0
  66. package/src/lib/model/commerce.js.map +1 -1
  67. package/src/lib/model/index.d.ts +1 -0
  68. package/src/lib/model/index.js +1 -0
  69. package/src/lib/model/index.js.map +1 -1
  70. package/src/lib/model/paid-media.d.ts +8 -0
  71. package/src/lib/model/paid-media.js +13 -0
  72. package/src/lib/model/paid-media.js.map +1 -1
  73. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  74. package/src/lib/model/pos-hardware-in-person.js +52 -20
  75. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  76. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  77. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  78. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  79. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  80. package/src/lib/model/pos-hardware-terms.js +68 -3
  81. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  82. package/src/lib/model/pos-hardware.d.ts +101 -15
  83. package/src/lib/model/pos-hardware.js +128 -18
  84. package/src/lib/model/pos-hardware.js.map +1 -1
  85. package/src/lib/model/pos-reader-splash.js +2 -2
  86. package/src/lib/model/pos-reader-splash.js.map +1 -1
  87. package/src/lib/model/product-write.d.ts +3 -0
  88. package/src/lib/model/subscription-view.d.ts +90 -0
  89. package/src/lib/model/subscription-view.js +176 -0
  90. package/src/lib/model/subscription-view.js.map +1 -0
  91. package/src/lib/server/billing-webhook.d.ts +27 -6
  92. package/src/lib/server/billing-webhook.js +271 -81
  93. package/src/lib/server/billing-webhook.js.map +1 -1
  94. package/src/lib/server/cancel-order.js +4 -3
  95. package/src/lib/server/cancel-order.js.map +1 -1
  96. package/src/lib/server/cart-checkout.js +105 -23
  97. package/src/lib/server/cart-checkout.js.map +1 -1
  98. package/src/lib/server/cart.js +15 -3
  99. package/src/lib/server/cart.js.map +1 -1
  100. package/src/lib/server/catalog.js +58 -22
  101. package/src/lib/server/catalog.js.map +1 -1
  102. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  103. package/src/lib/server/checkout-session-expiry.js +19 -5
  104. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  105. package/src/lib/server/checkout-status.js +4 -3
  106. package/src/lib/server/checkout-status.js.map +1 -1
  107. package/src/lib/server/checkout.js +98 -26
  108. package/src/lib/server/checkout.js.map +1 -1
  109. package/src/lib/server/connect.js +42 -11
  110. package/src/lib/server/connect.js.map +1 -1
  111. package/src/lib/server/draft-order.js +36 -7
  112. package/src/lib/server/draft-order.js.map +1 -1
  113. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  114. package/src/lib/server/manual-tax-rate.js +10 -6
  115. package/src/lib/server/manual-tax-rate.js.map +1 -1
  116. package/src/lib/server/membership-account.d.ts +22 -0
  117. package/src/lib/server/membership-account.js +52 -8
  118. package/src/lib/server/membership-account.js.map +1 -1
  119. package/src/lib/server/native-checkout.d.ts +10 -3
  120. package/src/lib/server/native-checkout.js +8 -3
  121. package/src/lib/server/native-checkout.js.map +1 -1
  122. package/src/lib/server/payment-method-domains.d.ts +50 -9
  123. package/src/lib/server/payment-method-domains.js +150 -51
  124. package/src/lib/server/payment-method-domains.js.map +1 -1
  125. package/src/lib/server/payment-methods.js +3 -2
  126. package/src/lib/server/payment-methods.js.map +1 -1
  127. package/src/lib/server/pos-auth.d.ts +3 -3
  128. package/src/lib/server/pos-auth.js +3 -3
  129. package/src/lib/server/pos-auth.js.map +1 -1
  130. package/src/lib/server/pos-cellular-billing.js +1 -1
  131. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  132. package/src/lib/server/pos-cellular-notify.js +1 -1
  133. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  134. package/src/lib/server/pos-cellular.js +1 -1
  135. package/src/lib/server/pos-cellular.js.map +1 -1
  136. package/src/lib/server/pos-hardware-admin.js +86 -13
  137. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  138. package/src/lib/server/pos-hardware-attach.js +5 -5
  139. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  140. package/src/lib/server/pos-hardware-cancel.js +65 -0
  141. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  142. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  143. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  144. package/src/lib/server/pos-hardware-closure.js +5 -8
  145. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  146. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  147. package/src/lib/server/pos-hardware-in-person.js +72 -17
  148. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  149. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  150. package/src/lib/server/pos-hardware-notify.js +30 -5
  151. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  152. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  153. package/src/lib/server/pos-hardware-readers.js +206 -85
  154. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  155. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  156. package/src/lib/server/pos-hardware-returns.js +39 -7
  157. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  158. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  159. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  160. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  161. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  162. package/src/lib/server/pos-hardware-sale.js +1 -0
  163. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  164. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  165. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  166. package/src/lib/server/pos-hardware-webhook.js +16 -3
  167. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  168. package/src/lib/server/pos-hardware.d.ts +14 -3
  169. package/src/lib/server/pos-hardware.js +83 -18
  170. package/src/lib/server/pos-hardware.js.map +1 -1
  171. package/src/lib/server/pos-ops-routes.js +2 -10
  172. package/src/lib/server/pos-ops-routes.js.map +1 -1
  173. package/src/lib/server/pos-order.js +5 -1
  174. package/src/lib/server/pos-order.js.map +1 -1
  175. package/src/lib/server/pos-stripe.d.ts +7 -7
  176. package/src/lib/server/pos-stripe.js +15 -13
  177. package/src/lib/server/pos-stripe.js.map +1 -1
  178. package/src/lib/server/pos-terminal.js +11 -3
  179. package/src/lib/server/pos-terminal.js.map +1 -1
  180. package/src/lib/server/quote-pay.d.ts +23 -1
  181. package/src/lib/server/quote-pay.js +111 -27
  182. package/src/lib/server/quote-pay.js.map +1 -1
  183. package/src/lib/server/quote.d.ts +2 -1
  184. package/src/lib/server/quote.js +12 -11
  185. package/src/lib/server/quote.js.map +1 -1
  186. package/src/lib/server/refund.js +13 -6
  187. package/src/lib/server/refund.js.map +1 -1
  188. package/src/lib/server/related.js +10 -3
  189. package/src/lib/server/related.js.map +1 -1
  190. package/src/lib/server/reserve.js +19 -6
  191. package/src/lib/server/reserve.js.map +1 -1
  192. package/src/lib/server/revenue-source.d.ts +6 -0
  193. package/src/lib/server/revenue-source.js +25 -9
  194. package/src/lib/server/revenue-source.js.map +1 -1
  195. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  196. package/src/lib/server/seller-stripe-account.js +99 -0
  197. package/src/lib/server/seller-stripe-account.js.map +1 -0
  198. package/src/lib/server/storefront-tax-record.js +6 -1
  199. package/src/lib/server/storefront-tax-record.js.map +1 -1
  200. package/src/lib/server/storefront-tax.d.ts +33 -2
  201. package/src/lib/server/storefront-tax.js +39 -3
  202. package/src/lib/server/storefront-tax.js.map +1 -1
  203. package/src/lib/server/stream.d.ts +2 -0
  204. package/src/lib/server/stream.js +22 -2
  205. package/src/lib/server/stream.js.map +1 -1
  206. package/src/lib/server/stripe-refund.d.ts +15 -0
  207. package/src/lib/server/stripe-refund.js +54 -26
  208. package/src/lib/server/stripe-refund.js.map +1 -1
  209. package/src/lib/server/subscription-portal.js +8 -3
  210. package/src/lib/server/subscription-portal.js.map +1 -1
  211. package/src/lib/server/tax-return-source.js +5 -1
  212. package/src/lib/server/tax-return-source.js.map +1 -1
  213. package/src/lib/server.js +2 -2
  214. package/src/lib/server.js.map +1 -1
@@ -27,19 +27,28 @@ export interface PosHardwareRegisterShare {
27
27
  /** The hardware lines at the prices rung. */
28
28
  itemsCents: number;
29
29
  discountCents: number;
30
- /** What tax was charged on: the items less the discount. */
30
+ /** The hardware's share of an online order's shipping; 0 at a register. */
31
+ shippingCents: number;
32
+ /** What tax was charged on: the items less the discount, plus the shipping share. */
31
33
  taxableCents: number;
32
34
  taxCents: number;
33
35
  totalCents: number;
34
36
  }
35
37
  /**
36
38
  * The hardware's share of a register sale, or `null` when the sale sold no
37
- * hardware. `discountCents` and `taxCents` are the SALE's.
39
+ * hardware. `discountCents`, `taxCents` and `shippingCents` are the SALE's.
40
+ *
41
+ * An online order of the platform's own store (AGL-4038) also charged
42
+ * shipping: the hardware takes its share of it by the same proportion as the
43
+ * discount, and the tax falls on the items less the discount plus the
44
+ * shipping, in proportion, as it was charged on the whole order. A register
45
+ * sale has no shipping, so its share is exactly as before.
38
46
  */
39
47
  export declare function posHardwareRegisterShare(input: {
40
48
  lines: readonly PosHardwareRegisterLine[];
41
49
  discountCents: number;
42
50
  taxCents: number;
51
+ shippingCents?: number;
43
52
  }): PosHardwareRegisterShare | null;
44
53
  /**
45
54
  * One unit per reader sold, in line order; accessories carry no serial and
@@ -85,6 +94,18 @@ export interface InPersonRegisterSale {
85
94
  * the register sale; absent, the receipt-and-sign notice at the sale.
86
95
  */
87
96
  termsAcceptance?: unknown;
97
+ /**
98
+ * Set for an ONLINE order of the platform's own store (AGL-4038): where it
99
+ * ships and who to. The order is then paid, not handed over: it waits to be
100
+ * prepared and shipped like one from the Hardware card, its tax is sourced
101
+ * where it ships, and the terms are the ones ticked at checkout (never the
102
+ * booth's notice).
103
+ */
104
+ storefront?: {
105
+ name: string | null;
106
+ phone: string | null;
107
+ address: unknown;
108
+ };
88
109
  }
89
110
  /**
90
111
  * The hardware order a register sale becomes. In-person hardware is handed
@@ -35,7 +35,8 @@
35
35
  * offline sale, a buyer with no account yet or no workspace yet — is
36
36
  * PENDING: kept in the selling workspace's own orders, on its "To attach"
37
37
  * list, until it is attached.
38
- *=========================================*/ import { POS_HARDWARE_CURRENCY, POS_HARDWARE_IN_PERSON_SHIPPING_LABEL, posHardwareBuyerAddress, posHardwareSku } from "./pos-hardware.js";
38
+ *=========================================*/ import { _ as _extends } from "@swc/helpers/_/_extends";
39
+ import { POS_HARDWARE_CURRENCY, POS_HARDWARE_IN_PERSON_SHIPPING_LABEL, POS_HARDWARE_SHIPPING_LABELS, posHardwareBuyerAddress, posHardwareSku } from "./pos-hardware.js";
39
40
  import { posHardwareTermsAcceptance, posHardwareTermsAcceptanceOf } from "./pos-hardware-terms.js";
40
41
  const whole = (value)=>{
41
42
  const number = Number(value);
@@ -48,7 +49,13 @@ const whole = (value)=>{
48
49
  }
49
50
  /**
50
51
  * The hardware's share of a register sale, or `null` when the sale sold no
51
- * hardware. `discountCents` and `taxCents` are the SALE's.
52
+ * hardware. `discountCents`, `taxCents` and `shippingCents` are the SALE's.
53
+ *
54
+ * An online order of the platform's own store (AGL-4038) also charged
55
+ * shipping: the hardware takes its share of it by the same proportion as the
56
+ * discount, and the tax falls on the items less the discount plus the
57
+ * shipping, in proportion, as it was charged on the whole order. A register
58
+ * sale has no shipping, so its share is exactly as before.
52
59
  */ export function posHardwareRegisterShare(input) {
53
60
  const lines = [];
54
61
  let saleItemsCents = 0;
@@ -70,12 +77,15 @@ const whole = (value)=>{
70
77
  const itemsCents = lines.reduce((sum, line)=>sum + line.lineCents, 0);
71
78
  const saleDiscountCents = Math.min(whole(input.discountCents), saleItemsCents);
72
79
  const discountCents = shareOf(saleDiscountCents, itemsCents, saleItemsCents);
73
- const taxableCents = Math.max(0, itemsCents - discountCents);
74
- const taxCents = shareOf(whole(input.taxCents), taxableCents, saleItemsCents - saleDiscountCents);
80
+ const saleShippingCents = whole(input.shippingCents);
81
+ const shippingCents = shareOf(saleShippingCents, itemsCents, saleItemsCents);
82
+ const taxableCents = Math.max(0, itemsCents - discountCents) + shippingCents;
83
+ const taxCents = shareOf(whole(input.taxCents), taxableCents, saleItemsCents - saleDiscountCents + saleShippingCents);
75
84
  return {
76
85
  lines,
77
86
  itemsCents,
78
87
  discountCents,
88
+ shippingCents,
79
89
  taxableCents,
80
90
  taxCents,
81
91
  totalCents: taxableCents + taxCents
@@ -135,12 +145,20 @@ const whole = (value)=>{
135
145
  * hardware's share of what the register taxed — so the platform's return
136
146
  * reads a stated base, never an inferred one.
137
147
  */ export function inPersonPosHardwareOrder(sale) {
138
- var _sale_serials, _ref, _attachment_hostId, _attachment_email, _sale_currency, _posHardwareTermsAcceptanceOf;
139
- var _sale_taxRegion;
148
+ var _sale_serials, _ref, _ref1, _posHardwareTermsAcceptanceOf, _attachment_hostId, _attachment_email, _ref2, _ref3, _sale_currency;
149
+ var _sale_storefront, _shipTo_state, _sale_storefront1, _sale_storefront2;
140
150
  const attachment = posHardwareAttachmentOf(sale.buyer);
141
151
  const attached = attachment.state === 'attached';
142
152
  const units = posHardwareUnits(sale.share.lines, (_sale_serials = sale.serials) != null ? _sale_serials : []);
143
- const state = (_ref = (_sale_taxRegion = sale.taxRegion) == null ? void 0 : _sale_taxRegion.state) != null ? _ref : null;
153
+ const online = Boolean(sale.storefront);
154
+ const shipTo = online ? posHardwareBuyerAddress((_sale_storefront = sale.storefront) == null ? void 0 : _sale_storefront.address) : null;
155
+ // Online, sourced where it ships; at the counter, where the store is.
156
+ const taxRegion = online ? shipTo ? {
157
+ country: shipTo.country,
158
+ state: (_ref = (_shipTo_state = shipTo.state) == null ? void 0 : _shipTo_state.toUpperCase()) != null ? _ref : null,
159
+ postalCode: shipTo.postalCode
160
+ } : null : sale.taxRegion;
161
+ const state = (_ref1 = taxRegion == null ? void 0 : taxRegion.state) != null ? _ref1 : null;
144
162
  const taxLines = sale.share.taxCents > 0 ? [
145
163
  {
146
164
  amountCents: sale.share.taxCents,
@@ -152,7 +170,14 @@ const whole = (value)=>{
152
170
  percentage: sale.ratePct
153
171
  }
154
172
  ] : [];
155
- return {
173
+ const acceptance = (_posHardwareTermsAcceptanceOf = posHardwareTermsAcceptanceOf(sale.termsAcceptance)) != null ? _posHardwareTermsAcceptanceOf : // Online, the checkout refuses without an acceptance, so there is no
174
+ // notice to fall back to; at the counter, paying under the receipt's and
175
+ // the booth sign's notice is agreeing (Terms 4.28).
176
+ online ? null : posHardwareTermsAcceptance({
177
+ method: 'notice',
178
+ atMs: sale.paidAtMs
179
+ });
180
+ return _extends({
156
181
  orgId: attached ? attachment.orgId : sale.sellerOrgId,
157
182
  // The buyer's store once they chose one; until then the workspace's,
158
183
  // and the buyer picks the store when they set the reader up.
@@ -162,7 +187,14 @@ const whole = (value)=>{
162
187
  lines: sale.share.lines,
163
188
  subtotalCents: sale.share.itemsCents,
164
189
  discountCents: sale.share.discountCents,
165
- shipping: {
190
+ shipping: online ? {
191
+ method: 'standard',
192
+ label: POS_HARDWARE_SHIPPING_LABELS.standard,
193
+ cents: sale.share.shippingCents,
194
+ name: (_ref2 = (_sale_storefront1 = sale.storefront) == null ? void 0 : _sale_storefront1.name) != null ? _ref2 : null,
195
+ phone: (_ref3 = (_sale_storefront2 = sale.storefront) == null ? void 0 : _sale_storefront2.phone) != null ? _ref3 : null,
196
+ address: shipTo
197
+ } : {
166
198
  method: 'in_person',
167
199
  label: POS_HARDWARE_IN_PERSON_SHIPPING_LABEL,
168
200
  cents: 0,
@@ -181,19 +213,19 @@ const whole = (value)=>{
181
213
  stripePaymentIntentId: null,
182
214
  stripeHardwareOrderId: null,
183
215
  tracking: null,
184
- status: 'delivered',
216
+ // Handed over at the sale, or paid online and waiting to be prepared.
217
+ status: online ? 'paid' : 'delivered',
185
218
  livemode: sale.livemode,
186
219
  createdAtMs: sale.paidAtMs,
187
220
  updatedAtMs: sale.paidAtMs,
188
- paidAtMs: sale.paidAtMs,
189
- deliveredAtMs: sale.paidAtMs,
190
- source: 'in_person',
191
- // Accepted on the tablet or the display before paying, or else agreed by
192
- // paying under the receipt's and the booth sign's notice (Terms 4.28).
193
- termsAcceptance: (_posHardwareTermsAcceptanceOf = posHardwareTermsAcceptanceOf(sale.termsAcceptance)) != null ? _posHardwareTermsAcceptanceOf : posHardwareTermsAcceptance({
194
- method: 'notice',
195
- atMs: sale.paidAtMs
196
- }),
221
+ paidAtMs: sale.paidAtMs
222
+ }, online ? {} : {
223
+ deliveredAtMs: sale.paidAtMs
224
+ }, {
225
+ source: online ? 'storefront' : 'in_person'
226
+ }, acceptance ? {
227
+ termsAcceptance: acceptance
228
+ } : {}, {
197
229
  posSale: {
198
230
  hostId: sale.sellerHostId,
199
231
  orgId: sale.sellerOrgId,
@@ -218,7 +250,7 @@ const whole = (value)=>{
218
250
  serialNumbers: units.flatMap((unit)=>unit.serialNumber ? [
219
251
  unit.serialNumber
220
252
  ] : [])
221
- };
253
+ });
222
254
  }
223
255
 
224
256
  //# sourceMappingURL=pos-hardware-in-person.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/pos-hardware-in-person.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\n/*==========================================\n * A REGISTER SALE OF HARDWARE BECOMES A HARDWARE ORDER (AGL-4038).\n *\n * The platform's own store sells readers at its register like anything else\n * it sells: its prices, its promotions, its tax rate, its tenders, its\n * account. What follows the sale is a hardware order for the buyer's\n * workspace, built here from the register sale as it was paid — pure, so the\n * money is specced without Firestore.\n *\n * THE HARDWARE'S SHARE OF THE SALE. A sale may hold a reader and a T-shirt.\n * The order takes the hardware lines at the prices they were rung at, and\n * the sale's discount and tax fall on them in proportion — the discount by\n * the lines' share of the items, the tax by their share of what was taxed\n * (the register taxes the whole basket, less its discount, at one rate).\n * Each share is rounded half up to the cent in integer math, and a sale of\n * hardware alone takes the whole discount and the whole tax, to the cent.\n *\n * WHO IT BELONGS TO. A sale a register user attached to an account and a\n * workspace is that workspace's order. Every other one — a kiosk sale, an\n * offline sale, a buyer with no account yet or no workspace yet — is\n * PENDING: kept in the selling workspace's own orders, on its \"To attach\"\n * list, until it is attached.\n *=========================================*/\n\nimport type { OrderHardwareBuyer } from './commerce-orders'\nimport {\n POS_HARDWARE_CURRENCY,\n POS_HARDWARE_IN_PERSON_SHIPPING_LABEL,\n posHardwareBuyerAddress,\n posHardwareSku,\n type PosHardwareAttachment,\n type PosHardwareLine,\n type PosHardwareOrder,\n type PosHardwareSkuId,\n type PosHardwareTaxLine,\n type PosHardwareTaxRegion,\n type PosHardwareUnit,\n} from './pos-hardware'\nimport { posHardwareTermsAcceptance, posHardwareTermsAcceptanceOf } from './pos-hardware-terms'\n\n/** One register line, with the hardware item its product is, when it is one. */\nexport interface PosHardwareRegisterLine {\n sku: PosHardwareSkuId | null\n quantity: number\n unitAmountCents: number\n}\n\nexport interface PosHardwareRegisterShare {\n lines: PosHardwareLine[]\n /** The hardware lines at the prices rung. */\n itemsCents: number\n discountCents: number\n /** What tax was charged on: the items less the discount. */\n taxableCents: number\n taxCents: number\n totalCents: number\n}\n\nconst whole = (value: unknown): number => {\n const number = Number(value)\n return Number.isSafeInteger(number) && number > 0 ? number : 0\n}\n\n/** `amount × part / of`, rounded half up, in integer math; 0 when `of` is 0. */\nfunction shareOf(amount: number, part: number, of: number): number {\n if (of <= 0 || amount <= 0 || part <= 0) return 0\n if (part >= of) return amount\n return Math.floor((amount * part * 2 + of) / (of * 2))\n}\n\n/**\n * The hardware's share of a register sale, or `null` when the sale sold no\n * hardware. `discountCents` and `taxCents` are the SALE's.\n */\nexport function posHardwareRegisterShare(input: {\n lines: readonly PosHardwareRegisterLine[]\n discountCents: number\n taxCents: number\n}): PosHardwareRegisterShare | null {\n const lines: PosHardwareLine[] = []\n let saleItemsCents = 0\n for (const line of input.lines) {\n const quantity = whole(line.quantity)\n const unitCents = whole(line.unitAmountCents)\n saleItemsCents += quantity * unitCents\n const sku = line.sku ? posHardwareSku(line.sku) : null\n if (!sku || !quantity) continue\n lines.push({ sku: sku.id, name: sku.displayName, quantity, unitCents, lineCents: quantity * unitCents })\n }\n if (!lines.length) return null\n const itemsCents = lines.reduce((sum, line) => sum + line.lineCents, 0)\n const saleDiscountCents = Math.min(whole(input.discountCents), saleItemsCents)\n const discountCents = shareOf(saleDiscountCents, itemsCents, saleItemsCents)\n const taxableCents = Math.max(0, itemsCents - discountCents)\n const taxCents = shareOf(whole(input.taxCents), taxableCents, saleItemsCents - saleDiscountCents)\n return { lines, itemsCents, discountCents, taxableCents, taxCents, totalCents: taxableCents + taxCents }\n}\n\n/**\n * One unit per reader sold, in line order; accessories carry no serial and\n * have no unit. `serials` are the serial numbers taken at the sale, in the\n * same order, already normalized; a reader with none waits for one.\n */\nexport function posHardwareUnits(\n lines: readonly PosHardwareLine[],\n serials: readonly string[] = [],\n): PosHardwareUnit[] {\n const units: PosHardwareUnit[] = []\n for (const line of lines) {\n if (posHardwareSku(line.sku)?.kind !== 'reader') continue\n for (let index = 0; index < line.quantity; index += 1) {\n units.push({\n sku: line.sku,\n serialNumber: serials[units.length] || null,\n readerId: null,\n hostId: null,\n registeredAtMs: null,\n })\n }\n }\n return units\n}\n\n/**\n * Whose the order is: the workspace the register attached, or pending. A\n * buyer with an account and a workspace is attached; one with only an\n * account or only an address is pending until they have a workspace.\n */\nexport function posHardwareAttachmentOf(buyer: OrderHardwareBuyer | null | undefined): PosHardwareAttachment {\n const text = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim() : null)\n const uid = text(buyer?.uid)\n const orgId = text(buyer?.orgId)\n const attached = Boolean(uid && orgId)\n return {\n state: attached ? 'attached' : 'pending',\n email: text(buyer?.email)?.toLowerCase() ?? null,\n uid,\n orgId: attached ? orgId : null,\n hostId: attached ? text(buyer?.hostId) : null,\n attachedBy: text(buyer?.attachedBy),\n attachedAtMs: attached && Number.isFinite(buyer?.attachedAtMs) ? Number(buyer?.attachedAtMs) : null,\n // The reseller's records of who bought it (AGL-4038), when known.\n name: text(buyer?.name)?.slice(0, 200) ?? null,\n address: posHardwareBuyerAddress(buyer?.address),\n }\n}\n\n/** The register sale, as the builder reads it. */\nexport interface InPersonRegisterSale {\n sellerHostId: string\n sellerOrgId: string\n registerOrderId: string\n number: number | null\n registerId: string | null\n kiosk: boolean\n offline: boolean\n share: PosHardwareRegisterShare\n /** When the sale was paid: the order's own stamp. */\n paidAtMs: number\n /** The tenders that paid it, as its payments name them. */\n tenders: string[]\n paymentLinkSessionId: string | null\n /** The address the receipt went to, kept for staff when nobody is attached. */\n receiptEmail: string | null\n buyer: OrderHardwareBuyer | null | undefined\n /** Serial numbers taken at the sale, normalized, in reader order. */\n serials?: readonly string[]\n /** Where the store taxes from: its own address's region. */\n taxRegion: PosHardwareTaxRegion | null\n /** The store's rate, in percent, when it charged one. */\n ratePct: number | null\n stripeAccountId: string | null\n livemode: boolean\n currency?: string\n /**\n * How the buyer agreed to the terms of sale before paying (AGL-4038), from\n * the register sale; absent, the receipt-and-sign notice at the sale.\n */\n termsAcceptance?: unknown\n}\n\n/**\n * The hardware order a register sale becomes. In-person hardware is handed\n * over at the sale, so the order starts at Delivered, and moves to Set up\n * once its readers are registered.\n *\n * The tax line states the base the store's rate was applied to — the\n * hardware's share of what the register taxed — so the platform's return\n * reads a stated base, never an inferred one.\n */\nexport function inPersonPosHardwareOrder(sale: InPersonRegisterSale): PosHardwareOrder {\n const attachment = posHardwareAttachmentOf(sale.buyer)\n const attached = attachment.state === 'attached'\n const units = posHardwareUnits(sale.share.lines, sale.serials ?? [])\n const state = sale.taxRegion?.state ?? null\n const taxLines: PosHardwareTaxLine[] =\n sale.share.taxCents > 0\n ? [\n {\n amountCents: sale.share.taxCents,\n taxabilityReason: null,\n taxRateId: null,\n taxableAmountCents: sale.share.taxableCents,\n jurisdiction: state,\n rateState: state,\n percentage: sale.ratePct,\n },\n ]\n : []\n return {\n orgId: attached ? (attachment.orgId as string) : sale.sellerOrgId,\n // The buyer's store once they chose one; until then the workspace's,\n // and the buyer picks the store when they set the reader up.\n hostId: attached ? (attachment.hostId ?? '') : '',\n createdBy: attachment.uid,\n contactEmail: attachment.email ?? sale.receiptEmail,\n lines: sale.share.lines,\n subtotalCents: sale.share.itemsCents,\n discountCents: sale.share.discountCents,\n shipping: {\n method: 'in_person',\n label: POS_HARDWARE_IN_PERSON_SHIPPING_LABEL,\n cents: 0,\n name: null,\n phone: null,\n address: null,\n // Sold at the counter: taxed where the store is, as every sale it rings.\n taxRegion: sale.taxRegion,\n },\n taxCents: sale.share.taxCents,\n totalCents: sale.share.totalCents,\n currency: sale.currency ?? POS_HARDWARE_CURRENCY,\n automaticTax: false,\n taxLines,\n stripeCheckoutSessionId: null,\n stripePaymentIntentId: null,\n stripeHardwareOrderId: null,\n tracking: null,\n status: 'delivered',\n livemode: sale.livemode,\n createdAtMs: sale.paidAtMs,\n updatedAtMs: sale.paidAtMs,\n paidAtMs: sale.paidAtMs,\n deliveredAtMs: sale.paidAtMs,\n source: 'in_person',\n // Accepted on the tablet or the display before paying, or else agreed by\n // paying under the receipt's and the booth sign's notice (Terms 4.28).\n termsAcceptance:\n posHardwareTermsAcceptanceOf(sale.termsAcceptance) ??\n posHardwareTermsAcceptance({ method: 'notice', atMs: sale.paidAtMs }),\n posSale: {\n hostId: sale.sellerHostId,\n orgId: sale.sellerOrgId,\n orderId: sale.registerOrderId,\n number: sale.number,\n registerId: sale.registerId,\n kiosk: sale.kiosk,\n offline: sale.offline,\n paymentLinkSessionId: sale.paymentLinkSessionId,\n },\n paidTo: {\n account: 'seller_store',\n hostId: sale.sellerHostId,\n orgId: sale.sellerOrgId,\n tenders: [...new Set(sale.tenders)],\n stripeAccountId: sale.stripeAccountId,\n },\n attachment,\n units,\n serialNumbers: units.flatMap((unit) => (unit.serialNumber ? [unit.serialNumber] : [])),\n }\n}\n"],"names":["POS_HARDWARE_CURRENCY","POS_HARDWARE_IN_PERSON_SHIPPING_LABEL","posHardwareBuyerAddress","posHardwareSku","posHardwareTermsAcceptance","posHardwareTermsAcceptanceOf","whole","value","number","Number","isSafeInteger","shareOf","amount","part","of","Math","floor","posHardwareRegisterShare","input","lines","saleItemsCents","line","quantity","unitCents","unitAmountCents","sku","push","id","name","displayName","lineCents","length","itemsCents","reduce","sum","saleDiscountCents","min","discountCents","taxableCents","max","taxCents","totalCents","posHardwareUnits","serials","units","kind","index","serialNumber","readerId","hostId","registeredAtMs","posHardwareAttachmentOf","buyer","text","trim","uid","orgId","attached","Boolean","state","email","toLowerCase","attachedBy","attachedAtMs","isFinite","slice","address","inPersonPosHardwareOrder","sale","attachment","share","taxRegion","taxLines","amountCents","taxabilityReason","taxRateId","taxableAmountCents","jurisdiction","rateState","percentage","ratePct","sellerOrgId","createdBy","contactEmail","receiptEmail","subtotalCents","shipping","method","label","cents","phone","currency","automaticTax","stripeCheckoutSessionId","stripePaymentIntentId","stripeHardwareOrderId","tracking","status","livemode","createdAtMs","paidAtMs","updatedAtMs","deliveredAtMs","source","termsAcceptance","atMs","posSale","sellerHostId","orderId","registerOrderId","registerId","kiosk","offline","paymentLinkSessionId","paidTo","account","tenders","Set","stripeAccountId","serialNumbers","flatMap","unit"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;2CAsB2C,GAG3C,SACEA,qBAAqB,EACrBC,qCAAqC,EACrCC,uBAAuB,EACvBC,cAAc,QAQT,oBAAgB;AACvB,SAASC,0BAA0B,EAAEC,4BAA4B,QAAQ,0BAAsB;AAoB/F,MAAMC,QAAQ,CAACC;IACb,MAAMC,SAASC,OAAOF;IACtB,OAAO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,KAAK1E,YAAY,GAAG;gBAAC0E,KAAK1E,YAAY;aAAC,GAAG,EAAE;IACtF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/pos-hardware-in-person.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\n/*==========================================\n * A REGISTER SALE OF HARDWARE BECOMES A HARDWARE ORDER (AGL-4038).\n *\n * The platform's own store sells readers at its register like anything else\n * it sells: its prices, its promotions, its tax rate, its tenders, its\n * account. What follows the sale is a hardware order for the buyer's\n * workspace, built here from the register sale as it was paid — pure, so the\n * money is specced without Firestore.\n *\n * THE HARDWARE'S SHARE OF THE SALE. A sale may hold a reader and a T-shirt.\n * The order takes the hardware lines at the prices they were rung at, and\n * the sale's discount and tax fall on them in proportion — the discount by\n * the lines' share of the items, the tax by their share of what was taxed\n * (the register taxes the whole basket, less its discount, at one rate).\n * Each share is rounded half up to the cent in integer math, and a sale of\n * hardware alone takes the whole discount and the whole tax, to the cent.\n *\n * WHO IT BELONGS TO. A sale a register user attached to an account and a\n * workspace is that workspace's order. Every other one — a kiosk sale, an\n * offline sale, a buyer with no account yet or no workspace yet — is\n * PENDING: kept in the selling workspace's own orders, on its \"To attach\"\n * list, until it is attached.\n *=========================================*/\n\nimport type { OrderHardwareBuyer } from './commerce-orders'\nimport {\n POS_HARDWARE_CURRENCY,\n POS_HARDWARE_IN_PERSON_SHIPPING_LABEL,\n POS_HARDWARE_SHIPPING_LABELS,\n posHardwareBuyerAddress,\n posHardwareSku,\n type PosHardwareAttachment,\n type PosHardwareLine,\n type PosHardwareOrder,\n type PosHardwareSkuId,\n type PosHardwareTaxLine,\n type PosHardwareTaxRegion,\n type PosHardwareUnit,\n} from './pos-hardware'\nimport { posHardwareTermsAcceptance, posHardwareTermsAcceptanceOf } from './pos-hardware-terms'\n\n/** One register line, with the hardware item its product is, when it is one. */\nexport interface PosHardwareRegisterLine {\n sku: PosHardwareSkuId | null\n quantity: number\n unitAmountCents: number\n}\n\nexport interface PosHardwareRegisterShare {\n lines: PosHardwareLine[]\n /** The hardware lines at the prices rung. */\n itemsCents: number\n discountCents: number\n /** The hardware's share of an online order's shipping; 0 at a register. */\n shippingCents: number\n /** What tax was charged on: the items less the discount, plus the shipping share. */\n taxableCents: number\n taxCents: number\n totalCents: number\n}\n\nconst whole = (value: unknown): number => {\n const number = Number(value)\n return Number.isSafeInteger(number) && number > 0 ? number : 0\n}\n\n/** `amount × part / of`, rounded half up, in integer math; 0 when `of` is 0. */\nfunction shareOf(amount: number, part: number, of: number): number {\n if (of <= 0 || amount <= 0 || part <= 0) return 0\n if (part >= of) return amount\n return Math.floor((amount * part * 2 + of) / (of * 2))\n}\n\n/**\n * The hardware's share of a register sale, or `null` when the sale sold no\n * hardware. `discountCents`, `taxCents` and `shippingCents` are the SALE's.\n *\n * An online order of the platform's own store (AGL-4038) also charged\n * shipping: the hardware takes its share of it by the same proportion as the\n * discount, and the tax falls on the items less the discount plus the\n * shipping, in proportion, as it was charged on the whole order. A register\n * sale has no shipping, so its share is exactly as before.\n */\nexport function posHardwareRegisterShare(input: {\n lines: readonly PosHardwareRegisterLine[]\n discountCents: number\n taxCents: number\n shippingCents?: number\n}): PosHardwareRegisterShare | null {\n const lines: PosHardwareLine[] = []\n let saleItemsCents = 0\n for (const line of input.lines) {\n const quantity = whole(line.quantity)\n const unitCents = whole(line.unitAmountCents)\n saleItemsCents += quantity * unitCents\n const sku = line.sku ? posHardwareSku(line.sku) : null\n if (!sku || !quantity) continue\n lines.push({ sku: sku.id, name: sku.displayName, quantity, unitCents, lineCents: quantity * unitCents })\n }\n if (!lines.length) return null\n const itemsCents = lines.reduce((sum, line) => sum + line.lineCents, 0)\n const saleDiscountCents = Math.min(whole(input.discountCents), saleItemsCents)\n const discountCents = shareOf(saleDiscountCents, itemsCents, saleItemsCents)\n const saleShippingCents = whole(input.shippingCents)\n const shippingCents = shareOf(saleShippingCents, itemsCents, saleItemsCents)\n const taxableCents = Math.max(0, itemsCents - discountCents) + shippingCents\n const taxCents = shareOf(whole(input.taxCents), taxableCents, saleItemsCents - saleDiscountCents + saleShippingCents)\n return { lines, itemsCents, discountCents, shippingCents, taxableCents, taxCents, totalCents: taxableCents + taxCents }\n}\n\n/**\n * One unit per reader sold, in line order; accessories carry no serial and\n * have no unit. `serials` are the serial numbers taken at the sale, in the\n * same order, already normalized; a reader with none waits for one.\n */\nexport function posHardwareUnits(\n lines: readonly PosHardwareLine[],\n serials: readonly string[] = [],\n): PosHardwareUnit[] {\n const units: PosHardwareUnit[] = []\n for (const line of lines) {\n if (posHardwareSku(line.sku)?.kind !== 'reader') continue\n for (let index = 0; index < line.quantity; index += 1) {\n units.push({\n sku: line.sku,\n serialNumber: serials[units.length] || null,\n readerId: null,\n hostId: null,\n registeredAtMs: null,\n })\n }\n }\n return units\n}\n\n/**\n * Whose the order is: the workspace the register attached, or pending. A\n * buyer with an account and a workspace is attached; one with only an\n * account or only an address is pending until they have a workspace.\n */\nexport function posHardwareAttachmentOf(buyer: OrderHardwareBuyer | null | undefined): PosHardwareAttachment {\n const text = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim() : null)\n const uid = text(buyer?.uid)\n const orgId = text(buyer?.orgId)\n const attached = Boolean(uid && orgId)\n return {\n state: attached ? 'attached' : 'pending',\n email: text(buyer?.email)?.toLowerCase() ?? null,\n uid,\n orgId: attached ? orgId : null,\n hostId: attached ? text(buyer?.hostId) : null,\n attachedBy: text(buyer?.attachedBy),\n attachedAtMs: attached && Number.isFinite(buyer?.attachedAtMs) ? Number(buyer?.attachedAtMs) : null,\n // The reseller's records of who bought it (AGL-4038), when known.\n name: text(buyer?.name)?.slice(0, 200) ?? null,\n address: posHardwareBuyerAddress(buyer?.address),\n }\n}\n\n/** The register sale, as the builder reads it. */\nexport interface InPersonRegisterSale {\n sellerHostId: string\n sellerOrgId: string\n registerOrderId: string\n number: number | null\n registerId: string | null\n kiosk: boolean\n offline: boolean\n share: PosHardwareRegisterShare\n /** When the sale was paid: the order's own stamp. */\n paidAtMs: number\n /** The tenders that paid it, as its payments name them. */\n tenders: string[]\n paymentLinkSessionId: string | null\n /** The address the receipt went to, kept for staff when nobody is attached. */\n receiptEmail: string | null\n buyer: OrderHardwareBuyer | null | undefined\n /** Serial numbers taken at the sale, normalized, in reader order. */\n serials?: readonly string[]\n /** Where the store taxes from: its own address's region. */\n taxRegion: PosHardwareTaxRegion | null\n /** The store's rate, in percent, when it charged one. */\n ratePct: number | null\n stripeAccountId: string | null\n livemode: boolean\n currency?: string\n /**\n * How the buyer agreed to the terms of sale before paying (AGL-4038), from\n * the register sale; absent, the receipt-and-sign notice at the sale.\n */\n termsAcceptance?: unknown\n /**\n * Set for an ONLINE order of the platform's own store (AGL-4038): where it\n * ships and who to. The order is then paid, not handed over: it waits to be\n * prepared and shipped like one from the Hardware card, its tax is sourced\n * where it ships, and the terms are the ones ticked at checkout (never the\n * booth's notice).\n */\n storefront?: {\n name: string | null\n phone: string | null\n address: unknown\n }\n}\n\n/**\n * The hardware order a register sale becomes. In-person hardware is handed\n * over at the sale, so the order starts at Delivered, and moves to Set up\n * once its readers are registered.\n *\n * The tax line states the base the store's rate was applied to — the\n * hardware's share of what the register taxed — so the platform's return\n * reads a stated base, never an inferred one.\n */\nexport function inPersonPosHardwareOrder(sale: InPersonRegisterSale): PosHardwareOrder {\n const attachment = posHardwareAttachmentOf(sale.buyer)\n const attached = attachment.state === 'attached'\n const units = posHardwareUnits(sale.share.lines, sale.serials ?? [])\n const online = Boolean(sale.storefront)\n const shipTo = online ? posHardwareBuyerAddress(sale.storefront?.address) : null\n // Online, sourced where it ships; at the counter, where the store is.\n const taxRegion: PosHardwareTaxRegion | null = online\n ? shipTo\n ? { country: shipTo.country, state: shipTo.state?.toUpperCase() ?? null, postalCode: shipTo.postalCode }\n : null\n : sale.taxRegion\n const state = taxRegion?.state ?? null\n const taxLines: PosHardwareTaxLine[] =\n sale.share.taxCents > 0\n ? [\n {\n amountCents: sale.share.taxCents,\n taxabilityReason: null,\n taxRateId: null,\n taxableAmountCents: sale.share.taxableCents,\n jurisdiction: state,\n rateState: state,\n percentage: sale.ratePct,\n },\n ]\n : []\n const acceptance =\n posHardwareTermsAcceptanceOf(sale.termsAcceptance) ??\n // Online, the checkout refuses without an acceptance, so there is no\n // notice to fall back to; at the counter, paying under the receipt's and\n // the booth sign's notice is agreeing (Terms 4.28).\n (online ? null : posHardwareTermsAcceptance({ method: 'notice', atMs: sale.paidAtMs }))\n return {\n orgId: attached ? (attachment.orgId as string) : sale.sellerOrgId,\n // The buyer's store once they chose one; until then the workspace's,\n // and the buyer picks the store when they set the reader up.\n hostId: attached ? (attachment.hostId ?? '') : '',\n createdBy: attachment.uid,\n contactEmail: attachment.email ?? sale.receiptEmail,\n lines: sale.share.lines,\n subtotalCents: sale.share.itemsCents,\n discountCents: sale.share.discountCents,\n shipping: online\n ? {\n method: 'standard',\n label: POS_HARDWARE_SHIPPING_LABELS.standard,\n cents: sale.share.shippingCents,\n name: sale.storefront?.name ?? null,\n phone: sale.storefront?.phone ?? null,\n address: shipTo,\n }\n : {\n method: 'in_person',\n label: POS_HARDWARE_IN_PERSON_SHIPPING_LABEL,\n cents: 0,\n name: null,\n phone: null,\n address: null,\n // Sold at the counter: taxed where the store is, as every sale it rings.\n taxRegion: sale.taxRegion,\n },\n taxCents: sale.share.taxCents,\n totalCents: sale.share.totalCents,\n currency: sale.currency ?? POS_HARDWARE_CURRENCY,\n automaticTax: false,\n taxLines,\n stripeCheckoutSessionId: null,\n stripePaymentIntentId: null,\n stripeHardwareOrderId: null,\n tracking: null,\n // Handed over at the sale, or paid online and waiting to be prepared.\n status: online ? 'paid' : 'delivered',\n livemode: sale.livemode,\n createdAtMs: sale.paidAtMs,\n updatedAtMs: sale.paidAtMs,\n paidAtMs: sale.paidAtMs,\n ...(online ? {} : { deliveredAtMs: sale.paidAtMs }),\n source: online ? 'storefront' : 'in_person',\n ...(acceptance ? { termsAcceptance: acceptance } : {}),\n posSale: {\n hostId: sale.sellerHostId,\n orgId: sale.sellerOrgId,\n orderId: sale.registerOrderId,\n number: sale.number,\n registerId: sale.registerId,\n kiosk: sale.kiosk,\n offline: sale.offline,\n paymentLinkSessionId: sale.paymentLinkSessionId,\n },\n paidTo: {\n account: 'seller_store',\n hostId: sale.sellerHostId,\n orgId: sale.sellerOrgId,\n tenders: [...new Set(sale.tenders)],\n stripeAccountId: sale.stripeAccountId,\n },\n attachment,\n units,\n serialNumbers: units.flatMap((unit) => (unit.serialNumber ? [unit.serialNumber] : [])),\n }\n}\n"],"names":["POS_HARDWARE_CURRENCY","POS_HARDWARE_IN_PERSON_SHIPPING_LABEL","POS_HARDWARE_SHIPPING_LABELS","posHardwareBuyerAddress","posHardwareSku","posHardwareTermsAcceptance","posHardwareTermsAcceptanceOf","whole","value","number","Number","isSafeInteger","shareOf","amount","part","of","Math","floor","posHardwareRegisterShare","input","lines","saleItemsCents","line","quantity","unitCents","unitAmountCents","sku","push","id","name","displayName","lineCents","length","itemsCents","reduce","sum","saleDiscountCents","min","discountCents","saleShippingCents","shippingCents","taxableCents","max","taxCents","totalCents","posHardwareUnits","serials","units","kind","index","serialNumber","readerId","hostId","registeredAtMs","posHardwareAttachmentOf","buyer","text","trim","uid","orgId","attached","Boolean","state","email","toLowerCase","attachedBy","attachedAtMs","isFinite","slice","address","inPersonPosHardwareOrder","sale","attachment","shipTo","share","online","storefront","taxRegion","country","toUpperCase","postalCode","taxLines","amountCents","taxabilityReason","taxRateId","taxableAmountCents","jurisdiction","rateState","percentage","ratePct","acceptance","termsAcceptance","method","atMs","paidAtMs","sellerOrgId","createdBy","contactEmail","receiptEmail","subtotalCents","shipping","label","standard","cents","phone","currency","automaticTax","stripeCheckoutSessionId","stripePaymentIntentId","stripeHardwareOrderId","tracking","status","livemode","createdAtMs","updatedAtMs","deliveredAtMs","source","posSale","sellerHostId","orderId","registerOrderId","registerId","kiosk","offline","paymentLinkSessionId","paidTo","account","tenders","Set","stripeAccountId","serialNumbers","flatMap","unit"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;2CAsB2C;AAG3C,SACEA,qBAAqB,EACrBC,qCAAqC,EACrCC,4BAA4B,EAC5BC,uBAAuB,EACvBC,cAAc,QAQT,oBAAgB;AACvB,SAASC,0BAA0B,EAAEC,4BAA4B,QAAQ,0BAAsB;AAsB/F,MAAMC,QAAQ,CAACC;IACb,MAAMC,SAASC,OAAOF;IACtB,OAAOE,OAAOC,aAAa,CAACF,WAAWA,SAAS,IAAIA,SAAS;AAC/D;AAEA,8EAA8E,GAC9E,SAASG,QAAQC,MAAc,EAAEC,IAAY,EAAEC,EAAU;IACvD,IAAIA,MAAM,KAAKF,UAAU,KAAKC,QAAQ,GAAG,OAAO;IAChD,IAAIA,QAAQC,IAAI,OAAOF;IACvB,OAAOG,KAAKC,KAAK,CAAC,AAACJ,CAAAA,SAASC,OAAO,IAAIC,EAAC,IAAMA,CAAAA,KAAK,CAAA;AACrD;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASG,yBAAyBC,KAKxC;IACC,MAAMC,QAA2B,EAAE;IACnC,IAAIC,iBAAiB;IACrB,KAAK,MAAMC,QAAQH,MAAMC,KAAK,CAAE;QAC9B,MAAMG,WAAWhB,MAAMe,KAAKC,QAAQ;QACpC,MAAMC,YAAYjB,MAAMe,KAAKG,eAAe;QAC5CJ,kBAAkBE,WAAWC;QAC7B,MAAME,MAAMJ,KAAKI,GAAG,GAAGtB,eAAekB,KAAKI,GAAG,IAAI;QAClD,IAAI,CAACA,OAAO,CAACH,UAAU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QAAQ;YACNC,SAAS;YACT1E,QAAQmB,KAAK+C,YAAY;YACzB3D,OAAOY,KAAKwB,WAAW;YACvBgC,SAAS;mBAAI,IAAIC,IAAIzD,KAAKwD,OAAO;aAAE;YACnCE,iBAAiB1D,KAAK0D,eAAe;QACvC;QACAzD;QACAzB;QACAmF,eAAenF,MAAMoF,OAAO,CAAC,CAACC,OAAUA,KAAKlF,YAAY,GAAG;gBAACkF,KAAKlF,YAAY;aAAC,GAAG,EAAE;;AAExF"}
@@ -138,7 +138,11 @@ export declare function posHardwareTaxSummary(rows: readonly PosHardwareTaxRowIn
138
138
  start: Date;
139
139
  end: Date;
140
140
  }): PosHardwareTaxSummary;
141
- /** The part of a storefront row an in-person hardware record accounts for. */
141
+ /**
142
+ * The part of a storefront row a hardware record of the platform's own store
143
+ * accounts for: an in-person sale's payment-link row, or an online order's
144
+ * own row (AGL-4038), filed under its Checkout Session id the same way.
145
+ */
142
146
  export interface PosHardwareStorefrontPart {
143
147
  storefrontTaxRowId: string;
144
148
  /** The hardware's share of the register sale, tax included. */
@@ -180,7 +180,8 @@ function emptyJurisdiction() {
180
180
  return summary;
181
181
  }
182
182
  /** The parts the hardware section counts, from its records. */ export function posHardwareStorefrontParts(records) {
183
- return records.flatMap((record)=>record.source === 'in_person' && record.livemode === true && typeof record.storefrontTaxRowId === 'string' && record.storefrontTaxRowId ? [
183
+ return records.flatMap((record)=>// A sale by the platform's own store, at its register or online (AGL-4038).
184
+ (record.source === 'in_person' || record.source === 'storefront') && record.livemode === true && typeof record.storefrontTaxRowId === 'string' && record.storefrontTaxRowId ? [
184
185
  {
185
186
  storefrontTaxRowId: record.storefrontTaxRowId,
186
187
  totalCents: cents(record.totalCents),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/pos-hardware-tax-summary.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\n/**\n * THE PLATFORM'S OWN HARDWARE SALES, SUMMED FOR ONE FILING PERIOD (AGL-4038).\n *\n * The platform is the seller of record for every card reader order, so these\n * are its OWN sales, not facilitated ones, and they belong on its sales tax\n * return. They are recorded in `posHardwareSales` — apart from the invoices\n * the return sums (`platformRevenue`, written only for a paid invoice, which a\n * hardware checkout never makes) and apart from the storefront's tax rows\n * (`storefrontTaxCollected`, whose recorder does not take a hardware session)\n * — so nothing here is already in another figure on the return. The return\n * folds them into its filing figures as the operator's own sales\n * (`server/pos-hardware-tax-return-source.ts`), each sale once.\n *\n * THE RULES, each pinned by `pos-hardware-tax-summary.spec.ts`:\n *\n * - **A sale is in the period it was PAID**, by `paidAtMs`, half-open: the\n * first instant of the period is in, the first instant of the next is not.\n * Its status today does not move it: an order paid in the period and\n * canceled later is still a sale of the period it was paid in.\n * - **Total sales** are receipts excluding the tax itself: the total less\n * the tax (the items and the shipping).\n * - **Taxable sales** are the base Stripe Tax applied its rate to, read from\n * the order's stored breakdown and never inferred. One order's lines are\n * one base taxed at several levels (state, county, city), each line\n * stating the same base, so the order's base is the LARGEST stated, never\n * their sum. An order taxed with no stated base adds nothing and is counted\n * out loud.\n * - **A refund is in the period it was MADE**, by the stamp of the status\n * that refunded it (`refundedAtMs`, or `canceledAtMs` for a cancel), and\n * is stated beside the sales, never netted from them — the platform's own\n * rule for its invoices. Hardware refunds are whole, so the refunded tax is\n * the order's own tax; a partial one is split in the order's own ratio.\n * - **A canceled order with no refund recorded** stays a sale and is counted\n * out loud: the record says canceled and nobody recorded the money coming\n * back.\n * - **Test-mode orders are not sales.** An order made with Stripe's test keys\n * is left out of every figure and counted, never dropped silently.\n * - **Where it shipped decides the jurisdiction**: a shipped sale is sourced\n * to its destination. No ship-to region is `unknown`, counted out loud.\n *\n * Integer cents throughout. Pure and total: no Firestore, no clock.\n */\n\nimport {\n accumulateTaxWorkingPapers,\n emptyTaxJurisdiction,\n taxJurisdictionKey,\n type TaxLineInput,\n type TaxReturnJurisdiction,\n} from '@aglyn/aglyn/app-utils/tax-jurisdiction-figures'\n\n/** A `posHardwareSales/{orderId}` record as the return reads it. */\nexport interface PosHardwareTaxRowInput {\n orderId: string\n totalCents?: unknown\n taxCents?: unknown\n currency?: unknown\n shipTo?: { country?: unknown; state?: unknown; postalCode?: unknown } | null\n automaticTax?: unknown\n taxLines?: TaxLineInput[] | null\n status?: unknown\n livemode?: unknown\n paidAtMs?: unknown\n refundedCents?: unknown\n refundedAtMs?: unknown\n canceledAtMs?: unknown\n /** `in_person` for a reader sold at a store's register (AGL-4038), else sold online. */\n source?: unknown\n /** The store whose register sold it, for an in-person sale. */\n posHostId?: unknown\n}\n\n/** One ship-to jurisdiction: the sales paid in the period and the refunds made in it. */\nexport interface PosHardwareTaxJurisdiction extends TaxReturnJurisdiction {\n /** Sales with no tax computed: sold without Stripe Tax. */\n untaxedOrders: number\n refundedOrders: number\n /** Refunded receipts excluding tax. */\n refundedSalesCents: number\n refundedTaxCents: number\n}\n\nexport interface PosHardwareTaxSummary {\n periodStart: string\n periodEnd: string\n /** Live sales paid in the period, in every jurisdiction. */\n orders: number\n totalSalesCents: number\n taxableSalesCents: number\n taxCollectedCents: number\n byJurisdiction: Record<string, PosHardwareTaxJurisdiction>\n refunds: {\n orders: number\n /** Everything refunded, tax included. */\n refundedCents: number\n refundedSalesCents: number\n refundedTaxCents: number\n }\n excluded: {\n /** Test-mode orders paid in the period: in no figure. */\n testModeOrders: number\n }\n attention: {\n untaxedOrders: number\n ordersMissingTaxableBase: number\n ordersMissingShipTo: number\n canceledWithoutRefund: number\n }\n}\n\nconst cents = (value: unknown): number => {\n const parsed = Number(value ?? 0)\n return Number.isFinite(parsed) ? Math.round(parsed) : 0\n}\n\nconst stamp = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n\nfunction emptyJurisdiction(): PosHardwareTaxJurisdiction {\n return {\n ...emptyTaxJurisdiction(),\n untaxedOrders: 0,\n refundedOrders: 0,\n refundedSalesCents: 0,\n refundedTaxCents: 0,\n }\n}\n\n/**\n * The base Stripe stated for one order, or null when no line states one: the\n * largest of the stated bases, because each jurisdiction level restates the\n * same base (see the module note).\n */\nexport function posHardwareTaxableBase(lines: readonly (TaxLineInput | undefined)[] | null | undefined): number | null {\n let base: number | null = null\n for (const line of lines ?? []) {\n const stated = line?.taxableAmountCents\n if (stated === null || stated === undefined || !Number.isFinite(Number(stated))) continue\n const rounded = Math.round(Number(stated))\n base = base === null ? rounded : Math.max(base, rounded)\n }\n return base\n}\n\n/** When the order's refund was made: the stamp of the status that made it. */\nexport function posHardwareRefundStamp(row: PosHardwareTaxRowInput): number | null {\n if (row.status === 'refunded') return stamp(row.refundedAtMs) ?? stamp(row.canceledAtMs)\n if (row.status === 'canceled') return stamp(row.canceledAtMs) ?? stamp(row.refundedAtMs)\n return stamp(row.refundedAtMs) ?? stamp(row.canceledAtMs)\n}\n\n/** How a row counts in the period: as a sale, as a refund, as both, or not at all. */\nexport function posHardwareRowInPeriod(\n row: PosHardwareTaxRowInput,\n period: { start: Date; end: Date },\n): { sale: boolean; refund: boolean } {\n const startMs = period.start.getTime()\n const endMs = period.end.getTime()\n const within = (at: number | null) => at !== null && at >= startMs && at < endMs\n return {\n sale: within(stamp(row.paidAtMs)),\n refund: cents(row.refundedCents) > 0 && within(posHardwareRefundStamp(row)),\n }\n}\n\n/** The period's figures from the records read for it. See the module note. */\nexport function posHardwareTaxSummary(\n rows: readonly PosHardwareTaxRowInput[],\n period: { start: Date; end: Date },\n): PosHardwareTaxSummary {\n const summary: PosHardwareTaxSummary = {\n periodStart: period.start.toISOString(),\n periodEnd: period.end.toISOString(),\n orders: 0,\n totalSalesCents: 0,\n taxableSalesCents: 0,\n taxCollectedCents: 0,\n byJurisdiction: {},\n refunds: { orders: 0, refundedCents: 0, refundedSalesCents: 0, refundedTaxCents: 0 },\n excluded: { testModeOrders: 0 },\n attention: {\n untaxedOrders: 0,\n ordersMissingTaxableBase: 0,\n ordersMissingShipTo: 0,\n canceledWithoutRefund: 0,\n },\n }\n\n // The reader merges three queries, so an order can arrive twice.\n const seen = new Set<string>()\n for (const row of rows ?? []) {\n if (!row?.orderId || seen.has(row.orderId)) continue\n seen.add(row.orderId)\n const placed = posHardwareRowInPeriod(row, period)\n if (!placed.sale && !placed.refund) continue\n if (row.livemode !== true) {\n if (placed.sale) summary.excluded.testModeOrders += 1\n continue\n }\n\n const total = cents(row.totalCents)\n const tax = cents(row.taxCents)\n const jurisdiction = taxJurisdictionKey(row.shipTo)\n const bucket = (summary.byJurisdiction[jurisdiction] ??= emptyJurisdiction())\n\n if (placed.sale) {\n const lines = Array.isArray(row.taxLines) ? row.taxLines : []\n const base = posHardwareTaxableBase(lines)\n const sales = total - tax\n summary.orders += 1\n summary.totalSalesCents += sales\n summary.taxableSalesCents += base ?? 0\n summary.taxCollectedCents += tax\n bucket.transactionCount += 1\n bucket.totalSalesCents += sales\n bucket.taxableSalesCents += base ?? 0\n bucket.taxCollectedCents += tax\n accumulateTaxWorkingPapers(bucket, lines)\n if (tax === 0 && row.automaticTax !== true) {\n bucket.untaxedOrders += 1\n summary.attention.untaxedOrders += 1\n }\n if (tax > 0 && base === null) summary.attention.ordersMissingTaxableBase += 1\n if (jurisdiction === 'unknown') summary.attention.ordersMissingShipTo += 1\n if ((row.status === 'canceled' || row.status === 'refunded') && cents(row.refundedCents) <= 0) {\n summary.attention.canceledWithoutRefund += 1\n }\n }\n\n if (placed.refund) {\n const refunded = cents(row.refundedCents)\n // Whole refunds give back the order's own tax; a partial one is split\n // in the order's own ratio, and a row with no total states no ratio.\n const refundedTax =\n refunded >= total ? tax : total > 0 && tax > 0 ? Math.round((refunded * tax) / total) : 0\n const refundedSales = refunded - refundedTax\n summary.refunds.orders += 1\n summary.refunds.refundedCents += refunded\n summary.refunds.refundedSalesCents += refundedSales\n summary.refunds.refundedTaxCents += refundedTax\n bucket.refundedOrders += 1\n bucket.refundedSalesCents += refundedSales\n bucket.refundedTaxCents += refundedTax\n }\n }\n return summary\n}\n\n/*==========================================\n * AN IN-PERSON SALE IS ON THE RETURN ONCE (AGL-4038).\n *\n * A card reader the platform sells at its own store's register is the\n * platform's own hardware sale, and the hardware section counts it from its\n * `posHardwareSales` record. A register sale paid by a payment link ALSO\n * files a storefront tax row for the whole register sale, under the link's\n * Checkout Session id — which the record names as `storefrontTaxRowId`. So\n * the storefront section takes the hardware's part out of that row: what is\n * left is the rest of the register sale, and a sale of hardware alone leaves\n * nothing. A sale paid in cash, on a reader or offline files no storefront\n * row, and the hardware section is its only line.\n *\n * Only a record the hardware section counts is taken out — a live one — so\n * a test sale is not removed from one section without being in the other.\n * The row is matched by its id, not by period, so a sale and its row that\n * fall either side of a period's edge still meet.\n *=========================================*/\n\n/** The part of a storefront row an in-person hardware record accounts for. */\nexport interface PosHardwareStorefrontPart {\n storefrontTaxRowId: string\n /** The hardware's share of the register sale, tax included. */\n totalCents: number\n taxCents: number\n}\n\n/** The parts the hardware section counts, from its records. */\nexport function posHardwareStorefrontParts(\n records: ReadonlyArray<{\n source?: unknown\n storefrontTaxRowId?: unknown\n totalCents?: unknown\n taxCents?: unknown\n livemode?: unknown\n }>,\n): PosHardwareStorefrontPart[] {\n return records.flatMap((record) =>\n record.source === 'in_person' &&\n record.livemode === true &&\n typeof record.storefrontTaxRowId === 'string' &&\n record.storefrontTaxRowId\n ? [{ storefrontTaxRowId: record.storefrontTaxRowId, totalCents: cents(record.totalCents), taxCents: cents(record.taxCents) }]\n : [],\n )\n}\n\n/**\n * The storefront rows with each in-person hardware part taken out: a row's\n * receipts and tax less the hardware's, and a row left with nothing dropped.\n * A row's stated tax lines are kept as they are: a register sale's row is a\n * manual-rate row, which states none.\n */\nexport function storefrontRowsWithoutInPersonHardware<\n Row extends { id: string; grossCents?: unknown; taxCents?: unknown },\n>(rows: readonly Row[], parts: readonly PosHardwareStorefrontPart[]): Row[] {\n const byRow = new Map<string, { totalCents: number; taxCents: number }>()\n for (const part of parts) {\n const held = byRow.get(part.storefrontTaxRowId) ?? { totalCents: 0, taxCents: 0 }\n byRow.set(part.storefrontTaxRowId, {\n totalCents: held.totalCents + part.totalCents,\n taxCents: held.taxCents + part.taxCents,\n })\n }\n return rows.flatMap((row) => {\n const part = byRow.get(row.id)\n if (!part) return [row]\n const gross = cents(row.grossCents) - part.totalCents\n if (gross <= 0) return []\n return [{ ...row, grossCents: gross, taxCents: Math.max(0, cents(row.taxCents) - part.taxCents) }]\n })\n}\n"],"names":["accumulateTaxWorkingPapers","emptyTaxJurisdiction","taxJurisdictionKey","cents","value","parsed","Number","isFinite","Math","round","stamp","emptyJurisdiction","untaxedOrders","refundedOrders","refundedSalesCents","refundedTaxCents","posHardwareTaxableBase","lines","base","line","stated","taxableAmountCents","undefined","rounded","max","posHardwareRefundStamp","row","status","refundedAtMs","canceledAtMs","posHardwareRowInPeriod","period","startMs","start","getTime","endMs","end","within","at","sale","paidAtMs","refund","refundedCents","posHardwareTaxSummary","rows","summary","periodStart","toISOString","periodEnd","orders","totalSalesCents","taxableSalesCents","taxCollectedCents","byJurisdiction","refunds","excluded","testModeOrders","attention","ordersMissingTaxableBase","ordersMissingShipTo","canceledWithoutRefund","seen","Set","jurisdiction","orderId","has","add","placed","livemode","total","totalCents","tax","taxCents","shipTo","bucket","Array","isArray","taxLines","sales","transactionCount","automaticTax","refunded","refundedTax","refundedSales","posHardwareStorefrontParts","records","flatMap","record","source","storefrontTaxRowId","storefrontRowsWithoutInPersonHardware","parts","byRow","Map","part","held","get","set","id","gross","grossCents"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,G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AGwB,KAAKxB,UAAU;YAC7CE,UAAUuB,KAAKvB,QAAQ,GAAGsB,KAAKtB,QAAQ;QACzC;IACF;IACA,OAAO5B,KAAK0C,OAAO,CAAC,CAAC5D;QACnB,MAAMoE,OAAOF,MAAMI,GAAG,CAACtE,IAAIwE,EAAE;QAC7B,IAAI,CAACJ,MAAM,OAAO;YAACpE;SAAI;QACvB,MAAMyE,QAAQhG,MAAMuB,IAAI0E,UAAU,IAAIN,KAAKxB,UAAU;QACrD,IAAI6B,SAAS,GAAG,OAAO,EAAE;QACzB,OAAO;YAAC,aAAKzE;gBAAK0E,YAAYD;gBAAO3B,UAAUhE,KAAKgB,GAAG,CAAC,GAAGrB,MAAMuB,IAAI8C,QAAQ,IAAIsB,KAAKtB,QAAQ;;SAAI;IACpG;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/pos-hardware-tax-summary.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\n/**\n * THE PLATFORM'S OWN HARDWARE SALES, SUMMED FOR ONE FILING PERIOD (AGL-4038).\n *\n * The platform is the seller of record for every card reader order, so these\n * are its OWN sales, not facilitated ones, and they belong on its sales tax\n * return. They are recorded in `posHardwareSales` — apart from the invoices\n * the return sums (`platformRevenue`, written only for a paid invoice, which a\n * hardware checkout never makes) and apart from the storefront's tax rows\n * (`storefrontTaxCollected`, whose recorder does not take a hardware session)\n * — so nothing here is already in another figure on the return. The return\n * folds them into its filing figures as the operator's own sales\n * (`server/pos-hardware-tax-return-source.ts`), each sale once.\n *\n * THE RULES, each pinned by `pos-hardware-tax-summary.spec.ts`:\n *\n * - **A sale is in the period it was PAID**, by `paidAtMs`, half-open: the\n * first instant of the period is in, the first instant of the next is not.\n * Its status today does not move it: an order paid in the period and\n * canceled later is still a sale of the period it was paid in.\n * - **Total sales** are receipts excluding the tax itself: the total less\n * the tax (the items and the shipping).\n * - **Taxable sales** are the base Stripe Tax applied its rate to, read from\n * the order's stored breakdown and never inferred. One order's lines are\n * one base taxed at several levels (state, county, city), each line\n * stating the same base, so the order's base is the LARGEST stated, never\n * their sum. An order taxed with no stated base adds nothing and is counted\n * out loud.\n * - **A refund is in the period it was MADE**, by the stamp of the status\n * that refunded it (`refundedAtMs`, or `canceledAtMs` for a cancel), and\n * is stated beside the sales, never netted from them — the platform's own\n * rule for its invoices. Hardware refunds are whole, so the refunded tax is\n * the order's own tax; a partial one is split in the order's own ratio.\n * - **A canceled order with no refund recorded** stays a sale and is counted\n * out loud: the record says canceled and nobody recorded the money coming\n * back.\n * - **Test-mode orders are not sales.** An order made with Stripe's test keys\n * is left out of every figure and counted, never dropped silently.\n * - **Where it shipped decides the jurisdiction**: a shipped sale is sourced\n * to its destination. No ship-to region is `unknown`, counted out loud.\n *\n * Integer cents throughout. Pure and total: no Firestore, no clock.\n */\n\nimport {\n accumulateTaxWorkingPapers,\n emptyTaxJurisdiction,\n taxJurisdictionKey,\n type TaxLineInput,\n type TaxReturnJurisdiction,\n} from '@aglyn/aglyn/app-utils/tax-jurisdiction-figures'\n\n/** A `posHardwareSales/{orderId}` record as the return reads it. */\nexport interface PosHardwareTaxRowInput {\n orderId: string\n totalCents?: unknown\n taxCents?: unknown\n currency?: unknown\n shipTo?: { country?: unknown; state?: unknown; postalCode?: unknown } | null\n automaticTax?: unknown\n taxLines?: TaxLineInput[] | null\n status?: unknown\n livemode?: unknown\n paidAtMs?: unknown\n refundedCents?: unknown\n refundedAtMs?: unknown\n canceledAtMs?: unknown\n /** `in_person` for a reader sold at a store's register (AGL-4038), else sold online. */\n source?: unknown\n /** The store whose register sold it, for an in-person sale. */\n posHostId?: unknown\n}\n\n/** One ship-to jurisdiction: the sales paid in the period and the refunds made in it. */\nexport interface PosHardwareTaxJurisdiction extends TaxReturnJurisdiction {\n /** Sales with no tax computed: sold without Stripe Tax. */\n untaxedOrders: number\n refundedOrders: number\n /** Refunded receipts excluding tax. */\n refundedSalesCents: number\n refundedTaxCents: number\n}\n\nexport interface PosHardwareTaxSummary {\n periodStart: string\n periodEnd: string\n /** Live sales paid in the period, in every jurisdiction. */\n orders: number\n totalSalesCents: number\n taxableSalesCents: number\n taxCollectedCents: number\n byJurisdiction: Record<string, PosHardwareTaxJurisdiction>\n refunds: {\n orders: number\n /** Everything refunded, tax included. */\n refundedCents: number\n refundedSalesCents: number\n refundedTaxCents: number\n }\n excluded: {\n /** Test-mode orders paid in the period: in no figure. */\n testModeOrders: number\n }\n attention: {\n untaxedOrders: number\n ordersMissingTaxableBase: number\n ordersMissingShipTo: number\n canceledWithoutRefund: number\n }\n}\n\nconst cents = (value: unknown): number => {\n const parsed = Number(value ?? 0)\n return Number.isFinite(parsed) ? Math.round(parsed) : 0\n}\n\nconst stamp = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n\nfunction emptyJurisdiction(): PosHardwareTaxJurisdiction {\n return {\n ...emptyTaxJurisdiction(),\n untaxedOrders: 0,\n refundedOrders: 0,\n refundedSalesCents: 0,\n refundedTaxCents: 0,\n }\n}\n\n/**\n * The base Stripe stated for one order, or null when no line states one: the\n * largest of the stated bases, because each jurisdiction level restates the\n * same base (see the module note).\n */\nexport function posHardwareTaxableBase(lines: readonly (TaxLineInput | undefined)[] | null | undefined): number | null {\n let base: number | null = null\n for (const line of lines ?? []) {\n const stated = line?.taxableAmountCents\n if (stated === null || stated === undefined || !Number.isFinite(Number(stated))) continue\n const rounded = Math.round(Number(stated))\n base = base === null ? rounded : Math.max(base, rounded)\n }\n return base\n}\n\n/** When the order's refund was made: the stamp of the status that made it. */\nexport function posHardwareRefundStamp(row: PosHardwareTaxRowInput): number | null {\n if (row.status === 'refunded') return stamp(row.refundedAtMs) ?? stamp(row.canceledAtMs)\n if (row.status === 'canceled') return stamp(row.canceledAtMs) ?? stamp(row.refundedAtMs)\n return stamp(row.refundedAtMs) ?? stamp(row.canceledAtMs)\n}\n\n/** How a row counts in the period: as a sale, as a refund, as both, or not at all. */\nexport function posHardwareRowInPeriod(\n row: PosHardwareTaxRowInput,\n period: { start: Date; end: Date },\n): { sale: boolean; refund: boolean } {\n const startMs = period.start.getTime()\n const endMs = period.end.getTime()\n const within = (at: number | null) => at !== null && at >= startMs && at < endMs\n return {\n sale: within(stamp(row.paidAtMs)),\n refund: cents(row.refundedCents) > 0 && within(posHardwareRefundStamp(row)),\n }\n}\n\n/** The period's figures from the records read for it. See the module note. */\nexport function posHardwareTaxSummary(\n rows: readonly PosHardwareTaxRowInput[],\n period: { start: Date; end: Date },\n): PosHardwareTaxSummary {\n const summary: PosHardwareTaxSummary = {\n periodStart: period.start.toISOString(),\n periodEnd: period.end.toISOString(),\n orders: 0,\n totalSalesCents: 0,\n taxableSalesCents: 0,\n taxCollectedCents: 0,\n byJurisdiction: {},\n refunds: { orders: 0, refundedCents: 0, refundedSalesCents: 0, refundedTaxCents: 0 },\n excluded: { testModeOrders: 0 },\n attention: {\n untaxedOrders: 0,\n ordersMissingTaxableBase: 0,\n ordersMissingShipTo: 0,\n canceledWithoutRefund: 0,\n },\n }\n\n // The reader merges three queries, so an order can arrive twice.\n const seen = new Set<string>()\n for (const row of rows ?? []) {\n if (!row?.orderId || seen.has(row.orderId)) continue\n seen.add(row.orderId)\n const placed = posHardwareRowInPeriod(row, period)\n if (!placed.sale && !placed.refund) continue\n if (row.livemode !== true) {\n if (placed.sale) summary.excluded.testModeOrders += 1\n continue\n }\n\n const total = cents(row.totalCents)\n const tax = cents(row.taxCents)\n const jurisdiction = taxJurisdictionKey(row.shipTo)\n const bucket = (summary.byJurisdiction[jurisdiction] ??= emptyJurisdiction())\n\n if (placed.sale) {\n const lines = Array.isArray(row.taxLines) ? row.taxLines : []\n const base = posHardwareTaxableBase(lines)\n const sales = total - tax\n summary.orders += 1\n summary.totalSalesCents += sales\n summary.taxableSalesCents += base ?? 0\n summary.taxCollectedCents += tax\n bucket.transactionCount += 1\n bucket.totalSalesCents += sales\n bucket.taxableSalesCents += base ?? 0\n bucket.taxCollectedCents += tax\n accumulateTaxWorkingPapers(bucket, lines)\n if (tax === 0 && row.automaticTax !== true) {\n bucket.untaxedOrders += 1\n summary.attention.untaxedOrders += 1\n }\n if (tax > 0 && base === null) summary.attention.ordersMissingTaxableBase += 1\n if (jurisdiction === 'unknown') summary.attention.ordersMissingShipTo += 1\n if ((row.status === 'canceled' || row.status === 'refunded') && cents(row.refundedCents) <= 0) {\n summary.attention.canceledWithoutRefund += 1\n }\n }\n\n if (placed.refund) {\n const refunded = cents(row.refundedCents)\n // Whole refunds give back the order's own tax; a partial one is split\n // in the order's own ratio, and a row with no total states no ratio.\n const refundedTax =\n refunded >= total ? tax : total > 0 && tax > 0 ? Math.round((refunded * tax) / total) : 0\n const refundedSales = refunded - refundedTax\n summary.refunds.orders += 1\n summary.refunds.refundedCents += refunded\n summary.refunds.refundedSalesCents += refundedSales\n summary.refunds.refundedTaxCents += refundedTax\n bucket.refundedOrders += 1\n bucket.refundedSalesCents += refundedSales\n bucket.refundedTaxCents += refundedTax\n }\n }\n return summary\n}\n\n/*==========================================\n * AN IN-PERSON SALE IS ON THE RETURN ONCE (AGL-4038).\n *\n * A card reader the platform sells at its own store's register is the\n * platform's own hardware sale, and the hardware section counts it from its\n * `posHardwareSales` record. A register sale paid by a payment link ALSO\n * files a storefront tax row for the whole register sale, under the link's\n * Checkout Session id — which the record names as `storefrontTaxRowId`. So\n * the storefront section takes the hardware's part out of that row: what is\n * left is the rest of the register sale, and a sale of hardware alone leaves\n * nothing. A sale paid in cash, on a reader or offline files no storefront\n * row, and the hardware section is its only line.\n *\n * Only a record the hardware section counts is taken out — a live one — so\n * a test sale is not removed from one section without being in the other.\n * The row is matched by its id, not by period, so a sale and its row that\n * fall either side of a period's edge still meet.\n *=========================================*/\n\n/**\n * The part of a storefront row a hardware record of the platform's own store\n * accounts for: an in-person sale's payment-link row, or an online order's\n * own row (AGL-4038), filed under its Checkout Session id the same way.\n */\nexport interface PosHardwareStorefrontPart {\n storefrontTaxRowId: string\n /** The hardware's share of the register sale, tax included. */\n totalCents: number\n taxCents: number\n}\n\n/** The parts the hardware section counts, from its records. */\nexport function posHardwareStorefrontParts(\n records: ReadonlyArray<{\n source?: unknown\n storefrontTaxRowId?: unknown\n totalCents?: unknown\n taxCents?: unknown\n livemode?: unknown\n }>,\n): PosHardwareStorefrontPart[] {\n return records.flatMap((record) =>\n // A sale by the platform's own store, at its register or online (AGL-4038).\n (record.source === 'in_person' || record.source === 'storefront') &&\n record.livemode === true &&\n typeof record.storefrontTaxRowId === 'string' &&\n record.storefrontTaxRowId\n ? [{ storefrontTaxRowId: record.storefrontTaxRowId, totalCents: cents(record.totalCents), taxCents: cents(record.taxCents) }]\n : [],\n )\n}\n\n/**\n * The storefront rows with each in-person hardware part taken out: a row's\n * receipts and tax less the hardware's, and a row left with nothing dropped.\n * A row's stated tax lines are kept as they are: a register sale's row is a\n * manual-rate row, which states none.\n */\nexport function storefrontRowsWithoutInPersonHardware<\n Row extends { id: string; grossCents?: unknown; taxCents?: unknown },\n>(rows: readonly Row[], parts: readonly PosHardwareStorefrontPart[]): Row[] {\n const byRow = new Map<string, { totalCents: number; taxCents: number }>()\n for (const part of parts) {\n const held = byRow.get(part.storefrontTaxRowId) ?? { totalCents: 0, taxCents: 0 }\n byRow.set(part.storefrontTaxRowId, {\n totalCents: held.totalCents + part.totalCents,\n taxCents: held.taxCents + part.taxCents,\n })\n }\n return rows.flatMap((row) => {\n const part = byRow.get(row.id)\n if (!part) return [row]\n const gross = cents(row.grossCents) - part.totalCents\n if (gross <= 0) return []\n return [{ ...row, grossCents: gross, taxCents: Math.max(0, cents(row.taxCents) - part.taxCents) }]\n })\n}\n"],"names":["accumulateTaxWorkingPapers","emptyTaxJurisdiction","taxJurisdictionKey","cents","value","parsed","Number","isFinite","Math","round","stamp","emptyJurisdiction","untaxedOrders","refundedOrders","refundedSalesCents","refundedTaxCents","posHardwareTaxableBase","lines","base","line","stated","taxableAmountCents","undefined","rounded","max","posHardwareRefundStamp","row","status","refundedAtMs","canceledAtMs","posHardwareRowInPeriod","period","startMs","start","getTime","endMs","end","within","at","sale","paidAtMs","refund","refundedCents","posHardwareTaxSummary","rows","summary","periodStart","toISOString","periodEnd","orders","totalSalesCents","taxableSalesCents","taxCollectedCents","byJurisdiction","refunds","excluded","testModeOrders","attention","ordersMissingTaxableBase","ordersMissingShipTo","canceledWithoutRefund","seen","Set","jurisdiction","orderId","has","add","placed","livemode","total","totalCents","tax","taxCents","shipTo","bucket","Array","isArray","taxLines","sales","transactionCount","automaticTax","refunded","refundedTax","refundedSales","posHardwareStorefrontParts","records","flatMap","record","source","storefrontTaxRowId","storefrontRowsWithoutInPersonHardware","parts","byRow","Map","part","held","get","set","id","gross","grossCents"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCC,GAED,SACEA,0BAA0B,EAC1BC,oBAAoB,EACpBC,kBAAkB,QAGb,kDAAiD;AA6DxD,MAAMC,QAAQ,CAACC;IACb,MAAMC,SAASC,OAAOF,gBAAAA,QAAS;IAC/B,OAAOE,OAAOC,QAAQ,CAACF,UAAUG,KAAKC,KAAK,CAACJ,UAAU;AACxD;AAEA,MAAMK,QAAQ,CAACN,QACb,OAAOA,UAAU,YAAYE,OAAOC,QAAQ,CAACH,SAASA,QAAQ;AAEhE,SAASO;IACP,OAAO,aACFV;QACHW,eAAe;QACfC,gBAAgB;QAChBC,oBAAoB;QACpBC,kBAAkB;;AAEtB;AAEA;;;;CAIC,GACD,OAAO,SAASC,uBAAuBC,KAA+D;IACpG,IAAIC,OAA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AUhE,KAAKgB,GAAG,CAAC,GAAGrB,MAAMuB,IAAI8C,QAAQ,IAAIsB,KAAKtB,QAAQ;;SAAI;IACpG;AACF"}
@@ -28,8 +28,13 @@ export declare function posHardwareTermsAddress(): string;
28
28
  * instead of it: the acceptance is of the Terms, which this summarizes.
29
29
  */
30
30
  export declare const POS_HARDWARE_TERMS_SUMMARY: readonly string[];
31
- /** How a buyer agreed to the terms of sale. */
32
- export type PosHardwareTermsMethod = 'tablet' | 'display' | 'notice';
31
+ /**
32
+ * How a buyer agreed to the terms of sale: at the booth on the register
33
+ * tablet or the customer display, by the receipt-and-sign notice, or ONLINE
34
+ * (AGL-4038) by ticking the terms and business use at checkout, in the
35
+ * platform's own store or on the Hardware card.
36
+ */
37
+ export type PosHardwareTermsMethod = 'tablet' | 'display' | 'notice' | 'online';
33
38
  /** `hardwareTermsAcceptance` on a register sale, and `termsAcceptance` on the hardware order. */
34
39
  export interface PosHardwareTermsAcceptance {
35
40
  version: string;
@@ -41,6 +46,12 @@ export interface PosHardwareTermsAcceptance {
41
46
  /** The address and browser of the device the buyer accepted on; null for a notice. */
42
47
  ip: string | null;
43
48
  userAgent: string | null;
49
+ /**
50
+ * The buyer confirmed they are buying for use in a business (AGL-4038):
51
+ * asked on its own at an online checkout, beside the terms. Absent on an
52
+ * acceptance at the booth, where the terms the buyer reads say so.
53
+ */
54
+ businessUse?: boolean;
44
55
  }
45
56
  /** An acceptance as stored, or null for anything that is not one. */
46
57
  export declare function posHardwareTermsAcceptanceOf(raw: unknown): PosHardwareTermsAcceptance | null;
@@ -52,6 +63,30 @@ export declare function posHardwareTermsAcceptance(input: {
52
63
  ip?: string | null;
53
64
  userAgent?: string | null;
54
65
  }): PosHardwareTermsAcceptance;
66
+ /** The plain sentence a checkout without the acceptance is refused with. */
67
+ export declare const POS_HARDWARE_TERMS_REQUIRED = "To buy card reader hardware, accept the hardware terms of sale (Terms, Sections 4.26\u20134.32) and confirm you are buying it for your business.";
68
+ /**
69
+ * Whether a checkout request carries the buyer's acceptance: the request's
70
+ * `hardwareTerms` says both `accepted` and `businessUse`, each literally true.
71
+ */
72
+ export declare function posHardwareTermsConfirmed(raw: unknown): boolean;
73
+ /**
74
+ * An online acceptance as Checkout Session metadata, every value within
75
+ * Stripe's 500-character limit. The caller prefixes each key as its params
76
+ * need (`metadata[...]`). No time: the session's own creation is when the
77
+ * buyer accepted, and a value that changed between two presses of one
78
+ * attempt would make Stripe refuse the idempotent retry.
79
+ */
80
+ export declare function posHardwareTermsMetadata(input: {
81
+ ip?: string | null;
82
+ userAgent?: string | null;
83
+ }): Record<string, string>;
84
+ /**
85
+ * The online acceptance a paid session's metadata carries, or null when it
86
+ * carries none. `atMs` is when the session was created (Stripe's `created`,
87
+ * in milliseconds), which is when the buyer pressed to pay having accepted.
88
+ */
89
+ export declare function posHardwareTermsFromMetadata(metadata: unknown, atMs: number): PosHardwareTermsAcceptance | null;
55
90
  /** Whether a register sale sells hardware: marked when rung, or recorded since. */
56
91
  export declare function isPosHardwareRegisterSale(order: {
57
92
  hardwareSalePending?: unknown;
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -60,7 +61,8 @@
60
61
  const METHODS = [
61
62
  'tablet',
62
63
  'display',
63
- 'notice'
64
+ 'notice',
65
+ 'online'
64
66
  ];
65
67
  /** An acceptance as stored, or null for anything that is not one. */ export function posHardwareTermsAcceptanceOf(raw) {
66
68
  var _value_method, _text, _text1;
@@ -70,7 +72,7 @@ const METHODS = [
70
72
  const atMs = Number(value['atMs']);
71
73
  if (!METHODS.includes(method) || !Number.isFinite(atMs) || atMs <= 0) return null;
72
74
  const text = (field, max)=>typeof value[field] === 'string' && value[field] ? value[field].slice(0, max) : null;
73
- return {
75
+ return _extends({
74
76
  version: (_text = text('version', 20)) != null ? _text : POS_HARDWARE_TERMS_VERSION,
75
77
  sections: (_text1 = text('sections', 40)) != null ? _text1 : POS_HARDWARE_TERMS_SECTIONS,
76
78
  method,
@@ -78,7 +80,9 @@ const METHODS = [
78
80
  staffUid: text('staffUid', 128),
79
81
  ip: text('ip', 100),
80
82
  userAgent: text('userAgent', 400)
81
- };
83
+ }, value['businessUse'] === true ? {
84
+ businessUse: true
85
+ } : {});
82
86
  }
83
87
  /** A fresh acceptance of the current terms of sale. */ export function posHardwareTermsAcceptance(input) {
84
88
  var _input_staffUid, _ref, _input_ip, _ref1, _input_userAgent;
@@ -93,6 +97,67 @@ const METHODS = [
93
97
  userAgent: input.method === 'notice' ? null : (_ref1 = (_this1 = (_input_userAgent = input.userAgent) != null ? _input_userAgent : null) == null ? void 0 : _this1.slice(0, 400)) != null ? _ref1 : null
94
98
  };
95
99
  }
100
+ /*==========================================
101
+ * ACCEPTING THE TERMS OF SALE ONLINE (AGL-4038).
102
+ *
103
+ * A checkout that sells hardware, in the platform's own store or on the
104
+ * Hardware card, asks two things beside the order: that the buyer accepts the
105
+ * terms of sale (Terms 4.26–4.32, linked), and that they are buying for use
106
+ * in a business. Both are required; a checkout without them is refused with
107
+ * {@link POS_HARDWARE_TERMS_REQUIRED}. The acceptance rides the Checkout
108
+ * Session's metadata ({@link posHardwareTermsMetadata}), because the order is
109
+ * written only once Stripe says the session is paid, and the webhook writes
110
+ * it onto the order as the booth's acceptance is.
111
+ *=========================================*/ /** The plain sentence a checkout without the acceptance is refused with. */ export const POS_HARDWARE_TERMS_REQUIRED = `To buy card reader hardware, accept the hardware terms of sale (Terms, Sections ${POS_HARDWARE_TERMS_SECTIONS}) and confirm you are buying it for your business.`;
112
+ /**
113
+ * Whether a checkout request carries the buyer's acceptance: the request's
114
+ * `hardwareTerms` says both `accepted` and `businessUse`, each literally true.
115
+ */ export function posHardwareTermsConfirmed(raw) {
116
+ const value = raw && typeof raw === 'object' ? raw : {};
117
+ return value['accepted'] === true && value['businessUse'] === true;
118
+ }
119
+ /** The metadata keys an online acceptance rides the Checkout Session under. */ const TERMS_METADATA = {
120
+ version: 'hardwareTermsVersion',
121
+ businessUse: 'hardwareTermsBusinessUse',
122
+ ip: 'hardwareTermsIp',
123
+ userAgent: 'hardwareTermsUserAgent'
124
+ };
125
+ /**
126
+ * An online acceptance as Checkout Session metadata, every value within
127
+ * Stripe's 500-character limit. The caller prefixes each key as its params
128
+ * need (`metadata[...]`). No time: the session's own creation is when the
129
+ * buyer accepted, and a value that changed between two presses of one
130
+ * attempt would make Stripe refuse the idempotent retry.
131
+ */ export function posHardwareTermsMetadata(input) {
132
+ return _extends({
133
+ [TERMS_METADATA.version]: POS_HARDWARE_TERMS_VERSION,
134
+ [TERMS_METADATA.businessUse]: 'true'
135
+ }, input.ip ? {
136
+ [TERMS_METADATA.ip]: String(input.ip).slice(0, 100)
137
+ } : {}, input.userAgent ? {
138
+ [TERMS_METADATA.userAgent]: String(input.userAgent).slice(0, 400)
139
+ } : {});
140
+ }
141
+ /**
142
+ * The online acceptance a paid session's metadata carries, or null when it
143
+ * carries none. `atMs` is when the session was created (Stripe's `created`,
144
+ * in milliseconds), which is when the buyer pressed to pay having accepted.
145
+ */ export function posHardwareTermsFromMetadata(metadata, atMs) {
146
+ const value = metadata && typeof metadata === 'object' ? metadata : {};
147
+ const version = typeof value[TERMS_METADATA.version] === 'string' ? value[TERMS_METADATA.version] : '';
148
+ if (!version || !Number.isFinite(atMs) || atMs <= 0 || value[TERMS_METADATA.businessUse] !== 'true') return null;
149
+ const text = (field, max)=>typeof value[field] === 'string' && value[field] ? value[field].slice(0, max) : null;
150
+ return {
151
+ version: version.slice(0, 20),
152
+ sections: POS_HARDWARE_TERMS_SECTIONS,
153
+ method: 'online',
154
+ atMs,
155
+ staffUid: null,
156
+ ip: text(TERMS_METADATA.ip, 100),
157
+ userAgent: text(TERMS_METADATA.userAgent, 400),
158
+ businessUse: true
159
+ };
160
+ }
96
161
  /** Whether a register sale sells hardware: marked when rung, or recorded since. */ export function isPosHardwareRegisterSale(order) {
97
162
  return (order == null ? void 0 : order.hardwareSalePending) === true || typeof (order == null ? void 0 : order.hardwareOrderId) === 'string' && Boolean(order.hardwareOrderId);
98
163
  }