@aglyn/plugins-commerce 1.14.0 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/account-subscriptions.d.ts +51 -0
  3. package/src/lib/components/account-subscriptions.js +168 -0
  4. package/src/lib/components/account-subscriptions.js.map +1 -0
  5. package/src/lib/components/account.js +12 -48
  6. package/src/lib/components/account.js.map +1 -1
  7. package/src/lib/components/cart.js +38 -9
  8. package/src/lib/components/cart.js.map +1 -1
  9. package/src/lib/components/commerce-console-page.js +6 -0
  10. package/src/lib/components/commerce-console-page.js.map +1 -1
  11. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  12. package/src/lib/components/commerce-console-sections.js +5 -0
  13. package/src/lib/components/commerce-console-sections.js.map +1 -1
  14. package/src/lib/components/console/paid-media.d.ts +1 -0
  15. package/src/lib/components/console/paid-media.js +15 -4
  16. package/src/lib/components/console/paid-media.js.map +1 -1
  17. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  18. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  19. package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
  20. package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
  21. package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
  22. package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
  23. package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
  24. package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
  25. package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
  26. package/src/lib/components/console/pos-cellular-control.component.js +5 -5
  27. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  28. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  29. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  30. package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
  31. package/src/lib/components/console/pos-hardware-card.component.js +77 -8
  32. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
  33. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
  34. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
  35. package/src/lib/components/console/pos-page.component.js +19 -2
  36. package/src/lib/components/console/pos-page.component.js.map +1 -1
  37. package/src/lib/components/console/product-editor-dialog.component.js +21 -2
  38. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  39. package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
  40. package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
  41. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
  42. package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
  43. package/src/lib/components/console/subscriptions-card.component.js +282 -0
  44. package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
  45. package/src/lib/components/hardware-terms-consent.d.ts +22 -0
  46. package/src/lib/components/hardware-terms-consent.js +85 -0
  47. package/src/lib/components/hardware-terms-consent.js.map +1 -0
  48. package/src/lib/components/product-detail.js +32 -8
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/components/quote-page-body.js +7 -3
  51. package/src/lib/components/quote-page-body.js.map +1 -1
  52. package/src/lib/components/related-products.js +6 -3
  53. package/src/lib/components/related-products.js.map +1 -1
  54. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  55. package/src/lib/components/storefront-payment-element.js +11 -7
  56. package/src/lib/components/storefront-payment-element.js.map +1 -1
  57. package/src/lib/constants/operator-alerts.d.ts +1 -1
  58. package/src/lib/constants/operator-alerts.js +4 -4
  59. package/src/lib/constants/operator-alerts.js.map +1 -1
  60. package/src/lib/model/commerce-orders.d.ts +6 -2
  61. package/src/lib/model/commerce-orders.js.map +1 -1
  62. package/src/lib/model/commerce-payment-methods.d.ts +27 -16
  63. package/src/lib/model/commerce-payment-methods.js +11 -83
  64. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  65. package/src/lib/model/commerce.d.ts +6 -0
  66. package/src/lib/model/commerce.js.map +1 -1
  67. package/src/lib/model/index.d.ts +1 -0
  68. package/src/lib/model/index.js +1 -0
  69. package/src/lib/model/index.js.map +1 -1
  70. package/src/lib/model/paid-media.d.ts +8 -0
  71. package/src/lib/model/paid-media.js +13 -0
  72. package/src/lib/model/paid-media.js.map +1 -1
  73. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  74. package/src/lib/model/pos-hardware-in-person.js +52 -20
  75. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  76. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  77. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  78. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  79. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  80. package/src/lib/model/pos-hardware-terms.js +68 -3
  81. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  82. package/src/lib/model/pos-hardware.d.ts +101 -15
  83. package/src/lib/model/pos-hardware.js +128 -18
  84. package/src/lib/model/pos-hardware.js.map +1 -1
  85. package/src/lib/model/pos-reader-splash.js +2 -2
  86. package/src/lib/model/pos-reader-splash.js.map +1 -1
  87. package/src/lib/model/product-write.d.ts +3 -0
  88. package/src/lib/model/subscription-view.d.ts +90 -0
  89. package/src/lib/model/subscription-view.js +176 -0
  90. package/src/lib/model/subscription-view.js.map +1 -0
  91. package/src/lib/server/billing-webhook.d.ts +27 -6
  92. package/src/lib/server/billing-webhook.js +271 -81
  93. package/src/lib/server/billing-webhook.js.map +1 -1
  94. package/src/lib/server/cancel-order.js +4 -3
  95. package/src/lib/server/cancel-order.js.map +1 -1
  96. package/src/lib/server/cart-checkout.js +105 -23
  97. package/src/lib/server/cart-checkout.js.map +1 -1
  98. package/src/lib/server/cart.js +15 -3
  99. package/src/lib/server/cart.js.map +1 -1
  100. package/src/lib/server/catalog.js +58 -22
  101. package/src/lib/server/catalog.js.map +1 -1
  102. package/src/lib/server/checkout-session-expiry.d.ts +1 -1
  103. package/src/lib/server/checkout-session-expiry.js +19 -5
  104. package/src/lib/server/checkout-session-expiry.js.map +1 -1
  105. package/src/lib/server/checkout-status.js +4 -3
  106. package/src/lib/server/checkout-status.js.map +1 -1
  107. package/src/lib/server/checkout.js +98 -26
  108. package/src/lib/server/checkout.js.map +1 -1
  109. package/src/lib/server/connect.js +42 -11
  110. package/src/lib/server/connect.js.map +1 -1
  111. package/src/lib/server/draft-order.js +36 -7
  112. package/src/lib/server/draft-order.js.map +1 -1
  113. package/src/lib/server/manual-tax-rate.d.ts +11 -3
  114. package/src/lib/server/manual-tax-rate.js +10 -6
  115. package/src/lib/server/manual-tax-rate.js.map +1 -1
  116. package/src/lib/server/membership-account.d.ts +22 -0
  117. package/src/lib/server/membership-account.js +52 -8
  118. package/src/lib/server/membership-account.js.map +1 -1
  119. package/src/lib/server/native-checkout.d.ts +10 -3
  120. package/src/lib/server/native-checkout.js +8 -3
  121. package/src/lib/server/native-checkout.js.map +1 -1
  122. package/src/lib/server/payment-method-domains.d.ts +50 -9
  123. package/src/lib/server/payment-method-domains.js +150 -51
  124. package/src/lib/server/payment-method-domains.js.map +1 -1
  125. package/src/lib/server/payment-methods.js +3 -2
  126. package/src/lib/server/payment-methods.js.map +1 -1
  127. package/src/lib/server/pos-auth.d.ts +3 -3
  128. package/src/lib/server/pos-auth.js +3 -3
  129. package/src/lib/server/pos-auth.js.map +1 -1
  130. package/src/lib/server/pos-cellular-billing.js +1 -1
  131. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  132. package/src/lib/server/pos-cellular-notify.js +1 -1
  133. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  134. package/src/lib/server/pos-cellular.js +1 -1
  135. package/src/lib/server/pos-cellular.js.map +1 -1
  136. package/src/lib/server/pos-hardware-admin.js +86 -13
  137. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  138. package/src/lib/server/pos-hardware-attach.js +5 -5
  139. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  140. package/src/lib/server/pos-hardware-cancel.js +65 -0
  141. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  142. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  143. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  144. package/src/lib/server/pos-hardware-closure.js +5 -8
  145. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  146. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  147. package/src/lib/server/pos-hardware-in-person.js +72 -17
  148. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  149. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  150. package/src/lib/server/pos-hardware-notify.js +30 -5
  151. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  152. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  153. package/src/lib/server/pos-hardware-readers.js +206 -85
  154. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  155. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  156. package/src/lib/server/pos-hardware-returns.js +39 -7
  157. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  158. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  159. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  160. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  161. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  162. package/src/lib/server/pos-hardware-sale.js +1 -0
  163. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  164. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  165. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  166. package/src/lib/server/pos-hardware-webhook.js +16 -3
  167. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  168. package/src/lib/server/pos-hardware.d.ts +14 -3
  169. package/src/lib/server/pos-hardware.js +83 -18
  170. package/src/lib/server/pos-hardware.js.map +1 -1
  171. package/src/lib/server/pos-ops-routes.js +2 -10
  172. package/src/lib/server/pos-ops-routes.js.map +1 -1
  173. package/src/lib/server/pos-order.js +5 -1
  174. package/src/lib/server/pos-order.js.map +1 -1
  175. package/src/lib/server/pos-stripe.d.ts +7 -7
  176. package/src/lib/server/pos-stripe.js +15 -13
  177. package/src/lib/server/pos-stripe.js.map +1 -1
  178. package/src/lib/server/pos-terminal.js +11 -3
  179. package/src/lib/server/pos-terminal.js.map +1 -1
  180. package/src/lib/server/quote-pay.d.ts +23 -1
  181. package/src/lib/server/quote-pay.js +111 -27
  182. package/src/lib/server/quote-pay.js.map +1 -1
  183. package/src/lib/server/quote.d.ts +2 -1
  184. package/src/lib/server/quote.js +12 -11
  185. package/src/lib/server/quote.js.map +1 -1
  186. package/src/lib/server/refund.js +13 -6
  187. package/src/lib/server/refund.js.map +1 -1
  188. package/src/lib/server/related.js +10 -3
  189. package/src/lib/server/related.js.map +1 -1
  190. package/src/lib/server/reserve.js +19 -6
  191. package/src/lib/server/reserve.js.map +1 -1
  192. package/src/lib/server/revenue-source.d.ts +6 -0
  193. package/src/lib/server/revenue-source.js +25 -9
  194. package/src/lib/server/revenue-source.js.map +1 -1
  195. package/src/lib/server/seller-stripe-account.d.ts +45 -0
  196. package/src/lib/server/seller-stripe-account.js +99 -0
  197. package/src/lib/server/seller-stripe-account.js.map +1 -0
  198. package/src/lib/server/storefront-tax-record.js +6 -1
  199. package/src/lib/server/storefront-tax-record.js.map +1 -1
  200. package/src/lib/server/storefront-tax.d.ts +33 -2
  201. package/src/lib/server/storefront-tax.js +39 -3
  202. package/src/lib/server/storefront-tax.js.map +1 -1
  203. package/src/lib/server/stream.d.ts +2 -0
  204. package/src/lib/server/stream.js +22 -2
  205. package/src/lib/server/stream.js.map +1 -1
  206. package/src/lib/server/stripe-refund.d.ts +15 -0
  207. package/src/lib/server/stripe-refund.js +54 -26
  208. package/src/lib/server/stripe-refund.js.map +1 -1
  209. package/src/lib/server/subscription-portal.js +8 -3
  210. package/src/lib/server/subscription-portal.js.map +1 -1
  211. package/src/lib/server/tax-return-source.js +5 -1
  212. package/src/lib/server/tax-return-source.js.map +1 -1
  213. package/src/lib/server.js +2 -2
  214. package/src/lib/server.js.map +1 -1
