@aglyn/plugins-commerce 1.15.2 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/README.md +1 -1
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +2 -1
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js +6 -1
  6. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  7. package/src/lib/components/console/pos/pos-api.d.ts +5 -0
  8. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  9. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
  10. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
  11. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  12. package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
  13. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  14. package/src/lib/components/console/pos-cellular-control.component.d.ts +5 -0
  15. package/src/lib/components/console/pos-cellular-control.component.js +29 -15
  16. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  17. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  18. package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
  19. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  20. package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
  21. package/src/lib/components/console/product-builder-fields.component.js +195 -0
  22. package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
  23. package/src/lib/components/console/product-editor-dialog.component.js +35 -2
  24. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  25. package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
  26. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  27. package/src/lib/components/console/quote-messages.component.d.ts +21 -0
  28. package/src/lib/components/console/quote-messages.component.js +185 -0
  29. package/src/lib/components/console/quote-messages.component.js.map +1 -0
  30. package/src/lib/components/console/quote-pay-link.component.js +1 -1
  31. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  32. package/src/lib/components/console/quote-proofs.component.js +30 -3
  33. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  34. package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
  35. package/src/lib/components/console/quote-settings-card.component.js +154 -24
  36. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  37. package/src/lib/components/product-builder-context.d.ts +22 -0
  38. package/src/lib/components/product-builder-context.js +21 -0
  39. package/src/lib/components/product-builder-context.js.map +1 -0
  40. package/src/lib/components/product-builder-mockup.d.ts +42 -0
  41. package/src/lib/components/product-builder-mockup.js +120 -0
  42. package/src/lib/components/product-builder-mockup.js.map +1 -0
  43. package/src/lib/components/product-builder-sample.d.ts +63 -0
  44. package/src/lib/components/product-builder-sample.js +96 -0
  45. package/src/lib/components/product-builder-sample.js.map +1 -0
  46. package/src/lib/components/product-choice-cards.d.ts +51 -0
  47. package/src/lib/components/product-choice-cards.js +311 -0
  48. package/src/lib/components/product-choice-cards.js.map +1 -0
  49. package/src/lib/components/product-detail-panels.d.ts +42 -0
  50. package/src/lib/components/product-detail-panels.js +185 -0
  51. package/src/lib/components/product-detail-panels.js.map +1 -0
  52. package/src/lib/components/product-detail.d.ts +20 -12
  53. package/src/lib/components/product-detail.js +136 -221
  54. package/src/lib/components/product-detail.js.map +1 -1
  55. package/src/lib/components/product-grid.d.ts +7 -0
  56. package/src/lib/components/product-grid.js +13 -9
  57. package/src/lib/components/product-grid.js.map +1 -1
  58. package/src/lib/components/product-name-lines.d.ts +37 -0
  59. package/src/lib/components/product-name-lines.js +36 -0
  60. package/src/lib/components/product-name-lines.js.map +1 -0
  61. package/src/lib/components/product-options-field-body.d.ts +9 -8
  62. package/src/lib/components/product-options-field-body.js +152 -3
  63. package/src/lib/components/product-options-field-body.js.map +1 -1
  64. package/src/lib/components/product-options-field.js +1 -1
  65. package/src/lib/components/product-options-field.js.map +1 -1
  66. package/src/lib/components/product-photo-fit.d.ts +49 -0
  67. package/src/lib/components/product-photo-fit.js +58 -0
  68. package/src/lib/components/product-photo-fit.js.map +1 -0
  69. package/src/lib/components/product-restock-notify.d.ts +12 -0
  70. package/src/lib/components/product-restock-notify.js +86 -0
  71. package/src/lib/components/product-restock-notify.js.map +1 -0
  72. package/src/lib/components/quote-messages-panel.d.ts +21 -0
  73. package/src/lib/components/quote-messages-panel.js +191 -0
  74. package/src/lib/components/quote-messages-panel.js.map +1 -0
  75. package/src/lib/components/quote-page-body.js +15 -1
  76. package/src/lib/components/quote-page-body.js.map +1 -1
  77. package/src/lib/components/quote-proof-panel.d.ts +6 -3
  78. package/src/lib/components/quote-proof-panel.js +139 -14
  79. package/src/lib/components/quote-proof-panel.js.map +1 -1
  80. package/src/lib/components/related-products.d.ts +7 -0
  81. package/src/lib/components/related-products.js +10 -7
  82. package/src/lib/components/related-products.js.map +1 -1
  83. package/src/lib/constants/quote-page.d.ts +8 -0
  84. package/src/lib/constants/quote-page.js +11 -0
  85. package/src/lib/constants/quote-page.js.map +1 -1
  86. package/src/lib/model/commerce-cart.d.ts +6 -1
  87. package/src/lib/model/commerce-cart.js +5 -1
  88. package/src/lib/model/commerce-cart.js.map +1 -1
  89. package/src/lib/model/commerce-invoices.js +5 -1
  90. package/src/lib/model/commerce-invoices.js.map +1 -1
  91. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  92. package/src/lib/model/commerce-pos-ops.js +3 -0
  93. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  94. package/src/lib/model/commerce-pos.d.ts +8 -0
  95. package/src/lib/model/commerce-pos.js.map +1 -1
  96. package/src/lib/model/commerce-quote-messages.d.ts +106 -0
  97. package/src/lib/model/commerce-quote-messages.js +146 -0
  98. package/src/lib/model/commerce-quote-messages.js.map +1 -0
  99. package/src/lib/model/commerce-quote-pay.d.ts +31 -2
  100. package/src/lib/model/commerce-quote-pay.js +31 -7
  101. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  102. package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
  103. package/src/lib/model/commerce-quote-proofs.js +73 -18
  104. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  105. package/src/lib/model/commerce-quote-request.d.ts +14 -4
  106. package/src/lib/model/commerce-quote-request.js +25 -2
  107. package/src/lib/model/commerce-quote-request.js.map +1 -1
  108. package/src/lib/model/commerce-quotes.d.ts +56 -3
  109. package/src/lib/model/commerce-quotes.js +47 -2
  110. package/src/lib/model/commerce-quotes.js.map +1 -1
  111. package/src/lib/model/commerce.d.ts +12 -1
  112. package/src/lib/model/commerce.js.map +1 -1
  113. package/src/lib/model/index.d.ts +1 -0
  114. package/src/lib/model/index.js +1 -0
  115. package/src/lib/model/index.js.map +1 -1
  116. package/src/lib/model/pos-cellular.d.ts +36 -4
  117. package/src/lib/model/pos-cellular.js +39 -4
  118. package/src/lib/model/pos-cellular.js.map +1 -1
  119. package/src/lib/model/product-card-rules.d.ts +41 -0
  120. package/src/lib/model/product-card-rules.js +90 -0
  121. package/src/lib/model/product-card-rules.js.map +1 -0
  122. package/src/lib/model/product-modifiers.d.ts +11 -0
  123. package/src/lib/model/product-modifiers.js +10 -0
  124. package/src/lib/model/product-modifiers.js.map +1 -1
  125. package/src/lib/model/product-write.d.ts +3 -0
  126. package/src/lib/server/billing-webhook.js +6 -2
  127. package/src/lib/server/billing-webhook.js.map +1 -1
  128. package/src/lib/server/cancel-order.js +15 -0
  129. package/src/lib/server/cancel-order.js.map +1 -1
  130. package/src/lib/server/channel-order-updates.js +15 -1
  131. package/src/lib/server/channel-order-updates.js.map +1 -1
  132. package/src/lib/server/channel-orders.js +20 -0
  133. package/src/lib/server/channel-orders.js.map +1 -1
  134. package/src/lib/server/checkout.js +1 -1
  135. package/src/lib/server/checkout.js.map +1 -1
  136. package/src/lib/server/local-fulfillment.js +1 -1
  137. package/src/lib/server/local-fulfillment.js.map +1 -1
  138. package/src/lib/server/pos-cellular-billing.d.ts +5 -4
  139. package/src/lib/server/pos-cellular-billing.js +24 -12
  140. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  141. package/src/lib/server/pos-cellular.d.ts +3 -1
  142. package/src/lib/server/pos-cellular.js +55 -33
  143. package/src/lib/server/pos-cellular.js.map +1 -1
  144. package/src/lib/server/pos-offline-sync.d.ts +3 -3
  145. package/src/lib/server/pos-offline-sync.js +17 -4
  146. package/src/lib/server/pos-offline-sync.js.map +1 -1
  147. package/src/lib/server/pos-order.js +17 -6
  148. package/src/lib/server/pos-order.js.map +1 -1
  149. package/src/lib/server/pos-payment.js +27 -11
  150. package/src/lib/server/pos-payment.js.map +1 -1
  151. package/src/lib/server/pos-reader-splash.js +10 -5
  152. package/src/lib/server/pos-reader-splash.js.map +1 -1
  153. package/src/lib/server/pos-readers.js +42 -12
  154. package/src/lib/server/pos-readers.js.map +1 -1
  155. package/src/lib/server/pos-return.js +19 -3
  156. package/src/lib/server/pos-return.js.map +1 -1
  157. package/src/lib/server/pos-stripe.d.ts +14 -0
  158. package/src/lib/server/pos-stripe.js +6 -2
  159. package/src/lib/server/pos-stripe.js.map +1 -1
  160. package/src/lib/server/pos-terminal-connection-token.js +23 -9
  161. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  162. package/src/lib/server/pos-terminal.d.ts +80 -14
  163. package/src/lib/server/pos-terminal.js +393 -123
  164. package/src/lib/server/pos-terminal.js.map +1 -1
  165. package/src/lib/server/product-drafts.d.ts +1 -1
  166. package/src/lib/server/product-drafts.js +4 -3
  167. package/src/lib/server/product-drafts.js.map +1 -1
  168. package/src/lib/server/product-writer.js +5 -4
  169. package/src/lib/server/product-writer.js.map +1 -1
  170. package/src/lib/server/product.d.ts +11 -0
  171. package/src/lib/server/product.js +18 -3
  172. package/src/lib/server/product.js.map +1 -1
  173. package/src/lib/server/products-write.js +4 -3
  174. package/src/lib/server/products-write.js.map +1 -1
  175. package/src/lib/server/quote-email.d.ts +26 -0
  176. package/src/lib/server/quote-email.js +73 -7
  177. package/src/lib/server/quote-email.js.map +1 -1
  178. package/src/lib/server/quote-messages.d.ts +72 -0
  179. package/src/lib/server/quote-messages.js +356 -0
  180. package/src/lib/server/quote-messages.js.map +1 -0
  181. package/src/lib/server/quote-pay.d.ts +42 -0
  182. package/src/lib/server/quote-pay.js +81 -4
  183. package/src/lib/server/quote-pay.js.map +1 -1
  184. package/src/lib/server/quote-proofs.d.ts +1 -1
  185. package/src/lib/server/quote-proofs.js +63 -19
  186. package/src/lib/server/quote-proofs.js.map +1 -1
  187. package/src/lib/server/quote.d.ts +12 -0
  188. package/src/lib/server/quote.js +69 -16
  189. package/src/lib/server/quote.js.map +1 -1
  190. package/src/lib/server/refund.js +3 -1
  191. package/src/lib/server/refund.js.map +1 -1
  192. package/src/lib/server/reserve-stock.js +9 -0
  193. package/src/lib/server/reserve-stock.js.map +1 -1
  194. package/src/lib/server/returns.js +15 -1
  195. package/src/lib/server/returns.js.map +1 -1
  196. package/src/lib/server/reviews.js +15 -0
  197. package/src/lib/server/reviews.js.map +1 -1
  198. package/src/lib/server/sold-out-drop.d.ts +58 -0
  199. package/src/lib/server/sold-out-drop.js +81 -0
  200. package/src/lib/server/sold-out-drop.js.map +1 -0
  201. package/src/lib/server/stock-levels.js +9 -0
  202. package/src/lib/server/stock-levels.js.map +1 -1
  203. package/src/lib/server/stripe-refund.d.ts +7 -0
  204. package/src/lib/server/stripe-refund.js +26 -7
  205. package/src/lib/server/stripe-refund.js.map +1 -1
  206. package/src/lib/server.d.ts +15 -0
  207. package/src/lib/server.js +30 -1
  208. package/src/lib/server.js.map +1 -1
  209. package/src/lib/tenant-emails.js +85 -2
  210. package/src/lib/tenant-emails.js.map +1 -1
  211. package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
  212. package/src/lib/testing/fake-seller-payment-account.js +40 -0
  213. package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
  214. package/src/lib/transfer/product-transfer.js +6 -5
  215. package/src/lib/transfer/product-transfer.js.map +1 -1
  216. package/src/lib/transfer/products.server.js +4 -3
  217. package/src/lib/transfer/products.server.js.map +1 -1
  218. package/src/lib/utils/quote-email-content.d.ts +6 -0
  219. package/src/lib/utils/quote-email-content.js +6 -3
  220. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -28,3 +28,11 @@ export declare const QUOTE_PAGE_COMPONENT_ID = "quote-page";
