@aglyn/plugins-commerce 1.10.0 → 1.11.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 (47) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/invoice-send.component.d.ts +9 -2
  3. package/src/lib/components/console/invoice-send.component.js +58 -30
  4. package/src/lib/components/console/invoice-send.component.js.map +1 -1
  5. package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +84 -0
  6. package/src/lib/components/console/pay-link-readiness-notice.component.js +164 -0
  7. package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -0
  8. package/src/lib/components/console/quote-editor-dialog.component.js +7 -8
  9. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  10. package/src/lib/components/console/quote-pay-link.component.d.ts +3 -0
  11. package/src/lib/components/console/quote-pay-link.component.js +9 -0
  12. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  13. package/src/lib/components/console/quote-send.component.d.ts +3 -0
  14. package/src/lib/components/console/quote-send.component.js +9 -0
  15. package/src/lib/components/console/quote-send.component.js.map +1 -1
  16. package/src/lib/components/quote-page-body.js +5 -3
  17. package/src/lib/components/quote-page-body.js.map +1 -1
  18. package/src/lib/model/commerce-invoices.d.ts +45 -5
  19. package/src/lib/model/commerce-invoices.js +46 -9
  20. package/src/lib/model/commerce-invoices.js.map +1 -1
  21. package/src/lib/model/commerce-quote-pay.d.ts +110 -6
  22. package/src/lib/model/commerce-quote-pay.js +182 -23
  23. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  24. package/src/lib/server/billing-webhook.js +4 -1
  25. package/src/lib/server/billing-webhook.js.map +1 -1
  26. package/src/lib/server/commerce-pdf.js +2 -1
  27. package/src/lib/server/commerce-pdf.js.map +1 -1
  28. package/src/lib/server/invoice-email.js +2 -1
  29. package/src/lib/server/invoice-email.js.map +1 -1
  30. package/src/lib/server/order-invoice-send.js +1 -1
  31. package/src/lib/server/order-invoice-send.js.map +1 -1
  32. package/src/lib/server/order-status.d.ts +5 -1
  33. package/src/lib/server/order-status.js +19 -5
  34. package/src/lib/server/order-status.js.map +1 -1
  35. package/src/lib/server/quote-email.js +2 -1
  36. package/src/lib/server/quote-email.js.map +1 -1
  37. package/src/lib/server/quote-pay.d.ts +39 -0
  38. package/src/lib/server/quote-pay.js +103 -43
  39. package/src/lib/server/quote-pay.js.map +1 -1
  40. package/src/lib/server/quote-proofs.js +13 -9
  41. package/src/lib/server/quote-proofs.js.map +1 -1
  42. package/src/lib/utils/invoice-email-content.d.ts +3 -1
  43. package/src/lib/utils/invoice-email-content.js +1 -1
  44. package/src/lib/utils/invoice-email-content.js.map +1 -1
  45. package/src/lib/utils/quote-email-content.d.ts +3 -1
  46. package/src/lib/utils/quote-email-content.js +3 -3
  47. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -16,9 +16,10 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
16
16
  * limitations under the License.
17
17
  */ import { visitorUploadIsInline } from "@aglyn/aglyn/app-utils/visitor-upload";
18
18
  import { appendOrderEvent, formatOrderNumber } from "./commerce-orders.js";
19
- import { computeQuoteTotals, describeQuoteTax, formatQuoteNumber, quoteLineAmounts, quotePaymentBlockedByApproval } from "./commerce-quotes.js";
19
+ import { computeQuoteTotals, describeQuoteTax, formatQuoteNumber, quoteLineAmounts, quotePaymentBlockedByApproval, quoteTaxBasisFromSettings } from "./commerce-quotes.js";
20
20
  import { currentQuoteProofs, latestQuoteResponse, quoteRespondRefusal } from "./commerce-quote-proofs.js";
21
- import { engineLineTaxPercentages } from "./commerce-tax-engine.js";
21
+ import { storefrontTaxDecision } from "./commerce-tax-decision.js";
22
+ import { engineLineTaxPercentages, storeTaxAllowsEngine } from "./commerce-tax-engine.js";
22
23
  import { withOrderListFields } from "./order-list-fields.js";