@@ -53,7 +53,20 @@ import { checkoutCreditProvider, checkoutCreditSold, decodeCheckoutCreditMetadat
53
53
  import { raiseOrderEvent } from "./order-events.js";
54
54
  import { handlePosStripeEvent } from "./pos-terminal.js";
55
55
  import { notifyPosSaleCompleted } from "./pos-sale.js";
56
+ import { recordSellerStoreSaleHardware, sellerStoreOrderHardwareFields } from "./pos-hardware-sale-fields.js";
56
57
  import { posOrderRefundStripeId } from "./pos-order-refund-ids.js";
58
+ import { isDirectChargeObject } from "./seller-stripe-account.js";
59
+ /**
60
+ * A Stripe subscription's current period end, in seconds (AGL-4191). Older API
61
+ * versions carry it on the subscription; newer ones moved it to each item.
62
+ * Exported for the spec.
63
+ */ export function subscriptionPeriodEnd(object) {
64
+ var _object_items_data_, _object_items_data, _object_items;
65
+ const own = Number(object == null ? void 0 : object.current_period_end);
66
+ if (Number.isFinite(own) && own > 0) return own;
67
+ const item = Number(object == null ? void 0 : (_object_items = object.items) == null ? void 0 : (_object_items_data = _object_items.data) == null ? void 0 : (_object_items_data_ = _object_items_data[0]) == null ? void 0 : _object_items_data_.current_period_end);
68
+ return Number.isFinite(item) && item > 0 ? item : null;
69
+ }
57
70
  /**
58
71
  * Assigns unassigned license keys for a digital product (AGL-308):
59
72
  * stamps order/email on the key docs, returns the key strings, and
@@ -656,7 +669,10 @@ async function findOrderForDispute(paymentIntentId) {
656
669
  * subscription billing forever with the books saying it had been stopped. The
657
670
  * `Idempotency-Key` covers the window where the claim is written and the
658
671
  * response never arrives.
659
- */ 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) {
660
676
  var _ref, _ref1;
661
677
  const stripeKey = process.env.STRIPE_SECRET_KEY;
662
678
  if (!stripeKey) {
@@ -689,11 +705,13 @@ async function findOrderForDispute(paymentIntentId) {
689
705
  };
690
706
  const response = await fetch(`https://api.stripe.com/v1/subscriptions/${encodeURIComponent(subscriptionId)}`, {
691
707
  method: 'POST',
692
- headers: {
708
+ headers: _extends({
693
709
  Authorization: `Bearer ${stripeKey}`,
694
710
  'Content-Type': 'application/x-www-form-urlencoded',
695
711
  'Idempotency-Key': `lapsed-stop-${subscriptionId}`
696
- },
712
+ }, stripeAccount ? {
713
+ 'Stripe-Account': stripeAccount
714
+ } : {}),
697
715
  body: new URLSearchParams({
698
716
  cancel_at_period_end: 'true'
699
717
  }).toString()
@@ -744,11 +762,18 @@ async function findOrderForDispute(paymentIntentId) {
744
762
  link: `/${hostId}/products`
745
763
  });
746
764
  }
747
- /** 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) {
748
771
  const response = await fetch(url, {
749
- headers: {
772
+ headers: _extends({
750
773
  Authorization: `Bearer ${stripeKey}`
751
- }
774
+ }, stripeAccount ? {
775
+ 'Stripe-Account': stripeAccount
776
+ } : {})
752
777
  });
753
778
  const body = await response.json().catch(()=>null);
754
779
  return {
@@ -757,6 +782,61 @@ async function findOrderForDispute(paymentIntentId) {
757
782
  body
758
783
  };
759
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
+ }
760
840
  /**
761
841
  * Re-price a storefront subscription's platform fee to the merchant's CURRENT
762
842
  * plan (AGL-2289) — and since AGL-2655 that figure is the plan's take plus
@@ -797,7 +877,7 @@ async function findOrderForDispute(paymentIntentId) {
797
877
  * A rate of 0 UNSETS the parameter rather than sending `0`: Stripe rejects a
798
878
  * zero `application_fee_percent`, and an empty value is how its API clears an
799
879
  * optional field. That is also what `checkout.ts` does by omitting the key.
800
- */ 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) {
801
881
  const stripeKey = process.env.STRIPE_SECRET_KEY;
802
882
  if (!stripeKey || !subscriptionId) return;
803
883
  const snapshot = await subscriptionRef.get().catch(()=>null);
@@ -808,13 +888,15 @@ async function findOrderForDispute(paymentIntentId) {
808
888
  if (Number.isFinite(stored) && Number(stored) === desiredFeePct) return;
809
889
  const response = await fetch(`https://api.stripe.com/v1/subscriptions/${encodeURIComponent(subscriptionId)}`, {
810
890
  method: 'POST',
811
- headers: {
891
+ headers: _extends({
812
892
  Authorization: `Bearer ${stripeKey}`,
813
893
  'Content-Type': 'application/x-www-form-urlencoded',
814
894
  // Keyed on the RATE as well as the subscription, so a later change
815
895
  // back is a new request rather than a replay of the old one.
816
896
  'Idempotency-Key': `fee-reprice-${subscriptionId}-${desiredFeePct}`
817
- },
897
+ }, stripeAccount ? {
898
+ 'Stripe-Account': stripeAccount
899
+ } : {}),
818
900
  body: new URLSearchParams({
819
901
  application_fee_percent: desiredFeePct > 0 ? String(desiredFeePct) : ''
820
902
  }).toString()
@@ -869,7 +951,7 @@ async function findOrderForDispute(paymentIntentId) {
869
951
  * repo cannot see — the same three-spelling problem `subscriptionMeta` and the
870
952
  * tax fields already solve by reading every form. `payment_intent` is the third
871
953
  * (the renewal order write at :1667 reads it), and it needs one more hop.
872
- */ async function resolveInvoiceChargeId(invoice, stripeKey) {
954
+ */ async function resolveInvoiceChargeId(invoice, stripeKey, stripeAccount) {
873
955
  var _ref;
874
956
  var _invoice_payments;
875
957
  const direct = invoice == null ? void 0 : invoice.charge;
@@ -881,7 +963,7 @@ async function findOrderForDispute(paymentIntentId) {
881
963
  const nested = payment == null ? void 0 : (_payment_payment1 = payment.payment) == null ? void 0 : _payment_payment1.payment_intent;
882
964
  if (typeof nested === 'string' && nested) {
883
965
  var _intent_body;
884
- 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);
885
967
  const latest = intent.ok ? (_intent_body = intent.body) == null ? void 0 : _intent_body.latest_charge : '';
886
968
  if (typeof latest === 'string' && latest) return latest;
887
969
  }
@@ -889,7 +971,7 @@ async function findOrderForDispute(paymentIntentId) {
889
971
  const paymentIntentId = invoice == null ? void 0 : invoice.payment_intent;
890
972
  if (typeof paymentIntentId === 'string' && paymentIntentId) {
891
973
  var _intent_body1;
892
- 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);
893
975
  const latest = intent.ok ? (_intent_body1 = intent.body) == null ? void 0 : _intent_body1.latest_charge : '';
894
976
  if (typeof latest === 'string' && latest) return latest;
895
977
  }
@@ -967,7 +1049,7 @@ async function findOrderForDispute(paymentIntentId) {
967
1049
  * `metadata[feeCents]` (items only) while Stripe had charged percent-of-total,
968
1050
  * so the same subscription's first and second cycles reported fees computed on
969
1051
  * different bases.
970
- */ async function chargeSubscriptionFeeOnItemsOnly(invoice, hostId, invoiceId) {
1052
+ */ async function chargeSubscriptionFeeOnItemsOnly(invoice, hostId, invoiceId, stripeAccount) {
971
1053
  var _ref, _fee_amount, _fee_amount_refunded;
972
1054
  var _fees_body_data, _fees_body;
973
1055
  const chargedCents = Math.max(0, Math.round(Number((_ref = invoice == null ? void 0 : invoice.application_fee_amount) != null ? _ref : 0)));
@@ -986,7 +1068,7 @@ async function findOrderForDispute(paymentIntentId) {
986
1068
  await reportFeeNotCorrected(hostId, invoiceId, 'STRIPE_SECRET_KEY is not set on this deployment');
987
1069
  return chargedCents;
988
1070
  }
989
- const chargeId = await resolveInvoiceChargeId(invoice, stripeKey);
1071
+ const chargeId = await resolveInvoiceChargeId(invoice, stripeKey, stripeAccount);
990
1072
  if (!chargeId) {
991
1073
  console.error('Subscription fee not corrected to the items-only base: the invoice names no charge (AGL-2317)', {
992
1074
  hostId,
@@ -1724,7 +1806,25 @@ async function findOrderForDispute(paymentIntentId) {
1724
1806
  * assignment helper (AGL-308). Registered via registerCommerceConsoleApi;
1725
1807
  * every section is idempotent by doc key and self-selects on
1726
1808
  * `object.metadata.type`, exactly as the inline route sections did.
1727
- */ export const commerceBillingWebhookHandler = async ({ type, object, event, requestHost })=>{
1809
+ */ /**
1810
+ * A Stripe address as an order stores it: only the parts Stripe filled.
1811
+ * Stripe sends an empty part as `null`, and the Admin SDK here refuses an
1812
+ * `undefined` value outright (no `ignoreUndefinedProperties`), so a part is
1813
+ * left out rather than written as `undefined`: an address with no second
1814
+ * line used to fail the whole order write.
1815
+ */ function stripeOrderAddress(name, address) {
1816
+ const parts = {
1817
+ name,
1818
+ line1: address == null ? void 0 : address.line1,
1819
+ line2: address == null ? void 0 : address.line2,
1820
+ city: address == null ? void 0 : address.city,
1821
+ state: address == null ? void 0 : address.state,
1822
+ postalCode: address == null ? void 0 : address.postal_code,
1823
+ country: address == null ? void 0 : address.country
1824
+ };
1825
+ return Object.fromEntries(Object.entries(parts).filter(([, value])=>typeof value === 'string' && value !== ''));
1826
+ }
1827
+ export const commerceBillingWebhookHandler = async ({ type, object, event, requestHost })=>{
1728
1828
  var _object_metadata, _object_metadata1, _object_metadata2, _object_metadata3, _object_metadata4;
1729
1829
  // THE MERCHANT'S PAYMENT ACCOUNT CHANGED. Every commerce money route —
1730
1830
  // checkout, cart checkout, draft orders, reservations, POS — gates the sale
@@ -1747,6 +1847,14 @@ async function findOrderForDispute(paymentIntentId) {
1747
1847
  })) {
1748
1848
  return;
1749
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;
1750
1858
  // THE REGISTER'S CARD PAYMENTS (AGL-3607): Terminal reader actions, register
1751
1859
  // PaymentIntents and register QR pages. Each names one payment on an open
1752
1860
  // sale and is settled by re-reading Stripe in `pos-terminal.ts`; every other
@@ -1867,7 +1975,18 @@ async function findOrderForDispute(paymentIntentId) {
1867
1975
  // AWAITED and never allowed to throw: a lost row is an understated tax
1868
1976
  // return, and `recordStorefrontTax` swallows its own failures precisely so
1869
1977
  // this cannot turn a recording problem into a redelivered billing webhook.
1870
- 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);
1871
1990
  if (type === 'customer.subscription.created' || type === 'customer.subscription.updated' || type === 'customer.subscription.deleted') {
1872
1991
  var _object_metadata13;
1873
1992
  // Storefront subscription status sync (AGL-303).
@@ -1878,7 +1997,14 @@ async function findOrderForDispute(paymentIntentId) {
1878
1997
  var _ref8;
1879
1998
  await firebaseAdmin.app().firestore().collection('hosts').doc(String(subHostId)).collection('subscriptions').doc(String(object.id)).set({
1880
1999
  status: type === 'customer.subscription.deleted' ? 'canceled' : String((_ref8 = object == null ? void 0 : object.status) != null ? _ref8 : 'active'),
1881
- currentPeriodEndMs: (object == null ? void 0 : object.current_period_end) ? object.current_period_end * 1000 : null
2000
+ // Newer Stripe API versions keep the period on the item, not
2001
+ // the subscription; either answers the same question.
2002
+ currentPeriodEndMs: subscriptionPeriodEnd(object) ? Number(subscriptionPeriodEnd(object)) * 1000 : null,
2003
+ // Cancelled in the billing portal: access runs to the period
2004
+ // end and nothing more is charged (AGL-4191). Without this the
2005
+ // account page and the Subscriptions list would promise a
2006
+ // renewal that will not happen.
2007
+ cancelAtPeriodEnd: type !== 'customer.subscription.deleted' && (object == null ? void 0 : object.cancel_at_period_end) === true
1882
2008
  }, {
1883
2009
  merge: true
1884
2010
  }).catch(()=>undefined);
@@ -1977,7 +2103,7 @@ async function findOrderForDispute(paymentIntentId) {
1977
2103
  checkoutSessionId: String(object.id)
1978
2104
  }, typeof (event == null ? void 0 : event.livemode) === 'boolean' ? {
1979
2105
  livemode: event.livemode
1980
- } : {}, {
2106
+ } : {}, directFields, {
1981
2107
  createdAtMs: Date.now(),
1982
2108
  // WHICH TAX this subscription will bill, for as long as it
1983
2109
  // lives (AGL-2323).
@@ -2218,7 +2344,14 @@ async function findOrderForDispute(paymentIntentId) {
2218
2344
  // is left is the figure the ledger stores. A transient Stripe failure
2219
2345
  // throws here rather than filing a fee we did not end up charging —
2220
2346
  // the redelivery re-runs it behind the invoice-id guard below.
2221
- 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);
2222
2355
  const { lineItems: invoiceLineItems, totals: computedInvoiceTotals } = CommerceModel.computeSubscriptionInvoiceOrder(object, snapshot);
2223
2356
  // `computeSubscriptionInvoiceOrder` reads `application_fee_amount`
2224
2357
  // verbatim, which is what Stripe DEBITED, not what Aglyn kept.
@@ -2409,7 +2542,7 @@ async function findOrderForDispute(paymentIntentId) {
2409
2542
  // through it, so inventing one would answer a question this
2410
2543
  // record cannot answer.
2411
2544
  reconstructedFromInvoiceId: invoiceId
2412
- }, rollup), {
2545
+ }, directFields, rollup), {
2413
2546
  merge: true
2414
2547
  });
2415
2548
  // The order itself (AGL-1750): `paid` and unfulfilled, so it enters
@@ -2423,7 +2556,7 @@ async function findOrderForDispute(paymentIntentId) {
2423
2556
  // is when the cycle was PAID — dating a redelivered cycle "now"
2424
2557
  // would file it under the wrong day in every orders view.
2425
2558
  if (shipsPhysically) {
2426
- var _ref6, _ref7, _ref8, _ref9, _ref10, _ref11, _ref12, _invoiceShipping_address_line1, _invoiceShipping_address_line2, _invoiceShipping_address_city, _invoiceShipping_address_state, _invoiceShipping_address_postal_code, _invoiceShipping_address_country, _invoiceTotals_feeCents;
2559
+ var _ref6, _ref7, _ref8, _ref9, _ref10, _ref11, _invoiceTotals_feeCents;
2427
2560
  const orderNumber = Number((_ref6 = orderCounter == null ? void 0 : orderCounter.get('next')) != null ? _ref6 : 1);
2428
2561
  transaction.set(counterRef, {
2429
2562
  next: orderNumber + 1
@@ -2454,19 +2587,12 @@ async function findOrderForDispute(paymentIntentId) {
2454
2587
  ],
2455
2588
  paymentIntentId: String((_ref7 = object == null ? void 0 : object.payment_intent) != null ? _ref7 : '') || null,
2456
2589
  subscriptionId,
2457
- invoiceId,
2590
+ invoiceId
2591
+ }, directFields, {
2458
2592
  customerName: (_ref8 = (_ref9 = object == null ? void 0 : object.customer_name) != null ? _ref9 : currentSubscription.get('customerName')) != null ? _ref8 : null,
2459
2593
  customerEmail: (_ref10 = (_ref11 = object == null ? void 0 : object.customer_email) != null ? _ref11 : currentSubscription.get('customerEmail')) != null ? _ref10 : null
2460
2594
  }, (invoiceShipping == null ? void 0 : invoiceShipping.address) ? {
2461
- shippingAddress: {
2462
- name: (_ref12 = invoiceShipping == null ? void 0 : invoiceShipping.name) != null ? _ref12 : undefined,
2463
- line1: (_invoiceShipping_address_line1 = invoiceShipping.address.line1) != null ? _invoiceShipping_address_line1 : undefined,
2464
- line2: (_invoiceShipping_address_line2 = invoiceShipping.address.line2) != null ? _invoiceShipping_address_line2 : undefined,
2465
- city: (_invoiceShipping_address_city = invoiceShipping.address.city) != null ? _invoiceShipping_address_city : undefined,
2466
- state: (_invoiceShipping_address_state = invoiceShipping.address.state) != null ? _invoiceShipping_address_state : undefined,
2467
- postalCode: (_invoiceShipping_address_postal_code = invoiceShipping.address.postal_code) != null ? _invoiceShipping_address_postal_code : undefined,
2468
- country: (_invoiceShipping_address_country = invoiceShipping.address.country) != null ? _invoiceShipping_address_country : undefined
2469
- }
2595
+ shippingAddress: stripeOrderAddress(invoiceShipping == null ? void 0 : invoiceShipping.name, invoiceShipping.address)
2470
2596
  } : {}, {
2471
2597
  amountCents: paidCents,
2472
2598
  feeCents: Number((_invoiceTotals_feeCents = invoiceTotals.feeCents) != null ? _invoiceTotals_feeCents : 0),
@@ -2494,7 +2620,14 @@ async function findOrderForDispute(paymentIntentId) {
2494
2620
  // RECORDED — the payment is already collected, and AGL-1732's rule is
2495
2621
  // that money collected must never go unfiled. The redelivery then
2496
2622
  // re-runs the reversal alone.
2497
- 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
+ }
2498
2631
  // BEFORE the redelivery short-circuit, deliberately (AGL-2071): a
2499
2632
  // cycle Aglyn has already recorded is exactly the cycle whose renewal
2500
2633
  // still needs stopping, and gating the stop on `recorded` would mean a
@@ -2508,7 +2641,8 @@ async function findOrderForDispute(paymentIntentId) {
2508
2641
  subscriberEmail: (_ref25 = (_ref26 = object == null ? void 0 : object.customer_email) != null ? _ref26 : soldSnapshot.get('customerEmail')) != null ? _ref25 : null,
2509
2642
  productName: snapshot.name || 'a subscription product',
2510
2643
  org: renewalOrg != null ? renewalOrg : null
2511
- });
2644
+ }, // A direct-charge subscription lives on the seller's account.
2645
+ saleAccount);
2512
2646
  } else if (renewalEntitled) {
2513
2647
  // RE-PRICE THE PLATFORM FEE (AGL-2289). `application_fee_percent` was
2514
2648
  // set once at the sale and never revisited, and it lives on the
@@ -2536,7 +2670,17 @@ async function findOrderForDispute(paymentIntentId) {
2536
2670
  const recurringBasisCents = CommerceModel.subscriptionRecurringBasisCents(object, soldSnapshot.get('lineItems'));
2537
2671
  if (recurringBasisCents > 0) {
2538
2672
  var _snapshot_productType;
2539
- 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);
2540
2684
  }
2541
2685
  }
2542
2686
  if (!recorded) return;
@@ -2585,17 +2729,16 @@ async function findOrderForDispute(paymentIntentId) {
2585
2729
  if (!isOpeningInvoice && paidCents > 0) {
2586
2730
  var _ref28, _ref29;
2587
2731
  const renewalEmail = (_ref28 = (_ref29 = object == null ? void 0 : object.customer_email) != null ? _ref29 : soldSnapshot.get('customerEmail')) != null ? _ref28 : null;
2588
- // A physical cycle now lands in Orders (AGL-1750), but the console
2589
- // still has no Subscriptions tab, so for a digital or service
2590
- // subscription this notification remains the only place a merchant
2591
- // learns the money arrived at all.
2732
+ // A physical cycle lands in Orders (AGL-1750); every cycle, digital
2733
+ // and service ones too, is listed under the subscription in
2734
+ // Products → Subscriptions (AGL-4191), which this links to.
2592
2735
  const renewalPrice = `$${(paidCents / 100).toFixed(2)}${interval ? `/${interval}` : ''}`;
2593
2736
  void notifyHostManagers(invoiceHostId, {
2594
2737
  type: 'content.order',
2595
2738
  title: `Subscription renewed on {site} — ${renewalPrice}`,
2596
2739
  // Whose subscription, to what and where (AGL-3432).
2597
2740
  body: `${renewalEmail ? `${String(renewalEmail)}'s` : 'A'} ` + `subscription to ${snapshot.name || 'a product'} on {site} ` + `renewed for ${renewalPrice}.`,
2598
- link: `/${invoiceHostId}/products`
2741
+ link: `/${invoiceHostId}/products/subscriptions?subscription=${encodeURIComponent(subscriptionId)}`
2599
2742
  });
2600
2743
  // RFM (AGL-328): a subscriber in month 12 has paid twelve times, and
2601
2744
  // counting only the first charge ranks them as a one-purchase
@@ -2682,7 +2825,7 @@ async function findOrderForDispute(paymentIntentId) {
2682
2825
  checkoutSessionId: String(object.id)
2683
2826
  }, typeof (event == null ? void 0 : event.livemode) === 'boolean' ? {
2684
2827
  livemode: event.livemode
2685
- } : {}, {
2828
+ } : {}, directFields, {
2686
2829
  paymentIntentId: String((_ref = object == null ? void 0 : object.payment_intent) != null ? _ref : '') || null,
2687
2830
  // The regime this stay carried, on the record the merchant
2688
2831
  // reads (AGL-1969).
@@ -2967,8 +3110,24 @@ async function findOrderForDispute(paymentIntentId) {
2967
3110
  console.error('commerce cart local fulfillment unreadable', String(object.id), error);
2968
3111
  return null;
2969
3112
  });
3113
+ // Card reader hardware sold online by the platform's own store
3114
+ // (AGL-4038): marked, with the terms the buyer ticked, so it becomes
3115
+ // a hardware order once written. Nothing on any other store.
3116
+ const cartHardware = await sellerStoreOrderHardwareFields({
3117
+ hostId: String(hostId),
3118
+ lineItems,
3119
+ products: productsById,
3120
+ metadata: object == null ? void 0 : object.metadata,
3121
+ createdSeconds: object == null ? void 0 : object.created,
3122
+ orgIdOf: async ()=>{
3123
+ var _ref, _ref1;
3124
+ var _owner_org;
3125
+ const owner = await getOrgForHost(String(hostId));
3126
+ return (_ref = (_ref1 = owner == null ? void 0 : owner.orgId) != null ? _ref1 : owner == null ? void 0 : (_owner_org = owner.org) == null ? void 0 : _owner_org.id) != null ? _ref : null;
3127
+ }
3128
+ });
2970
3129
  const created = await firestore.runTransaction(async (transaction)=>{
2971
- var _counter_get, _ref, _ref1, _ref2, _ref3, _ref4, _shipping_address_line1, _shipping_address_line2, _shipping_address_city, _shipping_address_state, _shipping_address_postal_code, _shipping_address_country, _ref5, _ref6;
3130
+ var _counter_get, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
2972
3131
  var _object_metadata, _object_customer_details, _object_customer_details1;
2973
3132
  const [existing, counter] = await Promise.all([
2974
3133
  transaction.get(orderRef),
@@ -3069,24 +3228,17 @@ async function findOrderForDispute(paymentIntentId) {
3069
3228
  checkoutSessionId: String(object.id)
3070
3229
  }, typeof (event == null ? void 0 : event.livemode) === 'boolean' ? {
3071
3230
  livemode: event.livemode
3072
- } : {}, {
3231
+ } : {}, directFields, {
3073
3232
  customerName: (_ref2 = object == null ? void 0 : (_object_customer_details = object.customer_details) == null ? void 0 : _object_customer_details.name) != null ? _ref2 : null,
3074
3233
  customerEmail: (_ref3 = object == null ? void 0 : (_object_customer_details1 = object.customer_details) == null ? void 0 : _object_customer_details1.email) != null ? _ref3 : null
3075
3234
  }, (shipping == null ? void 0 : shipping.address) && (cartLocalFulfillment == null ? void 0 : cartLocalFulfillment.fields.fulfillmentMethod) !== 'pickup' ? {
3076
- shippingAddress: {
3077
- name: (_ref4 = shipping == null ? void 0 : shipping.name) != null ? _ref4 : undefined,
3078
- line1: (_shipping_address_line1 = shipping.address.line1) != null ? _shipping_address_line1 : undefined,
3079
- line2: (_shipping_address_line2 = shipping.address.line2) != null ? _shipping_address_line2 : undefined,
3080
- city: (_shipping_address_city = shipping.address.city) != null ? _shipping_address_city : undefined,
3081
- state: (_shipping_address_state = shipping.address.state) != null ? _shipping_address_state : undefined,
3082
- postalCode: (_shipping_address_postal_code = shipping.address.postal_code) != null ? _shipping_address_postal_code : undefined,
3083
- country: (_shipping_address_country = shipping.address.country) != null ? _shipping_address_country : undefined
3084
- }
3085
- } : {}, (_ref5 = cartLocalFulfillment == null ? void 0 : cartLocalFulfillment.fields) != null ? _ref5 : {}, couponCode ? {
3235
+ shippingAddress: stripeOrderAddress(shipping == null ? void 0 : shipping.name, shipping.address)
3236
+ } : {}, (_ref4 = cartLocalFulfillment == null ? void 0 : cartLocalFulfillment.fields) != null ? _ref4 : {}, couponCode ? {
3086
3237
  couponCode
3087
3238
  } : {}, {
3088
- amountCents: Number((_ref6 = object == null ? void 0 : object.amount_total) != null ? _ref6 : 0),
3089
- feeCents: Number(feeCents != null ? feeCents : 0),
3239
+ amountCents: Number((_ref5 = object == null ? void 0 : object.amount_total) != null ? _ref5 : 0),
3240
+ feeCents: Number(feeCents != null ? feeCents : 0)
3241
+ }, cartHardware, {
3090
3242
  createdAtMs: Date.now(),
3091
3243
  createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
3092
3244
  })));
@@ -3097,6 +3249,14 @@ async function findOrderForDispute(paymentIntentId) {
3097
3249
  // the non-idempotent effects below (inventory / coupon / gift-card
3098
3250
  // decrements) that would otherwise double-apply.
3099
3251
  if (!created) return;
3252
+ // Its hardware order, by the register's own recorder (AGL-4038). A
3253
+ // miss stays marked and the To attach sweep records it.
3254
+ if (cartHardware.hardwareSalePending) {
3255
+ await recordSellerStoreSaleHardware({
3256
+ hostId: String(hostId),
3257
+ orderId: String(object.id)
3258
+ });
3259
+ }
3100
3260
  const cartOrderLabel = CommerceModel.formatOrderNumber({
3101
3261
  number: cartOrderNumber
3102
3262
  }, String(object.id));
@@ -3648,7 +3808,7 @@ async function findOrderForDispute(paymentIntentId) {
3648
3808
  // What the money was for, as the alert says it (AGL-4099).
3649
3809
  let unmatchedNoun = 'quote';
3650
3810
  const flipped = await firestore.runTransaction(async (transaction)=>{
3651
- var _snapshot_data, _snapshot_data1, _snapshot_data2, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _lifted_totals, _ref6, _shipTo_name, _shipTo_address_line1, _shipTo_address_line2, _shipTo_address_city, _shipTo_address_state, _shipTo_address_postal_code, _shipTo_address_country;
3811
+ var _snapshot_data, _snapshot_data1, _snapshot_data2, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _lifted_totals, _ref6;
3652
3812
  var _object_metadata, _object_customer_details, _object_metadata1, _object_customer_details1, _lifted_totals1;
3653
3813
  const snapshot = await transaction.get(orderRef);
3654
3814
  if (!snapshot.exists) return false;
@@ -3709,7 +3869,7 @@ async function findOrderForDispute(paymentIntentId) {
3709
3869
  }
3710
3870
  const paidQuote = CommerceModel.paidQuoteOrder(raw, String(orderId), facts);
3711
3871
  paidOrder = paidQuote;
3712
- transaction.set(orderRef, _extends({}, paidQuote, {
3872
+ transaction.set(orderRef, _extends({}, paidQuote, directFields, {
3713
3873
  createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
3714
3874
  }));
3715
3875
  return true;
@@ -3811,7 +3971,8 @@ async function findOrderForDispute(paymentIntentId) {
3811
3971
  // every register card sale would stamp `none` beside an order
3812
3972
  // plainly carrying tax.
3813
3973
  taxMode: storefrontTaxModeOf(object, Number((_ref2 = object == null ? void 0 : (_object_metadata1 = object.metadata) == null ? void 0 : _object_metadata1.taxCents) != null ? _ref2 : 0)),
3814
- 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, {
3815
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,
3816
3977
  timeline: CommerceModel.appendOrderEvent(lifted, 'paid'),
3817
3978
  // A paid draft is new to a shipping tool's feed (AGL-3613).
@@ -3828,15 +3989,7 @@ async function findOrderForDispute(paymentIntentId) {
3828
3989
  totalCents: Number.isFinite(chargedTotalCents) ? chargedTotalCents : Number((_ref6 = (_lifted_totals1 = lifted.totals) == null ? void 0 : _lifted_totals1.totalCents) != null ? _ref6 : 0) + shippingCents
3829
3990
  })
3830
3991
  } : {}, (shipTo == null ? void 0 : shipTo.address) ? {
3831
- shippingAddress: {
3832
- name: (_shipTo_name = shipTo.name) != null ? _shipTo_name : undefined,
3833
- line1: (_shipTo_address_line1 = shipTo.address.line1) != null ? _shipTo_address_line1 : undefined,
3834
- line2: (_shipTo_address_line2 = shipTo.address.line2) != null ? _shipTo_address_line2 : undefined,
3835
- city: (_shipTo_address_city = shipTo.address.city) != null ? _shipTo_address_city : undefined,
3836
- state: (_shipTo_address_state = shipTo.address.state) != null ? _shipTo_address_state : undefined,
3837
- postalCode: (_shipTo_address_postal_code = shipTo.address.postal_code) != null ? _shipTo_address_postal_code : undefined,
3838
- country: (_shipTo_address_country = shipTo.address.country) != null ? _shipTo_address_country : undefined
3839
- }
3992
+ shippingAddress: stripeOrderAddress(shipTo.name, shipTo.address)
3840
3993
  } : {}), {
3841
3994
  merge: true
3842
3995
  });
@@ -4151,8 +4304,30 @@ async function findOrderForDispute(paymentIntentId) {
4151
4304
  console.error('commerce buy-now local fulfillment unreadable', String(object.id), error);
4152
4305
  return null;
4153
4306
  });
4307
+ // Card reader hardware sold online by the platform's own store
4308
+ // (AGL-4038), as the cart branch marks it.
4309
+ const buyNowHardware = await sellerStoreOrderHardwareFields({
4310
+ hostId: String(hostId),
4311
+ lineItems: buyNowLineItems.map((line)=>_extends({}, line, {
4312
+ productId: String(productId)
4313
+ })),
4314
+ products: new Map([
4315
+ [
4316
+ String(productId),
4317
+ liftedForSnapshot
4318
+ ]
4319
+ ]),
4320
+ metadata: object == null ? void 0 : object.metadata,
4321
+ createdSeconds: object == null ? void 0 : object.created,
4322
+ orgIdOf: async ()=>{
4323
+ var _ref, _ref1;
4324
+ var _owner_org;
4325
+ const owner = await getOrgForHost(String(hostId));
4326
+ return (_ref = (_ref1 = owner == null ? void 0 : owner.orgId) != null ? _ref1 : owner == null ? void 0 : (_owner_org = owner.org) == null ? void 0 : _owner_org.id) != null ? _ref : null;
4327
+ }
4328
+ });
4154
4329
  const created = await firestore.runTransaction(async (transaction)=>{
4155
- var _counter_get, _ref, _ref1, _ref2, _object_shipping_details_name, _object_shipping_details_address_line1, _object_shipping_details_address_line2, _object_shipping_details_address_city, _object_shipping_details_address_state, _object_shipping_details_address_postal_code, _object_shipping_details_address_country, _ref3, _ref4;
4330
+ var _counter_get, _ref, _ref1, _ref2, _ref3, _ref4;
4156
4331
  var _object_metadata, _object_customer_details, _object_shipping_details, _object_customer_details1;
4157
4332
  const [existing, counter] = await Promise.all([
4158
4333
  transaction.get(orderRef),
@@ -4190,18 +4365,10 @@ async function findOrderForDispute(paymentIntentId) {
4190
4365
  checkoutSessionId: String(object.id)
4191
4366
  }, typeof (event == null ? void 0 : event.livemode) === 'boolean' ? {
4192
4367
  livemode: event.livemode
4193
- } : {}, {
4368
+ } : {}, directFields, {
4194
4369
  customerName: (_ref2 = object == null ? void 0 : (_object_customer_details = object.customer_details) == null ? void 0 : _object_customer_details.name) != null ? _ref2 : null
4195
4370
  }, (object == null ? void 0 : (_object_shipping_details = object.shipping_details) == null ? void 0 : _object_shipping_details.address) ? {
4196
- shippingAddress: {
4197
- name: (_object_shipping_details_name = object.shipping_details.name) != null ? _object_shipping_details_name : undefined,
4198
- line1: (_object_shipping_details_address_line1 = object.shipping_details.address.line1) != null ? _object_shipping_details_address_line1 : undefined,
4199
- line2: (_object_shipping_details_address_line2 = object.shipping_details.address.line2) != null ? _object_shipping_details_address_line2 : undefined,
4200
- city: (_object_shipping_details_address_city = object.shipping_details.address.city) != null ? _object_shipping_details_address_city : undefined,
4201
- state: (_object_shipping_details_address_state = object.shipping_details.address.state) != null ? _object_shipping_details_address_state : undefined,
4202
- postalCode: (_object_shipping_details_address_postal_code = object.shipping_details.address.postal_code) != null ? _object_shipping_details_address_postal_code : undefined,
4203
- country: (_object_shipping_details_address_country = object.shipping_details.address.country) != null ? _object_shipping_details_address_country : undefined
4204
- }
4371
+ shippingAddress: stripeOrderAddress(object.shipping_details.name, object.shipping_details.address)
4205
4372
  } : {}, (_ref3 = buyNowLocalFulfillment == null ? void 0 : buyNowLocalFulfillment.fields) != null ? _ref3 : {}, {
4206
4373
  createdAtMs: Date.now(),
4207
4374
  // Legacy Commerce Starter fields (AGL-90).
@@ -4211,7 +4378,7 @@ async function findOrderForDispute(paymentIntentId) {
4211
4378
  customerEmail: (_ref4 = object == null ? void 0 : (_object_customer_details1 = object.customer_details) == null ? void 0 : _object_customer_details1.email) != null ? _ref4 : null
4212
4379
  }, couponCode ? {
4213
4380
  couponCode
4214
- } : {}, {
4381
+ } : {}, buyNowHardware, {
4215
4382
  createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
4216
4383
  })));
4217
4384
  return true;
@@ -4219,6 +4386,13 @@ async function findOrderForDispute(paymentIntentId) {
4219
4386
  // Redelivery guard (AGL-498): skip the notification + fulfilment side
4220
4387
  // effects when this order already existed.
4221
4388
  if (!created) return;
4389
+ // Its hardware order, by the register's own recorder (AGL-4038).
4390
+ if (buyNowHardware.hardwareSalePending) {
4391
+ await recordSellerStoreSaleHardware({
4392
+ hostId: String(hostId),
4393
+ orderId: String(object.id)
4394
+ });
4395
+ }
4222
4396
  const buyNowOrderLabel = CommerceModel.formatOrderNumber({
4223
4397
  number: buyNowOrderNumber
4224
4398
  }, String(object.id));
@@ -4581,6 +4755,8 @@ async function findOrderForDispute(paymentIntentId) {
4581
4755
  };
4582
4756
  if (lookup.kind !== 'order') return;
4583
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;
4584
4760
  const hostId = String((_ref93 = (_snapshot_ref_parent_parent = snapshot.ref.parent.parent) == null ? void 0 : _snapshot_ref_parent_parent.id) != null ? _ref93 : '');
4585
4761
  const external = await recordExternalRefund(snapshot.ref, object);
4586
4762
  if (external && hostId) {
@@ -4651,6 +4827,7 @@ async function findOrderForDispute(paymentIntentId) {
4651
4827
  };
4652
4828
  if (lookup.kind !== 'order') return;
4653
4829
  const snapshot = lookup.snapshot;
4830
+ if (!connectEventOrderIsDirect(event, snapshot)) return;
4654
4831
  const hostId = String((_ref97 = (_snapshot_ref_parent_parent1 = snapshot.ref.parent.parent) == null ? void 0 : _snapshot_ref_parent_parent1.id) != null ? _ref97 : '');
4655
4832
  const order = CommerceModel.liftLegacyOrder((_snapshot_data1 = snapshot.data()) != null ? _snapshot_data1 : {});
4656
4833
  const orderCents = Number((_ref98 = (_ref99 = (_order_totals2 = order.totals) == null ? void 0 : _order_totals2.totalCents) != null ? _ref99 : order.amountCents) != null ? _ref98 : 0);
@@ -4720,9 +4897,14 @@ async function findOrderForDispute(paymentIntentId) {
4720
4897
  var _snapshot_ref_parent_parent2;
4721
4898
  const dispute = object != null ? object : {};
4722
4899
  const paymentIntentId = String((_dispute_payment_intent = dispute.payment_intent) != null ? _dispute_payment_intent : '');
4723
- const lookup = paymentIntentId ? await findOrderForDispute(paymentIntentId) : {
4900
+ const found = paymentIntentId ? await findOrderForDispute(paymentIntentId) : {
4724
4901
  kind: 'not-ours'
4725
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;
4726
4908
  // UNRESOLVED IS NOT NOT-OURS (AGL-2161). A lookup that could not run is
4727
4909
  // the platform's problem and is reported; a lookup that ran and matched
4728
4910
  // nothing is a marketplace, booking or platform-billing dispute, and
@@ -4745,6 +4927,11 @@ async function findOrderForDispute(paymentIntentId) {
4745
4927
  var _ref101;
4746
4928
  var _snapshot_ref_parent_parent3;
4747
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';
4748
4935
  if (type === 'charge.dispute.created') {
4749
4936
  var _snapshot_data2;
4750
4937
  // A chargeback's gift cards are frozen while it is open (AGL-3363).
@@ -4809,7 +4996,7 @@ async function findOrderForDispute(paymentIntentId) {
4809
4996
  await notifyHostManagers(hostId, {
4810
4997
  type: 'content.order',
4811
4998
  title: settled.lost ? `Chargeback lost — order ${disputedOrderLabel}` : 'Chargeback resolved in your favor',
4812
- 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.',
4813
5000
  link: `/${hostId}/products/orders`
4814
5001
  });
4815
5002
  // The customer's side of the ledger (AGL-1754), through the same
@@ -4861,7 +5048,10 @@ async function findOrderForDispute(paymentIntentId) {
4861
5048
  // transiently-failed reversal gets its retry — and gated inside on
4862
5049
  // the order's own `reversedTransferCents` marker, so it runs at most
4863
5050
  // once per dispute however many times Stripe delivers.
4864
- 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) {
4865
5055
  const pulledBackCents = await reverseSellerShare(snapshot.ref, dispute);
4866
5056
  // The merchant-experience half of the AGL-1794 decision, and not an
4867
5057
  // optional extra: the reversal takes money out of the connected