@aglyn/plugins-commerce 1.15.0 → 1.15.2

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 (87) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart.js +8 -3
  3. package/src/lib/components/cart.js.map +1 -1
  4. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  6. package/src/lib/components/console/subscription-detail-dialog.component.js +2 -2
  7. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
  8. package/src/lib/components/console/subscriptions-card.component.js +4 -2
  9. package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
  10. package/src/lib/components/product-detail.js +7 -3
  11. package/src/lib/components/product-detail.js.map +1 -1
  12. package/src/lib/components/quote-page-body.js +7 -3
  13. package/src/lib/components/quote-page-body.js.map +1 -1
  14. package/src/lib/components/related-products.js +6 -3
  15. package/src/lib/components/related-products.js.map +1 -1
  16. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  17. package/src/lib/components/storefront-payment-element.js +11 -7
  18. package/src/lib/components/storefront-payment-element.js.map +1 -1
  19. package/src/lib/model/commerce-payment-methods.d.ts +26 -39
  20. package/src/lib/model/commerce-payment-methods.js +11 -118
  21. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  22. package/src/lib/server/billing-webhook.d.ts +23 -0
  23. package/src/lib/server/billing-webhook.js +162 -30
  24. package/src/lib/server/billing-webhook.js.map +1 -1
  25. package/src/lib/server/cancel-order.js +4 -3
  26. package/src/lib/server/cancel-order.js.map +1 -1
  27. package/src/lib/server/cart-checkout.js +61 -14
  28. package/src/lib/server/cart-checkout.js.map +1 -1
  29. package/src/lib/server/catalog.js +58 -22
  30. package/src/lib/server/catalog.js.map +1 -1
  31. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  32. package/src/lib/server/checkout-session-expiry.js +19 -5
  33. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  34. package/src/lib/server/checkout-status.js +4 -3
  35. package/src/lib/server/checkout-status.js.map +1 -1
  36. package/src/lib/server/checkout.js +42 -12
  37. package/src/lib/server/checkout.js.map +1 -1
  38. package/src/lib/server/connect.js +42 -11
  39. package/src/lib/server/connect.js.map +1 -1
  40. package/src/lib/server/draft-order.js +37 -12
  41. package/src/lib/server/draft-order.js.map +1 -1
  42. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  43. package/src/lib/server/manual-tax-rate.js +10 -6
  44. package/src/lib/server/manual-tax-rate.js.map +1 -1
  45. package/src/lib/server/native-checkout.d.ts +10 -3
  46. package/src/lib/server/native-checkout.js +8 -3
  47. package/src/lib/server/native-checkout.js.map +1 -1
  48. package/src/lib/server/payment-method-domains.d.ts +50 -9
  49. package/src/lib/server/payment-method-domains.js +150 -51
  50. package/src/lib/server/payment-method-domains.js.map +1 -1
  51. package/src/lib/server/payment-methods.js +3 -2
  52. package/src/lib/server/payment-methods.js.map +1 -1
  53. package/src/lib/server/pos-order.js +5 -1
  54. package/src/lib/server/pos-order.js.map +1 -1
  55. package/src/lib/server/pos-stripe.d.ts +7 -7
  56. package/src/lib/server/pos-stripe.js +15 -13
  57. package/src/lib/server/pos-stripe.js.map +1 -1
  58. package/src/lib/server/pos-terminal.js +11 -3
  59. package/src/lib/server/pos-terminal.js.map +1 -1
  60. package/src/lib/server/quote-pay.d.ts +23 -1
  61. package/src/lib/server/quote-pay.js +112 -32
  62. package/src/lib/server/quote-pay.js.map +1 -1
  63. package/src/lib/server/quote.d.ts +2 -1
  64. package/src/lib/server/quote.js +12 -11
  65. package/src/lib/server/quote.js.map +1 -1
  66. package/src/lib/server/refund.js +13 -6
  67. package/src/lib/server/refund.js.map +1 -1
  68. package/src/lib/server/related.js +10 -3
  69. package/src/lib/server/related.js.map +1 -1
  70. package/src/lib/server/reserve.js +19 -6
  71. package/src/lib/server/reserve.js.map +1 -1
  72. package/src/lib/server/revenue-source.d.ts +6 -0
  73. package/src/lib/server/revenue-source.js +25 -9
  74. package/src/lib/server/revenue-source.js.map +1 -1
  75. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  76. package/src/lib/server/seller-stripe-account.js +99 -0
  77. package/src/lib/server/seller-stripe-account.js.map +1 -0
  78. package/src/lib/server/storefront-tax-record.js +6 -1
  79. package/src/lib/server/storefront-tax-record.js.map +1 -1
  80. package/src/lib/server/storefront-tax.d.ts +33 -2
  81. package/src/lib/server/storefront-tax.js +39 -3
  82. package/src/lib/server/storefront-tax.js.map +1 -1
  83. package/src/lib/server/stripe-refund.d.ts +15 -0
  84. package/src/lib/server/stripe-refund.js +54 -26
  85. package/src/lib/server/stripe-refund.js.map +1 -1
  86. package/src/lib/server/subscription-portal.js +8 -3
  87. package/src/lib/server/subscription-portal.js.map +1 -1