28
28
  export declare const QUOTE_PAGE_PATH = "pay-quote";
29
29
  /** The page's address for one quote and its signed link token, relative to the site. */
30
30
  export declare function quotePageHref(quoteId: string, token: string): string;
31
+ /** Where the site's built-in sign-in page is (the User Accounts plugin's own route). */
32
+ export declare const QUOTE_SIGN_IN_PATH = "/signin";
33
+ /**
34
+ * The sign-in page, returning to `back` (the quote page's own path and query)
35
+ * once the customer signs in (AGL-4206). The sign-in block honors `continue`
36
+ * for same-site paths only.
37
+ */
38
+ export declare function quoteSignInHref(back: string): string;
@@ -31,5 +31,16 @@ export const QUOTE_PAGE_PATH = 'pay-quote';
31
31
  });
32
32
  return `/${QUOTE_PAGE_PATH}?${query.toString()}`;
33
33
  }
34
+ /** Where the site's built-in sign-in page is (the User Accounts plugin's own route). */ export const QUOTE_SIGN_IN_PATH = '/signin';
35
+ /**
36
+ * The sign-in page, returning to `back` (the quote page's own path and query)
37
+ * once the customer signs in (AGL-4206). The sign-in block honors `continue`
38
+ * for same-site paths only.
39
+ */ export function quoteSignInHref(back) {
40
+ const path = back.startsWith('/') && !back.startsWith('//') ? back : `/${QUOTE_PAGE_PATH}`;
41
+ return `${QUOTE_SIGN_IN_PATH}?${new URLSearchParams({
42
+ continue: path
43
+ }).toString()}`;
44
+ }
34
45
 
35
46
  //# sourceMappingURL=quote-page.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/constants/quote-page.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 customer's quote page (AGL-4094), where a quote's pay link opens.\n *\n * The component id is persisted in screen documents; never rename it. The\n * path is where the site serves the page when it has no page of its own\n * there. It is `pay-quote` rather than `quote` because a business that sells\n * made-to-order work often has a \"Request a quote\" page at `/quote` already,\n * and a page of the site's own at an address always wins over this one: a pay\n * link there would open the request form.\n */\nexport const QUOTE_PAGE_COMPONENT_ID = 'quote-page'\n\nexport const QUOTE_PAGE_PATH = 'pay-quote'\n\n/** The page's address for one quote and its signed link token, relative to the site. */\nexport function quotePageHref(quoteId: string, token: string): string {\n const query = new URLSearchParams({ q: quoteId, t: token })\n return `/${QUOTE_PAGE_PATH}?${query.toString()}`\n}\n"],"names":["QUOTE_PAGE_COMPONENT_ID","QUOTE_PAGE_PATH","quotePageHref","quoteId","token","query","URLSearchParams","q","t","toString"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;CASC,GACD,OAAO,MAAMA,0BAA0B,aAAY;AAEnD,OAAO,MAAMC,kBAAkB,YAAW;AAE1C,sFAAsF,GACtF,OAAO,SAASC,cAAcC,OAAe,EAAEC,KAAa;IAC1D,MAAMC,QAAQ,IAAIC,gBAAgB;QAAEC,GAAGJ;QAASK,GAAGJ;IAAM;IACzD,OAAO,CAAC,CAAC,EAAEH,gBAAgB,CAAC,EAAEI,MAAMI,QAAQ,IAAI;AAClD"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/constants/quote-page.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 customer's quote page (AGL-4094), where a quote's pay link opens.\n *\n * The component id is persisted in screen documents; never rename it. The\n * path is where the site serves the page when it has no page of its own\n * there. It is `pay-quote` rather than `quote` because a business that sells\n * made-to-order work often has a \"Request a quote\" page at `/quote` already,\n * and a page of the site's own at an address always wins over this one: a pay\n * link there would open the request form.\n */\nexport const QUOTE_PAGE_COMPONENT_ID = 'quote-page'\n\nexport const QUOTE_PAGE_PATH = 'pay-quote'\n\n/** The page's address for one quote and its signed link token, relative to the site. */\nexport function quotePageHref(quoteId: string, token: string): string {\n const query = new URLSearchParams({ q: quoteId, t: token })\n return `/${QUOTE_PAGE_PATH}?${query.toString()}`\n}\n\n/** Where the site's built-in sign-in page is (the User Accounts plugin's own route). */\nexport const QUOTE_SIGN_IN_PATH = '/signin'\n\n/**\n * The sign-in page, returning to `back` (the quote page's own path and query)\n * once the customer signs in (AGL-4206). The sign-in block honors `continue`\n * for same-site paths only.\n */\nexport function quoteSignInHref(back: string): string {\n const path = back.startsWith('/') && !back.startsWith('//') ? back : `/${QUOTE_PAGE_PATH}`\n return `${QUOTE_SIGN_IN_PATH}?${new URLSearchParams({ continue: path }).toString()}`\n}\n"],"names":["QUOTE_PAGE_COMPONENT_ID","QUOTE_PAGE_PATH","quotePageHref","quoteId","token","query","URLSearchParams","q","t","toString","QUOTE_SIGN_IN_PATH","quoteSignInHref","back","path","startsWith","continue"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;CASC,GACD,OAAO,MAAMA,0BAA0B,aAAY;AAEnD,OAAO,MAAMC,kBAAkB,YAAW;AAE1C,sFAAsF,GACtF,OAAO,SAASC,cAAcC,OAAe,EAAEC,KAAa;IAC1D,MAAMC,QAAQ,IAAIC,gBAAgB;QAAEC,GAAGJ;QAASK,GAAGJ;IAAM;IACzD,OAAO,CAAC,CAAC,EAAEH,gBAAgB,CAAC,EAAEI,MAAMI,QAAQ,IAAI;AAClD;AAEA,sFAAsF,GACtF,OAAO,MAAMC,qBAAqB,UAAS;AAE3C;;;;CAIC,GACD,OAAO,SAASC,gBAAgBC,IAAY;IAC1C,MAAMC,OAAOD,KAAKE,UAAU,CAAC,QAAQ,CAACF,KAAKE,UAAU,CAAC,QAAQF,OAAO,CAAC,CAAC,EAAEX,iBAAiB;IAC1F,OAAO,GAAGS,mBAAmB,CAAC,EAAE,IAAIJ,gBAAgB;QAAES,UAAUF;IAAK,GAAGJ,QAAQ,IAAI;AACtF"}
@@ -50,7 +50,12 @@ export interface HostCart {
50
50
  createdAtMs?: number;
51
51
  }
52
52
  export declare const CART_MAX_LINES = 50;
53
- export declare const CART_MAX_QUANTITY = 99;
53
+ /**
54
+ * The most of one line a shopper can buy online (AGL-4205): 9,999, the same
55
+ * ceiling a quote line has (`QUOTE_MAX_QUANTITY`). It was 99, which stopped a
56
+ * print shop's 100-, 250- and 500-piece apparel orders at the product page.
57
+ */
58
+ export declare const CART_MAX_QUANTITY = 9999;
54
59
  /**
55
60
  * One cart line's identity: product, variant, use day and add-ons
56
61
  * (AGL-4100). A line with no add-ons keeps the key it always had, so a cart
@@ -22,7 +22,11 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
22
22
  * a stale price. Pure helpers; the cart API owns I/O.
23
23
  */ import { modifierSelectionKey } from "./product-modifiers.js";
24
24
  export const CART_MAX_LINES = 50;