23
24
  /*==========================================
24
25
  * PAYING A QUOTE (AGL-4094).
@@ -36,6 +37,8 @@ import { withOrderListFields } from "./order-list-fields.js";
36
37
  * - {@link quotePayRefusal}: why a quote cannot be paid now, if it cannot.
37
38
  * - {@link quotePaymentDisposition} and {@link paidQuoteOrder}: what a
38
39
  * completed payment does to the quote, and the order it becomes.
40
+ * - {@link quotePayTax}: the tax every one of them reads, which for a quote
41
+ * saved before the store chose its sales tax is the store's choice now.
39
42
  *
40
43
  * The customer side has no expiry and no open or closed states: a quote and
41
44
  * its link stay until the quote is paid or the business replaces the link.
@@ -60,6 +63,130 @@ import { withOrderListFields } from "./order-list-fields.js";
60
63
  const list = (order == null ? void 0 : order.quote) ? order.quote.unmatchedPayments : order == null ? void 0 : (_order_payLink = order.payLink) == null ? void 0 : _order_payLink.unmatchedPayments;
61
64
  return Array.isArray(list) ? list.filter((entry)=>entry && typeof entry === 'object') : [];
62
65
  }
66
+ /** The store a pay link reads, from the store settings document's data (nothing, for no document). */ export function payLinkStoreOf(settings) {
67
+ const tax = settings == null ? void 0 : settings.tax;
68
+ return {
69
+ tax: tax && typeof tax === 'object' ? tax : null
70
+ };
71
+ }
72
+ /** Whether a basis records that nobody had chosen the store's sales tax, which is no choice at all. */ export function quoteTaxIsUndecided(basis) {
73
+ return (basis == null ? void 0 : basis.kind) === 'none' && basis.reason === 'undecided';
74
+ }
75
+ /**
76
+ * The tax a quote is shown, charged and paid under (AGL-4162): the one answer
77
+ * the quote page, Pay, the payment's record (carried on its session) and the
78
+ * console's notice all read.
79
+ *
80
+ * A quote keeps the basis it was saved with, except one saved before the
81
+ * store chose how it handles sales tax. That basis records no choice, so the
82
+ * quote takes the store's choice as it stands now, through the same
83
+ * `quoteTaxBasisFromSettings` the editor prices a save with: no sales tax,
84
+ * prices that include tax, or Stripe Tax at payment. Nothing is written for
85
+ * it; the next save stores the same basis.
86
+ *
87
+ * The store's own rates on prices that exclude tax are the one choice not
88
+ * taken this way. On those settings a save asks the site's tax service where
89
+ * one is connected (`priceQuote` in `server/quote.ts`), and only that save
90
+ * knows the figure: which service is connected is the tax service's own to
91
+ * say. Such a quote keeps its basis, and so stays unpaid, until it is saved.
92
+ *
93
+ * Without a store, the stored basis stands.
94
+ */ export function quotePayTax(quote, store) {
95
+ var _ref;
96
+ const stored = (_ref = quote == null ? void 0 : quote.tax) != null ? _ref : {
97
+ kind: 'none',
98
+ reason: 'not-collected'
99
+ };
100
+ if (!store || !quoteTaxIsUndecided(stored)) return {
101
+ basis: stored,
102
+ source: 'stored'
103
+ };
104
+ if (storefrontTaxDecision({
105
+ settings: store.tax
106
+ }).kind === 'undecided') return {
107
+ basis: stored,
108
+ source: 'stored'
109
+ };
110
+ if (storeTaxAllowsEngine(store.tax)) return {
111
+ basis: stored,
112
+ source: 'save'
113
+ };
114
+ return {
115
+ basis: quoteTaxBasisFromSettings(store.tax, quote == null ? void 0 : quote.shipTo),
116
+ source: 'current'
117
+ };
118
+ }
119
+ const TAX_KINDS = new Set([
120
+ 'rate',
121
+ 'service',
122
+ 'at-payment',
123
+ 'none'
124
+ ]);
125
+ const NO_TAX_REASONS = new Set([
126
+ 'not-collected',
127
+ 'prices-include-tax',
128
+ 'no-rate',
129
+ 'undecided'
130
+ ]);
131
+ const BASIS_LABEL_MAX = 120;
132
+ /** A basis holding only what its kind carries, in one order, or null for anything that is not one. */ function tidyTaxBasis(raw) {
133
+ var _source_kind, _source_reason;
134
+ if (!raw || typeof raw !== 'object') return null;
135
+ const source = raw;
136
+ const kind = String((_source_kind = source['kind']) != null ? _source_kind : '');
137
+ if (!TAX_KINDS.has(kind)) return null;
138
+ const label = (value)=>typeof value === 'string' && value.trim() ? value.trim().slice(0, BASIS_LABEL_MAX) : '';
139
+ if (kind === 'rate') {
140
+ const pct = Number(source['pct']);
141
+ if (!Number.isFinite(pct)) return null;
142
+ const named = label(source['label']);
143
+ return _extends({
144
+ kind,
145
+ pct
146
+ }, named ? {
147
+ label: named
148
+ } : {});
149
+ }
150
+ if (kind === 'service') {
151
+ const taxCents = Math.round(Number(source['taxCents']));
152
+ if (!Number.isFinite(taxCents) || taxCents < 0) return null;
153
+ const named = label(source['providerLabel']);
154
+ return _extends({
155
+ kind,
156
+ taxCents
157
+ }, named ? {
158
+ providerLabel: named
159
+ } : {});
160
+ }
161
+ if (kind === 'at-payment') return {
162
+ kind
163
+ };
164
+ const reason = String((_source_reason = source['reason']) != null ? _source_reason : '');
165
+ return {
166
+ kind: 'none',
167
+ reason: NO_TAX_REASONS.has(reason) ? reason : 'not-collected'
168
+ };
169
+ }
170
+ /**
171
+ * A basis as one short string: what the quote page sends back with Pay, so a
172
+ * payment is refused when the tax it would charge is not the tax the page
173
+ * showed, and what a session records as the basis it charged. Equal bases
174
+ * have one key.
175
+ */ export function quoteTaxBasisKey(basis) {
176
+ var _tidyTaxBasis;
177
+ return JSON.stringify((_tidyTaxBasis = tidyTaxBasis(basis)) != null ? _tidyTaxBasis : {
178
+ kind: 'none',
179
+ reason: 'not-collected'
180
+ });
181
+ }
182
+ /** A basis back from {@link quoteTaxBasisKey}, or null for anything else. */ export function quoteTaxBasisFromKey(key) {
183
+ if (typeof key !== 'string' || !key || key.length > 500) return null;
184
+ try {
185
+ return tidyTaxBasis(JSON.parse(key));
186
+ } catch (unused) {
187
+ return null;
188
+ }
189
+ }
63
190
  const text = (value)=>{
64
191
  const trimmed = typeof value === 'string' ? value.trim() : '';
65
192
  return trimmed ? trimmed : null;
@@ -115,16 +242,20 @@ function discountLabel(discount) {
115
242
  /**
116
243
  * The quote page's view of an order document on the `quote` channel. Totals
117
244
  * are the stored lines' through {@link computeQuoteTotals} until the quote is
118
- * paid, and the paid order's own totals (what Stripe charged) after.
245
+ * paid, and the paid order's own totals (what Stripe charged) after. The tax
246
+ * is {@link quotePayTax}'s for the store given, and Pay belongs on the page
247
+ * only when nothing would refuse it: the store's payments included, when the
248
+ * caller says whether it can take them.
119
249
  */ export function buildQuotePageView(input) {
120
250
  var _order_lineItems, _ref, _text, _input_receiptUrl, _ref1;
121
- var _quote_tax, _quote_customer, _quote_customer1, _quote_customer2, _quote_customer3, _quote_tax1;
251
+ var _quote_customer, _quote_customer1, _quote_customer2, _quote_customer3;
122
252
  const { order } = input;
123
253
  const quote = order.quote;
124
254
  const lines = (_order_lineItems = order.lineItems) != null ? _order_lineItems : [];
125
255
  const status = quotePageStatus(order.status);
126
256
  const unpaid = status.status === 'unpaid';
127
- const charge = quoteCheckoutCharge(order, input.orderId);
257
+ const payTax = quotePayTax(quote, input.store);
258
+ const charge = quoteCheckoutCharge(order, input.orderId, input.store);
128
259
  const stored = order.totals;
129
260
  const totals = unpaid || !stored ? {
130
261
  itemsCents: charge.itemsCents,
@@ -140,7 +271,8 @@ function discountLabel(discount) {
140
271
  totalCents: cents(stored.totalCents)
141
272
  };
142
273
  const approvalRequired = unpaid && quotePaymentBlockedByApproval(quote);
143
- const taxAtPayment = unpaid && (quote == null ? void 0 : (_quote_tax = quote.tax) == null ? void 0 : _quote_tax.kind) === 'at-payment';
274
+ const taxAtPayment = unpaid && payTax.basis.kind === 'at-payment';
275
+ const refused = unpaid ? payLinkRefusalWithPayments(quotePayRefusal(order, input.orderId, input.store), input.paymentsReady) : null;
144
276
  return {
145
277
  state: 'quote',
146
278
  kind: 'quote',
@@ -157,7 +289,7 @@ function discountLabel(discount) {
157
289
  totals,
158
290
  discountLabel: discountLabel(quote == null ? void 0 : quote.discount),
159
291
  // Once paid, the tax is what was charged: Stripe's figure under Stripe Tax.
160
- taxLabel: unpaid || (quote == null ? void 0 : (_quote_tax1 = quote.tax) == null ? void 0 : _quote_tax1.kind) !== 'at-payment' ? describeQuoteTax(quote == null ? void 0 : quote.tax) : 'Tax',
292
+ taxLabel: unpaid || payTax.basis.kind !== 'at-payment' ? describeQuoteTax(payTax.basis) : 'Tax',
161
293
  taxAtPayment,
162
294
  shippingAtPayment: false,
163
295
  notes: text(quote == null ? void 0 : quote.notes),
@@ -167,7 +299,9 @@ function discountLabel(discount) {
167
299
  paidAtMs: paidAt(order),
168
300
  receiptUrl: unpaid ? null : (_input_receiptUrl = input.receiptUrl) != null ? _input_receiptUrl : null,
169
301
  approvalRequired,
170
- payable: unpaid && !approvalRequired && quotePayRefusal(order, input.orderId) === null,
302
+ payable: unpaid && refused === null,
303
+ notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'quote') : null,
304
+ taxKey: unpaid ? quoteTaxBasisKey(payTax.basis) : null,
171
305
  revision: Math.max(1, Number((_ref1 = quote == null ? void 0 : quote.revision) != null ? _ref1 : 1) || 1),
172
306
  proofs: currentQuoteProofs(quote).map((proof)=>{
173
307
  var _proof_name, _proof_contentType, _proof_contentType1;
@@ -240,7 +374,9 @@ function lineSummary(lines) {
240
374
  /**
241
375
  * The charge for a quote, from its stored lines, discount, shipping and tax
242
376
  * basis through {@link computeQuoteTotals} — the same function that priced it
243
- * when it was saved, so the page, the session and the stored quote agree.
377
+ * when it was saved, so the page, the session and the stored quote agree. The
378
+ * basis is {@link quotePayTax}'s: a quote saved before the store chose its
379
+ * sales tax is charged under the store's choice now.
244
380
  *
245
381
  * The goods are charged as at most two lines, the taxed and the tax-exempt,
246
382
  * each after its share of the discount. A store rate is applied to the taxed
@@ -248,17 +384,14 @@ function lineSummary(lines) {
248
384
  * amount the quote taxed, and the quote's figure is what is collected. A tax
249
385
  * service's figure is carried the same way, as the percentage of the taxed
250
386
  * line it amounts to. Included lines charge nothing and are not sent.
251
- */ export function quoteCheckoutCharge(order, orderId) {
252
- var _order_lineItems, _ref, _ref1;
253
- var _order_quote, _order_quote1, _order_quote_shipping, _order_quote2;
387
+ */ export function quoteCheckoutCharge(order, orderId, store) {
388
+ var _order_lineItems, _ref;
389
+ var _order_quote, _order_quote_shipping, _order_quote1;
254
390
  return payLinkCheckoutCharge({
255
391
  lineItems: (_order_lineItems = order.lineItems) != null ? _order_lineItems : [],
256
- tax: (_ref = (_order_quote = order.quote) == null ? void 0 : _order_quote.tax) != null ? _ref : {
257
- kind: 'none',
258
- reason: 'not-collected'
259
- },
260
- discount: (_ref1 = (_order_quote1 = order.quote) == null ? void 0 : _order_quote1.discount) != null ? _ref1 : null,
261
- shippingCents: Math.max(0, cents((_order_quote2 = order.quote) == null ? void 0 : (_order_quote_shipping = _order_quote2.shipping) == null ? void 0 : _order_quote_shipping.amountCents)),
392
+ tax: quotePayTax(order.quote, store).basis,
393
+ discount: (_ref = (_order_quote = order.quote) == null ? void 0 : _order_quote.discount) != null ? _ref : null,
394
+ shippingCents: Math.max(0, cents((_order_quote1 = order.quote) == null ? void 0 : (_order_quote_shipping = _order_quote1.shipping) == null ? void 0 : _order_quote_shipping.amountCents)),
262
395
  label: formatQuoteNumber(order, orderId)
263
396
  });
264
397
  }
@@ -329,15 +462,36 @@ function lineSummary(lines) {
329
462
  feeProductType: feeProductTypeOf(lineItems)
330
463
  };
331
464
  }
332
- /** Why a quote cannot be paid now, or null when it can. */ export function quotePayRefusal(order, orderId) {
333
- var _order_quote_tax, _order_quote;
465
+ /**
466
+ * Why a quote cannot be paid now, or null when it can. With the store, its
467
+ * tax is {@link quotePayTax}'s, and a store that has not chosen its sales tax
468
+ * refuses every sale (AGL-1999), whatever basis the quote was saved with.
469
+ */ export function quotePayRefusal(order, orderId, store) {
334
470
  if (order.status === 'cancelled' || order.status === 'refunded') return 'closed';
335
471
  if (order.status !== 'pending') return 'paid';
336
472
  if (quotePaymentBlockedByApproval(order.quote)) return 'approval-required';
337
- if (((_order_quote = order.quote) == null ? void 0 : (_order_quote_tax = _order_quote.tax) == null ? void 0 : _order_quote_tax.kind) === 'none' && order.quote.tax.reason === 'undecided') return 'tax-undecided';
338
- if (quoteCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay';
473
+ if (store && storefrontTaxDecision({
474
+ settings: store.tax
475
+ }).kind === 'undecided') return 'tax-undecided';
476
+ if (quoteTaxIsUndecided(quotePayTax(order.quote, store).basis)) return 'tax-undecided';
477
+ if (quoteCheckoutCharge(order, orderId, store).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay';
339
478
  return null;
340
479
  }
480
+ /**
481
+ * A pay link's refusal once the store's payments are judged too: a business
482
+ * that can't take a card payment now outranks every refusal but the ones a
483
+ * payment never gets past (paid, closed, not linked, waiting on the
484
+ * customer's approval). `paymentsReady` absent leaves the refusal as it is.
485
+ */ export function payLinkRefusalWithPayments(reason, paymentsReady) {
486
+ if (paymentsReady !== false) return reason;
487
+ if (reason === 'paid' || reason === 'closed' || reason === 'not-payable' || reason === 'approval-required') {
488
+ return reason;
489
+ }
490
+ return 'payments-unavailable';
491
+ }
492
+ /** What the customer is told when the business can't take a card payment now: the page's words and Pay's. */ export function payLinkPaymentsUnavailableMessage(storeName, kind) {
493
+ return `${storeName || 'This business'} can’t take payments online right now. Contact them to pay this ${kind === 'invoice' ? 'invoice' : 'quote'}.`;
494
+ }
341
495
  /** What the customer is told for a {@link QuotePayRefusal}, naming the business. */ export function quotePayRefusalMessage(reason, storeName) {
342
496
  const business = storeName.trim() || 'the business';
343
497
  switch(reason){
@@ -401,6 +555,9 @@ export function quotePaymentDisposition(order, payment) {
401
555
  * quote's bill-to bills it.
402
556
  * - The totals are what Stripe charged: its shipping and tax where it charged
403
557
  * any, the platform fee the session was minted with, and its total.
558
+ * - The quote keeps the tax basis it was paid under: the session's
559
+ * ({@link QuotePaymentFacts.taxBasis}) where the press took the store's
560
+ * choice for it, so the order says how its tax was worked out.
404
561
  * - The list fields (`withOrderListFields`) are stamped from all of that.
405
562
  */ export function paidQuoteOrder(order, orderId, facts) {
406
563
  var _ref, _order_totals, _ref1, _facts_shippingAddress, _text, _ref2, _text1, _facts_paymentIntentId;
@@ -446,7 +603,9 @@ export function quotePaymentDisposition(order, payment) {
446
603
  paymentIntentId: (_facts_paymentIntentId = facts.paymentIntentId) != null ? _facts_paymentIntentId : undefined,
447
604
  checkoutSessionId: facts.sessionId,
448
605
  timeline: appendOrderEvent(order, 'paid', `${label} paid through its pay link`, facts.paidAtMs),
449
- quote: _extends({}, quote, {
606
+ quote: _extends({}, quote, facts.taxBasis ? {
607
+ tax: facts.taxBasis
608
+ } : {}, {
450
609
  paidAtMs: facts.paidAtMs
451
610
  }),
452
611
  // New to a shipping tool's feed from the moment it is paid.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-quote-pay.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 { visitorUploadIsInline } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport type { ProductType } from './commerce'\nimport {\n appendOrderEvent,\n formatOrderNumber,\n type HostOrder,\n type OrderAddress,\n type OrderLineItem,\n type OrderStatus,\n} from './commerce-orders'\nimport {\n computeQuoteTotals,\n describeQuoteTax,\n formatQuoteNumber,\n quoteLineAmounts,\n quotePaymentBlockedByApproval,\n type OrderQuote,\n type QuoteDiscount,\n type QuoteTaxBasis,\n type QuoteUnmatchedPayment,\n} from './commerce-quotes'\nimport { currentQuoteProofs, latestQuoteResponse, quoteRespondRefusal } from './commerce-quote-proofs'\nimport type { StorefrontTaxMode } from './commerce-tax-decision'\nimport { engineLineTaxPercentages } from './commerce-tax-engine'\nimport { withOrderListFields, type OrderListFields } from './order-list-fields'\n\n/*==========================================\n * PAYING A QUOTE (AGL-4094).\n *\n * The customer opens the quote on the business's own site from a signed pay\n * link, sees it, and pays it. Everything here is pure, so the page's view,\n * the pay route's charge and the webhook's paid order all come from one\n * reading of the stored quote, and none of them from anything the browser\n * sends:\n *\n * - {@link buildQuotePageView}: the ONE projection of a quote that leaves the\n * server for a visitor holding the link, allow-listed field by field.\n * - {@link quoteCheckoutCharge}: what a Checkout Session charges, priced from\n * the stored lines, discount, shipping and tax basis.\n * - {@link quotePayRefusal}: why a quote cannot be paid now, if it cannot.\n * - {@link quotePaymentDisposition} and {@link paidQuoteOrder}: what a\n * completed payment does to the quote, and the order it becomes.\n *\n * The customer side has no expiry and no open or closed states: a quote and\n * its link stay until the quote is paid or the business replaces the link.\n *=========================================*/\n\n/** Stripe's smallest card charge; a quote that totals less cannot be paid by card. */\nexport const QUOTE_MIN_CHARGE_CENTS = 50\n\n/** The pay link version a quote is on; absent reads as the first. */\nexport function quoteLinkVersion(quote: Pick<OrderQuote, 'linkVersion'> | null | undefined): number {\n const version = Math.floor(Number(quote?.linkVersion))\n return Number.isFinite(version) && version >= 1 ? version : 1\n}\n\n/**\n * The pay link version any order is on (AGL-4099). A quote keeps its version\n * where slice 2 put it, `quote.linkVersion`, so every link already sent keeps\n * verifying; any other order keeps it as `payLink.version`. Absent reads as\n * the first either way.\n */\nexport function orderPayLinkVersion(order: Partial<Pick<HostOrder, 'quote' | 'payLink'>> | null | undefined): number {\n if (order?.quote) return quoteLinkVersion(order.quote)\n const version = Math.floor(Number(order?.payLink?.version))\n return Number.isFinite(version) && version >= 1 ? version : 1\n}\n\n/** Payments the order's pay link could not take: a quote's on the quote, any other order's on `payLink`. */\nexport function orderPayLinkUnmatched(\n order: Partial<Pick<HostOrder, 'quote' | 'payLink'>> | null | undefined,\n): QuoteUnmatchedPayment[] {\n const list = order?.quote ? order.quote.unmatchedPayments : order?.payLink?.unmatchedPayments\n return Array.isArray(list) ? list.filter((entry) => entry && typeof entry === 'object') : []\n}\n\n/*==========================================\n * THE CUSTOMER'S PAGE\n *=========================================*/\n\n/** An address as the quote page prints it: no phone. */\nexport interface QuotePageAddress {\n name: string | null\n line1: string | null\n line2: string | null\n city: string | null\n state: string | null\n postalCode: string | null\n country: string | null\n}\n\nexport interface QuotePageLine {\n name: string\n /** The option and add-ons chosen, as order lines print them. */\n variantLabel: string | null\n description: string | null\n sku: string | null\n quantity: number\n unitAmountCents: number\n /** What the line charges: 0 for an included line. */\n amountCents: number\n /** Included at no charge. */\n included: boolean\n}\n\n/** Where the quote stands, as its customer sees it. */\nexport type QuotePageStatus = 'unpaid' | 'paid' | 'canceled' | 'refunded'\n\n/** A proof as the quote page lists it: no storage path, nothing about who attached it. */\nexport interface QuotePageProof {\n id: string\n name: string\n contentType: string\n size: number\n /** Shown in the page as a picture; everything else is a download. */\n inline: boolean\n}\n\n/** The customer's latest answer to the revision the page shows. */\nexport interface QuotePageResponse {\n action: 'approve' | 'changes'\n atMs: number\n /** With an approval: the name it was given under. */\n name: string | null\n comment: string | null\n /** How many files came with it. */\n files: number\n}\n\n/**\n * What the quote page shows. Allow-listed, never spread: the order document\n * carries the customer's email and phone, Stripe ids, the business's own\n * timeline and who wrote the quote, none of which a forwarded link may show.\n * New fields are added here deliberately, or not at all.\n */\nexport interface QuotePageView {\n state: 'quote'\n /**\n * What the page shows (AGL-4099): a quote, or an invoice for an order the\n * business sent one for. An invoice has no proofs and no approval, and the\n * page says \"invoice\" where a quote's says \"quote\".\n */\n kind: 'quote' | 'invoice'\n storeName: string\n /** `Quote #1042`, or `Invoice #1042`. */\n number: string\n /** When the quote was last written, which is the date it carries. */\n dateMs: number | null\n /**\n * The edit of the quote this view shows. Pay sends it back, and a quote\n * changed since is refused, so nobody pays for a version they have not seen.\n */\n version: number\n currency: string\n customerName: string | null\n company: string | null\n billTo: QuotePageAddress | null\n shipTo: QuotePageAddress | null\n lines: QuotePageLine[]\n totals: {\n itemsCents: number\n discountCents: number\n shippingCents: number\n taxCents: number\n totalCents: number\n }\n /** `10% off`, or null for an amount or no discount. */\n discountLabel: string | null\n /** The tax line's label, or `Tax is added at payment`. */\n taxLabel: string\n /** Stripe Tax works the tax out when the customer pays; `taxCents` is 0 until then. */\n taxAtPayment: boolean\n /**\n * The customer picks a shipping rate when they pay (an invoiced draft\n * order, AGL-4099); `shippingCents` is 0 until then. A quote's shipping is\n * priced on it, so this is false for every quote.\n */\n shippingAtPayment: boolean\n notes: string | null\n terms: string | null\n status: QuotePageStatus\n statusLabel: string\n paidAtMs: number | null\n /** The order's status page, once paid. */\n receiptUrl: string | null\n /** The business asks the customer to approve the proof before paying. */\n approvalRequired: boolean\n /** A Pay button belongs on the page. */\n payable: boolean\n /** The revision the page shows (AGL-4096). */\n revision: number\n /** That revision's proofs. */\n proofs: QuotePageProof[]\n /** The customer's latest answer to it, if any. */\n response: QuotePageResponse | null\n /** Approve and Request changes belong on the page. */\n respondable: boolean\n}\n\n/** What a signed link for an older version of the quote opens: nothing of the quote. */\nexport interface QuotePageReplacedView {\n state: 'replaced'\n storeName: string\n}\n\nconst text = (value: unknown): string | null => {\n const trimmed = typeof value === 'string' ? value.trim() : ''\n return trimmed ? trimmed : null\n}\n\nconst cents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) ? number : 0\n}\n\n/** An address as the pay link's page prints it, or null when it says nothing. */\nexport function quotePageAddress(address: OrderAddress | null | undefined): QuotePageAddress | null {\n if (!address) return null\n const view: QuotePageAddress = {\n name: text(address.name),\n line1: text(address.line1),\n line2: text(address.line2),\n city: text(address.city),\n state: text(address.state),\n postalCode: text(address.postalCode),\n country: text(address.country),\n }\n return Object.values(view).some(Boolean) ? view : null\n}\n\n/** Where an order stands as the pay link's page says it. */\nexport function quotePageStatus(status: OrderStatus | string | undefined): { status: QuotePageStatus; label: string } {\n if (status === 'pending') return { status: 'unpaid', label: 'Unpaid' }\n if (status === 'cancelled') return { status: 'canceled', label: 'Canceled' }\n if (status === 'refunded') return { status: 'refunded', label: 'Refunded' }\n return { status: 'paid', label: 'Paid' }\n}\n\nfunction discountLabel(discount: QuoteDiscount | null | undefined): string | null {\n if (discount?.kind !== 'percent' || !(Number(discount.pct) > 0)) return null\n return `${Number(discount.pct)}% off`\n}\n\n/** When the quote was paid: its stamp, else the timeline's `paid` event. */\nfunction paidAt(order: Pick<HostOrder, 'status' | 'quote' | 'timeline'>): number | null {\n if (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 return event ? Number(event.atMs) || null : null\n}\n\n/**\n * The quote page's view of an order document on the `quote` channel. Totals\n * are the stored lines' through {@link computeQuoteTotals} until the quote is\n * paid, and the paid order's own totals (what Stripe charged) after.\n */\nexport function buildQuotePageView(input: {\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'totals' | 'quote' | 'timeline'>\n orderId: string\n storeName: string\n currency: string\n /** The order's status page, for a paid quote. */\n receiptUrl?: string | null\n}): QuotePageView {\n const { order } = input\n const quote = order.quote\n const lines = order.lineItems ?? []\n const status = quotePageStatus(order.status)\n const unpaid = status.status === 'unpaid'\n const charge = quoteCheckoutCharge(order, input.orderId)\n const stored = order.totals\n const totals = 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 approvalRequired = unpaid && quotePaymentBlockedByApproval(quote)\n const taxAtPayment = unpaid && quote?.tax?.kind === 'at-payment'\n return {\n state: 'quote',\n kind: 'quote',\n storeName: input.storeName,\n number: formatQuoteNumber(order, input.orderId),\n dateMs: Number(quote?.updatedAtMs ?? quote?.createdAtMs) || null,\n version: Number(quote?.updatedAtMs) || 0,\n currency: input.currency || 'USD',\n customerName: text(quote?.customer?.name) ?? text(quote?.customer?.company),\n company: text(quote?.customer?.name) ? text(quote?.customer?.company) : null,\n billTo: quotePageAddress(quote?.billTo),\n shipTo: quotePageAddress(quote?.shipTo),\n lines: quotePageLines(lines),\n totals,\n discountLabel: discountLabel(quote?.discount),\n // Once paid, the tax is what was charged: Stripe's figure under Stripe Tax.\n taxLabel: unpaid || quote?.tax?.kind !== 'at-payment' ? describeQuoteTax(quote?.tax) : 'Tax',\n taxAtPayment,\n shippingAtPayment: false,\n notes: text(quote?.notes),\n terms: text(quote?.terms),\n status: status.status,\n statusLabel: status.label,\n paidAtMs: paidAt(order),\n receiptUrl: unpaid ? null : (input.receiptUrl ?? null),\n approvalRequired,\n payable: unpaid && !approvalRequired && quotePayRefusal(order, input.orderId) === null,\n revision: Math.max(1, Number(quote?.revision ?? 1) || 1),\n proofs: currentQuoteProofs(quote).map((proof) => ({\n id: String(proof.id),\n name: String(proof.name ?? 'Proof'),\n contentType: String(proof.contentType ?? ''),\n size: Math.max(0, cents(proof.size)),\n inline: visitorUploadIsInline(String(proof.contentType ?? '')),\n })),\n response: pageResponse(quote),\n // The page is only ever a quote's, whatever the caller picked off the order.\n respondable: quoteRespondRefusal({ channel: 'quote', status: order.status, quote }) === null,\n }\n}\n\n/** Order lines as the pay link's page lists them: what each charges, nothing about stock or cost. */\nexport function quotePageLines(lines: readonly OrderLineItem[]): QuotePageLine[] {\n return lines.map((line) => {\n const included = line.included === true\n const quantity = Math.max(0, cents(line.quantity))\n const unitAmountCents = included ? 0 : Math.max(0, cents(line.unitAmountCents))\n return {\n name: String(line.name ?? ''),\n variantLabel: text(line.variantLabel),\n description: text(line.description),\n sku: text(line.sku),\n quantity,\n unitAmountCents,\n amountCents: unitAmountCents * quantity,\n included,\n }\n })\n}\n\n/** The latest answer, as the page may show it back to the link's holder: never the address or browser. */\nfunction pageResponse(quote: OrderQuote | null | undefined): QuotePageResponse | null {\n const latest = latestQuoteResponse(quote)\n if (!latest) return null\n return {\n action: latest.action === 'approve' ? 'approve' : 'changes',\n atMs: Number(latest.atMs) || 0,\n name: latest.action === 'approve' ? text(latest.name) : null,\n comment: latest.action === 'changes' ? text(latest.comment) : null,\n files: latest.files?.length ?? 0,\n }\n}\n\n/*==========================================\n * WHAT A PAYMENT CHARGES\n *=========================================*/\n\n/** One line of a quote's Checkout Session. */\nexport interface QuoteCheckoutLine {\n name: string\n /** The quote's lines this one charges for, as the hosted page lists them. */\n description: string\n amountCents: number\n /** False for tax-exempt products: no rate is applied and Stripe Tax is told it is nontaxable. */\n taxable: boolean\n}\n\n/** What a quote's Checkout Session charges, priced from the stored quote alone. */\nexport interface QuoteCheckoutCharge {\n /** The goods grouped by whether they are taxed, so one rate taxes exactly the quote's taxable amount. */\n lines: QuoteCheckoutLine[]\n itemsCents: number\n discountCents: number\n /** The goods after the discount: what the business is paid for them. */\n goodsCents: number\n taxableCents: number\n shippingCents: number\n /** The quote's tax; 0 when Stripe Tax works it out at payment. */\n taxCents: number\n /**\n * The percentage applied to the taxed line as a Stripe tax rate, or null\n * when no rate is applied (no tax, Stripe Tax, or tax charged as its own line).\n */\n taxPct: number | null\n taxAtPayment: boolean\n /** Goods, shipping and the quote's tax. Stripe Tax adds to it at payment. */\n totalCents: number\n /** What the platform fee prices the goods as. */\n feeProductType: ProductType\n}\n\nconst LINE_DESCRIPTION_MAX = 500\n\nfunction lineSummary(lines: readonly OrderLineItem[]): string {\n const parts = lines.map((line) => {\n const label = line.variantLabel ? `${line.name} (${line.variantLabel})` : line.name\n return `${Math.max(1, cents(line.quantity))} × ${label}`\n })\n const summary = parts.join(', ')\n return summary.length > LINE_DESCRIPTION_MAX ? `${summary.slice(0, LINE_DESCRIPTION_MAX - 1)}…` : summary\n}\n\n/** What the fee ladder prices the quote's charged goods as: physical when any line ships. */\nfunction feeProductTypeOf(lines: readonly OrderLineItem[]): ProductType {\n const charged = lines.filter((line) => !line.included)\n const types = new Set(charged.map((line) => line.productType ?? 'physical'))\n if (types.has('physical') || types.size === 0) return 'physical'\n return types.has('service') ? 'service' : 'digital'\n}\n\n/**\n * The charge for a quote, from its stored lines, discount, shipping and tax\n * basis through {@link computeQuoteTotals} — the same function that priced it\n * when it was saved, so the page, the session and the stored quote agree.\n *\n * The goods are charged as at most two lines, the taxed and the tax-exempt,\n * each after its share of the discount. A store rate is applied to the taxed\n * line as one Stripe tax rate, so Stripe's tax is the rate on exactly the\n * amount the quote taxed, and the quote's figure is what is collected. A tax\n * service's figure is carried the same way, as the percentage of the taxed\n * line it amounts to. Included lines charge nothing and are not sent.\n */\nexport function quoteCheckoutCharge(\n order: Pick<HostOrder, 'number' | 'lineItems' | 'quote'>,\n orderId: string,\n): QuoteCheckoutCharge {\n return payLinkCheckoutCharge({\n lineItems: order.lineItems ?? [],\n tax: order.quote?.tax ?? { kind: 'none', reason: 'not-collected' },\n discount: order.quote?.discount ?? null,\n shippingCents: Math.max(0, cents(order.quote?.shipping?.amountCents)),\n label: formatQuoteNumber(order, orderId),\n })\n}\n\n/**\n * What a pay link's Checkout Session charges for stored lines, a discount,\n * fixed shipping and a tax basis, under a label (`Quote #1042`,\n * `Invoice #1042`): {@link quoteCheckoutCharge}'s pricing, shared with an\n * invoiced order's (AGL-4099), so both are charged the same way.\n */\nexport function payLinkCheckoutCharge(input: {\n lineItems: readonly OrderLineItem[]\n tax: QuoteTaxBasis\n discount: QuoteDiscount | null\n shippingCents: number\n label: string\n}): QuoteCheckoutCharge {\n const { lineItems, tax, discount, shippingCents, label } = input\n const totals = computeQuoteTotals({ lines: lineItems, discount, shippingCents, tax })\n const amounts = quoteLineAmounts(lineItems, discount)\n const groups = [true, false].map((taxable) => {\n const members = lineItems\n .map((line, index) => ({ line, net: amounts.netCents[index] }))\n .filter(({ line, net }) => net > 0 && (line.taxExempt !== true) === taxable)\n return {\n taxable,\n amountCents: members.reduce((sum, { net }) => sum + net, 0),\n description: lineSummary(members.map(({ line }) => line)),\n }\n })\n const charged = groups.filter((group) => group.amountCents > 0)\n const lines: QuoteCheckoutLine[] = charged.map((group) => ({\n name: charged.length > 1 && !group.taxable ? `${label} (tax-exempt items)` : label,\n description: group.description,\n amountCents: group.amountCents,\n taxable: group.taxable,\n }))\n const taxableCents = groups[0].amountCents\n const taxPct =\n totals.taxCents > 0 && taxableCents > 0\n ? tax.kind === 'rate'\n ? Number(tax.pct)\n : engineLineTaxPercentages([{ amountCents: taxableCents, taxCents: totals.taxCents }], 0)[0]\n : null\n // A tax service can tax a quote whose goods are all exempt (on its\n // shipping, say): with no taxed line to carry a rate, its figure is\n // charged as a line of its own, so the customer still pays what the quote says.\n if (totals.taxCents > 0 && taxPct === null) {\n lines.push({\n name: tax.providerLabel ? `Sales tax (${tax.providerLabel})` : 'Sales tax',\n description: label,\n amountCents: totals.taxCents,\n taxable: false,\n })\n }\n return {\n lines,\n itemsCents: totals.itemsCents,\n discountCents: totals.discountCents,\n goodsCents: totals.itemsCents - totals.discountCents,\n taxableCents,\n shippingCents,\n taxCents: totals.taxCents,\n taxPct,\n taxAtPayment: totals.taxAtPayment,\n totalCents: totals.totalCents,\n feeProductType: feeProductTypeOf(lineItems),\n }\n}\n\n/*==========================================\n * WHETHER IT CAN BE PAID NOW\n *=========================================*/\n\nexport type QuotePayRefusal =\n | 'paid'\n | 'closed'\n | 'approval-required'\n | 'tax-undecided'\n | 'nothing-to-pay'\n\n/** Why a quote cannot be paid now, or null when it can. */\nexport function quotePayRefusal(\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote'>,\n orderId: string,\n): QuotePayRefusal | null {\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n if (order.status !== 'pending') return 'paid'\n if (quotePaymentBlockedByApproval(order.quote)) return 'approval-required'\n if (order.quote?.tax?.kind === 'none' && order.quote.tax.reason === 'undecided') return 'tax-undecided'\n if (quoteCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay'\n return null\n}\n\n/** What the customer is told for a {@link QuotePayRefusal}, naming the business. */\nexport function quotePayRefusalMessage(reason: QuotePayRefusal, storeName: string): string {\n const business = storeName.trim() || 'the business'\n switch (reason) {\n case 'paid':\n return 'This quote has been paid.'\n case 'closed':\n return `This quote 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 quote.`\n case 'nothing-to-pay':\n return `This quote has nothing to pay by card. Contact ${business} with any questions.`\n }\n}\n\n/*==========================================\n * WHEN A PAYMENT COMPLETES\n *=========================================*/\n\n/** What a completed Checkout Session says about the quote it paid. */\nexport interface QuotePaymentFacts {\n sessionId: string\n paymentIntentId: string | null\n /** The link version and quote edit the session was minted for, from its metadata. */\n linkVersion?: string | number | null\n quoteUpdatedAtMs?: string | number | null\n paidAtMs: number\n /** The payer, as Stripe collected them. */\n email: string | null\n name: string | null\n /** What Stripe charged in all, and its shipping and tax parts. */\n amountTotalCents: number | null\n shippingCents: number\n taxCents: number\n /** The platform fee the session was minted with. */\n feeCents: number\n taxMode: StorefrontTaxMode\n /** The address Stripe collected, when the session asked for one. */\n shippingAddress: OrderAddress | null\n}\n\n/**\n * What a completed payment does to a quote:\n *\n * - `pay`: the quote is unpaid and the payment is for it as it stands, so it\n * becomes the order.\n * - `superseded`: the quote is unpaid, but the payment was made through a pay\n * link the business replaced, or for a version of the quote it has since\n * changed. Taking it would record a sale at a price or for a link the\n * business withdrew.\n * - `already-paid`: another payment paid the quote first.\n * - `redelivery`: Stripe sending this same payment again; nothing to do.\n *\n * The two refusals keep the money visible: they are recorded on the quote and\n * the business is told, so a payment is never fulfilled twice and never lost.\n */\nexport type QuotePaymentDisposition = 'pay' | 'superseded' | 'already-paid' | 'redelivery'\n\nexport function quotePaymentDisposition(\n order: Pick<HostOrder, 'status' | 'quote' | 'checkoutSessionId' | 'paymentIntentId'> &\n Partial<Pick<HostOrder, 'payLink'>>,\n payment: Pick<QuotePaymentFacts, 'sessionId' | 'paymentIntentId' | 'linkVersion' | 'quoteUpdatedAtMs'>,\n): QuotePaymentDisposition {\n // Any order's pay link answers the same way (AGL-4099): an invoiced order\n // reads its version and its recorded payments off `payLink`, and its\n // session carries no quote edit to compare.\n const recorded = orderPayLinkUnmatched(order).some((entry) => entry?.sessionId === payment.sessionId)\n if (recorded) return 'redelivery'\n if (order.status !== 'pending') {\n const same =\n (order.checkoutSessionId && order.checkoutSessionId === payment.sessionId) ||\n (payment.paymentIntentId && order.paymentIntentId === payment.paymentIntentId)\n return same ? 'redelivery' : 'already-paid'\n }\n const sentVersion = payment.linkVersion\n if (sentVersion != null && sentVersion !== '' && Number(sentVersion) !== orderPayLinkVersion(order)) {\n return 'superseded'\n }\n const sentEdit = payment.quoteUpdatedAtMs\n if (sentEdit != null && sentEdit !== '' && Number(sentEdit) !== Number(order.quote?.updatedAtMs)) {\n return 'superseded'\n }\n return 'pay'\n}\n\n/** A payment the quote could not take, as {@link QuoteUnmatchedPayment} records it. */\nexport function quoteUnmatchedPayment(\n facts: Pick<QuotePaymentFacts, 'sessionId' | 'paymentIntentId' | 'amountTotalCents' | 'paidAtMs'>,\n reason: QuoteUnmatchedPayment['reason'],\n): QuoteUnmatchedPayment {\n return {\n sessionId: facts.sessionId,\n paymentIntentId: facts.paymentIntentId,\n amountCents: Math.max(0, cents(facts.amountTotalCents)),\n atMs: facts.paidAtMs,\n reason,\n }\n}\n\n/** The timeline line for a payment the quote (or an order's invoice, AGL-4099) could not take. */\nexport function quoteUnmatchedPaymentDetail(\n entry: QuoteUnmatchedPayment,\n noun: 'quote' | 'invoice' = 'quote',\n): string {\n const amount = `$${(entry.amountCents / 100).toFixed(2)}`\n return entry.reason === 'superseded'\n ? `A payment of ${amount} came through a pay link that was replaced, or for an earlier ` +\n `version of this ${noun}. The money is in Stripe and this ${noun} records no sale for it; ` +\n 'refund it in Stripe, or reconcile it by hand.'\n : `A second payment of ${amount} came in after this ${noun} was paid. The money is in Stripe ` +\n 'and no second sale was recorded; refund it in Stripe, or reconcile it by hand.'\n}\n\n/**\n * The order a paid quote becomes, the whole document as it will stand. A\n * quote carries none of the fields order lists read (`commerce-quotes.ts`);\n * paying it writes them:\n *\n * - `createdAtMs` is the time it was paid, the moment it became an order, so\n * it lists and counts on the day the money came in.\n * - The customer moves to the top-level fields every order reader asks\n * (`customerEmail`, `customerName`, `customerPhone`, `customerRecord`), the\n * payer's own email first, as a paid draft takes it.\n * - The address Stripe collected ships it, else the quote's ship-to; the\n * quote's bill-to bills it.\n * - The totals are what Stripe charged: its shipping and tax where it charged\n * any, the platform fee the session was minted with, and its total.\n * - The list fields (`withOrderListFields`) are stamped from all of that.\n */\nexport function paidQuoteOrder(\n order: HostOrder,\n orderId: string,\n facts: QuotePaymentFacts,\n): HostOrder & OrderListFields & { updatedAtMs: number; requiresShipping: boolean } {\n const quote = order.quote as OrderQuote\n const customer = quote?.customer ?? {}\n const stored = order.totals ?? { itemsCents: 0, discountCents: 0, shippingCents: 0, taxCents: 0, feeCents: 0, totalCents: 0 }\n const shippingCents = facts.shippingCents > 0 ? facts.shippingCents : cents(stored.shippingCents)\n const taxCents = facts.taxCents > 0 ? facts.taxCents : cents(stored.taxCents)\n const totalCents =\n facts.amountTotalCents != null && Number.isFinite(facts.amountTotalCents)\n ? facts.amountTotalCents\n : cents(stored.itemsCents) - cents(stored.discountCents) + shippingCents + taxCents\n const shippingAddress = facts.shippingAddress ?? quote?.shipTo ?? null\n const label = formatOrderNumber(order, orderId)\n const paid: HostOrder & { updatedAtMs: number } = {\n ...order,\n status: 'paid',\n createdAtMs: facts.paidAtMs,\n customerEmail: text(facts.email) ?? text(customer.email),\n customerName: text(customer.name) ?? text(facts.name) ?? text(customer.company),\n ...(text(customer.phone) ? { customerPhone: text(customer.phone) } : {}),\n ...(customer.record?.kind && customer.record?.id ? { customerRecord: { ...customer.record } } : {}),\n ...(shippingAddress ? { shippingAddress: { ...shippingAddress } } : {}),\n ...(quote?.billTo ? { billingAddress: { ...quote.billTo } } : {}),\n totals: {\n itemsCents: cents(stored.itemsCents),\n discountCents: cents(stored.discountCents),\n shippingCents,\n taxCents,\n feeCents: Math.max(0, cents(facts.feeCents)),\n totalCents,\n },\n taxMode: facts.taxMode,\n paymentIntentId: facts.paymentIntentId ?? undefined,\n checkoutSessionId: facts.sessionId,\n timeline: appendOrderEvent(order, 'paid', `${label} paid through its pay link`, facts.paidAtMs),\n quote: { ...quote, paidAtMs: facts.paidAtMs },\n // New to a shipping tool's feed from the moment it is paid.\n updatedAtMs: facts.paidAtMs,\n }\n if (!paid.paymentIntentId) delete paid.paymentIntentId\n return withOrderListFields(orderId, paid)\n}\n"],"names":["visitorUploadIsInline","appendOrderEvent","formatOrderNumber","computeQuoteTotals","describeQuoteTax","formatQuoteNumber","quoteLineAmounts","quotePaymentBlockedByApproval","currentQuoteProofs","latestQuoteResponse","quoteRespondRefusal","engineLineTaxPercentages","withOrderListFields","QUOTE_MIN_CHARGE_CENTS","quoteLinkVersion","quote","version","Math","floor","Number","linkVersion","isFinite","orderPayLinkVersion","order","payLink","orderPayLinkUnmatched","list","unmatchedPayments","Array","isArray","filter","entry","text","value","trimmed","trim","cents","number","round","quotePageAddress","address","view","name","line1","line2","city","state","postalCode","country","Object","values","some","Boolean","quotePageStatus","status","label","discountLabel","discount","kind","pct","paidAt","stamped","paidAtMs","event","timeline","find","atMs","buildQuotePageView","input","lines","lineItems","unpaid","charge","quoteCheckoutCharge","orderId","stored","totals","itemsCents","discountCents","shippingCents","taxCents","totalCents","approvalRequired","taxAtPayment","tax","storeName","dateMs","updatedAtMs","createdAtMs","currency","customerName","customer","company","billTo","shipTo","quotePageLines","taxLabel","shippingAtPayment","notes","terms","statusLabel","receiptUrl","payable","quotePayRefusal","revision","max","proofs","map","proof","id","String","contentType","size","inline","response","pageResponse","respondable","channel","line","included","quantity","unitAmountCents","variantLabel","description","sku","amountCents","latest","action","comment","files","length","LINE_DESCRIPTION_MAX","lineSummary","parts","summary","join","slice","feeProductTypeOf","charged","types","Set","productType","has","payLinkCheckoutCharge","reason","shipping","amounts","groups","taxable","members","index","net","netCents","taxExempt","reduce","sum","group","taxableCents","taxPct","push","providerLabel","goodsCents","feeProductType","quotePayRefusalMessage","business","quotePaymentDisposition","payment","recorded","sessionId","same","checkoutSessionId","paymentIntentId","sentVersion","sentEdit","quoteUpdatedAtMs","quoteUnmatchedPayment","facts","amountTotalCents","quoteUnmatchedPaymentDetail","noun","amount","toFixed","paidQuoteOrder","feeCents","shippingAddress","paid","customerEmail","email","phone","customerPhone","record","customerRecord","billingAddress","taxMode","undefined"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,wCAAuC;AAE7E,SACEC,gBAAgB,EAChBC,iBAAiB,QAKZ,uBAAmB;AAC1B,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,EAChBC,6BAA6B,QAKxB,uBAAmB;AAC1B,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,6BAAyB;AAEtG,SAASC,wBAAwB,QAAQ,2BAAuB;AAChE,SAASC,mBAAmB,QAA8B,yBAAqB;AAE/E;;;;;;;;;;;;;;;;;;;2CAmB2C,GAE3C,oFAAoF,GACpF,OAAO,MAAMC,yBAAyB,GAAE;AAExC,mEAAmE,GACnE,OAAO,SAASC,iBAAiBC,KAAyD;IACxF,MAAMC,UAAUC,KAAKC,KAAK,CAACC,OAAOJ,yBAAAA,MAAOK,WAAW;IACpD,OAAOD,OAAOE,QAAQ,CAACL,YAAYA,WAAW,IAAIA,UAAU;AAC9D;AAEA;;;;;CAKC,GACD,OAAO,SAASM,oBAAoBC,KAAuE;QAEvEA;IADlC,IAAIA,yBAAAA,MAAOR,KAAK,EAAE,OAAOD,iBAAiBS,MAAMR,KAAK;IACrD,MAAMC,UAAUC,KAAKC,KAAK,CAACC,OAAOI,0BAAAA,iBAAAA,MAAOC,OAAO,qBAAdD,eAAgBP,OAAO;IACzD,OAAOG,OAAOE,QAAQ,CAACL,YAAYA,WAAW,IAAIA,UAAU;AAC9D;AAEA,0GAA0G,GAC1G,OAAO,SAASS,sBACdF,KAAuE;QAEXA;IAA5D,MAAMG,OAAOH,CAAAA,yBAAAA,MAAOR,KAAK,IAAGQ,MAAMR,KAAK,CAACY,iBAAiB,GAAGJ,0BAAAA,iBAAAA,MAAOC,OAAO,qBAAdD,eAAgBI,iBAAiB;IAC7F,OAAOC,MAAMC,OAA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AAMlH,QAAQ;QAC9F/C,OAAO,aAAKA;YAAO+C,UAAUkH,MAAMlH,QAAQ;;QAC3C,4DAA4D;QAC5DyB,aAAayF,MAAMlH,QAAQ;;IAE7B,IAAI,CAAC2H,KAAKd,eAAe,EAAE,OAAOc,KAAKd,eAAe;IACtD,OAAO/J,oBAAoB8D,SAAS+G;AACtC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-quote-pay.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 { visitorUploadIsInline } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport type { ProductType } from './commerce'\nimport {\n appendOrderEvent,\n formatOrderNumber,\n type HostOrder,\n type OrderAddress,\n type OrderLineItem,\n type OrderStatus,\n} from './commerce-orders'\nimport {\n computeQuoteTotals,\n describeQuoteTax,\n formatQuoteNumber,\n quoteLineAmounts,\n quotePaymentBlockedByApproval,\n quoteTaxBasisFromSettings,\n type OrderQuote,\n type QuoteDiscount,\n type QuoteNoTaxReason,\n type QuoteTaxBasis,\n type QuoteTaxKind,\n type QuoteUnmatchedPayment,\n} from './commerce-quotes'\nimport { currentQuoteProofs, latestQuoteResponse, quoteRespondRefusal } from './commerce-quote-proofs'\nimport type { TaxSettings } from './commerce-tax'\nimport { storefrontTaxDecision, type StorefrontTaxMode } from './commerce-tax-decision'\nimport { engineLineTaxPercentages, storeTaxAllowsEngine } from './commerce-tax-engine'\nimport { withOrderListFields, type OrderListFields } from './order-list-fields'\n\n/*==========================================\n * PAYING A QUOTE (AGL-4094).\n *\n * The customer opens the quote on the business's own site from a signed pay\n * link, sees it, and pays it. Everything here is pure, so the page's view,\n * the pay route's charge and the webhook's paid order all come from one\n * reading of the stored quote, and none of them from anything the browser\n * sends:\n *\n * - {@link buildQuotePageView}: the ONE projection of a quote that leaves the\n * server for a visitor holding the link, allow-listed field by field.\n * - {@link quoteCheckoutCharge}: what a Checkout Session charges, priced from\n * the stored lines, discount, shipping and tax basis.\n * - {@link quotePayRefusal}: why a quote cannot be paid now, if it cannot.\n * - {@link quotePaymentDisposition} and {@link paidQuoteOrder}: what a\n * completed payment does to the quote, and the order it becomes.\n * - {@link quotePayTax}: the tax every one of them reads, which for a quote\n * saved before the store chose its sales tax is the store's choice now.\n *\n * The customer side has no expiry and no open or closed states: a quote and\n * its link stay until the quote is paid or the business replaces the link.\n *=========================================*/\n\n/** Stripe's smallest card charge; a quote that totals less cannot be paid by card. */\nexport const QUOTE_MIN_CHARGE_CENTS = 50\n\n/** The pay link version a quote is on; absent reads as the first. */\nexport function quoteLinkVersion(quote: Pick<OrderQuote, 'linkVersion'> | null | undefined): number {\n const version = Math.floor(Number(quote?.linkVersion))\n return Number.isFinite(version) && version >= 1 ? version : 1\n}\n\n/**\n * The pay link version any order is on (AGL-4099). A quote keeps its version\n * where slice 2 put it, `quote.linkVersion`, so every link already sent keeps\n * verifying; any other order keeps it as `payLink.version`. Absent reads as\n * the first either way.\n */\nexport function orderPayLinkVersion(order: Partial<Pick<HostOrder, 'quote' | 'payLink'>> | null | undefined): number {\n if (order?.quote) return quoteLinkVersion(order.quote)\n const version = Math.floor(Number(order?.payLink?.version))\n return Number.isFinite(version) && version >= 1 ? version : 1\n}\n\n/** Payments the order's pay link could not take: a quote's on the quote, any other order's on `payLink`. */\nexport function orderPayLinkUnmatched(\n order: Partial<Pick<HostOrder, 'quote' | 'payLink'>> | null | undefined,\n): QuoteUnmatchedPayment[] {\n const list = order?.quote ? order.quote.unmatchedPayments : order?.payLink?.unmatchedPayments\n return Array.isArray(list) ? list.filter((entry) => entry && typeof entry === 'object') : []\n}\n\n/*==========================================\n * THE TAX A QUOTE IS SHOWN AND PAID UNDER\n *=========================================*/\n\n/**\n * The store a pay link is read against: its sales tax choice, as\n * `hosts/{hostId}/settings/store` keeps it under `tax`. Absent or null, the\n * store has not chosen.\n */\nexport interface PayLinkStore {\n tax?: TaxSettings | null\n}\n\n/** The store a pay link reads, from the store settings document's data (nothing, for no document). */\nexport function payLinkStoreOf(settings: { tax?: unknown } | null | undefined): PayLinkStore {\n const tax = settings?.tax\n return { tax: tax && typeof tax === 'object' ? (tax as TaxSettings) : null }\n}\n\n/** Whether a basis records that nobody had chosen the store's sales tax, which is no choice at all. */\nexport function quoteTaxIsUndecided(basis: Pick<QuoteTaxBasis, 'kind' | 'reason'> | null | undefined): boolean {\n return basis?.kind === 'none' && basis.reason === 'undecided'\n}\n\n/**\n * Where a quote's tax comes from when it is shown and paid:\n *\n * - `stored`: the basis it was saved with.\n * - `current`: it was saved before the store chose, and takes the store's\n * choice as it stands now.\n * - `save`: it was saved before the store chose, and the store's choice now\n * prices it only when it is saved again.\n */\nexport type QuotePayTaxSource = 'stored' | 'current' | 'save'\n\nexport interface QuotePayTax {\n basis: QuoteTaxBasis\n source: QuotePayTaxSource\n}\n\n/**\n * The tax a quote is shown, charged and paid under (AGL-4162): the one answer\n * the quote page, Pay, the payment's record (carried on its session) and the\n * console's notice all read.\n *\n * A quote keeps the basis it was saved with, except one saved before the\n * store chose how it handles sales tax. That basis records no choice, so the\n * quote takes the store's choice as it stands now, through the same\n * `quoteTaxBasisFromSettings` the editor prices a save with: no sales tax,\n * prices that include tax, or Stripe Tax at payment. Nothing is written for\n * it; the next save stores the same basis.\n *\n * The store's own rates on prices that exclude tax are the one choice not\n * taken this way. On those settings a save asks the site's tax service where\n * one is connected (`priceQuote` in `server/quote.ts`), and only that save\n * knows the figure: which service is connected is the tax service's own to\n * say. Such a quote keeps its basis, and so stays unpaid, until it is saved.\n *\n * Without a store, the stored basis stands.\n */\nexport function quotePayTax(\n quote: Pick<OrderQuote, 'tax' | 'shipTo'> | null | undefined,\n store?: PayLinkStore | null,\n): QuotePayTax {\n const stored: QuoteTaxBasis = quote?.tax ?? { kind: 'none', reason: 'not-collected' }\n if (!store || !quoteTaxIsUndecided(stored)) return { basis: stored, source: 'stored' }\n if (storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') return { basis: stored, source: 'stored' }\n if (storeTaxAllowsEngine(store.tax)) return { basis: stored, source: 'save' }\n return { basis: quoteTaxBasisFromSettings(store.tax, quote?.shipTo), source: 'current' }\n}\n\nconst TAX_KINDS: ReadonlySet<string> = new Set<QuoteTaxKind>(['rate', 'service', 'at-payment', 'none'])\nconst NO_TAX_REASONS: ReadonlySet<string> = new Set<QuoteNoTaxReason>([\n 'not-collected',\n 'prices-include-tax',\n 'no-rate',\n 'undecided',\n])\nconst BASIS_LABEL_MAX = 120\n\n/** A basis holding only what its kind carries, in one order, or null for anything that is not one. */\nfunction tidyTaxBasis(raw: unknown): QuoteTaxBasis | null {\n if (!raw || typeof raw !== 'object') return null\n const source = raw as Record<string, unknown>\n const kind = String(source['kind'] ?? '')\n if (!TAX_KINDS.has(kind)) return null\n const label = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim().slice(0, BASIS_LABEL_MAX) : '')\n if (kind === 'rate') {\n const pct = Number(source['pct'])\n if (!Number.isFinite(pct)) return null\n const named = label(source['label'])\n return { kind, pct, ...(named ? { label: named } : {}) }\n }\n if (kind === 'service') {\n const taxCents = Math.round(Number(source['taxCents']))\n if (!Number.isFinite(taxCents) || taxCents < 0) return null\n const named = label(source['providerLabel'])\n return { kind, taxCents, ...(named ? { providerLabel: named } : {}) }\n }\n if (kind === 'at-payment') return { kind }\n const reason = String(source['reason'] ?? '')\n return { kind: 'none', reason: (NO_TAX_REASONS.has(reason) ? reason : 'not-collected') as QuoteNoTaxReason }\n}\n\n/**\n * A basis as one short string: what the quote page sends back with Pay, so a\n * payment is refused when the tax it would charge is not the tax the page\n * showed, and what a session records as the basis it charged. Equal bases\n * have one key.\n */\nexport function quoteTaxBasisKey(basis: QuoteTaxBasis): string {\n return JSON.stringify(tidyTaxBasis(basis) ?? { kind: 'none', reason: 'not-collected' })\n}\n\n/** A basis back from {@link quoteTaxBasisKey}, or null for anything else. */\nexport function quoteTaxBasisFromKey(key: unknown): QuoteTaxBasis | null {\n if (typeof key !== 'string' || !key || key.length > 500) return null\n try {\n return tidyTaxBasis(JSON.parse(key))\n } catch {\n return null\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S PAGE\n *=========================================*/\n\n/** An address as the quote page prints it: no phone. */\nexport interface QuotePageAddress {\n name: string | null\n line1: string | null\n line2: string | null\n city: string | null\n state: string | null\n postalCode: string | null\n country: string | null\n}\n\nexport interface QuotePageLine {\n name: string\n /** The option and add-ons chosen, as order lines print them. */\n variantLabel: string | null\n description: string | null\n sku: string | null\n quantity: number\n unitAmountCents: number\n /** What the line charges: 0 for an included line. */\n amountCents: number\n /** Included at no charge. */\n included: boolean\n}\n\n/** Where the quote stands, as its customer sees it. */\nexport type QuotePageStatus = 'unpaid' | 'paid' | 'canceled' | 'refunded'\n\n/** A proof as the quote page lists it: no storage path, nothing about who attached it. */\nexport interface QuotePageProof {\n id: string\n name: string\n contentType: string\n size: number\n /** Shown in the page as a picture; everything else is a download. */\n inline: boolean\n}\n\n/** The customer's latest answer to the revision the page shows. */\nexport interface QuotePageResponse {\n action: 'approve' | 'changes'\n atMs: number\n /** With an approval: the name it was given under. */\n name: string | null\n comment: string | null\n /** How many files came with it. */\n files: number\n}\n\n/**\n * What the quote page shows. Allow-listed, never spread: the order document\n * carries the customer's email and phone, Stripe ids, the business's own\n * timeline and who wrote the quote, none of which a forwarded link may show.\n * New fields are added here deliberately, or not at all.\n */\nexport interface QuotePageView {\n state: 'quote'\n /**\n * What the page shows (AGL-4099): a quote, or an invoice for an order the\n * business sent one for. An invoice has no proofs and no approval, and the\n * page says \"invoice\" where a quote's says \"quote\".\n */\n kind: 'quote' | 'invoice'\n storeName: string\n /** `Quote #1042`, or `Invoice #1042`. */\n number: string\n /** When the quote was last written, which is the date it carries. */\n dateMs: number | null\n /**\n * The edit of the quote this view shows. Pay sends it back, and a quote\n * changed since is refused, so nobody pays for a version they have not seen.\n */\n version: number\n currency: string\n customerName: string | null\n company: string | null\n billTo: QuotePageAddress | null\n shipTo: QuotePageAddress | null\n lines: QuotePageLine[]\n totals: {\n itemsCents: number\n discountCents: number\n shippingCents: number\n taxCents: number\n totalCents: number\n }\n /** `10% off`, or null for an amount or no discount. */\n discountLabel: string | null\n /** The tax line's label, or `Tax is added at payment`. */\n taxLabel: string\n /** Stripe Tax works the tax out when the customer pays; `taxCents` is 0 until then. */\n taxAtPayment: boolean\n /**\n * The customer picks a shipping rate when they pay (an invoiced draft\n * order, AGL-4099); `shippingCents` is 0 until then. A quote's shipping is\n * priced on it, so this is false for every quote.\n */\n shippingAtPayment: boolean\n notes: string | null\n terms: string | null\n status: QuotePageStatus\n statusLabel: string\n paidAtMs: number | null\n /** The order's status page, once paid. */\n receiptUrl: string | null\n /** The business asks the customer to approve the proof before paying. */\n approvalRequired: boolean\n /** A Pay button belongs on the page. */\n payable: boolean\n /**\n * What the page says in place of Pay when the business can't take payments\n * online right now (AGL-4162): the Pay route's own refusal, word for word.\n * Null otherwise, and the page asks the customer to contact the business.\n */\n notPayableMessage: string | null\n /**\n * The tax the quote's totals are priced under ({@link quoteTaxBasisKey}),\n * which Pay sends back as `tax`: a quote whose tax would charge differently\n * from the page is shown again before it is paid (AGL-4162). Null for an\n * invoice, whose tax is fixed when it is made, and once paid.\n */\n taxKey: string | null\n /** The revision the page shows (AGL-4096). */\n revision: number\n /** That revision's proofs. */\n proofs: QuotePageProof[]\n /** The customer's latest answer to it, if any. */\n response: QuotePageResponse | null\n /** Approve and Request changes belong on the page. */\n respondable: boolean\n}\n\n/** What a signed link for an older version of the quote opens: nothing of the quote. */\nexport interface QuotePageReplacedView {\n state: 'replaced'\n storeName: string\n}\n\nconst text = (value: unknown): string | null => {\n const trimmed = typeof value === 'string' ? value.trim() : ''\n return trimmed ? trimmed : null\n}\n\nconst cents = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) ? number : 0\n}\n\n/** An address as the pay link's page prints it, or null when it says nothing. */\nexport function quotePageAddress(address: OrderAddress | null | undefined): QuotePageAddress | null {\n if (!address) return null\n const view: QuotePageAddress = {\n name: text(address.name),\n line1: text(address.line1),\n line2: text(address.line2),\n city: text(address.city),\n state: text(address.state),\n postalCode: text(address.postalCode),\n country: text(address.country),\n }\n return Object.values(view).some(Boolean) ? view : null\n}\n\n/** Where an order stands as the pay link's page says it. */\nexport function quotePageStatus(status: OrderStatus | string | undefined): { status: QuotePageStatus; label: string } {\n if (status === 'pending') return { status: 'unpaid', label: 'Unpaid' }\n if (status === 'cancelled') return { status: 'canceled', label: 'Canceled' }\n if (status === 'refunded') return { status: 'refunded', label: 'Refunded' }\n return { status: 'paid', label: 'Paid' }\n}\n\nfunction discountLabel(discount: QuoteDiscount | null | undefined): string | null {\n if (discount?.kind !== 'percent' || !(Number(discount.pct) > 0)) return null\n return `${Number(discount.pct)}% off`\n}\n\n/** When the quote was paid: its stamp, else the timeline's `paid` event. */\nfunction paidAt(order: Pick<HostOrder, 'status' | 'quote' | 'timeline'>): number | null {\n if (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 return event ? Number(event.atMs) || null : null\n}\n\n/**\n * The quote page's view of an order document on the `quote` channel. Totals\n * are the stored lines' through {@link computeQuoteTotals} until the quote is\n * paid, and the paid order's own totals (what Stripe charged) after. The tax\n * is {@link quotePayTax}'s for the store given, and Pay belongs on the page\n * only when nothing would refuse it: the store's payments included, when the\n * caller says whether it can take them.\n */\nexport function buildQuotePageView(input: {\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'totals' | 'quote' | 'timeline'>\n orderId: string\n storeName: string\n currency: string\n /** The order's status page, for a paid quote. */\n receiptUrl?: string | null\n /** The store's sales tax choice, which a quote saved before it was made takes. */\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 quote = order.quote\n const lines = order.lineItems ?? []\n const status = quotePageStatus(order.status)\n const unpaid = status.status === 'unpaid'\n const payTax = quotePayTax(quote, input.store)\n const charge = quoteCheckoutCharge(order, input.orderId, input.store)\n const stored = order.totals\n const totals = 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 approvalRequired = unpaid && quotePaymentBlockedByApproval(quote)\n const taxAtPayment = unpaid && payTax.basis.kind === 'at-payment'\n const refused = unpaid\n ? payLinkRefusalWithPayments(quotePayRefusal(order, input.orderId, input.store), input.paymentsReady)\n : null\n return {\n state: 'quote',\n kind: 'quote',\n storeName: input.storeName,\n number: formatQuoteNumber(order, input.orderId),\n dateMs: Number(quote?.updatedAtMs ?? quote?.createdAtMs) || null,\n version: Number(quote?.updatedAtMs) || 0,\n currency: input.currency || 'USD',\n customerName: text(quote?.customer?.name) ?? text(quote?.customer?.company),\n company: text(quote?.customer?.name) ? text(quote?.customer?.company) : null,\n billTo: quotePageAddress(quote?.billTo),\n shipTo: quotePageAddress(quote?.shipTo),\n lines: quotePageLines(lines),\n totals,\n discountLabel: discountLabel(quote?.discount),\n // Once paid, the tax is what was charged: Stripe's figure under Stripe Tax.\n taxLabel: unpaid || payTax.basis.kind !== 'at-payment' ? describeQuoteTax(payTax.basis) : 'Tax',\n taxAtPayment,\n shippingAtPayment: false,\n notes: text(quote?.notes),\n terms: text(quote?.terms),\n status: status.status,\n statusLabel: status.label,\n paidAtMs: paidAt(order),\n receiptUrl: unpaid ? null : (input.receiptUrl ?? null),\n approvalRequired,\n payable: unpaid && refused === null,\n notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'quote') : null,\n taxKey: unpaid ? quoteTaxBasisKey(payTax.basis) : null,\n revision: Math.max(1, Number(quote?.revision ?? 1) || 1),\n proofs: currentQuoteProofs(quote).map((proof) => ({\n id: String(proof.id),\n name: String(proof.name ?? 'Proof'),\n contentType: String(proof.contentType ?? ''),\n size: Math.max(0, cents(proof.size)),\n inline: visitorUploadIsInline(String(proof.contentType ?? '')),\n })),\n response: pageResponse(quote),\n // The page is only ever a quote's, whatever the caller picked off the order.\n respondable: quoteRespondRefusal({ channel: 'quote', status: order.status, quote }) === null,\n }\n}\n\n/** Order lines as the pay link's page lists them: what each charges, nothing about stock or cost. */\nexport function quotePageLines(lines: readonly OrderLineItem[]): QuotePageLine[] {\n return lines.map((line) => {\n const included = line.included === true\n const quantity = Math.max(0, cents(line.quantity))\n const unitAmountCents = included ? 0 : Math.max(0, cents(line.unitAmountCents))\n return {\n name: String(line.name ?? ''),\n variantLabel: text(line.variantLabel),\n description: text(line.description),\n sku: text(line.sku),\n quantity,\n unitAmountCents,\n amountCents: unitAmountCents * quantity,\n included,\n }\n })\n}\n\n/** The latest answer, as the page may show it back to the link's holder: never the address or browser. */\nfunction pageResponse(quote: OrderQuote | null | undefined): QuotePageResponse | null {\n const latest = latestQuoteResponse(quote)\n if (!latest) return null\n return {\n action: latest.action === 'approve' ? 'approve' : 'changes',\n atMs: Number(latest.atMs) || 0,\n name: latest.action === 'approve' ? text(latest.name) : null,\n comment: latest.action === 'changes' ? text(latest.comment) : null,\n files: latest.files?.length ?? 0,\n }\n}\n\n/*==========================================\n * WHAT A PAYMENT CHARGES\n *=========================================*/\n\n/** One line of a quote's Checkout Session. */\nexport interface QuoteCheckoutLine {\n name: string\n /** The quote's lines this one charges for, as the hosted page lists them. */\n description: string\n amountCents: number\n /** False for tax-exempt products: no rate is applied and Stripe Tax is told it is nontaxable. */\n taxable: boolean\n}\n\n/** What a quote's Checkout Session charges, priced from the stored quote alone. */\nexport interface QuoteCheckoutCharge {\n /** The goods grouped by whether they are taxed, so one rate taxes exactly the quote's taxable amount. */\n lines: QuoteCheckoutLine[]\n itemsCents: number\n discountCents: number\n /** The goods after the discount: what the business is paid for them. */\n goodsCents: number\n taxableCents: number\n shippingCents: number\n /** The quote's tax; 0 when Stripe Tax works it out at payment. */\n taxCents: number\n /**\n * The percentage applied to the taxed line as a Stripe tax rate, or null\n * when no rate is applied (no tax, Stripe Tax, or tax charged as its own line).\n */\n taxPct: number | null\n taxAtPayment: boolean\n /** Goods, shipping and the quote's tax. Stripe Tax adds to it at payment. */\n totalCents: number\n /** What the platform fee prices the goods as. */\n feeProductType: ProductType\n}\n\nconst LINE_DESCRIPTION_MAX = 500\n\nfunction lineSummary(lines: readonly OrderLineItem[]): string {\n const parts = lines.map((line) => {\n const label = line.variantLabel ? `${line.name} (${line.variantLabel})` : line.name\n return `${Math.max(1, cents(line.quantity))} × ${label}`\n })\n const summary = parts.join(', ')\n return summary.length > LINE_DESCRIPTION_MAX ? `${summary.slice(0, LINE_DESCRIPTION_MAX - 1)}…` : summary\n}\n\n/** What the fee ladder prices the quote's charged goods as: physical when any line ships. */\nfunction feeProductTypeOf(lines: readonly OrderLineItem[]): ProductType {\n const charged = lines.filter((line) => !line.included)\n const types = new Set(charged.map((line) => line.productType ?? 'physical'))\n if (types.has('physical') || types.size === 0) return 'physical'\n return types.has('service') ? 'service' : 'digital'\n}\n\n/**\n * The charge for a quote, from its stored lines, discount, shipping and tax\n * basis through {@link computeQuoteTotals} — the same function that priced it\n * when it was saved, so the page, the session and the stored quote agree. The\n * basis is {@link quotePayTax}'s: a quote saved before the store chose its\n * sales tax is charged under the store's choice now.\n *\n * The goods are charged as at most two lines, the taxed and the tax-exempt,\n * each after its share of the discount. A store rate is applied to the taxed\n * line as one Stripe tax rate, so Stripe's tax is the rate on exactly the\n * amount the quote taxed, and the quote's figure is what is collected. A tax\n * service's figure is carried the same way, as the percentage of the taxed\n * line it amounts to. Included lines charge nothing and are not sent.\n */\nexport function quoteCheckoutCharge(\n order: Pick<HostOrder, 'number' | 'lineItems' | 'quote'>,\n orderId: string,\n store?: PayLinkStore | null,\n): QuoteCheckoutCharge {\n return payLinkCheckoutCharge({\n lineItems: order.lineItems ?? [],\n tax: quotePayTax(order.quote, store).basis,\n discount: order.quote?.discount ?? null,\n shippingCents: Math.max(0, cents(order.quote?.shipping?.amountCents)),\n label: formatQuoteNumber(order, orderId),\n })\n}\n\n/**\n * What a pay link's Checkout Session charges for stored lines, a discount,\n * fixed shipping and a tax basis, under a label (`Quote #1042`,\n * `Invoice #1042`): {@link quoteCheckoutCharge}'s pricing, shared with an\n * invoiced order's (AGL-4099), so both are charged the same way.\n */\nexport function payLinkCheckoutCharge(input: {\n lineItems: readonly OrderLineItem[]\n tax: QuoteTaxBasis\n discount: QuoteDiscount | null\n shippingCents: number\n label: string\n}): QuoteCheckoutCharge {\n const { lineItems, tax, discount, shippingCents, label } = input\n const totals = computeQuoteTotals({ lines: lineItems, discount, shippingCents, tax })\n const amounts = quoteLineAmounts(lineItems, discount)\n const groups = [true, false].map((taxable) => {\n const members = lineItems\n .map((line, index) => ({ line, net: amounts.netCents[index] }))\n .filter(({ line, net }) => net > 0 && (line.taxExempt !== true) === taxable)\n return {\n taxable,\n amountCents: members.reduce((sum, { net }) => sum + net, 0),\n description: lineSummary(members.map(({ line }) => line)),\n }\n })\n const charged = groups.filter((group) => group.amountCents > 0)\n const lines: QuoteCheckoutLine[] = charged.map((group) => ({\n name: charged.length > 1 && !group.taxable ? `${label} (tax-exempt items)` : label,\n description: group.description,\n amountCents: group.amountCents,\n taxable: group.taxable,\n }))\n const taxableCents = groups[0].amountCents\n const taxPct =\n totals.taxCents > 0 && taxableCents > 0\n ? tax.kind === 'rate'\n ? Number(tax.pct)\n : engineLineTaxPercentages([{ amountCents: taxableCents, taxCents: totals.taxCents }], 0)[0]\n : null\n // A tax service can tax a quote whose goods are all exempt (on its\n // shipping, say): with no taxed line to carry a rate, its figure is\n // charged as a line of its own, so the customer still pays what the quote says.\n if (totals.taxCents > 0 && taxPct === null) {\n lines.push({\n name: tax.providerLabel ? `Sales tax (${tax.providerLabel})` : 'Sales tax',\n description: label,\n amountCents: totals.taxCents,\n taxable: false,\n })\n }\n return {\n lines,\n itemsCents: totals.itemsCents,\n discountCents: totals.discountCents,\n goodsCents: totals.itemsCents - totals.discountCents,\n taxableCents,\n shippingCents,\n taxCents: totals.taxCents,\n taxPct,\n taxAtPayment: totals.taxAtPayment,\n totalCents: totals.totalCents,\n feeProductType: feeProductTypeOf(lineItems),\n }\n}\n\n/*==========================================\n * WHETHER IT CAN BE PAID NOW\n *=========================================*/\n\nexport type QuotePayRefusal =\n | 'paid'\n | 'closed'\n | 'approval-required'\n | 'tax-undecided'\n | 'nothing-to-pay'\n\n/**\n * Why a quote cannot be paid now, or null when it can. With the store, its\n * tax is {@link quotePayTax}'s, and a store that has not chosen its sales tax\n * refuses every sale (AGL-1999), whatever basis the quote was saved with.\n */\nexport function quotePayRefusal(\n order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote'>,\n orderId: string,\n store?: PayLinkStore | null,\n): QuotePayRefusal | null {\n if (order.status === 'cancelled' || order.status === 'refunded') return 'closed'\n if (order.status !== 'pending') return 'paid'\n if (quotePaymentBlockedByApproval(order.quote)) return 'approval-required'\n if (store && storefrontTaxDecision({ settings: store.tax }).kind === 'undecided') return 'tax-undecided'\n if (quoteTaxIsUndecided(quotePayTax(order.quote, store).basis)) return 'tax-undecided'\n if (quoteCheckoutCharge(order, orderId, store).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay'\n return null\n}\n\n/**\n * A pay link's refusal once the store's payments are judged too: a business\n * that can't take a card payment now outranks every refusal but the ones a\n * payment never gets past (paid, closed, not linked, waiting on the\n * customer's approval). `paymentsReady` absent leaves the refusal as it is.\n */\nexport function payLinkRefusalWithPayments<Reason extends string>(\n reason: Reason | null,\n paymentsReady: boolean | undefined,\n): Reason | 'payments-unavailable' | null {\n if (paymentsReady !== false) return reason\n if (reason === 'paid' || reason === 'closed' || reason === 'not-payable' || reason === 'approval-required') {\n return reason\n }\n return 'payments-unavailable'\n}\n\n/** What the customer is told when the business can't take a card payment now: the page's words and Pay's. */\nexport function payLinkPaymentsUnavailableMessage(storeName: string, kind: 'quote' | 'invoice'): string {\n return `${storeName || 'This business'} can’t take payments online right now. Contact them to pay this ${kind === 'invoice' ? 'invoice' : 'quote'}.`\n}\n\n/** What the customer is told for a {@link QuotePayRefusal}, naming the business. */\nexport function quotePayRefusalMessage(reason: QuotePayRefusal, storeName: string): string {\n const business = storeName.trim() || 'the business'\n switch (reason) {\n case 'paid':\n return 'This quote has been paid.'\n case 'closed':\n return `This quote 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 quote.`\n case 'nothing-to-pay':\n return `This quote has nothing to pay by card. Contact ${business} with any questions.`\n }\n}\n\n/*==========================================\n * WHEN A PAYMENT COMPLETES\n *=========================================*/\n\n/** What a completed Checkout Session says about the quote it paid. */\nexport interface QuotePaymentFacts {\n sessionId: string\n paymentIntentId: string | null\n /** The link version and quote edit the session was minted for, from its metadata. */\n linkVersion?: string | number | null\n quoteUpdatedAtMs?: string | number | null\n paidAtMs: number\n /** The payer, as Stripe collected them. */\n email: string | null\n name: string | null\n /** What Stripe charged in all, and its shipping and tax parts. */\n amountTotalCents: number | null\n shippingCents: number\n taxCents: number\n /** The platform fee the session was minted with. */\n feeCents: number\n taxMode: StorefrontTaxMode\n /** The address Stripe collected, when the session asked for one. */\n shippingAddress: OrderAddress | null\n /**\n * The tax the session charged under when it was not the quote's stored\n * basis: {@link quotePayTax}'s answer for a quote saved before the store\n * chose its sales tax, carried on the session (`quoteTax`,\n * {@link quoteTaxBasisKey}) by the press that opened it (AGL-4162).\n */\n taxBasis?: QuoteTaxBasis | null\n}\n\n/**\n * What a completed payment does to a quote:\n *\n * - `pay`: the quote is unpaid and the payment is for it as it stands, so it\n * becomes the order.\n * - `superseded`: the quote is unpaid, but the payment was made through a pay\n * link the business replaced, or for a version of the quote it has since\n * changed. Taking it would record a sale at a price or for a link the\n * business withdrew.\n * - `already-paid`: another payment paid the quote first.\n * - `redelivery`: Stripe sending this same payment again; nothing to do.\n *\n * The two refusals keep the money visible: they are recorded on the quote and\n * the business is told, so a payment is never fulfilled twice and never lost.\n */\nexport type QuotePaymentDisposition = 'pay' | 'superseded' | 'already-paid' | 'redelivery'\n\nexport function quotePaymentDisposition(\n order: Pick<HostOrder, 'status' | 'quote' | 'checkoutSessionId' | 'paymentIntentId'> &\n Partial<Pick<HostOrder, 'payLink'>>,\n payment: Pick<QuotePaymentFacts, 'sessionId' | 'paymentIntentId' | 'linkVersion' | 'quoteUpdatedAtMs'>,\n): QuotePaymentDisposition {\n // Any order's pay link answers the same way (AGL-4099): an invoiced order\n // reads its version and its recorded payments off `payLink`, and its\n // session carries no quote edit to compare.\n const recorded = orderPayLinkUnmatched(order).some((entry) => entry?.sessionId === payment.sessionId)\n if (recorded) return 'redelivery'\n if (order.status !== 'pending') {\n const same =\n (order.checkoutSessionId && order.checkoutSessionId === payment.sessionId) ||\n (payment.paymentIntentId && order.paymentIntentId === payment.paymentIntentId)\n return same ? 'redelivery' : 'already-paid'\n }\n const sentVersion = payment.linkVersion\n if (sentVersion != null && sentVersion !== '' && Number(sentVersion) !== orderPayLinkVersion(order)) {\n return 'superseded'\n }\n const sentEdit = payment.quoteUpdatedAtMs\n if (sentEdit != null && sentEdit !== '' && Number(sentEdit) !== Number(order.quote?.updatedAtMs)) {\n return 'superseded'\n }\n return 'pay'\n}\n\n/** A payment the quote could not take, as {@link QuoteUnmatchedPayment} records it. */\nexport function quoteUnmatchedPayment(\n facts: Pick<QuotePaymentFacts, 'sessionId' | 'paymentIntentId' | 'amountTotalCents' | 'paidAtMs'>,\n reason: QuoteUnmatchedPayment['reason'],\n): QuoteUnmatchedPayment {\n return {\n sessionId: facts.sessionId,\n paymentIntentId: facts.paymentIntentId,\n amountCents: Math.max(0, cents(facts.amountTotalCents)),\n atMs: facts.paidAtMs,\n reason,\n }\n}\n\n/** The timeline line for a payment the quote (or an order's invoice, AGL-4099) could not take. */\nexport function quoteUnmatchedPaymentDetail(\n entry: QuoteUnmatchedPayment,\n noun: 'quote' | 'invoice' = 'quote',\n): string {\n const amount = `$${(entry.amountCents / 100).toFixed(2)}`\n return entry.reason === 'superseded'\n ? `A payment of ${amount} came through a pay link that was replaced, or for an earlier ` +\n `version of this ${noun}. The money is in Stripe and this ${noun} records no sale for it; ` +\n 'refund it in Stripe, or reconcile it by hand.'\n : `A second payment of ${amount} came in after this ${noun} was paid. The money is in Stripe ` +\n 'and no second sale was recorded; refund it in Stripe, or reconcile it by hand.'\n}\n\n/**\n * The order a paid quote becomes, the whole document as it will stand. A\n * quote carries none of the fields order lists read (`commerce-quotes.ts`);\n * paying it writes them:\n *\n * - `createdAtMs` is the time it was paid, the moment it became an order, so\n * it lists and counts on the day the money came in.\n * - The customer moves to the top-level fields every order reader asks\n * (`customerEmail`, `customerName`, `customerPhone`, `customerRecord`), the\n * payer's own email first, as a paid draft takes it.\n * - The address Stripe collected ships it, else the quote's ship-to; the\n * quote's bill-to bills it.\n * - The totals are what Stripe charged: its shipping and tax where it charged\n * any, the platform fee the session was minted with, and its total.\n * - The quote keeps the tax basis it was paid under: the session's\n * ({@link QuotePaymentFacts.taxBasis}) where the press took the store's\n * choice for it, so the order says how its tax was worked out.\n * - The list fields (`withOrderListFields`) are stamped from all of that.\n */\nexport function paidQuoteOrder(\n order: HostOrder,\n orderId: string,\n facts: QuotePaymentFacts,\n): HostOrder & OrderListFields & { updatedAtMs: number; requiresShipping: boolean } {\n const quote = order.quote as OrderQuote\n const customer = quote?.customer ?? {}\n const stored = order.totals ?? { itemsCents: 0, discountCents: 0, shippingCents: 0, taxCents: 0, feeCents: 0, totalCents: 0 }\n const shippingCents = facts.shippingCents > 0 ? facts.shippingCents : cents(stored.shippingCents)\n const taxCents = facts.taxCents > 0 ? facts.taxCents : cents(stored.taxCents)\n const totalCents =\n facts.amountTotalCents != null && Number.isFinite(facts.amountTotalCents)\n ? facts.amountTotalCents\n : cents(stored.itemsCents) - cents(stored.discountCents) + shippingCents + taxCents\n const shippingAddress = facts.shippingAddress ?? quote?.shipTo ?? null\n const label = formatOrderNumber(order, orderId)\n const paid: HostOrder & { updatedAtMs: number } = {\n ...order,\n status: 'paid',\n createdAtMs: facts.paidAtMs,\n customerEmail: text(facts.email) ?? text(customer.email),\n customerName: text(customer.name) ?? text(facts.name) ?? text(customer.company),\n ...(text(customer.phone) ? { customerPhone: text(customer.phone) } : {}),\n ...(customer.record?.kind && customer.record?.id ? { customerRecord: { ...customer.record } } : {}),\n ...(shippingAddress ? { shippingAddress: { ...shippingAddress } } : {}),\n ...(quote?.billTo ? { billingAddress: { ...quote.billTo } } : {}),\n totals: {\n itemsCents: cents(stored.itemsCents),\n discountCents: cents(stored.discountCents),\n shippingCents,\n taxCents,\n feeCents: Math.max(0, cents(facts.feeCents)),\n totalCents,\n },\n taxMode: facts.taxMode,\n paymentIntentId: facts.paymentIntentId ?? undefined,\n checkoutSessionId: facts.sessionId,\n timeline: appendOrderEvent(order, 'paid', `${label} paid through its pay link`, facts.paidAtMs),\n quote: { ...quote, ...(facts.taxBasis ? { tax: facts.taxBasis } : {}), paidAtMs: facts.paidAtMs },\n // New to a shipping tool's feed from the moment it is paid.\n updatedAtMs: facts.paidAtMs,\n }\n if (!paid.paymentIntentId) delete paid.paymentIntentId\n return withOrderListFields(orderId, paid)\n}\n"],"names":["visitorUploadIsInline","appendOrderEvent","formatOrderNumber","computeQuoteTotals","describeQuoteTax","formatQuoteNumber","quoteLineAmounts","quotePaymentBlockedByApproval","quoteTaxBasisFromSettings","currentQuoteProofs","latestQuoteResponse","quoteRespondRefusal","storefrontTaxDecision","engineLineTaxPercentages","storeTaxAllowsEngine","withOrderListFields","QUOTE_MIN_CHARGE_CENTS","quoteLinkVersion","quote","version","Math","floor","Number","linkVersion","isFinite","orderPayLinkVersion","order","payLink","orderPayLinkUnmatched","list","unmatchedPayments","Array","isArray","filter","entry","payLinkStoreOf","settings","tax","quoteTaxIsUndecided","basis","kind","reason","quotePayTax","store","stored","source","shipTo","TAX_KINDS","Set","NO_TAX_REASONS","BASIS_LABEL_MAX","tidyTaxBasis","raw","String","has","label","value","trim","slice","pct","named","taxCents","round","providerLabel","quoteTaxBasisKey","JSON","stringify","quoteTaxBasisFromKey","key","length","parse","text","trimmed","cents","number","quotePageAddress","address","view","name","line1","line2","city","state","postalCode","country","Object","values","some","Boolean","quotePageStatus","status","discountLabel","discount","paidAt","stamped","paidAtMs","event","timeline","find","atMs","buildQuotePageView","input","lines","lineItems","unpaid","payTax","charge","quoteCheckoutCharge","orderId","totals","itemsCents","discountCents","shippingCents","totalCents","approvalRequired","taxAtPayment","refused","payLinkRefusalWithPayments","quotePayRefusal","paymentsReady","storeName","dateMs","updatedAtMs","createdAtMs","currency","customerName","customer","company","billTo","quotePageLines","taxLabel","shippingAtPayment","notes","terms","statusLabel","receiptUrl","payable","notPayableMessage","payLinkPaymentsUnavailableMessage","taxKey","revision","max","proofs","map","proof","id","contentType","size","inline","response","pageResponse","respondable","channel","line","included","quantity","unitAmountCents","variantLabel","description","sku","amountCents","latest","action","comment","files","LINE_DESCRIPTION_MAX","lineSummary","parts","summary","join","feeProductTypeOf","charged","types","productType","payLinkCheckoutCharge","shipping","amounts","groups","taxable","members","index","net","netCents","taxExempt","reduce","sum","group","taxableCents","taxPct","push","goodsCents","feeProductType","quotePayRefusalMessage","business","quotePaymentDisposition","payment","recorded","sessionId","same","checkoutSessionId","paymentIntentId","sentVersion","sentEdit","quoteUpdatedAtMs","quoteUnmatchedPayment","facts","amountTotalCents","quoteUnmatchedPaymentDetail","noun","amount","toFixed","paidQuoteOrder","feeCents","shippingAddress","paid","customerEmail","email","phone","customerPhone","record","customerRecord","billingAddress","taxMode","undefined","taxBasis"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,wCAAuC;AAE7E,SACEC,gBAAgB,EAChBC,iBAAiB,QAKZ,uBAAmB;AAC1B,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,gBAAgB,EAChBC,6BAA6B,EAC7BC,yBAAyB,QAOpB,uBAAmB;AAC1B,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,mBAAmB,QAAQ,6BAAyB;AAEtG,SAASC,qBAAqB,QAAgC,6BAAyB;AACvF,SAASC,wBAAwB,EAAEC,oBAAoB,QAAQ,2BAAuB;AACtF,SAASC,mBAAmB,QAA8B,yBAAqB;AAE/E;;;;;;;;;;;;;;;;;;;;;2CAqB2C,GAE3C,oFAAoF,GACpF,OAAO,MAAMC,yBAAyB,GAAE;AAExC,mEAAmE,GACnE,OAAO,SAASC,iBAAiBC,KAAyD;IACxF,MAAMC,UAAUC,KAAKC,KAAK,CAACC,OAAOJ,yBAAAA,MAAOK,WAAW;IACpD,OAAOD,OAAOE,QAAQ,CAACL,YAAYA,WAAW,IAAIA,UAAU;AAC9D;AAEA;;;;;CAKC,GACD,OAAO,SAASM,oBAAoBC,KAAuE;QAEvEA;IADlC,IAAIA,yBAAAA,MAAOR,KAAK,EAAE,OAAOD,iBAAiBS,MAAMR,KAAK;IACrD,MAAMC,UAAUC,KAAKC,KAAK,CAACC,OAAOI,0BAAAA,iBAAAA,MAAOC,OAAO,qBAAdD,eAAgBP,OAAO;IACzD,OAAOG,OAAOE,QAAQ,CAACL,YAAYA,WAAW,IAAIA,UAAU;AAC9D;AAEA,0GAA0G,GAC1G,OAAO,SAASS,sBACdF,KAAuE;QAEXA;IAA5D,MAAMG,OAAOH,CAAAA,yBAAAA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AAK,IAAI;QAAEC,eAAenJ,KAAKuD,SAAS2F,KAAK;IAAE,IAAI,CAAC,GAClE3F,EAAAA,mBAAAA,SAAS6F,MAAM,qBAAf7F,iBAAiBtF,IAAI,OAAIsF,oBAAAA,SAAS6F,MAAM,qBAAf7F,kBAAiBmB,EAAE,IAAG;QAAE2E,gBAAgB,aAAK9F,SAAS6F,MAAM;IAAG,IAAI,CAAC,GAC7FN,kBAAkB;QAAEA,iBAAiB,aAAKA;IAAkB,IAAI,CAAC,GACjEnM,CAAAA,yBAAAA,MAAO8G,MAAM,IAAG;QAAE6F,gBAAgB,aAAK3M,MAAM8G,MAAM;IAAG,IAAI,CAAC;QAC/DnB,QAAQ;YACNC,YAAYrC,MAAM7B,OAAOkE,UAAU;YACnCC,eAAetC,MAAM7B,OAAOmE,aAAa;YACzCC;YACAnD;YACAuJ,UAAUhM,KAAKyH,GAAG,CAAC,GAAGpE,MAAMoI,MAAMO,QAAQ;YAC1CnG;QACF;QACA6G,SAASjB,MAAMiB,OAAO;QACtBtB,eAAe,GAAEK,yBAAAA,MAAML,eAAe,YAArBK,yBAAyBkB;QAC1CxB,mBAAmBM,MAAMR,SAAS;QAClCpG,UAAUhG,iBAAiByB,OAAO,QAAQ,GAAG6B,MAAM,0BAA0B,CAAC,EAAEsJ,MAAM9G,QAAQ;QAC9F7E,OAAO,aAAKA,OAAW2L,MAAMmB,QAAQ,GAAG;YAAE3L,KAAKwK,MAAMmB,QAAQ;QAAC,IAAI,CAAC;YAAIjI,UAAU8G,MAAM9G,QAAQ;;QAC/F,4DAA4D;QAC5D2B,aAAamF,MAAM9G,QAAQ;;IAE7B,IAAI,CAACuH,KAAKd,eAAe,EAAE,OAAOc,KAAKd,eAAe;IACtD,OAAOzL,oBAAoB6F,SAAS0G;AACtC"}
@@ -3660,7 +3660,7 @@ async function findOrderForDispute(paymentIntentId) {
3660
3660
  // and the business is told, as a paid-after-cancel payment is.
3661
3661
  if (raw && CommerceModel.isQuote(raw) && raw.quote) {
3662
3662
  var _ref7, _ref8, _ref9, _ref10, _ref11, _ref12, _ref13, _ref14;
3663
- var _object_metadata2, _object_metadata3, _object_customer_details2, _object_customer_details3, _object_metadata4, _object_metadata5;
3663
+ var _object_metadata2, _object_metadata3, _object_customer_details2, _object_customer_details3, _object_metadata4, _object_metadata5, _object_metadata6;
3664
3664
  const facts = {
3665
3665
  sessionId: String((_ref7 = object == null ? void 0 : object.id) != null ? _ref7 : ''),
3666
3666
  paymentIntentId: String((_ref8 = object == null ? void 0 : object.payment_intent) != null ? _ref8 : '') || null,
@@ -3674,6 +3674,9 @@ async function findOrderForDispute(paymentIntentId) {
3674
3674
  taxCents: stripeTaxCents,
3675
3675
  feeCents: Number((_ref13 = object == null ? void 0 : (_object_metadata4 = object.metadata) == null ? void 0 : _object_metadata4.feeCents) != null ? _ref13 : 0) || 0,
3676
3676
  taxMode: storefrontTaxModeOf(object, Number((_ref14 = object == null ? void 0 : (_object_metadata5 = object.metadata) == null ? void 0 : _object_metadata5.taxCents) != null ? _ref14 : 0)),
3677
+ // The basis Pay charged a quote saved before the store chose its
3678
+ // sales tax under (AGL-4162); absent, the quote's own stands.
3679
+ taxBasis: CommerceModel.quoteTaxBasisFromKey(object == null ? void 0 : (_object_metadata6 = object.metadata) == null ? void 0 : _object_metadata6.quoteTax),
3677
3680
  shippingAddress: (shipTo == null ? void 0 : shipTo.address) ? Object.fromEntries(Object.entries({
3678
3681
  name: shipTo.name,
3679
3682
  line1: shipTo.address.line1,