@@ -55,6 +55,7 @@ import { handlePosStripeEvent } from "./pos-terminal.js";
55
55
  import { notifyPosSaleCompleted } from "./pos-sale.js";
56
56
  import { recordSellerStoreSaleHardware, sellerStoreOrderHardwareFields } from "./pos-hardware-sale-fields.js";
57
57
  import { posOrderRefundStripeId } from "./pos-order-refund-ids.js";
58
+ import { isDirectChargeObject } from "./seller-stripe-account.js";
58
59
  /**
59
60
  * A Stripe subscription's current period end, in seconds (AGL-4191). Older API
60
61
  * versions carry it on the subscription; newer ones moved it to each item.
@@ -668,7 +669,10 @@ async function findOrderForDispute(paymentIntentId) {
668
669
  * subscription billing forever with the books saying it had been stopped. The
669
670
  * `Idempotency-Key` covers the window where the claim is written and the
670
671
  * response never arrives.
671
- */ async function stopLapsedStorefrontSubscription(hostId, subscriptionId, subscriptionRef, /** Who subscribed to what, and the workspace, for the merchant's notice. */ notice) {
672
+ */ async function stopLapsedStorefrontSubscription(hostId, subscriptionId, subscriptionRef, /** Who subscribed to what, and the workspace, for the merchant's notice. */ notice, /**
673
+ * The seller's account for a DIRECT-charge subscription, which lives there
674
+ * rather than on the platform; absent for a destination one.
675
+ */ stripeAccount) {
672
676
  var _ref, _ref1;
673
677
  const stripeKey = process.env.STRIPE_SECRET_KEY;
674
678
  if (!stripeKey) {
@@ -701,11 +705,13 @@ async function findOrderForDispute(paymentIntentId) {
701
705
  };
702
706
  const response = await fetch(`https://api.stripe.com/v1/subscriptions/${encodeURIComponent(subscriptionId)}`, {
703
707
  method: 'POST',
704
- headers: {
708
+ headers: _extends({
705
709
  Authorization: `Bearer ${stripeKey}`,
706
710
  'Content-Type': 'application/x-www-form-urlencoded',
707
711
  'Idempotency-Key': `lapsed-stop-${subscriptionId}`
708
- },
712
+ }, stripeAccount ? {
713
+ 'Stripe-Account': stripeAccount
714
+ } : {}),
709
715
  body: new URLSearchParams({
710
716
  cancel_at_period_end: 'true'
711
717
  }).toString()
@@ -756,11 +762,18 @@ async function findOrderForDispute(paymentIntentId) {
756
762
  link: `/${hostId}/products`
757
763
  });
758
764
  }
759
- /** One authorized GET against the Stripe API, body parsed either way. */ async function stripeGet(url, stripeKey) {
765
+ /**
766
+ * One authorized GET against the Stripe API, body parsed either way. A
767
+ * `stripeAccount` reads the object ON that connected account: a direct
768
+ * charge's payment intent, charge and invoice live there, and the platform
769
+ * key alone answers 404 for them.
770
+ */ async function stripeGet(url, stripeKey, stripeAccount) {
760
771
  const response = await fetch(url, {
761
- headers: {
772
+ headers: _extends({
762
773
  Authorization: `Bearer ${stripeKey}`
763
- }
774
+ }, stripeAccount ? {
775
+ 'Stripe-Account': stripeAccount
776
+ } : {})
764
777
  });
765
778
  const body = await response.json().catch(()=>null);
766
779
  return {
@@ -769,6 +782,61 @@ async function findOrderForDispute(paymentIntentId) {
769
782
  body
770
783
  };
771
784
  }
785
+ /**
786
+ * The connected account a Connect-delivered event belongs to, or null for an
787
+ * event on the platform's own account. Direct-charge sales are created ON the
788
+ * seller's account, so their events arrive through the Connect destination
789
+ * with the seller named at the top level.
790
+ */ export function connectEventAccount(event) {
791
+ const account = event == null ? void 0 : event.account;
792
+ return typeof account === 'string' && account ? account : null;
793
+ }
794
+ /**
795
+ * Event types whose object is a charge-level object (a charge, a dispute, an
796
+ * early fraud warning, a review) with no metadata of ours: whether a
797
+ * Connect-delivered one is a direct sale is decided by the order it finds.
798
+ */ const CHARGE_LEVEL_EVENT_TYPES = new Set([
799
+ 'charge.refunded',
800
+ 'charge.dispute.created',
801
+ 'charge.dispute.closed',
802
+ 'radar.early_fraud_warning.created',
803
+ 'review.opened',
804
+ 'review.closed'
805
+ ]);
806
+ /**
807
+ * Whether this handler should act on the event at all, as far as WHOSE
808
+ * account it came from can say. A platform event always passes. A
809
+ * Connect-delivered one passes only when its object says it was sold by
810
+ * direct charge, or when it is a charge-level event the order lookup will
811
+ * judge ({@link connectEventOrderIsDirect}). Exported for the spec.
812
+ */ export function connectEventIsForDirectSale(type, object, event) {
813
+ if (!connectEventAccount(event)) return true;
814
+ if (CHARGE_LEVEL_EVENT_TYPES.has(String(type))) return true;
815
+ return isDirectChargeObject(object);
816
+ }
817
+ /**
818
+ * A charge-level event's order, judged by its delivery: a platform event
819
+ * always fits, and a Connect-delivered one fits only an order recorded as a
820
+ * direct sale. The seller's copy of a destination sale finds nothing to act
821
+ * on, rather than a second refund or chargeback on the platform's order.
822
+ */ function connectEventOrderIsDirect(event, snapshot) {
823
+ if (!connectEventAccount(event)) return true;
824
+ return snapshot.get('chargeModel') === 'direct';
825
+ }
826
+ /**
827
+ * The fields a direct sale's records carry so every later reader can tell it
828
+ * apart without asking Stripe: `refund.ts` refunds on the seller's account,
829
+ * the revenue report counts the application fee as Aglyn's whole take, and
830
+ * the dispute branch leaves the transfer reversal out. Empty for a
831
+ * destination sale, so those documents are written exactly as before.
832
+ */ export function directChargeRecordFields(direct, account) {
833
+ if (!direct) return {};
834
+ return _extends({
835
+ chargeModel: 'direct'
836
+ }, account ? {
837
+ stripeAccountId: account
838
+ } : {});
839
+ }
772
840
  /**
773
841
  * Re-price a storefront subscription's platform fee to the merchant's CURRENT
774
842
  * plan (AGL-2289) — and since AGL-2655 that figure is the plan's take plus
@@ -809,7 +877,7 @@ async function findOrderForDispute(paymentIntentId) {
809
877
  * A rate of 0 UNSETS the parameter rather than sending `0`: Stripe rejects a
810
878
  * zero `application_fee_percent`, and an empty value is how its API clears an
811
879
  * optional field. That is also what `checkout.ts` does by omitting the key.
812
- */ async function repriceStorefrontSubscriptionFee(subscriptionRef, subscriptionId, desiredFeePct) {
880
+ */ async function repriceStorefrontSubscriptionFee(subscriptionRef, subscriptionId, desiredFeePct, /** The seller's account, for a DIRECT-charge subscription that lives there. */ stripeAccount) {
813
881
  const stripeKey = process.env.STRIPE_SECRET_KEY;
814
882
  if (!stripeKey || !subscriptionId) return;
815
883
  const snapshot = await subscriptionRef.get().catch(()=>null);
@@ -820,13 +888,15 @@ async function findOrderForDispute(paymentIntentId) {
820
888
  if (Number.isFinite(stored) && Number(stored) === desiredFeePct) return;
821
889
  const response = await fetch(`https://api.stripe.com/v1/subscriptions/${encodeURIComponent(subscriptionId)}`, {
822
890
  method: 'POST',
823
- headers: {
891
+ headers: _extends({
824
892
  Authorization: `Bearer ${stripeKey}`,
825
893
  'Content-Type': 'application/x-www-form-urlencoded',
826
894
  // Keyed on the RATE as well as the subscription, so a later change
827
895
  // back is a new request rather than a replay of the old one.
828
896
  'Idempotency-Key': `fee-reprice-${subscriptionId}-${desiredFeePct}`
829
- },
897
+ }, stripeAccount ? {
898
+ 'Stripe-Account': stripeAccount
899
+ } : {}),
830
900
  body: new URLSearchParams({
831
901
  application_fee_percent: desiredFeePct > 0 ? String(desiredFeePct) : ''
832
902
  }).toString()
@@ -881,7 +951,7 @@ async function findOrderForDispute(paymentIntentId) {
881
951
  * repo cannot see — the same three-spelling problem `subscriptionMeta` and the
882
952
  * tax fields already solve by reading every form. `payment_intent` is the third
883
953
  * (the renewal order write at :1667 reads it), and it needs one more hop.
884
- */ async function resolveInvoiceChargeId(invoice, stripeKey) {
954
+ */ async function resolveInvoiceChargeId(invoice, stripeKey, stripeAccount) {
885
955
  var _ref;
886
956
  var _invoice_payments;
887
957
  const direct = invoice == null ? void 0 : invoice.charge;
@@ -893,7 +963,7 @@ async function findOrderForDispute(paymentIntentId) {
893
963
  const nested = payment == null ? void 0 : (_payment_payment1 = payment.payment) == null ? void 0 : _payment_payment1.payment_intent;
894
964
  if (typeof nested === 'string' && nested) {
895
965
  var _intent_body;
896
- const intent = await stripeGet(`https://api.stripe.com/v1/payment_intents/${encodeURIComponent(nested)}`, stripeKey);
966
+ const intent = await stripeGet(`https://api.stripe.com/v1/payment_intents/${encodeURIComponent(nested)}`, stripeKey, stripeAccount);
897
967
  const latest = intent.ok ? (_intent_body = intent.body) == null ? void 0 : _intent_body.latest_charge : '';
898
968
  if (typeof latest === 'string' && latest) return latest;
899
969
  }
@@ -901,7 +971,7 @@ async function findOrderForDispute(paymentIntentId) {
901
971
  const paymentIntentId = invoice == null ? void 0 : invoice.payment_intent;
902
972
  if (typeof paymentIntentId === 'string' && paymentIntentId) {
903
973
  var _intent_body1;
904
- const intent = await stripeGet(`https://api.stripe.com/v1/payment_intents/${encodeURIComponent(paymentIntentId)}`, stripeKey);
974
+ const intent = await stripeGet(`https://api.stripe.com/v1/payment_intents/${encodeURIComponent(paymentIntentId)}`, stripeKey, stripeAccount);
905
975
  const latest = intent.ok ? (_intent_body1 = intent.body) == null ? void 0 : _intent_body1.latest_charge : '';
906
976
  if (typeof latest === 'string' && latest) return latest;
907
977
  }
@@ -979,7 +1049,7 @@ async function findOrderForDispute(paymentIntentId) {
979
1049
  * `metadata[feeCents]` (items only) while Stripe had charged percent-of-total,
980
1050
  * so the same subscription's first and second cycles reported fees computed on
981
1051
  * different bases.
982
- */ async function chargeSubscriptionFeeOnItemsOnly(invoice, hostId, invoiceId) {
1052
+ */ async function chargeSubscriptionFeeOnItemsOnly(invoice, hostId, invoiceId, stripeAccount) {
983
1053
  var _ref, _fee_amount, _fee_amount_refunded;
984
1054
  var _fees_body_data, _fees_body;
985
1055
  const chargedCents = Math.max(0, Math.round(Number((_ref = invoice == null ? void 0 : invoice.application_fee_amount) != null ? _ref : 0)));
@@ -998,7 +1068,7 @@ async function findOrderForDispute(paymentIntentId) {
998
1068
  await reportFeeNotCorrected(hostId, invoiceId, 'STRIPE_SECRET_KEY is not set on this deployment');
999
1069
  return chargedCents;
1000
1070
  }
1001
- const chargeId = await resolveInvoiceChargeId(invoice, stripeKey);
1071
+ const chargeId = await resolveInvoiceChargeId(invoice, stripeKey, stripeAccount);
1002
1072
  if (!chargeId) {
1003
1073
  console.error('Subscription fee not corrected to the items-only base: the invoice names no charge (AGL-2317)', {
1004
1074
  hostId,
@@ -1777,6 +1847,14 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
1777
1847
  })) {
1778
1848
  return;
1779
1849
  }
1850
+ // A CONNECT-DELIVERED EVENT IS OURS ONLY FOR A DIRECT SALE. The seller's
1851
+ // account also sees its side of every DESTINATION sale (the `py_` payment
1852
+ // the transfer created, the refund a transfer reversal makes), and those
1853
+ // carry none of our metadata. The platform-side event already ran this
1854
+ // handler for that sale, so acting on the seller's copy would record it
1855
+ // twice. Charge-level events (refunds, disputes, fraud signals) are judged
1856
+ // below by the order they find, which says how it was sold.
1857
+ if (!connectEventIsForDirectSale(type, object, event)) return;
1780
1858
  // THE REGISTER'S CARD PAYMENTS (AGL-3607): Terminal reader actions, register
1781
1859
  // PaymentIntents and register QR pages. Each names one payment on an open
1782
1860
  // sale and is settled by re-reading Stripe in `pos-terminal.ts`; every other
@@ -1897,7 +1975,18 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
1897
1975
  // AWAITED and never allowed to throw: a lost row is an understated tax
1898
1976
  // return, and `recordStorefrontTax` swallows its own failures precisely so
1899
1977
  // this cannot turn a recording problem into a redelivered billing webhook.
1900
- await recordStorefrontTax(String(type), object);
1978
+ //
1979
+ // NOT for a DIRECT charge. That session lives on the seller's own account,
1980
+ // Stripe Tax computed it against the SELLER's registrations, and the money
1981
+ // settled into the seller's balance: the seller owns and remits the tax,
1982
+ // so it is no row on Aglyn's return, and Aglyn did not facilitate the sale
1983
+ // into the buyer's state either.
1984
+ const directSale = isDirectChargeObject(object);
1985
+ // The seller's account for a direct sale, for every Stripe call below that
1986
+ // touches its objects, and the fields its records carry (empty otherwise).
1987
+ const saleAccount = directSale ? connectEventAccount(event) : null;
1988
+ const directFields = directChargeRecordFields(directSale, saleAccount);
1989
+ if (!directSale) await recordStorefrontTax(String(type), object);
1901
1990
  if (type === 'customer.subscription.created' || type === 'customer.subscription.updated' || type === 'customer.subscription.deleted') {
1902
1991
  var _object_metadata13;
1903
1992
  // Storefront subscription status sync (AGL-303).
@@ -2014,7 +2103,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
2014
2103
  checkoutSessionId: String(object.id)
2015
2104
  }, typeof (event == null ? void 0 : event.livemode) === 'boolean' ? {
2016
2105
  livemode: event.livemode
2017
- } : {}, {
2106
+ } : {}, directFields, {
2018
2107
  createdAtMs: Date.now(),
2019
2108
  // WHICH TAX this subscription will bill, for as long as it
2020
2109
  // lives (AGL-2323).
@@ -2255,7 +2344,14 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
2255
2344
  // is left is the figure the ledger stores. A transient Stripe failure
2256
2345
  // throws here rather than filing a fee we did not end up charging —
2257
2346
  // the redelivery re-runs it behind the invoice-id guard below.
2258
- const feeCentsInForce = await chargeSubscriptionFeeOnItemsOnly(object, invoiceHostId, invoiceId);
2347
+ //
2348
+ // A DIRECT-charge subscription gets the same repair: its percent is
2349
+ // the take alone, but Stripe still applies it to the whole invoice,
2350
+ // and the take is a share of the goods, never of the seller's own
2351
+ // sales tax or shipping (Terms 4.3). The charge is read on the
2352
+ // seller's account; the application fee and its refund live on the
2353
+ // platform either way.
2354
+ const feeCentsInForce = await chargeSubscriptionFeeOnItemsOnly(object, invoiceHostId, invoiceId, directSale ? saleAccount : null);
2259
2355
  const { lineItems: invoiceLineItems, totals: computedInvoiceTotals } = CommerceModel.computeSubscriptionInvoiceOrder(object, snapshot);
2260
2356
  // `computeSubscriptionInvoiceOrder` reads `application_fee_amount`
2261
2357
  // verbatim, which is what Stripe DEBITED, not what Aglyn kept.
@@ -2446,7 +2542,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
2446
2542
  // through it, so inventing one would answer a question this
2447
2543
  // record cannot answer.
2448
2544
  reconstructedFromInvoiceId: invoiceId
2449
- }, rollup), {
2545
+ }, directFields, rollup), {
2450
2546
  merge: true
2451
2547
  });
2452
2548
  // The order itself (AGL-1750): `paid` and unfulfilled, so it enters
@@ -2491,7 +2587,8 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
2491
2587
  ],
2492
2588
  paymentIntentId: String((_ref7 = object == null ? void 0 : object.payment_intent) != null ? _ref7 : '') || null,
2493
2589
  subscriptionId,
2494
- invoiceId,
2590
+ invoiceId
2591
+ }, directFields, {
2495
2592
  customerName: (_ref8 = (_ref9 = object == null ? void 0 : object.customer_name) != null ? _ref9 : currentSubscription.get('customerName')) != null ? _ref8 : null,
2496
2593
  customerEmail: (_ref10 = (_ref11 = object == null ? void 0 : object.customer_email) != null ? _ref11 : currentSubscription.get('customerEmail')) != null ? _ref10 : null
2497
2594
  }, (invoiceShipping == null ? void 0 : invoiceShipping.address) ? {
@@ -2523,7 +2620,14 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
2523
2620
  // RECORDED — the payment is already collected, and AGL-1732's rule is
2524
2621
  // that money collected must never go unfiled. The redelivery then
2525
2622
  // re-runs the reversal alone.
2526
- await reverseSubscriptionTaxToPlatform(object, invoiceHostId, subscriptionRef, invoiceId);
2623
+ //
2624
+ // Never on a DIRECT-charge subscription: the invoice lives on the
2625
+ // seller's account, Stripe Tax computed it on the seller's
2626
+ // registrations, and there is no transfer to take the tax back from.
2627
+ // The seller owns that tax.
2628
+ if (!directSale) {
2629
+ await reverseSubscriptionTaxToPlatform(object, invoiceHostId, subscriptionRef, invoiceId);
2630
+ }
2527
2631
  // BEFORE the redelivery short-circuit, deliberately (AGL-2071): a
2528
2632
  // cycle Aglyn has already recorded is exactly the cycle whose renewal
2529
2633
  // still needs stopping, and gating the stop on `recorded` would mean a
@@ -2537,7 +2641,8 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
2537
2641
  subscriberEmail: (_ref25 = (_ref26 = object == null ? void 0 : object.customer_email) != null ? _ref26 : soldSnapshot.get('customerEmail')) != null ? _ref25 : null,
2538
2642
  productName: snapshot.name || 'a subscription product',
2539
2643
  org: renewalOrg != null ? renewalOrg : null
2540
- });
2644
+ }, // A direct-charge subscription lives on the seller's account.
2645
+ saleAccount);
2541
2646
  } else if (renewalEntitled) {
2542
2647
  // RE-PRICE THE PLATFORM FEE (AGL-2289). `application_fee_percent` was
2543
2648
  // set once at the sale and never revisited, and it lives on the
@@ -2565,7 +2670,17 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
2565
2670
  const recurringBasisCents = CommerceModel.subscriptionRecurringBasisCents(object, soldSnapshot.get('lineItems'));
2566
2671
  if (recurringBasisCents > 0) {
2567
2672
  var _snapshot_productType;
2568
- await repriceStorefrontSubscriptionFee(subscriptionRef, subscriptionId, Aglyn.resolveSubscriptionFeePercent(renewalOrg, (_snapshot_productType = snapshot.productType) != null ? _snapshot_productType : 'physical', recurringBasisCents));
2673
+ var _object_automatic_tax;
2674
+ await repriceStorefrontSubscriptionFee(subscriptionRef, subscriptionId, Aglyn.resolveSubscriptionFeePercent(renewalOrg, (_snapshot_productType = snapshot.productType) != null ? _snapshot_productType : 'physical', recurringBasisCents, // The same Stripe Tax recovery the sale priced in (AGL-4198),
2675
+ // read off the invoice so a renewal never re-prices it away.
2676
+ // A direct-charge subscription is re-priced to the take alone,
2677
+ // as `checkout.ts` sold it: Stripe bills the seller its own
2678
+ // processing, so there is nothing to pass through.
2679
+ directSale ? {
2680
+ direct: true
2681
+ } : {
2682
+ stripeTax: (object == null ? void 0 : (_object_automatic_tax = object.automatic_tax) == null ? void 0 : _object_automatic_tax.enabled) === true
2683
+ }), saleAccount);
2569
2684
  }
2570
2685
  }
2571
2686
  if (!recorded) return;
@@ -2710,7 +2825,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
2710
2825
  checkoutSessionId: String(object.id)
2711
2826
  }, typeof (event == null ? void 0 : event.livemode) === 'boolean' ? {
2712
2827
  livemode: event.livemode
2713
- } : {}, {
2828
+ } : {}, directFields, {
2714
2829
  paymentIntentId: String((_ref = object == null ? void 0 : object.payment_intent) != null ? _ref : '') || null,
2715
2830
  // The regime this stay carried, on the record the merchant
2716
2831
  // reads (AGL-1969).
@@ -3113,7 +3228,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3113
3228
  checkoutSessionId: String(object.id)
3114
3229
  }, typeof (event == null ? void 0 : event.livemode) === 'boolean' ? {
3115
3230
  livemode: event.livemode
3116
- } : {}, {
3231
+ } : {}, directFields, {
3117
3232
  customerName: (_ref2 = object == null ? void 0 : (_object_customer_details = object.customer_details) == null ? void 0 : _object_customer_details.name) != null ? _ref2 : null,
3118
3233
  customerEmail: (_ref3 = object == null ? void 0 : (_object_customer_details1 = object.customer_details) == null ? void 0 : _object_customer_details1.email) != null ? _ref3 : null
3119
3234
  }, (shipping == null ? void 0 : shipping.address) && (cartLocalFulfillment == null ? void 0 : cartLocalFulfillment.fields.fulfillmentMethod) !== 'pickup' ? {
@@ -3754,7 +3869,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3754
3869
  }
3755
3870
  const paidQuote = CommerceModel.paidQuoteOrder(raw, String(orderId), facts);
3756
3871
  paidOrder = paidQuote;
3757
- transaction.set(orderRef, _extends({}, paidQuote, {
3872
+ transaction.set(orderRef, _extends({}, paidQuote, directFields, {
3758
3873
  createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
3759
3874
  }));
3760
3875
  return true;
@@ -3856,7 +3971,8 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3856
3971
  // every register card sale would stamp `none` beside an order
3857
3972
  // plainly carrying tax.
3858
3973
  taxMode: storefrontTaxModeOf(object, Number((_ref2 = object == null ? void 0 : (_object_metadata1 = object.metadata) == null ? void 0 : _object_metadata1.taxCents) != null ? _ref2 : 0)),
3859
- paymentIntentId: String((_ref3 = object == null ? void 0 : object.payment_intent) != null ? _ref3 : '') || null,
3974
+ paymentIntentId: String((_ref3 = object == null ? void 0 : object.payment_intent) != null ? _ref3 : '') || null
3975
+ }, directFields, {
3860
3976
  customerEmail: (_ref4 = (_ref5 = object == null ? void 0 : (_object_customer_details1 = object.customer_details) == null ? void 0 : _object_customer_details1.email) != null ? _ref5 : lifted.customerEmail) != null ? _ref4 : null,
3861
3977
  timeline: CommerceModel.appendOrderEvent(lifted, 'paid'),
3862
3978
  // A paid draft is new to a shipping tool's feed (AGL-3613).
@@ -4249,7 +4365,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4249
4365
  checkoutSessionId: String(object.id)
4250
4366
  }, typeof (event == null ? void 0 : event.livemode) === 'boolean' ? {
4251
4367
  livemode: event.livemode
4252
- } : {}, {
4368
+ } : {}, directFields, {
4253
4369
  customerName: (_ref2 = object == null ? void 0 : (_object_customer_details = object.customer_details) == null ? void 0 : _object_customer_details.name) != null ? _ref2 : null
4254
4370
  }, (object == null ? void 0 : (_object_shipping_details = object.shipping_details) == null ? void 0 : _object_shipping_details.address) ? {
4255
4371
  shippingAddress: stripeOrderAddress(object.shipping_details.name, object.shipping_details.address)
@@ -4639,6 +4755,8 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4639
4755
  };
4640
4756
  if (lookup.kind !== 'order') return;
4641
4757
  const snapshot = lookup.snapshot;
4758
+ // The seller's copy of a destination sale's refund is not a second one.
4759
+ if (!connectEventOrderIsDirect(event, snapshot)) return;
4642
4760
  const hostId = String((_ref93 = (_snapshot_ref_parent_parent = snapshot.ref.parent.parent) == null ? void 0 : _snapshot_ref_parent_parent.id) != null ? _ref93 : '');
4643
4761
  const external = await recordExternalRefund(snapshot.ref, object);
4644
4762
  if (external && hostId) {
@@ -4709,6 +4827,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4709
4827
  };
4710
4828
  if (lookup.kind !== 'order') return;
4711
4829
  const snapshot = lookup.snapshot;
4830
+ if (!connectEventOrderIsDirect(event, snapshot)) return;
4712
4831
  const hostId = String((_ref97 = (_snapshot_ref_parent_parent1 = snapshot.ref.parent.parent) == null ? void 0 : _snapshot_ref_parent_parent1.id) != null ? _ref97 : '');
4713
4832
  const order = CommerceModel.liftLegacyOrder((_snapshot_data1 = snapshot.data()) != null ? _snapshot_data1 : {});
4714
4833
  const orderCents = Number((_ref98 = (_ref99 = (_order_totals2 = order.totals) == null ? void 0 : _order_totals2.totalCents) != null ? _ref99 : order.amountCents) != null ? _ref98 : 0);
@@ -4778,9 +4897,14 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4778
4897
  var _snapshot_ref_parent_parent2;
4779
4898
  const dispute = object != null ? object : {};
4780
4899
  const paymentIntentId = String((_dispute_payment_intent = dispute.payment_intent) != null ? _dispute_payment_intent : '');
4781
- const lookup = paymentIntentId ? await findOrderForDispute(paymentIntentId) : {
4900
+ const found = paymentIntentId ? await findOrderForDispute(paymentIntentId) : {
4782
4901
  kind: 'not-ours'
4783
4902
  };
4903
+ // A Connect-delivered dispute on an order that was not a direct sale is
4904
+ // not this order's dispute: the platform's own event is.
4905
+ const lookup = found.kind === 'order' && !connectEventOrderIsDirect(event, found.snapshot) ? {
4906
+ kind: 'not-ours'
4907
+ } : found;
4784
4908
  // UNRESOLVED IS NOT NOT-OURS (AGL-2161). A lookup that could not run is
4785
4909
  // the platform's problem and is reported; a lookup that ran and matched
4786
4910
  // nothing is a marketplace, booking or platform-billing dispute, and
@@ -4803,6 +4927,11 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4803
4927
  var _ref101;
4804
4928
  var _snapshot_ref_parent_parent3;
4805
4929
  const hostId = String((_ref101 = (_snapshot_ref_parent_parent3 = snapshot.ref.parent.parent) == null ? void 0 : _snapshot_ref_parent_parent3.id) != null ? _ref101 : '');
4930
+ // A DIRECT-charge order was paid on the seller's own account, so the
4931
+ // dispute is on that account too: Stripe took the money and the dispute
4932
+ // fee from the seller's balance, and there is no transfer for Aglyn to
4933
+ // pull back. The order says so.
4934
+ const disputeOnSellerAccount = snapshot.get('chargeModel') === 'direct';
4806
4935
  if (type === 'charge.dispute.created') {
4807
4936
  var _snapshot_data2;
4808
4937
  // A chargeback's gift cards are frozen while it is open (AGL-3363).
@@ -4867,7 +4996,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4867
4996
  await notifyHostManagers(hostId, {
4868
4997
  type: 'content.order',
4869
4998
  title: settled.lost ? `Chargeback lost — order ${disputedOrderLabel}` : 'Chargeback resolved in your favor',
4870
- body: settled.lost ? `The chargeback on order ${disputedOrderLabel} on {site} was ` + 'decided in the shopper\'s favor, and their bank took back ' + `$${(settled.reversedCents / 100).toFixed(2)}. If part of the ` + 'sale had been paid out to you, a separate notice says what ' + 'is taken back from your balance.' : `The chargeback on order ${disputedOrderLabel} on {site} ` + 'closed in your favor. Nothing is taken back from you for it.',
4999
+ body: settled.lost ? disputeOnSellerAccount ? `The chargeback on order ${disputedOrderLabel} on {site} was ` + 'decided in the shopper\'s favor, and their bank took back ' + `$${(settled.reversedCents / 100).toFixed(2)} from your ` + 'Stripe balance.' : `The chargeback on order ${disputedOrderLabel} on {site} was ` + 'decided in the shopper\'s favor, and their bank took back ' + `$${(settled.reversedCents / 100).toFixed(2)}. If part of the ` + 'sale had been paid out to you, a separate notice says what ' + 'is taken back from your balance.' : `The chargeback on order ${disputedOrderLabel} on {site} ` + 'closed in your favor. Nothing is taken back from you for it.',
4871
5000
  link: `/${hostId}/products/orders`
4872
5001
  });
4873
5002
  // The customer's side of the ledger (AGL-1754), through the same
@@ -4919,7 +5048,10 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4919
5048
  // transiently-failed reversal gets its retry — and gated inside on
4920
5049
  // the order's own `reversedTransferCents` marker, so it runs at most
4921
5050
  // once per dispute however many times Stripe delivers.
4922
- if (String((_ref104 = dispute == null ? void 0 : dispute.status) != null ? _ref104 : '') === 'lost') {
5051
+ //
5052
+ // Never for a DIRECT charge: the shopper's bank already took the money
5053
+ // from the seller's own balance, and there is no transfer to reverse.
5054
+ if (String((_ref104 = dispute == null ? void 0 : dispute.status) != null ? _ref104 : '') === 'lost' && !disputeOnSellerAccount) {
4923
5055
  const pulledBackCents = await reverseSellerShare(snapshot.ref, dispute);
4924
5056
  // The merchant-experience half of the AGL-1794 decision, and not an
4925
5057
  // optional extra: the reversal takes money out of the connected