25
- export const CART_MAX_QUANTITY = 99;
25
+ /**
26
+ * The most of one line a shopper can buy online (AGL-4205): 9,999, the same
27
+ * ceiling a quote line has (`QUOTE_MAX_QUANTITY`). It was 99, which stopped a
28
+ * print shop's 100-, 250- and 500-piece apparel orders at the product page.
29
+ */ export const CART_MAX_QUANTITY = 9999;
26
30
  /**
27
31
  * One cart line's identity: product, variant, use day and add-ons
28
32
  * (AGL-4100). A line with no add-ons keeps the key it always had, so a cart
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-cart.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Cart v1 (AGL-293): a server-backed cart doc at\n * `hosts/{hostId}/carts/{cartId}`, keyed by an httpOnly cookie. Lines\n * store only ids + quantity — display data and prices resolve from the\n * product docs at read/checkout time, so a stale cart can never charge\n * a stale price. Pure helpers; the cart API owns I/O.\n */\n\nimport { modifierSelectionKey, type ModifierSelection } from './product-modifiers'\n\nexport interface CartLine {\n productId: string\n /** Absent = the product's default variant. */\n variantId?: string\n quantity: number\n /**\n * The day the shopper chose to use a check-in item (AGL-4043),\n * `YYYY-MM-DD` on the store's calendar. Absent: the day they buy. Two\n * different days of one pass are two lines.\n */\n useDayKey?: string\n /**\n * The add-ons the shopper chose on the product's page (AGL-4100), ids\n * only, in the product's group order: priced from the product on every\n * read and at checkout, never stored with a price. Absent: none. The same\n * product with different choices is a different line.\n */\n modifiers?: ModifierSelection[]\n}\n\n/** `hosts/{hostId}/carts/{cartId}` doc. */\nexport interface HostCart {\n lines: CartLine[]\n /** Storefront customer once signed in (AGL-294 merge). */\n customerId?: string\n updatedAtMs?: number\n createdAtMs?: number\n}\n\nexport const CART_MAX_LINES = 50\nexport const CART_MAX_QUANTITY = 99\n\n/**\n * One cart line's identity: product, variant, use day and add-ons\n * (AGL-4100). A line with no add-ons keeps the key it always had, so a cart\n * stored before add-ons were sold online reads, merges and removes as it did.\n */\nexport function cartLineKey(\n line: Pick<CartLine, 'productId' | 'variantId' | 'useDayKey' | 'modifiers'>,\n): string {\n const base = `${line.productId}:${line.variantId ?? ''}:${line.useDayKey ?? ''}`\n const choices = modifierSelectionKey(line.modifiers)\n return choices ? `${base}:${choices}` : base\n}\n\nconst lineKey = cartLineKey\n\n/**\n * A line quantity, coerced to a whole finite number (AGL-2285).\n *\n * `Math.round(line.quantity)` was the whole sanitiser, and `Math.round(NaN)` is\n * `NaN` — which then walked past the guard below, because `NaN <= 0` is\n * `false`. A cart line with `quantity: NaN` (a legal Firestore double) was\n * stored, and from there `cartCount` reported `NaN` in the mini-cart badge and\n * `cart-checkout.ts` computed `itemsCents`, the platform fee and the Stripe\n * `line_items[n][quantity]` as `NaN` too — so Stripe 400s and the shopper\n * cannot check out AT ALL until they find the poisoned line and remove it.\n *\n * Answering 0 is what makes the existing `<= 0` guard do its job: an\n * unusable quantity removes the line (or refuses to add one) rather than\n * writing a value nothing downstream can compare against. The same lesson as\n * AGL-2229 one collection over — `Math.max`/`Math.min`/`Math.round` propagate\n * `NaN`, they do not discard it.\n */\nfunction wholeQuantity(value: unknown): number {\n const quantity = Math.round(Number(value ?? 0))\n return Number.isFinite(quantity) ? quantity : 0\n}\n\n/**\n * Adds/merges a line (quantities accumulate), clamped to per-line and\n * line-count caps. Quantity ≤ 0 removes the line.\n */\nexport function upsertCartLine(\n cart: Pick<HostCart, 'lines'>,\n line: CartLine,\n mode: 'add' | 'set' = 'add',\n): CartLine[] {\n const quantity = wholeQuantity(line.quantity)\n const key = lineKey(line)\n const existing = cart.lines.find((item) => lineKey(item) === key)\n if (!existing) {\n if (quantity <= 0) return cart.lines\n if (cart.lines.length >= CART_MAX_LINES) return cart.lines\n return [\n ...cart.lines,\n { ...line, quantity: Math.min(CART_MAX_QUANTITY, quantity) },\n ]\n }\n // The STORED side is coerced too (AGL-2285): a line written before this\n // guard, or by any other writer, can still hold a non-finite quantity, and\n // adding to it would carry that forward forever.\n const nextQuantity =\n mode === 'add' ? wholeQuantity(existing.quantity) + quantity : quantity\n if (nextQuantity <= 0) {\n return cart.lines.filter((item) => lineKey(item) !== key)\n }\n return cart.lines.map((item) =>\n lineKey(item) === key\n ? { ...item, quantity: Math.min(CART_MAX_QUANTITY, nextQuantity) }\n : item,\n )\n}\n\nexport function removeCartLine(\n cart: Pick<HostCart, 'lines'>,\n line: Pick<CartLine, 'productId' | 'variantId' | 'useDayKey' | 'modifiers'>,\n): CartLine[] {\n const key = lineKey(line)\n return cart.lines.filter((item) => lineKey(item) !== key)\n}\n\n/** Total units across lines (the mini-cart badge). */\nexport function cartCount(cart: Pick<HostCart, 'lines'> | undefined): number {\n // Coerced per line (AGL-2285) so one stored `NaN` cannot make the badge read\n // `NaN` for a cart that otherwise has real items in it.\n return (cart?.lines ?? []).reduce(\n (sum, line) => sum + wholeQuantity(line?.quantity),\n 0,\n )\n}\n\n/**\n * Merges a guest cart into a customer cart on sign-in (AGL-294):\n * quantities accumulate per line, capped as usual.\n */\nexport function mergeCarts(\n customerCart: Pick<HostCart, 'lines'>,\n guestCart: Pick<HostCart, 'lines'>,\n): CartLine[] {\n let lines = [...customerCart.lines]\n for (const line of guestCart.lines) {\n lines = upsertCartLine({ lines }, line, 'add')\n }\n return lines\n}\n"],"names":["modifierSelectionKey","CART_MAX_LINES","CART_MAX_QUANTITY","cartLineKey","line","base","productId","variantId","useDayKey","choices","modifiers","lineKey","wholeQuantity","value","quantity","Math","round","Number","isFinite","upsertCartLine","cart","mode","key","existing","lines","find","item","length","min","nextQuantity","filter","map","removeCartLine","cartCount","reduce","sum","mergeCarts","customerCart","guestCart"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GAED,SAASA,oBAAoB,QAAgC,yBAAqB;AA+BlF,OAAO,MAAMC,iBAAiB,GAAE;AAChC,OAAO,MAAMC,oBAAoB,GAAE;AAEnC;;;;CAIC,GACD,OAAO,SAASC,YACdC,IAA2E;QAEzCA,iBAAwBA;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AAQe,UAAUJ,MACd,aAAKI;YAAMZ,UAAUC,KAAKa,GAAG,CAAC1B,mBAAmB2B;aACjDH;AAER;AAEA,OAAO,SAASM,eACdZ,IAA6B,EAC7BhB,IAA2E;IAE3E,MAAMkB,MAAMX,QAAQP;IACpB,OAAOgB,KAAKI,KAAK,CAACM,MAAM,CAAC,CAACJ,OAASf,QAAQe,UAAUJ;AACvD;AAEA,oDAAoD,GACpD,OAAO,SAASW,UAAUb,IAAyC;;IACjE,6EAA6E;IAC7E,wDAAwD;IACxD,OAAO,SAACA,wBAAAA,KAAMI,KAAK,mBAAI,EAAE,EAAEU,MAAM,CAC/B,CAACC,KAAK/B,OAAS+B,MAAMvB,cAAcR,wBAAAA,KAAMU,QAAQ,GACjD;AAEJ;AAEA;;;CAGC,GACD,OAAO,SAASsB,WACdC,YAAqC,EACrCC,SAAkC;IAElC,IAAId,QAAQ;WAAIa,aAAab,KAAK;KAAC;IACnC,KAAK,MAAMpB,QAAQkC,UAAUd,KAAK,CAAE;QAClCA,QAAQL,eAAe;YAAEK;QAAM,GAAGpB,MAAM;IAC1C;IACA,OAAOoB;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-cart.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Cart v1 (AGL-293): a server-backed cart doc at\n * `hosts/{hostId}/carts/{cartId}`, keyed by an httpOnly cookie. Lines\n * store only ids + quantity — display data and prices resolve from the\n * product docs at read/checkout time, so a stale cart can never charge\n * a stale price. Pure helpers; the cart API owns I/O.\n */\n\nimport { modifierSelectionKey, type ModifierSelection } from './product-modifiers'\n\nexport interface CartLine {\n productId: string\n /** Absent = the product's default variant. */\n variantId?: string\n quantity: number\n /**\n * The day the shopper chose to use a check-in item (AGL-4043),\n * `YYYY-MM-DD` on the store's calendar. Absent: the day they buy. Two\n * different days of one pass are two lines.\n */\n useDayKey?: string\n /**\n * The add-ons the shopper chose on the product's page (AGL-4100), ids\n * only, in the product's group order: priced from the product on every\n * read and at checkout, never stored with a price. Absent: none. The same\n * product with different choices is a different line.\n */\n modifiers?: ModifierSelection[]\n}\n\n/** `hosts/{hostId}/carts/{cartId}` doc. */\nexport interface HostCart {\n lines: CartLine[]\n /** Storefront customer once signed in (AGL-294 merge). */\n customerId?: string\n updatedAtMs?: number\n createdAtMs?: number\n}\n\nexport const CART_MAX_LINES = 50\n/**\n * The most of one line a shopper can buy online (AGL-4205): 9,999, the same\n * ceiling a quote line has (`QUOTE_MAX_QUANTITY`). It was 99, which stopped a\n * print shop's 100-, 250- and 500-piece apparel orders at the product page.\n */\nexport const CART_MAX_QUANTITY = 9_999\n\n/**\n * One cart line's identity: product, variant, use day and add-ons\n * (AGL-4100). A line with no add-ons keeps the key it always had, so a cart\n * stored before add-ons were sold online reads, merges and removes as it did.\n */\nexport function cartLineKey(\n line: Pick<CartLine, 'productId' | 'variantId' | 'useDayKey' | 'modifiers'>,\n): string {\n const base = `${line.productId}:${line.variantId ?? ''}:${line.useDayKey ?? ''}`\n const choices = modifierSelectionKey(line.modifiers)\n return choices ? `${base}:${choices}` : base\n}\n\nconst lineKey = cartLineKey\n\n/**\n * A line quantity, coerced to a whole finite number (AGL-2285).\n *\n * `Math.round(line.quantity)` was the whole sanitiser, and `Math.round(NaN)` is\n * `NaN` — which then walked past the guard below, because `NaN <= 0` is\n * `false`. A cart line with `quantity: NaN` (a legal Firestore double) was\n * stored, and from there `cartCount` reported `NaN` in the mini-cart badge and\n * `cart-checkout.ts` computed `itemsCents`, the platform fee and the Stripe\n * `line_items[n][quantity]` as `NaN` too — so Stripe 400s and the shopper\n * cannot check out AT ALL until they find the poisoned line and remove it.\n *\n * Answering 0 is what makes the existing `<= 0` guard do its job: an\n * unusable quantity removes the line (or refuses to add one) rather than\n * writing a value nothing downstream can compare against. The same lesson as\n * AGL-2229 one collection over — `Math.max`/`Math.min`/`Math.round` propagate\n * `NaN`, they do not discard it.\n */\nfunction wholeQuantity(value: unknown): number {\n const quantity = Math.round(Number(value ?? 0))\n return Number.isFinite(quantity) ? quantity : 0\n}\n\n/**\n * Adds/merges a line (quantities accumulate), clamped to per-line and\n * line-count caps. Quantity ≤ 0 removes the line.\n */\nexport function upsertCartLine(\n cart: Pick<HostCart, 'lines'>,\n line: CartLine,\n mode: 'add' | 'set' = 'add',\n): CartLine[] {\n const quantity = wholeQuantity(line.quantity)\n const key = lineKey(line)\n const existing = cart.lines.find((item) => lineKey(item) === key)\n if (!existing) {\n if (quantity <= 0) return cart.lines\n if (cart.lines.length >= CART_MAX_LINES) return cart.lines\n return [\n ...cart.lines,\n { ...line, quantity: Math.min(CART_MAX_QUANTITY, quantity) },\n ]\n }\n // The STORED side is coerced too (AGL-2285): a line written before this\n // guard, or by any other writer, can still hold a non-finite quantity, and\n // adding to it would carry that forward forever.\n const nextQuantity =\n mode === 'add' ? wholeQuantity(existing.quantity) + quantity : quantity\n if (nextQuantity <= 0) {\n return cart.lines.filter((item) => lineKey(item) !== key)\n }\n return cart.lines.map((item) =>\n lineKey(item) === key\n ? { ...item, quantity: Math.min(CART_MAX_QUANTITY, nextQuantity) }\n : item,\n )\n}\n\nexport function removeCartLine(\n cart: Pick<HostCart, 'lines'>,\n line: Pick<CartLine, 'productId' | 'variantId' | 'useDayKey' | 'modifiers'>,\n): CartLine[] {\n const key = lineKey(line)\n return cart.lines.filter((item) => lineKey(item) !== key)\n}\n\n/** Total units across lines (the mini-cart badge). */\nexport function cartCount(cart: Pick<HostCart, 'lines'> | undefined): number {\n // Coerced per line (AGL-2285) so one stored `NaN` cannot make the badge read\n // `NaN` for a cart that otherwise has real items in it.\n return (cart?.lines ?? []).reduce(\n (sum, line) => sum + wholeQuantity(line?.quantity),\n 0,\n )\n}\n\n/**\n * Merges a guest cart into a customer cart on sign-in (AGL-294):\n * quantities accumulate per line, capped as usual.\n */\nexport function mergeCarts(\n customerCart: Pick<HostCart, 'lines'>,\n guestCart: Pick<HostCart, 'lines'>,\n): CartLine[] {\n let lines = [...customerCart.lines]\n for (const line of guestCart.lines) {\n lines = upsertCartLine({ lines }, line, 'add')\n }\n return lines\n}\n"],"names":["modifierSelectionKey","CART_MAX_LINES","CART_MAX_QUANTITY","cartLineKey","line","base","productId","variantId","useDayKey","choices","modifiers","lineKey","wholeQuantity","value","quantity","Math","round","Number","isFinite","upsertCartLine","cart","mode","key","existing","lines","find","item","length","min","nextQuantity","filter","map","removeCartLine","cartCount","reduce","sum","mergeCarts","customerCart","guestCart"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;CAMC,GAED,SAASA,oBAAoB,QAAgC,yBAAqB;AA+BlF,OAAO,MAAMC,iBAAiB,GAAE;AAChC;;;;CAIC,GACD,OAAO,MAAMC,oBAAoB,KAAK;AAEtC;;;;CAIC,GACD,OAAO,SAASC,YACdC,IAA2E;QAEzCA,iBAAwBA;IAA1D,MAAMC,OAAO,GAAGD,KAAKE,SAAS,CAAC,CAAC,GAAEF,kBAAAA,KAAKG,SAAS,YAAdH,kBAAkB,GAAG,CAAC,GAAEA,kBAAAA,KAAKI,SAAS,YAAdJ,kBAAkB,IAAI;IAChF,MAAMK,UAAUT,qBAAqBI,KAAKM,SAAS;IACnD,OAAOD,UAAU,GAAGJ,KAAK,CAAC,EAAEI,SAAS,GAAGJ;AAC1C;AAEA,MAAMM,UAAUR;AAEhB;;;;;;;;;;;;;;;;CAgBC,GACD,SAASS,cAAcC,KAAc;IACnC,MAAMC,WAAWC,KAAKC,KAAK,CAACC,OAAOJ,gBAAAA,QAAS;IAC5C,OAAOI,OAAOC,QAA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BAAAA,KAAMU,QAAQ,GACjD;AAEJ;AAEA;;;CAGC,GACD,OAAO,SAASsB,WACdC,YAAqC,EACrCC,SAAkC;IAElC,IAAId,QAAQ;WAAIa,aAAab,KAAK;KAAC;IACnC,KAAK,MAAMpB,QAAQkC,UAAUd,KAAK,CAAE;QAClCA,QAAQL,eAAe;YAAEK;QAAM,GAAGpB,MAAM;IAC1C;IACA,OAAOoB;AACT"}
@@ -256,7 +256,11 @@ export function invoicePayRefusal(order, orderId, /** The store's sales tax choi
256
256
  revision: 1,
257
257
  proofs: [],
258
258
  response: null,
259
- respondable: false
259
+ respondable: false,
260
+ approvalStatements: [],
261
+ proofAccess: 'open',
262
+ proofAccessMessage: null,
263
+ messages: []
260
264
  };
261
265
  }
262
266
  /*==========================================
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-invoices.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n appendOrderEvent,\n formatOrderNumber,\n orderCreatedAtMs,\n type HostOrder,\n type OrderStatus,\n type OrderTimelineEvent,\n} from './commerce-orders'\nimport {\n QUOTE_MIN_CHARGE_CENTS,\n payLinkCheckoutCharge,\n payLinkPaymentsUnavailableMessage,\n payLinkRefusalWithPayments,\n quoteCheckoutCharge,\n quotePageAddress,\n quotePageLines,\n quotePageStatus,\n quotePayRefusal,\n quotePayRefusalMessage,\n quotePayTax,\n type PayLinkStore,\n type QuoteCheckoutCharge,\n type QuotePageView,\n type QuotePayRefusal,\n} from './commerce-quote-pay'\nimport { lastQuoteSend } from './commerce-quote-email'\nimport {\n isQuote,\n quoteIsProofOnly,\n type OrderInvoiceSendRecord,\n type QuoteEmailThread,\n type QuoteTaxBasis,\n} from './commerce-quotes'\nimport type { ResolvedShippingRate } from './commerce-shipping'\nimport { storefrontTaxDecision } from './commerce-tax-decision'\nimport { lineRequiresShipping } from './order-fulfillment'\n\n/*==========================================\n * INVOICES FOR ORDERS AND QUOTES (AGL-4099).\n *\n * The business emails an invoice for an order or a quote: unpaid, it asks\n * for payment through ONE lasting pay link; paid, it is the record. The link\n * is slice 2's (`/pay-quote?q=&t=`, AGL-4094), generalized rather than made\n * twice:\n *\n * - THE TOKEN is unchanged: `<version>.<HMAC(quote-link:hostId:orderId:version)>`,\n * no expiry. An order id names one document under `hosts/{hostId}/orders`\n * whatever its channel, so the same signature serves any order.\n * - THE VERSION is the quote's `quote.linkVersion` for a quote, as before,\n * so every link already sent keeps verifying; any other order keeps its own\n * as `payLink.version` (`orderPayLinkVersion`). Absent reads as 1.\n * - WHICH ORDERS the link opens ({@link orderPayLinkKind}): a quote, and a\n * draft order (`channel: 'draft'`), the two a business composes for a\n * customer to pay online. A register sale still open takes its payment at\n * the register, an online order was paid at checkout, and a marketplace\n * order on its channel, so none of them is linked; their invoices go out\n * paid, as the record.\n * - THE PAGE shows a non-quote order as \"Invoice #N\", with no proofs and no\n * approval ({@link buildInvoicePageView}).\n * - THE CHARGE is priced from the stored lines and totals on every press\n * ({@link invoiceCheckoutCharge}): the draft's discount, its frozen tax (or\n * Stripe Tax at payment where the draft used it), and the shipping rates\n * the draft offered when it was made (`draftShipping`).\n *\n * Pure: the console, the routes and the webhook read the same answers.\n *=========================================*/\n\n/** Which page a pay link opens for an order: a quote, an invoice, or none. */\nexport type OrderPayLinkKind = 'quote' | 'invoice'\n\n/** The most invoice sends an order keeps on record; the oldest go first. */\nexport const INVOICE_MAX_SENDS = 50\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nconst cents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) ? number : 0\n}\n\nconst text = (value: unknown): string | null => {\n const trimmed = typeof value === 'string' ? value.trim() : ''\n return trimmed ? trimmed : null\n}\n\n/**\n * Which page the lasting pay link opens for an order, or null when it opens\n * none: a quote (with its quote section), or a draft order as an invoice.\n */\nexport function orderPayLinkKind(\n order: Pick<HostOrder, 'channel'> & Partial<Pick<HostOrder, 'quote'>> | null | undefined,\n): OrderPayLinkKind | null {\n if (!order) return null\n if (isQuote(order)) return order.quote ? 'quote' : null\n return order.channel === 'draft' ? 'invoice' : null\n}\n\n/** `Invoice #1042`: the order's own number, which a paid quote keeps too. */\nexport function formatInvoiceNumber(order: Pick<HostOrder, 'number'>, orderId?: string): string {\n return `Invoice ${formatOrderNumber(order, orderId)}`\n}\n\nconst PAID_STATUSES: ReadonlySet<OrderStatus | string> = new Set([\n 'paid',\n 'partially_fulfilled',\n 'fulfilled',\n 'delivered',\n])\n\n/** The order is paid (and not refunded or canceled): its invoice is the record. */\nexport function invoiceIsPaid(order: Pick<HostOrder, 'status'> | null | undefined): boolean {\n return PAID_STATUSES.has(String(order?.status ?? ''))\n}\n\n/**\n * When the order was paid: a quote's stamp, else the timeline's `paid`\n * event, else (an order created paid, as checkout's are) when it was made.\n * Null for an order not paid.\n */\nexport function orderPaidAtMs(\n order: Pick<HostOrder, 'status' | 'quote' | 'timeline'> & { createdAtMs?: number } | null | undefined,\n): number | null {\n if (!order || order.status === 'pending') return null\n const stamped = Number(order.quote?.paidAtMs)\n if (Number.isFinite(stamped) && stamped > 0) return stamped\n const event = (order.timeline ?? []).find((entry) => entry?.event === 'paid')\n if (event && Number(event.atMs) > 0) return Number(event.atMs)\n const created = orderCreatedAtMs(order as never)\n return created > 0 ? created : null\n}\n\n/*==========================================\n * WHAT AN INVOICE'S PAY LINK CHARGES\n *=========================================*/\n\n/** What an invoice's Checkout Session charges, with the rates a draft lets the buyer pick from. */\nexport interface InvoiceCheckoutCharge extends QuoteCheckoutCharge {\n /** The draft's shipping rates, picked at payment; empty when shipping is fixed or there is none. */\n shippingOptions: ResolvedShippingRate[]\n /** Where those rates ship; empty with none. */\n shippingCountries: string[]\n}\n\n/**\n * The tax basis an order's stored figures give its invoice: Stripe Tax at\n * payment where the order was composed under it, its frozen tax as a fixed\n * figure (charged as the rate that yields it on the taxed line, the way a tax\n * service's quote is), else none.\n */\nexport function invoiceTaxBasis(order: Pick<HostOrder, 'taxMode' | 'totals'>): QuoteTaxBasis {\n if (order.taxMode === 'stripe-automatic') return { kind: 'at-payment' }\n const taxCents = Math.max(0, cents(order.totals?.taxCents))\n if (taxCents > 0) return { kind: 'service', taxCents }\n return { kind: 'none', reason: 'not-collected' }\n}\n\n/** A stored draft rate, as Stripe is given it, or null for one that is not a rate. */\nfunction draftRate(option: unknown): ResolvedShippingRate | null {\n if (!option || typeof option !== 'object') return null\n const source = option as Record<string, unknown>\n const name = text(source['name'])\n const amountCents = cents(source['amountCents'])\n if (!name || amountCents < 0) return null\n return { rateId: String(source['rateId'] ?? '') || name, name, amountCents }\n}\n\n/**\n * What an invoice's pay link charges, from the stored order alone. A quote is\n * charged as slice 2 charges it; any other order from its lines, its\n * discount, its tax ({@link invoiceTaxBasis}) and, for a draft, the shipping\n * rates it offered when it was made (Stripe asks for the address and the\n * buyer picks one, as on the draft's first link).\n */\nexport function invoiceCheckoutCharge(\n order: Pick<HostOrder, 'number' | 'lineItems' | 'quote' | 'totals' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null,\n): InvoiceCheckoutCharge {\n if (order.quote) return { ...quoteCheckoutCharge(order, orderId, store), shippingOptions: [], shippingCountries: [] }\n const discountCents = Math.max(0, cents(order.totals?.discountCents))\n const charge = payLinkCheckoutCharge({\n lineItems: order.lineItems ?? [],\n tax: invoiceTaxBasis(order),\n discount: discountCents > 0 ? { kind: 'amount', amountCents: discountCents } : null,\n shippingCents: 0,\n label: formatInvoiceNumber(order, orderId),\n })\n const options = (order.draftShipping?.options ?? [])\n .map(draftRate)\n .filter((rate): rate is ResolvedShippingRate => rate !== null)\n .slice(0, 5)\n const countries = (order.draftShipping?.countries ?? [])\n .map((country) => String(country ?? '').trim().toUpperCase())\n .filter((country) => /^[A-Z]{2}$/.test(country))\n return { ...charge, shippingOptions: options, shippingCountries: options.length ? countries : [] }\n}\n\n/*==========================================\n * WHETHER AN INVOICE CAN BE PAID NOW\n *=========================================*/\n\n/**\n * Why an order cannot be paid through its pay link now: a quote's reasons,\n * and two of an invoice's own. `not-payable` is an order the link does not\n * open (a register sale still open, say); `shipping-unknown` is a draft made\n * before drafts kept their shipping rates, whose shipping cannot be charged.\n */\nexport type InvoicePayRefusal = QuotePayRefusal | 'not-payable' | 'shipping-unknown'\n\nexport function invoicePayRefusal(\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote' | 'totals' | 'taxMode' | 'channel'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n /** The store's sales tax choice; with it, a store that has not chosen refuses (AGL-1999). */\n store?: PayLinkStore | null,\n): InvoicePayRefusal | null {\n const kind = orderPayLinkKind(order)\n if (kind === 'quote') return quotePayRefusal(order, orderId, store)\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n if (order.status !== 'pending') return 'paid'\n if (kind !== 'invoice') return 'not-payable'\n if (store && storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') return 'tax-undecided'\n const ships = (order.lineItems ?? []).some((line) => line && !line.included && lineRequiresShipping(line))\n if (ships && !order.draftShipping) return 'shipping-unknown'\n if (invoiceCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay'\n return null\n}\n\n/** What the customer is told for a refusal, in the page's words: \"quote\" or \"invoice\". */\nexport function invoicePayRefusalMessage(\n reason: InvoicePayRefusal,\n storeName: string,\n kind: OrderPayLinkKind,\n): string {\n const business = storeName.trim() || 'the business'\n if (kind === 'quote' && reason !== 'not-payable' && reason !== 'shipping-unknown') {\n return quotePayRefusalMessage(reason, storeName)\n }\n switch (reason) {\n case 'paid':\n return 'This invoice has been paid.'\n case 'closed':\n return `This invoice is closed. Contact ${business} with any questions.`\n case 'approval-required':\n return `${business} asks you to approve the proof before you pay.`\n case 'tax-undecided':\n return `${business} has not finished setting up payments. Contact them to pay this invoice.`\n case 'nothing-to-pay':\n return `This invoice has nothing to pay by card. Contact ${business} with any questions.`\n case 'not-payable':\n case 'shipping-unknown':\n return `This invoice can’t be paid online. Contact ${business} to pay it.`\n }\n}\n\n/*==========================================\n * WHAT THE CONSOLE TELLS THE BUSINESS\n *=========================================*/\n\n/**\n * What stands between a pay link and a payment that the business fixes in\n * the console (AGL-4162):\n *\n * - `payments`: the workspace can't take card payments yet.\n * - `tax-undecided`: the store has not chosen how it handles sales tax.\n * - `tax-save`: the quote was saved before the store chose, and the store's\n * choice now prices it only on a save (`quotePayTax`'s `save`).\n */\nexport type PayLinkGap = 'payments' | 'tax-undecided' | 'tax-save'\n\n/**\n * What the console's \"Customers can't pay this … online yet\" notice names,\n * for an unpaid quote or a draft order's invoice, or a quote not saved yet\n * (`order: null`), which will be saved under the store's choice as it stands.\n * The same answers Pay refuses on: `invoicePayRefusal` with the store, and\n * the payment account check the page and Pay share.\n *\n * Null while either answer is unknown, so the notice waits rather than tell a\n * store that is set up to set up. Empty for anything the pay link does not\n * charge (a paid, closed or unlinked order) or that nothing stands in front of.\n * A refusal that is not the business's setup (approval, an amount too small)\n * is said where it is decided, not here.\n */\nexport function payLinkGaps(input: {\n order: (Pick<HostOrder, 'status' | 'channel'> & Partial<Pick<HostOrder, 'quote' | 'lineItems'>>) | null\n /** The workspace can take card payments; null while that is unknown. */\n paymentsReady: boolean | null\n /** The store's sales tax choice; undefined while it is being read. */\n store: PayLinkStore | undefined\n}): PayLinkGap[] | null {\n const { order, store } = input\n if (input.paymentsReady === null || store === undefined) return null\n if (order && (order.status !== 'pending' || orderPayLinkKind(order) === null)) return []\n // A proof only quote charges nothing until it has lines (AGL-4184).\n if (order?.quote && quoteIsProofOnly(order)) return []\n const gaps: PayLinkGap[] = []\n if (!input.paymentsReady) gaps.push('payments')\n if (storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') gaps.push('tax-undecided')\n else if (order?.quote && quotePayTax(order.quote, store).source === 'save') gaps.push('tax-save')\n return gaps\n}\n\n/*==========================================\n * THE CUSTOMER'S PAGE FOR AN INVOICE\n *=========================================*/\n\n/**\n * The pay link's page for an order that is not a quote: \"Invoice #N\", its\n * lines and totals, the customer's addresses, and Pay while it is unpaid. No\n * proofs, no approval, no notes or terms (an order carries none). Allow-listed\n * as the quote's view is: the order's email, phone, Stripe ids and timeline\n * never leave the server.\n */\nexport function buildInvoicePageView(input: {\n order: Pick<\n HostOrder,\n | 'number'\n | 'status'\n | 'channel'\n | 'lineItems'\n | 'totals'\n | 'quote'\n | 'timeline'\n | 'taxMode'\n | 'customerName'\n | 'billingAddress'\n | 'shippingAddress'\n > &\n Partial<Pick<HostOrder, 'draftShipping'>> & { createdAtMs?: number }\n orderId: string\n storeName: string\n currency: string\n /** The order's status page, once paid. */\n receiptUrl?: string | null\n /** The store's sales tax choice; with it, a store that has not chosen refuses Pay (AGL-1999). */\n store?: PayLinkStore | null\n /** Whether the business can take a card payment now; absent, it is not judged here. */\n paymentsReady?: boolean\n}): QuotePageView {\n const { order } = input\n const status = quotePageStatus(order.status)\n const unpaid = status.status === 'unpaid'\n const charge = invoiceCheckoutCharge(order, input.orderId, input.store)\n const refused = unpaid\n ? payLinkRefusalWithPayments(invoicePayRefusal(order, input.orderId, input.store), input.paymentsReady)\n : null\n const stored = order.totals\n const totals =\n unpaid || !stored\n ? {\n itemsCents: charge.itemsCents,\n discountCents: charge.discountCents,\n shippingCents: charge.shippingCents,\n taxCents: charge.taxCents,\n totalCents: charge.totalCents,\n }\n : {\n itemsCents: cents(stored.itemsCents),\n discountCents: cents(stored.discountCents),\n shippingCents: cents(stored.shippingCents),\n taxCents: cents(stored.taxCents),\n totalCents: cents(stored.totalCents),\n }\n const taxAtPayment = unpaid && charge.taxAtPayment\n const created = orderCreatedAtMs(order as never)\n return {\n state: 'quote',\n kind: 'invoice',\n proofOnly: false,\n storeName: input.storeName,\n number: formatInvoiceNumber(order, input.orderId),\n dateMs: created > 0 ? created : null,\n // An invoice is not edited; the page has no version to send back.\n version: 0,\n currency: input.currency || 'USD',\n customerName: text(order.customerName),\n company: null,\n billTo: quotePageAddress(order.billingAddress),\n shipTo: quotePageAddress(order.shippingAddress),\n lines: quotePageLines(order.lineItems ?? []),\n totals,\n discountLabel: null,\n taxLabel: taxAtPayment ? 'Tax is added at payment' : 'Tax',\n taxAtPayment,\n shippingAtPayment: unpaid && charge.shippingOptions.length > 0,\n notes: null,\n terms: null,\n status: status.status,\n statusLabel: status.label,\n paidAtMs: orderPaidAtMs(order),\n receiptUrl: unpaid ? null : (input.receiptUrl ?? null),\n approvalRequired: false,\n payable: unpaid && refused === null,\n notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'invoice') : null,\n taxKey: null,\n revision: 1,\n proofs: [],\n response: null,\n respondable: false,\n }\n}\n\n/*==========================================\n * EMAILING AN INVOICE\n *=========================================*/\n\n/** The order's invoice sends on record, oldest first. */\nexport function invoiceSends(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord[] {\n return Array.isArray(order?.invoiceSends)\n ? order.invoiceSends.filter((send) => send && typeof send === 'object')\n : []\n}\n\n/** The last time the order's invoice was emailed, or null. */\nexport function lastInvoiceSend(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord | null {\n const sends = invoiceSends(order)\n return sends.length ? sends[sends.length - 1] : null\n}\n\n/** Where the invoice goes: what was typed, else the order's customer, else a quote's. */\nexport function invoiceSendRecipient(\n order: Pick<HostOrder, 'customerEmail' | 'quote'> | null | undefined,\n typed: string | null | undefined,\n): string {\n return (\n String(typed ?? '').trim() ||\n String(order?.customerEmail ?? '').trim() ||\n String(order?.quote?.customer?.email ?? '').trim()\n )\n}\n\n/**\n * Who the console's Send invoice form starts addressed to: the customer's\n * email, else where the last invoice went, else (for a quote) where the quote\n * was last emailed, so an order or quote that names no email still opens\n * addressed to the customer it was already sent to.\n */\nexport function invoiceSendPrefill(order: Pick<HostOrder, 'customerEmail' | 'quote' | 'invoiceSends'> | null | undefined): string {\n return (\n invoiceSendRecipient(order, null) ||\n String(lastInvoiceSend(order)?.to ?? '').trim() ||\n String(lastQuoteSend(order?.quote)?.to ?? '').trim()\n )\n}\n\n/**\n * The conversation an invoice replies into: a quote's own (its emails, and a\n * request's confirmation before them), else the order's, which the first\n * invoice starts.\n */\nexport function invoiceEmailThread(\n order: Pick<HostOrder, 'quote' | 'emailThread'> | null | undefined,\n): QuoteEmailThread | null {\n if (order?.quote) return order.quote.emailThread ?? null\n return order?.emailThread ?? null\n}\n\n/**\n * The subject an invoice defaults to: the conversation's, so it stays one\n * conversation in the customer's mailbox, else `Invoice #1042 from Acme Signs`.\n */\nexport function invoiceEmailDefaultSubject(\n order: Pick<HostOrder, 'number' | 'quote' | 'emailThread'>,\n businessName: string,\n orderId?: string,\n): string {\n const thread = String(invoiceEmailThread(order)?.subject ?? '').trim()\n if (thread) return thread\n const name = String(businessName ?? '').trim()\n const number = formatInvoiceNumber(order, orderId)\n return name ? `${number} from ${name}` : number\n}\n\n/** Why an invoice cannot be emailed now, and what the console says. */\nexport type InvoiceSendRefusal =\n | 'unknown'\n | 'closed'\n | 'empty'\n | 'not-payable'\n | 'approval-required'\n | 'tax-undecided'\n | 'tax-save'\n | 'nothing-to-pay'\n | 'shipping-unknown'\n | 'no-address'\n | 'bad-address'\n\n/**\n * Why the order's invoice cannot be emailed to `to` now, if it cannot:\n * a canceled or refunded order, one with nothing on it, an unpaid order its\n * pay link cannot take payment for (and why), and the address.\n */\nexport function invoiceSendRefusal(\n order:\n | (Pick<HostOrder, 'number' | 'status' | 'channel' | 'lineItems' | 'totals' | 'quote' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>)\n | null\n | undefined,\n orderId: string,\n to: string,\n /** The store's sales tax choice, as the pay link reads it (`invoicePayRefusal`). */\n store?: PayLinkStore | null,\n): InvoiceSendRefusal | null {\n if (!order) return 'unknown'\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n const lines = (order.lineItems ?? []).filter(Boolean)\n if (!lines.length && cents(order.totals?.totalCents) <= 0) return 'empty'\n if (!invoiceIsPaid(order)) {\n const refused = invoicePayRefusal(order, orderId, store)\n if (refused === 'closed') return 'closed'\n // A quote saved before the store chose: the store has chosen, and a save prices it.\n if (refused === 'tax-undecided' && order.quote && quotePayTax(order.quote, store).source === 'save') {\n return 'tax-save'\n }\n if (refused && refused !== 'paid') return refused\n }\n if (!to) return 'no-address'\n if (to.length > 320 || !EMAIL.test(to)) return 'bad-address'\n return null\n}\n\n/** What the console says for a refused invoice send. */\nexport function invoiceSendRefusalMessage(reason: InvoiceSendRefusal): string {\n switch (reason) {\n case 'unknown':\n return 'Unknown order'\n case 'closed':\n return 'This order was canceled or refunded, so it has no invoice to send.'\n case 'empty':\n return 'This order has no items and no total, so there is nothing to put on an invoice.'\n case 'not-payable':\n return 'This order isn’t paid yet, and it can’t be paid online from an invoice. Take its payment where the sale was made, then send the invoice.'\n case 'approval-required':\n return 'This quote asks your customer to approve the proof before they pay, and they haven’t yet. Send the quote so they can approve it, then send the invoice.'\n case 'tax-undecided':\n return 'Sales tax isn’t set up for this store yet, so the invoice can’t be paid online. Finish the tax settings, then send it.'\n case 'tax-save':\n return 'This quote was saved before your store chose how it handles sales tax. Save the quote again, then send the invoice.'\n case 'nothing-to-pay':\n return 'This invoice totals less than $0.50, so it can’t be paid by card.'\n case 'shipping-unknown':\n return 'This draft order was made before invoices could charge its shipping, so its invoice can’t be paid online. Make a new draft order and send its invoice.'\n case 'no-address':\n return 'This order has no email for the customer. Type where to send the invoice.'\n case 'bad-address':\n return 'Enter a valid email address to send the invoice to.'\n }\n}\n\n/** The HTTP status a refused send answers with. */\nexport function invoiceSendRefusalStatus(reason: InvoiceSendRefusal): number {\n if (reason === 'unknown') return 404\n if (reason === 'no-address' || reason === 'bad-address') return 400\n return 409\n}\n\n/**\n * What an invoice email changes on the order, as a merge: the send on\n * record, a line on the timeline, and the conversation moved on, on the\n * quote for a quote and on the order otherwise.\n */\nexport function invoiceSendPatch(\n order: Pick<HostOrder, 'timeline' | 'invoiceSends' | 'quote'>,\n send: OrderInvoiceSendRecord,\n thread: QuoteEmailThread,\n): {\n timeline: OrderTimelineEvent[]\n invoiceSends: OrderInvoiceSendRecord[]\n emailThread?: QuoteEmailThread\n quote?: { emailThread: QuoteEmailThread }\n} {\n return {\n timeline: appendOrderEvent(\n order,\n 'invoice-sent',\n // The address is on the send record, which erasure clears; the timeline keeps none.\n `${send.paid ? 'Paid invoice' : 'Invoice'} emailed to the customer by ${send.by}`,\n send.atMs,\n ),\n invoiceSends: [...invoiceSends(order), send].slice(-INVOICE_MAX_SENDS),\n ...(order.quote ? { quote: { emailThread: thread } } : { emailThread: thread }),\n }\n}\n"],"names":["appendOrderEvent","formatOrderNumber","orderCreatedAtMs","QUOTE_MIN_CHARGE_CENTS","payLinkCheckoutCharge","payLinkPaymentsUnavailableMessage","payLinkRefusalWithPayments","quoteCheckoutCharge","quotePageAddress","quotePageLines","quotePageStatus","quotePayRefusal","quotePayRefusalMessage","quotePayTax","lastQuoteSend","isQuote","quoteIsProofOnly","storefrontTaxDecision","lineRequiresShipping","INVOICE_MAX_SENDS","EMAIL","cents","value","number","Math","round","Number","isFinite","text","trimmed","trim","orderPayLinkKind","order","quote","channel","formatInvoiceNumber","orderId","PAID_STATUSES","Set","invoiceIsPaid","has","String","status","orderPaidAtMs","stamped","paidAtMs","event","timeline","find","entry","atMs","created","invoiceTaxBasis","taxMode","kind","taxCents","max","totals","reason","draftRate","option","source","name","amountCents","rateId","invoiceCheckoutCharge","store","shippingOptions","shippingCountries","discountCents","charge","lineItems","tax","discount","shippingCents","label","options","draftShipping","map","filter","rate","slice","countries","country","toUpperCase","test","length","invoicePayRefusal","settings","ships","some","line","included","totalCents","invoicePayRefusalMessage","storeName","business","payLinkGaps","input","paymentsReady","undefined","gaps","push","buildInvoicePageView","unpaid","refused","stored","itemsCents","taxAtPayment","state","proofOnly","dateMs","version","currency","customerName","company","billTo","billingAddress","shipTo","shippingAddress","lines","discountLabel","taxLabel","shippingAtPayment","notes","terms","statusLabel","receiptUrl","approvalRequired","payable","notPayableMessage","taxKey","revision","proofs","response","respondable","invoiceSends","Array","isArray","send","lastInvoiceSend","sends","invoiceSendRecipient","typed","customerEmail","customer","email","invoiceSendPrefill","to","invoiceEmailThread","emailThread","invoiceEmailDefaultSubject","businessName","thread","subject","invoiceSendRefusal","Boolean","invoiceSendRefusalMessage","invoiceSendRefusalStatus","invoiceSendPatch","paid","by"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,QAIX,uBAAmB;AAC1B,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,iCAAiC,EACjCC,0BAA0B,EAC1BC,mBAAmB,EACnBC,gBAAgB,EAChBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,sBAAsB,EACtBC,WAAW,QAKN,0BAAsB;AAC7B,SAASC,aAAa,QAAQ,4BAAwB;AACtD,SACEC,OAAO,EACPC,gBAAgB,QAIX,uBAAmB;AAE1B,SAASC,qBAAqB,QAAQ,6BAAyB;AAC/D,SAASC,oBAAoB,QAAQ,yBAAqB;AAmC1D,0EAA0E,GAC1E,OAAO,MAAMC,oBAAoB,GAAE;AAEnC,MAAMC,QAAQ;AAEd,MAAMC,QAAQ,CAACC;IACb,MAAMC,SAASC,KAAKC,KAAK,CAACC,OAAOJ;IACjC,OAAOI,OAAOC,QAAQ,CAACJ,UAAUA,SAAS;AAC5C;AA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,OAAO;QACL1G,UAAU/C,iBACRgC,OACA,gBACA,oFAAoF;QACpF,GAAG2G,KAAKqB,IAAI,GAAG,iBAAiB,UAAU,4BAA4B,EAAErB,KAAKsB,EAAE,EAAE,EACjFtB,KAAKzF,IAAI;QAEXsF,cAAc;eAAIA,aAAaxG;YAAQ2G;SAAK,CAAC1D,KAAK,CAAC,CAAC9D;OAChDa,MAAMC,KAAK,GAAG;QAAEA,OAAO;YAAEqH,aAAaG;QAAO;IAAE,IAAI;QAAEH,aAAaG;IAAO;AAEjF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-invoices.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n appendOrderEvent,\n formatOrderNumber,\n orderCreatedAtMs,\n type HostOrder,\n type OrderStatus,\n type OrderTimelineEvent,\n} from './commerce-orders'\nimport {\n QUOTE_MIN_CHARGE_CENTS,\n payLinkCheckoutCharge,\n payLinkPaymentsUnavailableMessage,\n payLinkRefusalWithPayments,\n quoteCheckoutCharge,\n quotePageAddress,\n quotePageLines,\n quotePageStatus,\n quotePayRefusal,\n quotePayRefusalMessage,\n quotePayTax,\n type PayLinkStore,\n type QuoteCheckoutCharge,\n type QuotePageView,\n type QuotePayRefusal,\n} from './commerce-quote-pay'\nimport { lastQuoteSend } from './commerce-quote-email'\nimport {\n isQuote,\n quoteIsProofOnly,\n type OrderInvoiceSendRecord,\n type QuoteEmailThread,\n type QuoteTaxBasis,\n} from './commerce-quotes'\nimport type { ResolvedShippingRate } from './commerce-shipping'\nimport { storefrontTaxDecision } from './commerce-tax-decision'\nimport { lineRequiresShipping } from './order-fulfillment'\n\n/*==========================================\n * INVOICES FOR ORDERS AND QUOTES (AGL-4099).\n *\n * The business emails an invoice for an order or a quote: unpaid, it asks\n * for payment through ONE lasting pay link; paid, it is the record. The link\n * is slice 2's (`/pay-quote?q=&t=`, AGL-4094), generalized rather than made\n * twice:\n *\n * - THE TOKEN is unchanged: `<version>.<HMAC(quote-link:hostId:orderId:version)>`,\n * no expiry. An order id names one document under `hosts/{hostId}/orders`\n * whatever its channel, so the same signature serves any order.\n * - THE VERSION is the quote's `quote.linkVersion` for a quote, as before,\n * so every link already sent keeps verifying; any other order keeps its own\n * as `payLink.version` (`orderPayLinkVersion`). Absent reads as 1.\n * - WHICH ORDERS the link opens ({@link orderPayLinkKind}): a quote, and a\n * draft order (`channel: 'draft'`), the two a business composes for a\n * customer to pay online. A register sale still open takes its payment at\n * the register, an online order was paid at checkout, and a marketplace\n * order on its channel, so none of them is linked; their invoices go out\n * paid, as the record.\n * - THE PAGE shows a non-quote order as \"Invoice #N\", with no proofs and no\n * approval ({@link buildInvoicePageView}).\n * - THE CHARGE is priced from the stored lines and totals on every press\n * ({@link invoiceCheckoutCharge}): the draft's discount, its frozen tax (or\n * Stripe Tax at payment where the draft used it), and the shipping rates\n * the draft offered when it was made (`draftShipping`).\n *\n * Pure: the console, the routes and the webhook read the same answers.\n *=========================================*/\n\n/** Which page a pay link opens for an order: a quote, an invoice, or none. */\nexport type OrderPayLinkKind = 'quote' | 'invoice'\n\n/** The most invoice sends an order keeps on record; the oldest go first. */\nexport const INVOICE_MAX_SENDS = 50\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nconst cents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) ? number : 0\n}\n\nconst text = (value: unknown): string | null => {\n const trimmed = typeof value === 'string' ? value.trim() : ''\n return trimmed ? trimmed : null\n}\n\n/**\n * Which page the lasting pay link opens for an order, or null when it opens\n * none: a quote (with its quote section), or a draft order as an invoice.\n */\nexport function orderPayLinkKind(\n order: Pick<HostOrder, 'channel'> & Partial<Pick<HostOrder, 'quote'>> | null | undefined,\n): OrderPayLinkKind | null {\n if (!order) return null\n if (isQuote(order)) return order.quote ? 'quote' : null\n return order.channel === 'draft' ? 'invoice' : null\n}\n\n/** `Invoice #1042`: the order's own number, which a paid quote keeps too. */\nexport function formatInvoiceNumber(order: Pick<HostOrder, 'number'>, orderId?: string): string {\n return `Invoice ${formatOrderNumber(order, orderId)}`\n}\n\nconst PAID_STATUSES: ReadonlySet<OrderStatus | string> = new Set([\n 'paid',\n 'partially_fulfilled',\n 'fulfilled',\n 'delivered',\n])\n\n/** The order is paid (and not refunded or canceled): its invoice is the record. */\nexport function invoiceIsPaid(order: Pick<HostOrder, 'status'> | null | undefined): boolean {\n return PAID_STATUSES.has(String(order?.status ?? ''))\n}\n\n/**\n * When the order was paid: a quote's stamp, else the timeline's `paid`\n * event, else (an order created paid, as checkout's are) when it was made.\n * Null for an order not paid.\n */\nexport function orderPaidAtMs(\n order: Pick<HostOrder, 'status' | 'quote' | 'timeline'> & { createdAtMs?: number } | null | undefined,\n): number | null {\n if (!order || order.status === 'pending') return null\n const stamped = Number(order.quote?.paidAtMs)\n if (Number.isFinite(stamped) && stamped > 0) return stamped\n const event = (order.timeline ?? []).find((entry) => entry?.event === 'paid')\n if (event && Number(event.atMs) > 0) return Number(event.atMs)\n const created = orderCreatedAtMs(order as never)\n return created > 0 ? created : null\n}\n\n/*==========================================\n * WHAT AN INVOICE'S PAY LINK CHARGES\n *=========================================*/\n\n/** What an invoice's Checkout Session charges, with the rates a draft lets the buyer pick from. */\nexport interface InvoiceCheckoutCharge extends QuoteCheckoutCharge {\n /** The draft's shipping rates, picked at payment; empty when shipping is fixed or there is none. */\n shippingOptions: ResolvedShippingRate[]\n /** Where those rates ship; empty with none. */\n shippingCountries: string[]\n}\n\n/**\n * The tax basis an order's stored figures give its invoice: Stripe Tax at\n * payment where the order was composed under it, its frozen tax as a fixed\n * figure (charged as the rate that yields it on the taxed line, the way a tax\n * service's quote is), else none.\n */\nexport function invoiceTaxBasis(order: Pick<HostOrder, 'taxMode' | 'totals'>): QuoteTaxBasis {\n if (order.taxMode === 'stripe-automatic') return { kind: 'at-payment' }\n const taxCents = Math.max(0, cents(order.totals?.taxCents))\n if (taxCents > 0) return { kind: 'service', taxCents }\n return { kind: 'none', reason: 'not-collected' }\n}\n\n/** A stored draft rate, as Stripe is given it, or null for one that is not a rate. */\nfunction draftRate(option: unknown): ResolvedShippingRate | null {\n if (!option || typeof option !== 'object') return null\n const source = option as Record<string, unknown>\n const name = text(source['name'])\n const amountCents = cents(source['amountCents'])\n if (!name || amountCents < 0) return null\n return { rateId: String(source['rateId'] ?? '') || name, name, amountCents }\n}\n\n/**\n * What an invoice's pay link charges, from the stored order alone. A quote is\n * charged as slice 2 charges it; any other order from its lines, its\n * discount, its tax ({@link invoiceTaxBasis}) and, for a draft, the shipping\n * rates it offered when it was made (Stripe asks for the address and the\n * buyer picks one, as on the draft's first link).\n */\nexport function invoiceCheckoutCharge(\n order: Pick<HostOrder, 'number' | 'lineItems' | 'quote' | 'totals' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null,\n): InvoiceCheckoutCharge {\n if (order.quote) return { ...quoteCheckoutCharge(order, orderId, store), shippingOptions: [], shippingCountries: [] }\n const discountCents = Math.max(0, cents(order.totals?.discountCents))\n const charge = payLinkCheckoutCharge({\n lineItems: order.lineItems ?? [],\n tax: invoiceTaxBasis(order),\n discount: discountCents > 0 ? { kind: 'amount', amountCents: discountCents } : null,\n shippingCents: 0,\n label: formatInvoiceNumber(order, orderId),\n })\n const options = (order.draftShipping?.options ?? [])\n .map(draftRate)\n .filter((rate): rate is ResolvedShippingRate => rate !== null)\n .slice(0, 5)\n const countries = (order.draftShipping?.countries ?? [])\n .map((country) => String(country ?? '').trim().toUpperCase())\n .filter((country) => /^[A-Z]{2}$/.test(country))\n return { ...charge, shippingOptions: options, shippingCountries: options.length ? countries : [] }\n}\n\n/*==========================================\n * WHETHER AN INVOICE CAN BE PAID NOW\n *=========================================*/\n\n/**\n * Why an order cannot be paid through its pay link now: a quote's reasons,\n * and two of an invoice's own. `not-payable` is an order the link does not\n * open (a register sale still open, say); `shipping-unknown` is a draft made\n * before drafts kept their shipping rates, whose shipping cannot be charged.\n */\nexport type InvoicePayRefusal = QuotePayRefusal | 'not-payable' | 'shipping-unknown'\n\nexport function invoicePayRefusal(\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote' | 'totals' | 'taxMode' | 'channel'> &\n Partial<Pick<HostOrder, 'draftShipping'>>,\n orderId: string,\n /** The store's sales tax choice; with it, a store that has not chosen refuses (AGL-1999). */\n store?: PayLinkStore | null,\n): InvoicePayRefusal | null {\n const kind = orderPayLinkKind(order)\n if (kind === 'quote') return quotePayRefusal(order, orderId, store)\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n if (order.status !== 'pending') return 'paid'\n if (kind !== 'invoice') return 'not-payable'\n if (store && storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') return 'tax-undecided'\n const ships = (order.lineItems ?? []).some((line) => line && !line.included && lineRequiresShipping(line))\n if (ships && !order.draftShipping) return 'shipping-unknown'\n if (invoiceCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay'\n return null\n}\n\n/** What the customer is told for a refusal, in the page's words: \"quote\" or \"invoice\". */\nexport function invoicePayRefusalMessage(\n reason: InvoicePayRefusal,\n storeName: string,\n kind: OrderPayLinkKind,\n): string {\n const business = storeName.trim() || 'the business'\n if (kind === 'quote' && reason !== 'not-payable' && reason !== 'shipping-unknown') {\n return quotePayRefusalMessage(reason, storeName)\n }\n switch (reason) {\n case 'paid':\n return 'This invoice has been paid.'\n case 'closed':\n return `This invoice is closed. Contact ${business} with any questions.`\n case 'approval-required':\n return `${business} asks you to approve the proof before you pay.`\n case 'tax-undecided':\n return `${business} has not finished setting up payments. Contact them to pay this invoice.`\n case 'nothing-to-pay':\n return `This invoice has nothing to pay by card. Contact ${business} with any questions.`\n case 'not-payable':\n case 'shipping-unknown':\n return `This invoice can’t be paid online. Contact ${business} to pay it.`\n }\n}\n\n/*==========================================\n * WHAT THE CONSOLE TELLS THE BUSINESS\n *=========================================*/\n\n/**\n * What stands between a pay link and a payment that the business fixes in\n * the console (AGL-4162):\n *\n * - `payments`: the workspace can't take card payments yet.\n * - `tax-undecided`: the store has not chosen how it handles sales tax.\n * - `tax-save`: the quote was saved before the store chose, and the store's\n * choice now prices it only on a save (`quotePayTax`'s `save`).\n */\nexport type PayLinkGap = 'payments' | 'tax-undecided' | 'tax-save'\n\n/**\n * What the console's \"Customers can't pay this … online yet\" notice names,\n * for an unpaid quote or a draft order's invoice, or a quote not saved yet\n * (`order: null`), which will be saved under the store's choice as it stands.\n * The same answers Pay refuses on: `invoicePayRefusal` with the store, and\n * the payment account check the page and Pay share.\n *\n * Null while either answer is unknown, so the notice waits rather than tell a\n * store that is set up to set up. Empty for anything the pay link does not\n * charge (a paid, closed or unlinked order) or that nothing stands in front of.\n * A refusal that is not the business's setup (approval, an amount too small)\n * is said where it is decided, not here.\n */\nexport function payLinkGaps(input: {\n order: (Pick<HostOrder, 'status' | 'channel'> & Partial<Pick<HostOrder, 'quote' | 'lineItems'>>) | null\n /** The workspace can take card payments; null while that is unknown. */\n paymentsReady: boolean | null\n /** The store's sales tax choice; undefined while it is being read. */\n store: PayLinkStore | undefined\n}): PayLinkGap[] | null {\n const { order, store } = input\n if (input.paymentsReady === null || store === undefined) return null\n if (order && (order.status !== 'pending' || orderPayLinkKind(order) === null)) return []\n // A proof only quote charges nothing until it has lines (AGL-4184).\n if (order?.quote && quoteIsProofOnly(order)) return []\n const gaps: PayLinkGap[] = []\n if (!input.paymentsReady) gaps.push('payments')\n if (storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') gaps.push('tax-undecided')\n else if (order?.quote && quotePayTax(order.quote, store).source === 'save') gaps.push('tax-save')\n return gaps\n}\n\n/*==========================================\n * THE CUSTOMER'S PAGE FOR AN INVOICE\n *=========================================*/\n\n/**\n * The pay link's page for an order that is not a quote: \"Invoice #N\", its\n * lines and totals, the customer's addresses, and Pay while it is unpaid. No\n * proofs, no approval, no notes or terms (an order carries none). Allow-listed\n * as the quote's view is: the order's email, phone, Stripe ids and timeline\n * never leave the server.\n */\nexport function buildInvoicePageView(input: {\n order: Pick<\n HostOrder,\n | 'number'\n | 'status'\n | 'channel'\n | 'lineItems'\n | 'totals'\n | 'quote'\n | 'timeline'\n | 'taxMode'\n | 'customerName'\n | 'billingAddress'\n | 'shippingAddress'\n > &\n Partial<Pick<HostOrder, 'draftShipping'>> & { createdAtMs?: number }\n orderId: string\n storeName: string\n currency: string\n /** The order's status page, once paid. */\n receiptUrl?: string | null\n /** The store's sales tax choice; with it, a store that has not chosen refuses Pay (AGL-1999). */\n store?: PayLinkStore | null\n /** Whether the business can take a card payment now; absent, it is not judged here. */\n paymentsReady?: boolean\n}): QuotePageView {\n const { order } = input\n const status = quotePageStatus(order.status)\n const unpaid = status.status === 'unpaid'\n const charge = invoiceCheckoutCharge(order, input.orderId, input.store)\n const refused = unpaid\n ? payLinkRefusalWithPayments(invoicePayRefusal(order, input.orderId, input.store), input.paymentsReady)\n : null\n const stored = order.totals\n const totals =\n unpaid || !stored\n ? {\n itemsCents: charge.itemsCents,\n discountCents: charge.discountCents,\n shippingCents: charge.shippingCents,\n taxCents: charge.taxCents,\n totalCents: charge.totalCents,\n }\n : {\n itemsCents: cents(stored.itemsCents),\n discountCents: cents(stored.discountCents),\n shippingCents: cents(stored.shippingCents),\n taxCents: cents(stored.taxCents),\n totalCents: cents(stored.totalCents),\n }\n const taxAtPayment = unpaid && charge.taxAtPayment\n const created = orderCreatedAtMs(order as never)\n return {\n state: 'quote',\n kind: 'invoice',\n proofOnly: false,\n storeName: input.storeName,\n number: formatInvoiceNumber(order, input.orderId),\n dateMs: created > 0 ? created : null,\n // An invoice is not edited; the page has no version to send back.\n version: 0,\n currency: input.currency || 'USD',\n customerName: text(order.customerName),\n company: null,\n billTo: quotePageAddress(order.billingAddress),\n shipTo: quotePageAddress(order.shippingAddress),\n lines: quotePageLines(order.lineItems ?? []),\n totals,\n discountLabel: null,\n taxLabel: taxAtPayment ? 'Tax is added at payment' : 'Tax',\n taxAtPayment,\n shippingAtPayment: unpaid && charge.shippingOptions.length > 0,\n notes: null,\n terms: null,\n status: status.status,\n statusLabel: status.label,\n paidAtMs: orderPaidAtMs(order),\n receiptUrl: unpaid ? null : (input.receiptUrl ?? null),\n approvalRequired: false,\n payable: unpaid && refused === null,\n notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'invoice') : null,\n taxKey: null,\n revision: 1,\n proofs: [],\n response: null,\n respondable: false,\n approvalStatements: [],\n proofAccess: 'open',\n proofAccessMessage: null,\n messages: [],\n }\n}\n\n/*==========================================\n * EMAILING AN INVOICE\n *=========================================*/\n\n/** The order's invoice sends on record, oldest first. */\nexport function invoiceSends(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord[] {\n return Array.isArray(order?.invoiceSends)\n ? order.invoiceSends.filter((send) => send && typeof send === 'object')\n : []\n}\n\n/** The last time the order's invoice was emailed, or null. */\nexport function lastInvoiceSend(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord | null {\n const sends = invoiceSends(order)\n return sends.length ? sends[sends.length - 1] : null\n}\n\n/** Where the invoice goes: what was typed, else the order's customer, else a quote's. */\nexport function invoiceSendRecipient(\n order: Pick<HostOrder, 'customerEmail' | 'quote'> | null | undefined,\n typed: string | null | undefined,\n): string {\n return (\n String(typed ?? '').trim() ||\n String(order?.customerEmail ?? '').trim() ||\n String(order?.quote?.customer?.email ?? '').trim()\n )\n}\n\n/**\n * Who the console's Send invoice form starts addressed to: the customer's\n * email, else where the last invoice went, else (for a quote) where the quote\n * was last emailed, so an order or quote that names no email still opens\n * addressed to the customer it was already sent to.\n */\nexport function invoiceSendPrefill(order: Pick<HostOrder, 'customerEmail' | 'quote' | 'invoiceSends'> | null | undefined): string {\n return (\n invoiceSendRecipient(order, null) ||\n String(lastInvoiceSend(order)?.to ?? '').trim() ||\n String(lastQuoteSend(order?.quote)?.to ?? '').trim()\n )\n}\n\n/**\n * The conversation an invoice replies into: a quote's own (its emails, and a\n * request's confirmation before them), else the order's, which the first\n * invoice starts.\n */\nexport function invoiceEmailThread(\n order: Pick<HostOrder, 'quote' | 'emailThread'> | null | undefined,\n): QuoteEmailThread | null {\n if (order?.quote) return order.quote.emailThread ?? null\n return order?.emailThread ?? null\n}\n\n/**\n * The subject an invoice defaults to: the conversation's, so it stays one\n * conversation in the customer's mailbox, else `Invoice #1042 from Acme Signs`.\n */\nexport function invoiceEmailDefaultSubject(\n order: Pick<HostOrder, 'number' | 'quote' | 'emailThread'>,\n businessName: string,\n orderId?: string,\n): string {\n const thread = String(invoiceEmailThread(order)?.subject ?? '').trim()\n if (thread) return thread\n const name = String(businessName ?? '').trim()\n const number = formatInvoiceNumber(order, orderId)\n return name ? `${number} from ${name}` : number\n}\n\n/** Why an invoice cannot be emailed now, and what the console says. */\nexport type InvoiceSendRefusal =\n | 'unknown'\n | 'closed'\n | 'empty'\n | 'not-payable'\n | 'approval-required'\n | 'tax-undecided'\n | 'tax-save'\n | 'nothing-to-pay'\n | 'shipping-unknown'\n | 'no-address'\n | 'bad-address'\n\n/**\n * Why the order's invoice cannot be emailed to `to` now, if it cannot:\n * a canceled or refunded order, one with nothing on it, an unpaid order its\n * pay link cannot take payment for (and why), and the address.\n */\nexport function invoiceSendRefusal(\n order:\n | (Pick<HostOrder, 'number' | 'status' | 'channel' | 'lineItems' | 'totals' | 'quote' | 'taxMode'> &\n Partial<Pick<HostOrder, 'draftShipping'>>)\n | null\n | undefined,\n orderId: string,\n to: string,\n /** The store's sales tax choice, as the pay link reads it (`invoicePayRefusal`). */\n store?: PayLinkStore | null,\n): InvoiceSendRefusal | null {\n if (!order) return 'unknown'\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n const lines = (order.lineItems ?? []).filter(Boolean)\n if (!lines.length && cents(order.totals?.totalCents) <= 0) return 'empty'\n if (!invoiceIsPaid(order)) {\n const refused = invoicePayRefusal(order, orderId, store)\n if (refused === 'closed') return 'closed'\n // A quote saved before the store chose: the store has chosen, and a save prices it.\n if (refused === 'tax-undecided' && order.quote && quotePayTax(order.quote, store).source === 'save') {\n return 'tax-save'\n }\n if (refused && refused !== 'paid') return refused\n }\n if (!to) return 'no-address'\n if (to.length > 320 || !EMAIL.test(to)) return 'bad-address'\n return null\n}\n\n/** What the console says for a refused invoice send. */\nexport function invoiceSendRefusalMessage(reason: InvoiceSendRefusal): string {\n switch (reason) {\n case 'unknown':\n return 'Unknown order'\n case 'closed':\n return 'This order was canceled or refunded, so it has no invoice to send.'\n case 'empty':\n return 'This order has no items and no total, so there is nothing to put on an invoice.'\n case 'not-payable':\n return 'This order isn’t paid yet, and it can’t be paid online from an invoice. Take its payment where the sale was made, then send the invoice.'\n case 'approval-required':\n return 'This quote asks your customer to approve the proof before they pay, and they haven’t yet. Send the quote so they can approve it, then send the invoice.'\n case 'tax-undecided':\n return 'Sales tax isn’t set up for this store yet, so the invoice can’t be paid online. Finish the tax settings, then send it.'\n case 'tax-save':\n return 'This quote was saved before your store chose how it handles sales tax. Save the quote again, then send the invoice.'\n case 'nothing-to-pay':\n return 'This invoice totals less than $0.50, so it can’t be paid by card.'\n case 'shipping-unknown':\n return 'This draft order was made before invoices could charge its shipping, so its invoice can’t be paid online. Make a new draft order and send its invoice.'\n case 'no-address':\n return 'This order has no email for the customer. Type where to send the invoice.'\n case 'bad-address':\n return 'Enter a valid email address to send the invoice to.'\n }\n}\n\n/** The HTTP status a refused send answers with. */\nexport function invoiceSendRefusalStatus(reason: InvoiceSendRefusal): number {\n if (reason === 'unknown') return 404\n if (reason === 'no-address' || reason === 'bad-address') return 400\n return 409\n}\n\n/**\n * What an invoice email changes on the order, as a merge: the send on\n * record, a line on the timeline, and the conversation moved on, on the\n * quote for a quote and on the order otherwise.\n */\nexport function invoiceSendPatch(\n order: Pick<HostOrder, 'timeline' | 'invoiceSends' | 'quote'>,\n send: OrderInvoiceSendRecord,\n thread: QuoteEmailThread,\n): {\n timeline: OrderTimelineEvent[]\n invoiceSends: OrderInvoiceSendRecord[]\n emailThread?: QuoteEmailThread\n quote?: { emailThread: QuoteEmailThread }\n} {\n return {\n timeline: appendOrderEvent(\n order,\n 'invoice-sent',\n // The address is on the send record, which erasure clears; the timeline keeps none.\n `${send.paid ? 'Paid invoice' : 'Invoice'} emailed to the customer by ${send.by}`,\n send.atMs,\n ),\n invoiceSends: [...invoiceSends(order), send].slice(-INVOICE_MAX_SENDS),\n ...(order.quote ? { quote: { emailThread: thread } } : { emailThread: thread }),\n }\n}\n"],"names":["appendOrderEvent","formatOrderNumber","orderCreatedAtMs","QUOTE_MIN_CHARGE_CENTS","payLinkCheckoutCharge","payLinkPaymentsUnavailableMessage","payLinkRefusalWithPayments","quoteCheckoutCharge","quotePageAddress","quotePageLines","quotePageStatus","quotePayRefusal","quotePayRefusalMessage","quotePayTax","lastQuoteSend","isQuote","quoteIsProofOnly","storefrontTaxDecision","lineRequiresShipping","INVOICE_MAX_SENDS","EMAIL","cents","value","number","Math","round","Number","isFinite","text","trimmed","trim","orderPayLinkKind","order","quote","channel","formatInvoiceNumber","orderId","PAID_STATUSES","Set","invoiceIsPaid","has","String","status","orderPaidAtMs","stamped","paidAtMs","event","timeline","find","entry","atMs","created","invoiceTaxBasis","taxMode","kind","taxCents","max","totals","reason","draftRate","option","source","name","amountCents","rateId","invoiceCheckoutCharge","store","shippingOptions","shippingCountries","discountCents","charge","lineItems","tax","discount","shippingCents","label","options","draftShipping","map","filter","rate","slice","countries","country","toUpperCase","test","length","invoicePayRefusal","settings","ships","some","line","included","totalCents","invoicePayRefusalMessage","storeName","business","payLinkGaps","input","paymentsReady","undefined","gaps","push","buildInvoicePageView","unpaid","refused","stored","itemsCents","taxAtPayment","state","proofOnly","dateMs","version","currency","customerName","company","billTo","billingAddress","shipTo","shippingAddress","lines","discountLabel","taxLabel","shippingAtPayment","notes","terms","statusLabel","receiptUrl","approvalRequired","payable","notPayableMessage","taxKey","revision","proofs","response","respondable","approvalStatements","proofAccess","proofAccessMessage","messages","invoiceSends","Array","isArray","send","lastInvoiceSend","sends","invoiceSendRecipient","typed","customerEmail","customer","email","invoiceSendPrefill","to","invoiceEmailThread","emailThread","invoiceEmailDefaultSubject","businessName","thread","subject","invoiceSendRefusal","Boolean","invoiceSendRefusalMessage","invoiceSendRefusalStatus","invoiceSendPatch","paid","by"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,QAIX,uBAAmB;AAC1B,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,iCAAiC,EACjCC,0BAA0B,EAC1BC,mBAAmB,EACnBC,gBAAgB,EAChBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,sBAAsB,EACtBC,WAAW,QAKN,0BAAsB;AAC7B,SAASC,aAAa,QAAQ,4BAAwB;AACtD,SACEC,OAAO,EACPC,gBAAgB,QAIX,uBAAmB;AAE1B,SAASC,qBAAqB,QAAQ,6BAAyB;AAC/D,SAASC,oBAAoB,QAAQ,yBAAqB;AAmC1D,0EAA0E,GAC1E,OAAO,MAAMC,oBAAoB,GAAE;AAEnC,MAAMC,QAAQ;AAEd,MAAMC,QAAQ,CAACC;IACb,MAAMC,SAASC,KAAKC,KAAK,CAACC,OAAOJ;IACjC,OAAOI,OAAOC,QAAQ,CAACJ,UAAUA,SAAS;AAC5C;AAEA,MAAMK,OAAO,CAACN;IACZ,MAAMO,UAAU,OAAOP,UAAU,WAAWA,MAAMQ,IAA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;QACL9G,UAAU/C,iBACRgC,OACA,gBACA,oFAAoF;QACpF,GAAG+G,KAAKqB,IAAI,GAAG,iBAAiB,UAAU,4BAA4B,EAAErB,KAAKsB,EAAE,EAAE,EACjFtB,KAAK7F,IAAI;QAEX0F,cAAc;eAAIA,aAAa5G;YAAQ+G;SAAK,CAAC9D,KAAK,CAAC,CAAC9D;OAChDa,MAAMC,KAAK,GAAG;QAAEA,OAAO;YAAEyH,aAAaG;QAAO;IAAE,IAAI;QAAEH,aAAaG;IAAO;AAEjF"}
@@ -46,6 +46,9 @@ export interface PosOrderTender {
46
46
  last4?: string;
47
47
  cashTenderedCents?: number;
48
48
  changeCents?: number;
49
+ /** Where a card tender's charge lives: on the store's own account when `direct`. */
50
+ chargeModel?: 'direct';
51
+ stripeAccountId?: string;
49
52
  }
50
53
  /** The order fields the tender reader looks at. */
51
54
  export interface PosTenderSource {
@@ -88,6 +88,9 @@ const isTenderMethod = (value)=>typeof value === 'string' && POS_TENDER_METHODS.
88
88
  cashTenderedCents: wholeCents(payment.cashTenderedCents)
89
89
  } : {}, payment.changeCents != null ? {
90
90
  changeCents: wholeCents(payment.changeCents)
91
+ } : {}, payment.chargeModel === 'direct' && payment.stripeAccountId ? {
92
+ chargeModel: 'direct',
93
+ stripeAccountId: payment.stripeAccountId
91
94
  } : {});
92
95
  });
93
96
  }