@aglyn/plugins-commerce 1.15.2 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/README.md +1 -1
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +2 -1
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js +6 -1
  6. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  7. package/src/lib/components/console/pos/pos-api.d.ts +5 -0
  8. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  9. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
  10. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
  11. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  12. package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
  13. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  14. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  15. package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
  16. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  17. package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
  18. package/src/lib/components/console/product-builder-fields.component.js +195 -0
  19. package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
  20. package/src/lib/components/console/product-editor-dialog.component.js +35 -2
  21. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  22. package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
  23. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  24. package/src/lib/components/console/quote-messages.component.d.ts +21 -0
  25. package/src/lib/components/console/quote-messages.component.js +185 -0
  26. package/src/lib/components/console/quote-messages.component.js.map +1 -0
  27. package/src/lib/components/console/quote-pay-link.component.js +1 -1
  28. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  29. package/src/lib/components/console/quote-proofs.component.js +30 -3
  30. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  31. package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
  32. package/src/lib/components/console/quote-settings-card.component.js +154 -24
  33. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  34. package/src/lib/components/product-builder-context.d.ts +22 -0
  35. package/src/lib/components/product-builder-context.js +21 -0
  36. package/src/lib/components/product-builder-context.js.map +1 -0
  37. package/src/lib/components/product-builder-mockup.d.ts +42 -0
  38. package/src/lib/components/product-builder-mockup.js +120 -0
  39. package/src/lib/components/product-builder-mockup.js.map +1 -0
  40. package/src/lib/components/product-builder-sample.d.ts +63 -0
  41. package/src/lib/components/product-builder-sample.js +96 -0
  42. package/src/lib/components/product-builder-sample.js.map +1 -0
  43. package/src/lib/components/product-choice-cards.d.ts +51 -0
  44. package/src/lib/components/product-choice-cards.js +311 -0
  45. package/src/lib/components/product-choice-cards.js.map +1 -0
  46. package/src/lib/components/product-detail-panels.d.ts +42 -0
  47. package/src/lib/components/product-detail-panels.js +185 -0
  48. package/src/lib/components/product-detail-panels.js.map +1 -0
  49. package/src/lib/components/product-detail.d.ts +20 -12
  50. package/src/lib/components/product-detail.js +136 -221
  51. package/src/lib/components/product-detail.js.map +1 -1
  52. package/src/lib/components/product-grid.d.ts +7 -0
  53. package/src/lib/components/product-grid.js +11 -8
  54. package/src/lib/components/product-grid.js.map +1 -1
  55. package/src/lib/components/product-options-field-body.d.ts +9 -8
  56. package/src/lib/components/product-options-field-body.js +152 -3
  57. package/src/lib/components/product-options-field-body.js.map +1 -1
  58. package/src/lib/components/product-options-field.js +1 -1
  59. package/src/lib/components/product-options-field.js.map +1 -1
  60. package/src/lib/components/product-photo-fit.d.ts +49 -0
  61. package/src/lib/components/product-photo-fit.js +58 -0
  62. package/src/lib/components/product-photo-fit.js.map +1 -0
  63. package/src/lib/components/product-restock-notify.d.ts +12 -0
  64. package/src/lib/components/product-restock-notify.js +86 -0
  65. package/src/lib/components/product-restock-notify.js.map +1 -0
  66. package/src/lib/components/quote-messages-panel.d.ts +21 -0
  67. package/src/lib/components/quote-messages-panel.js +191 -0
  68. package/src/lib/components/quote-messages-panel.js.map +1 -0
  69. package/src/lib/components/quote-page-body.js +15 -1
  70. package/src/lib/components/quote-page-body.js.map +1 -1
  71. package/src/lib/components/quote-proof-panel.d.ts +6 -3
  72. package/src/lib/components/quote-proof-panel.js +139 -14
  73. package/src/lib/components/quote-proof-panel.js.map +1 -1
  74. package/src/lib/components/related-products.d.ts +7 -0
  75. package/src/lib/components/related-products.js +8 -6
  76. package/src/lib/components/related-products.js.map +1 -1
  77. package/src/lib/constants/quote-page.d.ts +8 -0
  78. package/src/lib/constants/quote-page.js +11 -0
  79. package/src/lib/constants/quote-page.js.map +1 -1
  80. package/src/lib/model/commerce-cart.d.ts +6 -1
  81. package/src/lib/model/commerce-cart.js +5 -1
  82. package/src/lib/model/commerce-cart.js.map +1 -1
  83. package/src/lib/model/commerce-invoices.js +5 -1
  84. package/src/lib/model/commerce-invoices.js.map +1 -1
  85. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  86. package/src/lib/model/commerce-pos-ops.js +3 -0
  87. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  88. package/src/lib/model/commerce-pos.d.ts +8 -0
  89. package/src/lib/model/commerce-pos.js.map +1 -1
  90. package/src/lib/model/commerce-quote-messages.d.ts +106 -0
  91. package/src/lib/model/commerce-quote-messages.js +146 -0
  92. package/src/lib/model/commerce-quote-messages.js.map +1 -0
  93. package/src/lib/model/commerce-quote-pay.d.ts +31 -2
  94. package/src/lib/model/commerce-quote-pay.js +31 -7
  95. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  96. package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
  97. package/src/lib/model/commerce-quote-proofs.js +73 -18
  98. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  99. package/src/lib/model/commerce-quote-request.d.ts +14 -4
  100. package/src/lib/model/commerce-quote-request.js +25 -2
  101. package/src/lib/model/commerce-quote-request.js.map +1 -1
  102. package/src/lib/model/commerce-quotes.d.ts +56 -3
  103. package/src/lib/model/commerce-quotes.js +47 -2
  104. package/src/lib/model/commerce-quotes.js.map +1 -1
  105. package/src/lib/model/commerce.d.ts +12 -1
  106. package/src/lib/model/commerce.js.map +1 -1
  107. package/src/lib/model/index.d.ts +1 -0
  108. package/src/lib/model/index.js +1 -0
  109. package/src/lib/model/index.js.map +1 -1
  110. package/src/lib/model/pos-cellular.d.ts +5 -0
  111. package/src/lib/model/pos-cellular.js.map +1 -1
  112. package/src/lib/model/product-card-rules.d.ts +41 -0
  113. package/src/lib/model/product-card-rules.js +90 -0
  114. package/src/lib/model/product-card-rules.js.map +1 -0
  115. package/src/lib/model/product-modifiers.d.ts +11 -0
  116. package/src/lib/model/product-modifiers.js +10 -0
  117. package/src/lib/model/product-modifiers.js.map +1 -1
  118. package/src/lib/model/product-write.d.ts +3 -0
  119. package/src/lib/server/billing-webhook.js +6 -2
  120. package/src/lib/server/billing-webhook.js.map +1 -1
  121. package/src/lib/server/cancel-order.js +15 -0
  122. package/src/lib/server/cancel-order.js.map +1 -1
  123. package/src/lib/server/channel-order-updates.js +15 -1
  124. package/src/lib/server/channel-order-updates.js.map +1 -1
  125. package/src/lib/server/channel-orders.js +20 -0
  126. package/src/lib/server/channel-orders.js.map +1 -1
  127. package/src/lib/server/checkout.js +1 -1
  128. package/src/lib/server/checkout.js.map +1 -1
  129. package/src/lib/server/local-fulfillment.js +1 -1
  130. package/src/lib/server/local-fulfillment.js.map +1 -1
  131. package/src/lib/server/pos-cellular-billing.d.ts +1 -1
  132. package/src/lib/server/pos-cellular-billing.js +2 -1
  133. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  134. package/src/lib/server/pos-cellular.d.ts +3 -1
  135. package/src/lib/server/pos-cellular.js +15 -8
  136. package/src/lib/server/pos-cellular.js.map +1 -1
  137. package/src/lib/server/pos-offline-sync.d.ts +3 -3
  138. package/src/lib/server/pos-offline-sync.js +17 -4
  139. package/src/lib/server/pos-offline-sync.js.map +1 -1
  140. package/src/lib/server/pos-order.js +17 -6
  141. package/src/lib/server/pos-order.js.map +1 -1
  142. package/src/lib/server/pos-payment.js +27 -11
  143. package/src/lib/server/pos-payment.js.map +1 -1
  144. package/src/lib/server/pos-reader-splash.js +10 -5
  145. package/src/lib/server/pos-reader-splash.js.map +1 -1
  146. package/src/lib/server/pos-readers.js +34 -10
  147. package/src/lib/server/pos-readers.js.map +1 -1
  148. package/src/lib/server/pos-return.js +19 -3
  149. package/src/lib/server/pos-return.js.map +1 -1
  150. package/src/lib/server/pos-stripe.d.ts +14 -0
  151. package/src/lib/server/pos-stripe.js +6 -2
  152. package/src/lib/server/pos-stripe.js.map +1 -1
  153. package/src/lib/server/pos-terminal-connection-token.js +23 -9
  154. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  155. package/src/lib/server/pos-terminal.d.ts +80 -14
  156. package/src/lib/server/pos-terminal.js +393 -123
  157. package/src/lib/server/pos-terminal.js.map +1 -1
  158. package/src/lib/server/product-drafts.d.ts +1 -1
  159. package/src/lib/server/product-drafts.js +4 -3
  160. package/src/lib/server/product-drafts.js.map +1 -1
  161. package/src/lib/server/product-writer.js +5 -4
  162. package/src/lib/server/product-writer.js.map +1 -1
  163. package/src/lib/server/product.d.ts +11 -0
  164. package/src/lib/server/product.js +18 -3
  165. package/src/lib/server/product.js.map +1 -1
  166. package/src/lib/server/products-write.js +4 -3
  167. package/src/lib/server/products-write.js.map +1 -1
  168. package/src/lib/server/quote-email.d.ts +26 -0
  169. package/src/lib/server/quote-email.js +73 -7
  170. package/src/lib/server/quote-email.js.map +1 -1
  171. package/src/lib/server/quote-messages.d.ts +72 -0
  172. package/src/lib/server/quote-messages.js +356 -0
  173. package/src/lib/server/quote-messages.js.map +1 -0
  174. package/src/lib/server/quote-pay.d.ts +42 -0
  175. package/src/lib/server/quote-pay.js +81 -4
  176. package/src/lib/server/quote-pay.js.map +1 -1
  177. package/src/lib/server/quote-proofs.d.ts +1 -1
  178. package/src/lib/server/quote-proofs.js +63 -19
  179. package/src/lib/server/quote-proofs.js.map +1 -1
  180. package/src/lib/server/quote.d.ts +12 -0
  181. package/src/lib/server/quote.js +44 -14
  182. package/src/lib/server/quote.js.map +1 -1
  183. package/src/lib/server/refund.js +3 -1
  184. package/src/lib/server/refund.js.map +1 -1
  185. package/src/lib/server/reserve-stock.js +9 -0
  186. package/src/lib/server/reserve-stock.js.map +1 -1
  187. package/src/lib/server/returns.js +15 -1
  188. package/src/lib/server/returns.js.map +1 -1
  189. package/src/lib/server/reviews.js +15 -0
  190. package/src/lib/server/reviews.js.map +1 -1
  191. package/src/lib/server/sold-out-drop.d.ts +58 -0
  192. package/src/lib/server/sold-out-drop.js +81 -0
  193. package/src/lib/server/sold-out-drop.js.map +1 -0
  194. package/src/lib/server/stock-levels.js +9 -0
  195. package/src/lib/server/stock-levels.js.map +1 -1
  196. package/src/lib/server/stripe-refund.d.ts +7 -0
  197. package/src/lib/server/stripe-refund.js +26 -7
  198. package/src/lib/server/stripe-refund.js.map +1 -1
  199. package/src/lib/server.js +2 -0
  200. package/src/lib/server.js.map +1 -1
  201. package/src/lib/tenant-emails.js +85 -2
  202. package/src/lib/tenant-emails.js.map +1 -1
  203. package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
  204. package/src/lib/testing/fake-seller-payment-account.js +40 -0
  205. package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
  206. package/src/lib/transfer/product-transfer.js +6 -5
  207. package/src/lib/transfer/product-transfer.js.map +1 -1
  208. package/src/lib/transfer/products.server.js +4 -3
  209. package/src/lib/transfer/products.server.js.map +1 -1
  210. package/src/lib/utils/quote-email-content.d.ts +6 -0
  211. package/src/lib/utils/quote-email-content.js +6 -3
  212. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -17,6 +17,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  */ import { createHash } from "node:crypto";
18
18
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
19
19
  import { merchantAccountIsReady } from "@aglyn/tenant-data-admin/server/payment-provider";
20
+ import { sellerPaymentAccount } from "@aglyn/tenant-data-admin/server/seller-payment-account";
20
21
  import { cardAuthenticationParams, checkoutSessionCardAuthenticationParams } from "@aglyn/tenant-data-admin/server/stripe-card-authentication";
21
22
  import * as CommerceModel from "../model/index.js";
22
23
  import { POS_CURRENCY, posCardApplicationFeeCents, posStripe, posStripeErrorMessage, posStripeTestMode, posTerminalAvailable } from "./pos-stripe.js";
@@ -26,12 +27,27 @@ import { applyPosPayment, readPosSale } from "./pos-sale.js";
26
27
  *
27
28
  * ## Where the readers live
28
29
  *
29
- * Every register charge is a DESTINATION charge on the platform account, so
30
- * Stripe's rule for that model applies: Locations and Readers are created on
31
- * the PLATFORM with the platform key, and identify their merchant by
32
- * metadata. One Location per site (`hosts/{hostId}/terminal/config`), and one
30
+ * Two shapes, decided by the store's selling account
31
+ * ({@link posMerchantAccount}, which asks `sellerPaymentAccount`):
32
+ *
33
+ * - DESTINATION (every Express account, so every store before the switch):
34
+ * the charge is made on the PLATFORM account and transferred on, so
35
+ * Stripe's rule for that model applies: Locations and Readers are created
36
+ * on the platform with the platform key, and identify their merchant by
37
+ * metadata.
38
+ * - DIRECT (a store on its own full Stripe account, ToS v24 section
39
+ * 10.2(a)): EVERY Terminal object, the Location, its Configuration, the
40
+ * Readers, each connection token and each PaymentIntent, is made ON the
41
+ * store's account with the `Stripe-Account` header. A connection token
42
+ * sees only its own account's readers and locations, so nothing may mix.
43
+ *
44
+ * One Location per site (`hosts/{hostId}/terminal/config`), and one
33
45
  * `hosts/{hostId}/terminalReaders/{readerId}` document per reader, written
34
- * only here. The document is what makes a reader THIS site's: every call that
46
+ * only here. Each records the account it was made on
47
+ * (`stripeLocationAccount`, `stripeAccount`; absent = the platform), and an
48
+ * id made on another account than the store sells on now is never used: a
49
+ * Location is made again on the store's account, and a reader must be
50
+ * registered again. The reader document is what makes a reader THIS site's: every call that
35
51
  * names a reader reads it under the caller's own site first, so one store can
36
52
  * never drive, rename or remove another's reader, and the reader's own
37
53
  * `metadata.hostId` is checked again before a payment is sent to it.
@@ -65,23 +81,71 @@ import { applyPosPayment, readPosSale } from "./pos-sale.js";
65
81
  delete next.failureMessage;
66
82
  return next;
67
83
  }
68
- /** The merchant's connected account, when it can take card payments now. */ export async function posMerchantAccount(hostId, org) {
69
- var _ref;
70
- const ownerUid = String((_ref = org == null ? void 0 : org['ownerUid']) != null ? _ref : '');
71
- if (!ownerUid) return null;
72
- const profile = await firebaseAdmin.app().firestore().collection('profiles').doc(ownerUid).get();
73
- const accountId = profile.get('stripeAccountId');
84
+ /**
85
+ * The merchant's connected account and its charge model, when it can take
86
+ * card payments now. The ONE door every in-person card route reads the
87
+ * store's account through; where the account is recorded is
88
+ * `sellerPaymentAccount`'s business, not this file's.
89
+ */ export async function posMerchantAccount(hostId, org) {
90
+ const seller = await sellerPaymentAccount(hostId, org);
91
+ if (!seller) return null;
74
92
  if (!merchantAccountIsReady({
75
- accountId,
76
- chargesEnabled: profile.get('stripeChargesEnabled'),
77
- accountLivemode: profile.get('stripeAccountLivemode')
93
+ accountId: seller.accountId,
94
+ chargesEnabled: seller.chargesEnabled,
95
+ accountLivemode: seller.accountLivemode
78
96
  }, {
79
97
  subject: `POS card payment host ${hostId}`
80
98
  })) {
81
99
  return null;
82
100
  }
83
- return String(accountId);
101
+ return {
102
+ accountId: seller.accountId,
103
+ chargeModel: seller.chargeModel
104
+ };
105
+ }
106
+ /**
107
+ * The account the site's Terminal objects belong on NOW: the store's own for
108
+ * a direct-charge store, null (the platform) for every other. Not gated on
109
+ * readiness: a Location or a reader belongs where the store will sell.
110
+ */ export async function posTerminalAccount(hostId, org) {
111
+ const seller = await sellerPaymentAccount(hostId, org);
112
+ return (seller == null ? void 0 : seller.chargeModel) === 'direct' ? seller.accountId : null;
84
113
  }
114
+ /** The account a stored Terminal id was made on; null for the platform. */ function recordedAccount(value) {
115
+ const id = typeof value === 'string' ? value.trim() : '';
116
+ return id || null;
117
+ }
118
+ /** The account a card payment's Stripe objects live on; null for the platform. */ export function posPaymentAccount(payment) {
119
+ return payment.chargeModel === 'direct' ? recordedAccount(payment.stripeAccountId) : null;
120
+ }
121
+ /** The account a reader is registered on; null for the platform. */ export function posReaderAccount(reader) {
122
+ return recordedAccount(reader.stripeAccount);
123
+ }
124
+ /** What a cashier reads when a reader sits on another account than the store sells on. */ export const POS_READER_ON_OTHER_ACCOUNT = 'This card reader was set up before the store started taking payments on its own Stripe account. Remove it in Registers and devices, then add it again with the new code it shows.';
125
+ /**
126
+ * The site's Location, when it was made on `account` (null: the platform).
127
+ * A Location made on another account is no Location for this one.
128
+ */ function locationOnAccount(config, account) {
129
+ var _config_get;
130
+ const locationId = String((_config_get = config.get('stripeLocationId')) != null ? _config_get : '');
131
+ if (!locationId) return null;
132
+ return recordedAccount(config.get('stripeLocationAccount')) === account ? locationId : null;
133
+ }
134
+ /**
135
+ * Everything on the site's terminal document that describes the Location's
136
+ * ONE Configuration. Cleared when the Location is made again on another
137
+ * account, so tipping, offline mode, the start-up screen and 4G are written
138
+ * onto a configuration on the new account rather than answered from flags
139
+ * that describe the old one.
140
+ */ const LOCATION_BOUND_FIELDS = [
141
+ 'stripeConfigurationId',
142
+ 'stripeConfigurationAssigned',
143
+ 'tippingKey',
144
+ 'offlineEnabled',
145
+ 'offlineConfigurationId',
146
+ 'splashAppliedKey',
147
+ 'splashAppliedAtMs'
148
+ ];
85
149
  function terminalConfigRef(hostId) {
86
150
  return firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('terminal').doc('config');
87
151
  }
@@ -124,29 +188,68 @@ export function posTerminalAddressProblem(address) {
124
188
  ])).digest('hex').slice(0, 16);
125
189
  return `pos-location:${hostId}:${fingerprint}`;
126
190
  }
191
+ /** A Location's address as Stripe returns it, in the console's shape. */ function locationAddressOf(location) {
192
+ const address = location == null ? void 0 : location.address;
193
+ if (!address || typeof address !== 'object') return undefined;
194
+ const text = (value)=>typeof value === 'string' ? value : '';
195
+ return _extends({
196
+ line1: text(address.line1)
197
+ }, text(address.line2) ? {
198
+ line2: text(address.line2)
199
+ } : {}, {
200
+ city: text(address.city)
201
+ }, text(address.state) ? {
202
+ state: text(address.state)
203
+ } : {}, {
204
+ postalCode: text(address.postal_code),
205
+ country: text(address.country)
206
+ });
207
+ }
127
208
  /**
128
- * The site's Terminal Location, created on first use (on the PLATFORM, with
129
- * the merchant named in metadata). Its address is the store's, because Stripe
130
- * uses it to configure the reader for the right country.
209
+ * The site's Terminal Location, created on first use, on the account the
210
+ * store sells on ({@link posTerminalAccount}): the PLATFORM for a destination
211
+ * store, with the merchant named in metadata, or the store's OWN account for
212
+ * a direct-charge store. Its address is the store's, because Stripe uses it
213
+ * to configure the reader for the right country.
214
+ *
215
+ * A Location recorded on another account (a store that sold through the
216
+ * platform before it moved to its own account) is made again on the store's
217
+ * account, at the address given or else the old Location's own, and the
218
+ * configuration it carried is set up again there.
131
219
  */ export async function ensurePosTerminalLocation(options) {
132
220
  var _existing_get;
133
221
  var _created_body;
222
+ const account = options.account !== undefined ? options.account : await posTerminalAccount(options.hostId);
134
223
  const ref = terminalConfigRef(options.hostId);
135
224
  const existing = await ref.get();
136
225
  const known = String((_existing_get = existing.get('stripeLocationId')) != null ? _existing_get : '');
137
- if (known) return {
226
+ const knownAccount = recordedAccount(existing.get('stripeLocationAccount'));
227
+ if (known && knownAccount === account) return {
138
228
  ok: true,
139
229
  locationId: known
140
230
  };
141
- const problem = posTerminalAddressProblem(options.address);
231
+ let addressGiven = options.address;
232
+ if (known && !addressGiven) {
233
+ const previous = await posStripe('GET', `terminal/locations/${known}`, {
234
+ stripeAccount: knownAccount
235
+ });
236
+ if (previous.ok) addressGiven = locationAddressOf(previous.body);
237
+ }
238
+ const problem = posTerminalAddressProblem(addressGiven);
142
239
  if (problem) return {
143
240
  ok: false,
144
241
  status: 400,
145
242
  error: problem
146
243
  };
147
- const address = options.address;
148
- const created = await posStripe('POST', 'terminal/locations', {
149
- idempotencyKey: posTerminalLocationKey(options.hostId, options.displayName, address),
244
+ const address = addressGiven;
245
+ const locationKey = posTerminalLocationKey(options.hostId, options.displayName, address);
246
+ const created = await posStripe('POST', 'terminal/locations', _extends({
247
+ // A direct store's key names its account: the same address once made on
248
+ // the platform must never replay the platform's Location.
249
+ idempotencyKey: account ? `${locationKey}:${account}` : locationKey
250
+ }, account ? {
251
+ stripeAccount: account
252
+ } : {}, {
150
253
  params: {
151
254
  display_name: options.displayName.slice(0, 100) || 'Store',
152
255
  'address[line1]': address.line1,
@@ -158,7 +261,7 @@ export function posTerminalAddressProblem(address) {
158
261
  'metadata[orgId]': options.orgId,
159
262
  'metadata[hostId]': options.hostId
160
263
  }
161
- });
264
+ }));
162
265
  if (!created.ok || !((_created_body = created.body) == null ? void 0 : _created_body.id)) {
163
266
  return {
164
267
  ok: false,
@@ -166,13 +269,47 @@ export function posTerminalAddressProblem(address) {
166
269
  error: posStripeErrorMessage(created.body, 'The reader location could not be set up.')
167
270
  };
168
271
  }
169
- await ref.set({
272
+ const replaced = Boolean(known);
273
+ await ref.set(_extends({
170
274
  stripeLocationId: String(created.body.id),
171
275
  livemode: Boolean(created.body.livemode),
172
276
  createdAtMs: Date.now()
173
- }, {
277
+ }, account ? {
278
+ stripeLocationAccount: account
279
+ } : {}, replaced ? _extends({}, account ? {} : {
280
+ stripeLocationAccount: firebaseAdmin.firestore.FieldValue.delete()
281
+ }, Object.fromEntries(LOCATION_BOUND_FIELDS.map((field)=>[
282
+ field,
283
+ firebaseAdmin.firestore.FieldValue.delete()
284
+ ])), {
285
+ replacedLocation: {
286
+ id: known,
287
+ account: knownAccount != null ? knownAccount : 'platform',
288
+ atMs: Date.now()
289
+ }
290
+ }) : {}), {
174
291
  merge: true
175
292
  });
293
+ // 4G was on for the old Location's readers: it is turned on again on the
294
+ // new one's configuration, so readers registered there keep it (AGL-4038).
295
+ if (replaced && existing.get('cellularEnabled') === true) {
296
+ const saved = await savePosReaderConfiguration(options.hostId, {
297
+ 'cellular[enabled]': true
298
+ }, 'cellular-on');
299
+ if ('error' in saved) {
300
+ console.error('[pos-terminal] 4G not turned on for the new location', options.hostId, saved.error);
301
+ } else {
302
+ await ref.set({
303
+ cellularConfigurationId: saved.configurationId
304
+ }, {
305
+ merge: true
306
+ });
307
+ await import("./pos-cellular.js").then((cellular)=>cellular.syncPosCellularReaders({
308
+ hostId: options.hostId,
309
+ orgId: options.orgId
310
+ })).catch((error)=>console.error('[pos-terminal] 4G records not moved', options.hostId, error));
311
+ }
312
+ }
176
313
  // A new Location starts with the store's reader start-up screen (AGL-4048).
177
314
  // Never fatal, and loaded only here: it draws images.
178
315
  await import("./pos-reader-splash.js").then((splash)=>splash.applyPosReaderSplash(options.hostId)).catch((error)=>console.error('[pos-terminal] start-up screen not applied', options.hostId, error));
@@ -211,13 +348,19 @@ export function posTerminalAddressProblem(address) {
211
348
  ok: false,
212
349
  error: 'no-location'
213
350
  };
351
+ // The configuration lives where its Location does: the store's own account
352
+ // for a direct-charge store's Location, the platform otherwise.
353
+ const account = recordedAccount(config.get('stripeLocationAccount'));
354
+ const onAccount = account ? {
355
+ stripeAccount: account
356
+ } : {};
214
357
  const known = String((_config_get1 = config.get('stripeConfigurationId')) != null ? _config_get1 : '');
215
358
  if (known) {
216
359
  var _ref;
217
360
  var _updated_body_error, _updated_body;
218
- const updated = await posStripe('POST', `terminal/configurations/${known}`, {
361
+ const updated = await posStripe('POST', `terminal/configurations/${known}`, _extends({
219
362
  params
220
- });
363
+ }, onAccount));
221
364
  if (!updated.ok) return {
222
365
  ok: false,
223
366
  error: String((_ref = (_updated_body = updated.body) == null ? void 0 : (_updated_body_error = _updated_body.error) == null ? void 0 : _updated_body_error.code) != null ? _ref : updated.status)
@@ -225,7 +368,7 @@ export function posTerminalAddressProblem(address) {
225
368
  // A configuration recorded before AGL-4048 was only ever recorded once
226
369
  // it was assigned, so only an explicit `false` still owes the assignment.
227
370
  if (config.get('stripeConfigurationAssigned') === false) {
228
- const assigned = await assignPosReaderConfiguration(hostId, locationId, known);
371
+ const assigned = await assignPosReaderConfiguration(hostId, locationId, known, account);
229
372
  if (!assigned) return {
230
373
  ok: false,
231
374
  error: 'assignment'
@@ -236,10 +379,10 @@ export function posTerminalAddressProblem(address) {
236
379
  configurationId: known
237
380
  };
238
381
  }
239
- const created = await posStripe('POST', 'terminal/configurations', {
382
+ const created = await posStripe('POST', 'terminal/configurations', _extends({
240
383
  params,
241
- idempotencyKey: `pos-configuration:${hostId}:${createKey}`
242
- });
384
+ idempotencyKey: account ? `pos-configuration:${hostId}:${account}:${createKey}` : `pos-configuration:${hostId}:${createKey}`
385
+ }, onAccount));
243
386
  if (!created.ok || !((_created_body = created.body) == null ? void 0 : _created_body.id)) {
244
387
  var _ref1;
245
388
  var _created_body_error, _created_body1;
@@ -265,10 +408,10 @@ export function posTerminalAddressProblem(address) {
265
408
  if (winner !== createdId) {
266
409
  var _ref2;
267
410
  var _updated_body_error1, _updated_body1;
268
- const updated = await posStripe('POST', `terminal/configurations/${winner}`, {
411
+ const updated = await posStripe('POST', `terminal/configurations/${winner}`, _extends({
269
412
  params
270
- });
271
- await posStripe('DELETE', `terminal/configurations/${createdId}`).catch(()=>undefined);
413
+ }, onAccount));
414
+ await posStripe('DELETE', `terminal/configurations/${createdId}`, onAccount).catch(()=>undefined);
272
415
  if (!updated.ok) return {
273
416
  ok: false,
274
417
  error: String((_ref2 = (_updated_body1 = updated.body) == null ? void 0 : (_updated_body_error1 = _updated_body1.error) == null ? void 0 : _updated_body_error1.code) != null ? _ref2 : updated.status)
@@ -278,7 +421,7 @@ export function posTerminalAddressProblem(address) {
278
421
  configurationId: winner
279
422
  };
280
423
  }
281
- const assigned = await assignPosReaderConfiguration(hostId, locationId, createdId);
424
+ const assigned = await assignPosReaderConfiguration(hostId, locationId, createdId, account);
282
425
  return assigned ? {
283
426
  ok: true,
284
427
  configurationId: createdId
@@ -287,12 +430,14 @@ export function posTerminalAddressProblem(address) {
287
430
  error: 'assignment'
288
431
  };
289
432
  }
290
- async function assignPosReaderConfiguration(hostId, locationId, configurationId) {
291
- const assigned = await posStripe('POST', `terminal/locations/${locationId}`, {
433
+ async function assignPosReaderConfiguration(hostId, locationId, configurationId, account) {
434
+ const assigned = await posStripe('POST', `terminal/locations/${locationId}`, _extends({
292
435
  params: {
293
436
  configuration_overrides: configurationId
294
437
  }
295
- });
438
+ }, account ? {
439
+ stripeAccount: account
440
+ } : {}));
296
441
  if (!assigned.ok) {
297
442
  var _assigned_body;
298
443
  console.error('[pos-terminal] configuration assignment failed', hostId, (_assigned_body = assigned.body) == null ? void 0 : _assigned_body.error);
@@ -331,10 +476,12 @@ async function assignPosReaderConfiguration(hostId, locationId, configurationId)
331
476
  merge: true
332
477
  });
333
478
  }
334
- /** Reads a reader from Stripe and keeps its status on the site's document. */ export async function refreshPosReaderStatus(hostId, readerId) {
479
+ /** Reads a reader from Stripe and keeps its status on the site's document. */ export async function refreshPosReaderStatus(hostId, readerId, /** The account the reader is registered on ({@link posReaderAccount}); null for the platform. */ account = null) {
335
480
  var _ref, _ref1;
336
481
  var _fetched_body, _fetched_body1;
337
- const fetched = await posStripe('GET', `terminal/readers/${readerId}`);
482
+ const fetched = await posStripe('GET', `terminal/readers/${readerId}`, account ? {
483
+ stripeAccount: account
484
+ } : {});
338
485
  if (!fetched.ok) return null;
339
486
  const status = String((_ref = (_fetched_body = fetched.body) == null ? void 0 : _fetched_body.status) != null ? _ref : 'offline');
340
487
  await readerRef(hostId, readerId).set({
@@ -435,20 +582,42 @@ async function assignPosReaderConfiguration(hostId, locationId, configurationId)
435
582
  }
436
583
  });
437
584
  }
438
- function paymentIntentParams(start, payment, destination, extra) {
585
+ /** Whether a store sells by direct charge, for the fee and the request. */ function isDirect(merchant) {
586
+ return merchant.chargeModel === 'direct';
587
+ }
588
+ /** The `posStripe` option that puts a request on a direct store's account. */ function onMerchant(merchant) {
589
+ return isDirect(merchant) ? {
590
+ stripeAccount: merchant.accountId
591
+ } : {};
592
+ }
593
+ /** The `posStripe` option for a recorded account (null: the platform). */ function onAccount(account) {
594
+ return account ? {
595
+ stripeAccount: account
596
+ } : {};
597
+ }
598
+ /** What a direct card payment records about where it lives; nothing for a destination one. */ function directPaymentFields(merchant) {
599
+ return isDirect(merchant) ? {
600
+ chargeModel: 'direct',
601
+ stripeAccountId: merchant.accountId
602
+ } : {};
603
+ }
604
+ function paymentIntentParams(start, payment, merchant, extra) {
439
605
  var _payment_takeFeeCents;
440
606
  const chargeCents = start.amountCents + start.tipCents;
441
607
  const methodTypes = extra['payment_method_types'];
442
- const fee = posCardApplicationFeeCents({
608
+ const fee = posCardApplicationFeeCents(_extends({
443
609
  takeShareCents: Number((_payment_takeFeeCents = payment.takeFeeCents) != null ? _payment_takeFeeCents : 0),
444
610
  chargeCents,
445
611
  // A reader's card is in person; a typed card is an online card (AGL-4198).
446
612
  inPerson: Array.isArray(methodTypes) && methodTypes.includes('card_present')
447
- });
613
+ }, isDirect(merchant) ? {
614
+ direct: true
615
+ } : {}));
448
616
  return _extends({
449
617
  amount: chargeCents,
450
- currency: POS_CURRENCY,
451
- 'transfer_data[destination]': destination
618
+ currency: POS_CURRENCY
619
+ }, isDirect(merchant) ? {} : {
620
+ 'transfer_data[destination]': merchant.accountId
452
621
  }, fee > 0 ? {
453
622
  application_fee_amount: fee
454
623
  } : {}, {
@@ -457,14 +626,18 @@ function paymentIntentParams(start, payment, destination, extra) {
457
626
  'metadata[orderId]': start.orderId,
458
627
  'metadata[paymentId]': start.paymentId,
459
628
  'metadata[tipCents]': String(start.tipCents)
460
- }, extra);
629
+ }, isDirect(merchant) ? {
630
+ 'metadata[chargeModel]': 'direct'
631
+ } : {}, extra);
461
632
  }
462
633
  /**
463
634
  * Creates (or finds) the card-present PaymentIntent for one payment WITHOUT
464
635
  * choosing how the card is collected: reserves the amount in the ledger and
465
- * creates a manual-capture destination charge to the merchant (settled on
466
- * Aglyn's platform account, with no `on_behalf_of`, as ToS §10.7 states),
467
- * keyed by the payment so a retry returns the same intent.
636
+ * creates a manual-capture charge, keyed by the payment so a retry returns
637
+ * the same intent. For a destination store it is a destination charge to the
638
+ * merchant (settled on Aglyn's platform account, with no `on_behalf_of`, as
639
+ * ToS §10.7 states); for a direct-charge store it is made ON the store's own
640
+ * account (ToS v24 §10.2(a)) with Aglyn's take as the application fee.
468
641
  *
469
642
  * Two collectors use it. {@link startCardPresentPayment} pushes the intent
470
643
  * to a smart reader the site owns; a native companion app (AGL-3618)
@@ -473,6 +646,7 @@ function paymentIntentParams(start, payment, destination, extra) {
473
646
  * payment is recorded by {@link refreshPosCardPayment}, keyed on the intent's
474
647
  * metadata, from the register's poll or the webhook alike.
475
648
  */ export async function createCardPresentIntent(start) {
649
+ var _start_readerAccount;
476
650
  var _intent_body;
477
651
  // Live card-present payments wait for Terminal to be switched on for the
478
652
  // platform (`STRIPE_TERMINAL_LIVE_ENABLED`); the hidden controls are not
@@ -484,23 +658,34 @@ function paymentIntentParams(start, payment, destination, extra) {
484
658
  error: 'Card readers are not available for this store yet.'
485
659
  };
486
660
  }
487
- const destination = await posMerchantAccount(start.hostId, start.org);
488
- if (!destination) return {
661
+ const merchant = await posMerchantAccount(start.hostId, start.org);
662
+ if (!merchant) return {
489
663
  ok: false,
490
664
  status: 409,
491
665
  error: 'Card payments not set up'
492
666
  };
493
- const reserved = await reserveCardPayment(start, 'card_present', start.readerId ? {
667
+ // A reader answers only to the account it is registered on, and the intent
668
+ // is made on the store's: a reader registered on the platform cannot take
669
+ // a direct store's card. Refused before anything is reserved.
670
+ if (start.readerId && ((_start_readerAccount = start.readerAccount) != null ? _start_readerAccount : null) !== (isDirect(merchant) ? merchant.accountId : null)) {
671
+ return {
672
+ ok: false,
673
+ status: 409,
674
+ error: POS_READER_ON_OTHER_ACCOUNT
675
+ };
676
+ }
677
+ const reserved = await reserveCardPayment(start, 'card_present', _extends({}, start.readerId ? {
494
678
  readerId: start.readerId
495
- } : {});
679
+ } : {}, directPaymentFields(merchant)));
496
680
  if (!reserved.ok || !reserved.payment) return reserved;
497
681
  const payment = reserved.payment;
498
682
  if (payment.status !== 'pending') return reserved;
499
683
  // Keyed by the payment: a second call for the same payment replays the
500
684
  // intent Stripe already made rather than opening another.
501
- const intent = await posStripe('POST', 'payment_intents', {
502
- idempotencyKey: `pos-pi:${payment.id}`,
503
- params: paymentIntentParams(start, payment, destination, _extends({
685
+ const intent = await posStripe('POST', 'payment_intents', _extends({
686
+ idempotencyKey: `pos-pi:${payment.id}`
687
+ }, onMerchant(merchant), {
688
+ params: paymentIntentParams(start, payment, merchant, _extends({
504
689
  payment_method_types: POS_CURRENCY === 'usd' ? [
505
690
  'card_present'
506
691
  ] : [
@@ -513,7 +698,7 @@ function paymentIntentParams(start, payment, destination, extra) {
513
698
  } : {}, {
514
699
  description: 'In-store purchase'
515
700
  }))
516
- });
701
+ }));
517
702
  if (!intent.ok || !((_intent_body = intent.body) == null ? void 0 : _intent_body.id)) {
518
703
  return await patchCardPayment(start.hostId, start.orderId, payment.id, (current)=>_extends({}, current, {
519
704
  status: 'failed',
@@ -545,7 +730,8 @@ function paymentIntentParams(start, payment, destination, extra) {
545
730
  };
546
731
  await syncPosReaderTipping(start.hostId, start.settings).catch((error)=>console.error('[pos-terminal] tipping sync failed', error));
547
732
  const created = await createCardPresentIntent(_extends({}, start, {
548
- readerId: reader.id
733
+ readerId: reader.id,
734
+ readerAccount: posReaderAccount(reader)
549
735
  }));
550
736
  if (!created.ok || !created.payment || !created.paymentIntentId) return created;
551
737
  if (created.payment.status !== 'pending') return created;
@@ -554,6 +740,7 @@ function paymentIntentParams(start, payment, destination, extra) {
554
740
  orderId: start.orderId,
555
741
  paymentId: created.payment.id,
556
742
  readerId: reader.id,
743
+ account: posPaymentAccount(created.payment),
557
744
  paymentIntentId: created.paymentIntentId,
558
745
  // A tip the customer already chose on the display is in the amount;
559
746
  // asking again on the reader would ask twice.
@@ -561,26 +748,45 @@ function paymentIntentParams(start, payment, destination, extra) {
561
748
  attempt: 0
562
749
  });
563
750
  }
564
- /** The site's Terminal Location id, or null before a reader was ever set up. */ export async function posTerminalLocationId(hostId) {
751
+ /** The site's recorded Location id on any account, or null before a reader was ever set up. */ export async function posTerminalRecordedLocationId(hostId) {
565
752
  var _config_get;
566
753
  const config = await terminalConfigRef(hostId).get();
567
754
  return String((_config_get = config.get('stripeLocationId')) != null ? _config_get : '') || null;
568
755
  }
756
+ /**
757
+ * The site's Terminal Location id on the account the store sells on now, or
758
+ * null before a reader was ever set up there. A Location made on another
759
+ * account (the platform, for a store now on its own) is not this store's
760
+ * Location any more: {@link ensurePosTerminalLocation} makes it again.
761
+ */ export async function posTerminalLocationId(hostId, account) {
762
+ const [config, current] = await Promise.all([
763
+ terminalConfigRef(hostId).get(),
764
+ account !== undefined ? Promise.resolve(account) : posTerminalAccount(hostId)
765
+ ]);
766
+ return locationOnAccount(config, current);
767
+ }
569
768
  /**
570
769
  * A Terminal SDK connection token scoped to the site's own Location, for a
571
770
  * native companion app's SDK (AGL-3618). Scoping it to the Location is what
572
771
  * keeps one store's app from discovering another store's readers: Stripe
573
772
  * only lets a location-scoped token connect to readers in that Location.
574
773
  * Null when the site has no Location yet, never an unscoped token.
774
+ *
775
+ * A direct-charge store's token is minted ON its own account (the
776
+ * `Stripe-Account` header), as Stripe's Terminal-with-direct-charges guide
777
+ * asks: the SDK then sees that account's Location and readers, collects the
778
+ * intents this server made there, and creates any intent of its own (a card
779
+ * taken offline) on that account too.
575
780
  */ export async function createPosTerminalConnectionToken(hostId) {
576
781
  var _token_body;
577
- const locationId = await posTerminalLocationId(hostId);
782
+ const account = await posTerminalAccount(hostId);
783
+ const locationId = await posTerminalLocationId(hostId, account);
578
784
  if (!locationId) return null;
579
- const token = await posStripe('POST', 'terminal/connection_tokens', {
785
+ const token = await posStripe('POST', 'terminal/connection_tokens', _extends({
580
786
  params: {
581
787
  location: locationId
582
788
  }
583
- });
789
+ }, onAccount(account)));
584
790
  if (!token.ok || !((_token_body = token.body) == null ? void 0 : _token_body.secret)) return null;
585
791
  return {
586
792
  secret: String(token.body.secret),
@@ -588,15 +794,16 @@ function paymentIntentParams(start, payment, destination, extra) {
588
794
  };
589
795
  }
590
796
  async function sendToReader(input) {
591
- const processed = await posStripe('POST', `terminal/readers/${input.readerId}/process_payment_intent`, {
592
- idempotencyKey: `pos-process:${input.paymentId}:${input.attempt}`,
797
+ const processed = await posStripe('POST', `terminal/readers/${input.readerId}/process_payment_intent`, _extends({
798
+ idempotencyKey: `pos-process:${input.paymentId}:${input.attempt}`
799
+ }, onAccount(input.account), {
593
800
  params: _extends({
594
801
  payment_intent: input.paymentIntentId,
595
802
  'process_config[enable_customer_cancellation]': true
596
803
  }, input.skipTipping ? {
597
804
  'process_config[skip_tipping]': true
598
805
  } : {})
599
- });
806
+ }));
600
807
  if (!processed.ok) {
601
808
  return await patchCardPayment(input.hostId, input.orderId, input.paymentId, (current)=>_extends({}, current, {
602
809
  status: 'failed',
@@ -636,6 +843,13 @@ async function sendToReader(input) {
636
843
  status: 404,
637
844
  error: 'That card reader is not on this site.'
638
845
  };
846
+ if (posReaderAccount(reader) !== posPaymentAccount(payment)) {
847
+ return {
848
+ ok: false,
849
+ status: 409,
850
+ error: POS_READER_ON_OTHER_ACCOUNT
851
+ };
852
+ }
639
853
  // Back to pending first, so the amount is reserved again before the reader
640
854
  // is asked; a sale paid meanwhile by another tender refuses here.
641
855
  const rearmed = await applyPosPayment({
@@ -683,6 +897,7 @@ async function sendToReader(input) {
683
897
  orderId: input.orderId,
684
898
  paymentId: input.paymentId,
685
899
  readerId: reader.id,
900
+ account: posPaymentAccount(payment),
686
901
  paymentIntentId: payment.paymentIntentId,
687
902
  skipTipping: !input.settings.tippingEnabled || Number((_payment_tipCents = payment.tipCents) != null ? _payment_tipCents : 0) > 0,
688
903
  attempt
@@ -703,25 +918,26 @@ async function sendToReader(input) {
703
918
  error: 'The card could not be read. Enter it again.'
704
919
  };
705
920
  }
706
- const destination = await posMerchantAccount(start.hostId, start.org);
707
- if (!destination) return {
921
+ const merchant = await posMerchantAccount(start.hostId, start.org);
922
+ if (!merchant) return {
708
923
  ok: false,
709
924
  status: 409,
710
925
  error: 'Card payments not set up'
711
926
  };
712
- const reserved = await reserveCardPayment(start, 'card_keyed', {});
927
+ const reserved = await reserveCardPayment(start, 'card_keyed', directPaymentFields(merchant));
713
928
  if (!reserved.ok || !reserved.payment) return reserved;
714
929
  const payment = reserved.payment;
715
930
  if (payment.status !== 'pending') return reserved;
716
- const intent = await posStripe('POST', 'payment_intents', {
717
- idempotencyKey: `pos-pi:${payment.id}`,
718
- params: paymentIntentParams(start, payment, destination, _extends({
931
+ const intent = await posStripe('POST', 'payment_intents', _extends({
932
+ idempotencyKey: `pos-pi:${payment.id}`
933
+ }, onMerchant(merchant), {
934
+ params: paymentIntentParams(start, payment, merchant, _extends({
719
935
  payment_method_types: [
720
936
  'card'
721
937
  ],
722
938
  description: 'In-store purchase (typed card)'
723
939
  }, cardAuthenticationParams('one-time')))
724
- });
940
+ }));
725
941
  if (!intent.ok || !((_intent_body = intent.body) == null ? void 0 : _intent_body.id) || !((_intent_body1 = intent.body) == null ? void 0 : _intent_body1.client_secret)) {
726
942
  return await patchCardPayment(start.hostId, start.orderId, payment.id, (current)=>_extends({}, current, {
727
943
  status: 'failed',
@@ -732,10 +948,16 @@ async function sendToReader(input) {
732
948
  paymentIntentId: String(intent.body.id),
733
949
  livemode: Boolean(intent.body.livemode)
734
950
  }));
735
- if (!paymentMethodId) return _extends({}, updated, {
736
- clientSecret: String(intent.body.client_secret)
737
- });
738
- return await confirmKeyedCard(start, payment.id, String(intent.body.id), paymentMethodId);
951
+ if (!paymentMethodId) {
952
+ // A direct store's intent lives on its own account, so the console's
953
+ // Payment Element must load Stripe for that account to confirm it.
954
+ return _extends({}, updated, {
955
+ clientSecret: String(intent.body.client_secret)
956
+ }, isDirect(merchant) ? {
957
+ stripeAccount: merchant.accountId
958
+ } : {});
959
+ }
960
+ return await confirmKeyedCard(start, payment.id, String(intent.body.id), paymentMethodId, isDirect(merchant) ? merchant.accountId : null);
739
961
  }
740
962
  /** A PaymentMethod id as Stripe mints them; anything else never reaches Stripe. */ function isPaymentMethodId(value) {
741
963
  return /^pm_[A-Za-z0-9]{8,64}$/.test(value);
@@ -746,10 +968,13 @@ async function sendToReader(input) {
746
968
  * sent the number to Stripe alone, which answered with a PaymentMethod, and
747
969
  * hands this route only its id. The server confirms the intent with it, with
748
970
  * the platform's secret key, and records the payment from Stripe's answer as
749
- * every card payment is. A card whose bank asks for the cardholder's approval
971
+ * every card payment is. The device made that PaymentMethod with the
972
+ * PLATFORM's publishable key, so for a direct-charge store's intent it is
973
+ * first cloned onto the store's account (Stripe's PaymentMethod cloning for
974
+ * direct charges) and the clone confirms it. A card whose bank asks for the cardholder's approval
750
975
  * (3-D Secure) cannot be approved at the register, so that intent is released
751
976
  * and the payment fails with words that point at Card (QR).
752
- */ async function confirmKeyedCard(start, paymentId, intentId, paymentMethodId) {
977
+ */ async function confirmKeyedCard(start, paymentId, intentId, paymentMethodId, account) {
753
978
  var _ref, _ref1;
754
979
  var _confirmed_body, _confirmed_body_error_payment_intent, _confirmed_body_error, _confirmed_body1, _confirmed_body2;
755
980
  const input = {
@@ -757,17 +982,40 @@ async function sendToReader(input) {
757
982
  orderId: start.orderId,
758
983
  paymentId
759
984
  };
760
- const confirmed = await posStripe('POST', `payment_intents/${intentId}/confirm`, {
985
+ let method = paymentMethodId;
986
+ if (account) {
987
+ var _cloned_body;
988
+ const cloned = await posStripe('POST', 'payment_methods', {
989
+ idempotencyKey: `pos-keyed-clone:${account}:${paymentMethodId}`,
990
+ stripeAccount: account,
991
+ params: {
992
+ payment_method: paymentMethodId
993
+ }
994
+ });
995
+ if (!cloned.ok || !((_cloned_body = cloned.body) == null ? void 0 : _cloned_body.id)) {
996
+ const message = posStripeErrorMessage(cloned.body, 'The card was not accepted.');
997
+ await posStripe('POST', `payment_intents/${intentId}/cancel`, {
998
+ idempotencyKey: `pos-cancel:${intentId}`,
999
+ stripeAccount: account
1000
+ });
1001
+ return await patchCardPayment(start.hostId, start.orderId, paymentId, (current)=>current.status === 'pending' ? _extends({}, current, {
1002
+ status: 'failed',
1003
+ failureMessage: message
1004
+ }) : null);
1005
+ }
1006
+ method = String(cloned.body.id);
1007
+ }
1008
+ const confirmed = await posStripe('POST', `payment_intents/${intentId}/confirm`, _extends({
761
1009
  idempotencyKey: `pos-keyed-confirm:${intentId}:${paymentMethodId}`,
762
1010
  params: {
763
- payment_method: paymentMethodId
1011
+ payment_method: method
764
1012
  }
765
- });
1013
+ }, onAccount(account)));
766
1014
  const status = String((_ref = (_ref1 = (_confirmed_body = confirmed.body) == null ? void 0 : _confirmed_body.status) != null ? _ref1 : (_confirmed_body1 = confirmed.body) == null ? void 0 : (_confirmed_body_error = _confirmed_body1.error) == null ? void 0 : (_confirmed_body_error_payment_intent = _confirmed_body_error.payment_intent) == null ? void 0 : _confirmed_body_error_payment_intent.status) != null ? _ref : '');
767
1015
  if (status === 'requires_action') {
768
- await posStripe('POST', `payment_intents/${intentId}/cancel`, {
1016
+ await posStripe('POST', `payment_intents/${intentId}/cancel`, _extends({
769
1017
  idempotencyKey: `pos-cancel:${intentId}`
770
- });
1018
+ }, onAccount(account)));
771
1019
  return await patchCardPayment(start.hostId, start.orderId, paymentId, (current)=>current.status === 'pending' ? _extends({}, current, {
772
1020
  status: 'failed',
773
1021
  failureMessage: KEYED_CARD_NEEDS_AUTHENTICATION
@@ -776,9 +1024,9 @@ async function sendToReader(input) {
776
1024
  if (!confirmed.ok && ((_confirmed_body2 = confirmed.body) == null ? void 0 : _confirmed_body2.error) && !confirmed.body.error.payment_intent) {
777
1025
  // Refused before the card was tried (a stale method, a bad request): say so, leave nothing pending.
778
1026
  const message = posStripeErrorMessage(confirmed.body, 'The card was not accepted.');
779
- await posStripe('POST', `payment_intents/${intentId}/cancel`, {
1027
+ await posStripe('POST', `payment_intents/${intentId}/cancel`, _extends({
780
1028
  idempotencyKey: `pos-cancel:${intentId}`
781
- });
1029
+ }, onAccount(account)));
782
1030
  return await patchCardPayment(start.hostId, start.orderId, paymentId, (current)=>current.status === 'pending' ? _extends({}, current, {
783
1031
  status: 'failed',
784
1032
  failureMessage: message
@@ -794,24 +1042,27 @@ async function sendToReader(input) {
794
1042
  */ export async function startCardLinkPayment(start) {
795
1043
  var _payment_takeFeeCents;
796
1044
  var _session_body;
797
- const destination = await posMerchantAccount(start.hostId, start.org);
798
- if (!destination) return {
1045
+ const merchant = await posMerchantAccount(start.hostId, start.org);
1046
+ if (!merchant) return {
799
1047
  ok: false,
800
1048
  status: 409,
801
1049
  error: 'Card payments not set up'
802
1050
  };
803
- const reserved = await reserveCardPayment(start, 'card_link', {});
1051
+ const reserved = await reserveCardPayment(start, 'card_link', directPaymentFields(merchant));
804
1052
  if (!reserved.ok || !reserved.payment) return reserved;
805
1053
  const payment = reserved.payment;
806
1054
  if (payment.checkoutSessionId || payment.status !== 'pending') return reserved;
807
- const fee = posCardApplicationFeeCents({
1055
+ const fee = posCardApplicationFeeCents(_extends({
808
1056
  takeShareCents: Number((_payment_takeFeeCents = payment.takeFeeCents) != null ? _payment_takeFeeCents : 0),
809
1057
  chargeCents: start.amountCents + start.tipCents,
810
1058
  // A card link is paid online, on the customer's own phone (AGL-4198).
811
1059
  inPerson: false
812
- });
813
- const session = await posStripe('POST', 'checkout/sessions', {
814
- idempotencyKey: `pos-link:${payment.id}`,
1060
+ }, isDirect(merchant) ? {
1061
+ direct: true
1062
+ } : {}));
1063
+ const session = await posStripe('POST', 'checkout/sessions', _extends({
1064
+ idempotencyKey: `pos-link:${payment.id}`
1065
+ }, onMerchant(merchant), {
815
1066
  params: _extends({
816
1067
  mode: 'payment'
817
1068
  }, checkoutSessionCardAuthenticationParams('payment'), {
@@ -827,10 +1078,12 @@ async function sendToReader(input) {
827
1078
  'line_items[1][price_data][currency]': POS_CURRENCY,
828
1079
  'line_items[1][price_data][unit_amount]': start.tipCents,
829
1080
  'line_items[1][price_data][product_data][name]': 'Tip'
830
- } : {}, {
831
- 'payment_intent_data[transfer_data][destination]': destination
1081
+ } : {}, isDirect(merchant) ? {} : {
1082
+ 'payment_intent_data[transfer_data][destination]': merchant.accountId
832
1083
  }, fee > 0 ? {
833
1084
  'payment_intent_data[application_fee_amount]': fee
1085
+ } : {}, isDirect(merchant) ? {
1086
+ 'payment_intent_data[metadata][chargeModel]': 'direct'
834
1087
  } : {}, {
835
1088
  'payment_intent_data[metadata][kind]': 'pos',
836
1089
  'payment_intent_data[metadata][hostId]': start.hostId,
@@ -843,8 +1096,10 @@ async function sendToReader(input) {
843
1096
  'metadata[hostId]': start.hostId,
844
1097
  'metadata[orderId]': start.orderId,
845
1098
  'metadata[paymentId]': payment.id
846
- })
847
- });
1099
+ }, isDirect(merchant) ? {
1100
+ 'metadata[chargeModel]': 'direct'
1101
+ } : {})
1102
+ }));
848
1103
  if (!session.ok || !((_session_body = session.body) == null ? void 0 : _session_body.url)) {
849
1104
  return await patchCardPayment(start.hostId, start.orderId, payment.id, (current)=>_extends({}, current, {
850
1105
  status: 'failed',
@@ -884,12 +1139,14 @@ async function sendToReader(input) {
884
1139
  */ export function posCaptureFeeCents(payment, intent) {
885
1140
  var _payment_takeFeeCents, _ref;
886
1141
  const methodTypes = intent == null ? void 0 : intent.payment_method_types;
887
- return posCardApplicationFeeCents({
1142
+ return posCardApplicationFeeCents(_extends({
888
1143
  takeShareCents: Number((_payment_takeFeeCents = payment.takeFeeCents) != null ? _payment_takeFeeCents : 0),
889
1144
  chargeCents: Math.max(0, Math.round(Number((_ref = intent == null ? void 0 : intent.amount) != null ? _ref : 0))),
890
1145
  // The intent says how it was paid: a reader's card is in person (AGL-4198).
891
1146
  inPerson: !Array.isArray(methodTypes) || methodTypes.includes('card_present')
892
- });
1147
+ }, payment.chargeModel === 'direct' ? {
1148
+ direct: true
1149
+ } : {}));
893
1150
  }
894
1151
  /**
895
1152
  * Brings one card payment up to date with Stripe, from a webhook or the
@@ -921,11 +1178,13 @@ async function sendToReader(input) {
921
1178
  changed: false
922
1179
  };
923
1180
  }
1181
+ // Every object of this payment lives where it was made (null: the platform).
1182
+ const on = onAccount(posPaymentAccount(payment));
924
1183
  let paymentIntentId = (_payment_paymentIntentId = payment.paymentIntentId) != null ? _payment_paymentIntentId : '';
925
1184
  if (!paymentIntentId && payment.checkoutSessionId) {
926
1185
  var _ref;
927
1186
  var _session_body, _session_body1;
928
- const session = await posStripe('GET', `checkout/sessions/${payment.checkoutSessionId}`);
1187
+ const session = await posStripe('GET', `checkout/sessions/${payment.checkoutSessionId}`, on);
929
1188
  if (session.ok && ((_session_body = session.body) == null ? void 0 : _session_body.status) === 'expired' && payment.status === 'pending') {
930
1189
  return await patchCardPayment(input.hostId, input.orderId, payment.id, (current)=>current.status === 'pending' ? _extends({}, current, {
931
1190
  status: 'canceled'
@@ -940,11 +1199,11 @@ async function sendToReader(input) {
940
1199
  completed: false,
941
1200
  changed: false
942
1201
  };
943
- let intent = (await posStripe('GET', `payment_intents/${paymentIntentId}`, {
1202
+ let intent = (await posStripe('GET', `payment_intents/${paymentIntentId}`, _extends({
944
1203
  params: {
945
1204
  'expand[]': 'latest_charge'
946
1205
  }
947
- })).body;
1206
+ }, on))).body;
948
1207
  if (!(intent == null ? void 0 : intent.id)) return {
949
1208
  ok: true,
950
1209
  order,
@@ -964,9 +1223,9 @@ async function sendToReader(input) {
964
1223
  var _captured_body;
965
1224
  if (order.status !== 'pending' && payment.status !== 'pending') {
966
1225
  // Nothing to capture into: the sale is gone. Release the hold.
967
- await posStripe('POST', `payment_intents/${intent.id}/cancel`, {
1226
+ await posStripe('POST', `payment_intents/${intent.id}/cancel`, _extends({
968
1227
  idempotencyKey: `pos-release:${intent.id}`
969
- });
1228
+ }, on));
970
1229
  return {
971
1230
  ok: true,
972
1231
  order,
@@ -976,14 +1235,14 @@ async function sendToReader(input) {
976
1235
  };
977
1236
  }
978
1237
  const fee = posCaptureFeeCents(payment, intent);
979
- const captured = await posStripe('POST', `payment_intents/${intent.id}/capture`, {
1238
+ const captured = await posStripe('POST', `payment_intents/${intent.id}/capture`, _extends({
980
1239
  idempotencyKey: `pos-capture:${intent.id}`,
981
1240
  params: _extends({}, fee > 0 ? {
982
1241
  application_fee_amount: fee
983
1242
  } : {}, {
984
1243
  'expand[]': 'latest_charge'
985
1244
  })
986
- });
1245
+ }, on));
987
1246
  if (captured.ok && ((_captured_body = captured.body) == null ? void 0 : _captured_body.id)) intent = captured.body;
988
1247
  else {
989
1248
  var _captured_body1;
@@ -1039,7 +1298,7 @@ async function sendToReader(input) {
1039
1298
  // intent, so ask the reader too.
1040
1299
  if (payment.method === 'card_present' && payment.readerId && payment.status === 'pending') {
1041
1300
  var _action_process_payment_intent;
1042
- const reader = await refreshPosReaderStatus(input.hostId, payment.readerId);
1301
+ const reader = await refreshPosReaderStatus(input.hostId, payment.readerId, posPaymentAccount(payment));
1043
1302
  const action = reader == null ? void 0 : reader.action;
1044
1303
  if ((action == null ? void 0 : action.type) === 'process_payment_intent' && (action == null ? void 0 : (_action_process_payment_intent = action.process_payment_intent) == null ? void 0 : _action_process_payment_intent.payment_intent) === intent.id && (action == null ? void 0 : action.status) === 'failed') {
1045
1304
  var _action_failure_message;
@@ -1069,9 +1328,10 @@ async function sendToReader(input) {
1069
1328
  if (!refreshed.ok || !refreshed.payment) return refreshed;
1070
1329
  const payment = refreshed.payment;
1071
1330
  if (payment.status === 'succeeded' || payment.status === 'canceled') return refreshed;
1331
+ const on = onAccount(posPaymentAccount(payment));
1072
1332
  if (payment.method === 'card_present' && payment.readerId) {
1073
1333
  var _cleared_body_error, _cleared_body;
1074
- const cleared = await posStripe('POST', `terminal/readers/${payment.readerId}/cancel_action`);
1334
+ const cleared = await posStripe('POST', `terminal/readers/${payment.readerId}/cancel_action`, on);
1075
1335
  if (!cleared.ok && ((_cleared_body = cleared.body) == null ? void 0 : (_cleared_body_error = _cleared_body.error) == null ? void 0 : _cleared_body_error.code) === 'terminal_reader_busy') {
1076
1336
  return {
1077
1337
  ok: false,
@@ -1081,14 +1341,14 @@ async function sendToReader(input) {
1081
1341
  }
1082
1342
  }
1083
1343
  if (payment.paymentIntentId) {
1084
- await posStripe('POST', `payment_intents/${payment.paymentIntentId}/cancel`, {
1344
+ await posStripe('POST', `payment_intents/${payment.paymentIntentId}/cancel`, _extends({
1085
1345
  idempotencyKey: `pos-cancel:${payment.paymentIntentId}`
1086
- });
1346
+ }, on));
1087
1347
  }
1088
1348
  if (payment.checkoutSessionId) {
1089
- await posStripe('POST', `checkout/sessions/${payment.checkoutSessionId}/expire`, {
1349
+ await posStripe('POST', `checkout/sessions/${payment.checkoutSessionId}/expire`, _extends({
1090
1350
  idempotencyKey: `pos-expire:${payment.checkoutSessionId}`
1091
- });
1351
+ }, on));
1092
1352
  }
1093
1353
  // Re-read: a payment that completed in the gap is recorded as paid.
1094
1354
  const settled = await refreshPosCardPayment(input);
@@ -1126,13 +1386,13 @@ async function sendToReader(input) {
1126
1386
  status: 404,
1127
1387
  error: 'That card reader is not on this site.'
1128
1388
  };
1129
- const presented = await posStripe('POST', `test_helpers/terminal/readers/${reader.id}/present_payment_method`, {
1389
+ const presented = await posStripe('POST', `test_helpers/terminal/readers/${reader.id}/present_payment_method`, _extends({}, onAccount(posReaderAccount(reader)), {
1130
1390
  params: _extends({
1131
1391
  type: 'card_present'
1132
1392
  }, input.cardNumber && /^[0-9]{12,19}$/.test(input.cardNumber) ? {
1133
1393
  'card_present[number]': input.cardNumber
1134
1394
  } : {})
1135
- });
1395
+ }));
1136
1396
  if (!presented.ok) {
1137
1397
  return {
1138
1398
  ok: false,
@@ -1164,16 +1424,21 @@ async function sendToReader(input) {
1164
1424
  * by trusting the event's own copy (whose API version predates the tip
1165
1425
  * fields). Returns the site when the event was the register's, so the
1166
1426
  * dispatcher can count it as claimed; null for every other event.
1427
+ *
1428
+ * `account` is the connected account a Connect-delivered event came from
1429
+ * (`connectEventAccount`): a direct-charge store's reader and intents live
1430
+ * there, so the reader event's intent is read there. The settlement itself
1431
+ * reads the account the payment recorded, never the event's word.
1167
1432
  */ export async function handlePosStripeEvent(input) {
1168
1433
  var _object_metadata;
1169
1434
  const { type, object } = input;
1170
1435
  let ref = null;
1171
1436
  if (type === 'terminal.reader.action_succeeded' || type === 'terminal.reader.action_failed') {
1172
- var _ref;
1437
+ var _ref, _input_account;
1173
1438
  var _object_action_process_payment_intent, _object_action, _object_action1, _intent_body_metadata, _intent_body;
1174
1439
  const intentId = String((_ref = object == null ? void 0 : (_object_action = object.action) == null ? void 0 : (_object_action_process_payment_intent = _object_action.process_payment_intent) == null ? void 0 : _object_action_process_payment_intent.payment_intent) != null ? _ref : '');
1175
1440
  if ((object == null ? void 0 : (_object_action1 = object.action) == null ? void 0 : _object_action1.type) !== 'process_payment_intent' || !intentId) return null;
1176
- const intent = await posStripe('GET', `payment_intents/${intentId}`);
1441
+ const intent = await posStripe('GET', `payment_intents/${intentId}`, onAccount((_input_account = input.account) != null ? _input_account : null));
1177
1442
  if (!intent.ok || ((_intent_body = intent.body) == null ? void 0 : (_intent_body_metadata = _intent_body.metadata) == null ? void 0 : _intent_body_metadata.kind) !== 'pos') return null;
1178
1443
  ref = posPaymentRef(intent.body.metadata);
1179
1444
  } else if (type === 'payment_intent.amount_capturable_updated' || type === 'payment_intent.succeeded' || type === 'payment_intent.payment_failed' || type === 'payment_intent.canceled') {
@@ -1221,14 +1486,18 @@ function offlineCardIntent(body) {
1221
1486
  failureMessage: String((_ref9 = (_error_message = error.message) != null ? _error_message : error.decline_code) != null ? _ref9 : 'The card was declined.')
1222
1487
  } : {});
1223
1488
  }
1224
- /** Reads one offline card's PaymentIntent, with its charge's card details. */ export async function retrievePosOfflineCardIntent(paymentIntentId) {
1225
- const fetched = await posStripe('GET', `payment_intents/${encodeURIComponent(paymentIntentId)}`, {
1489
+ /**
1490
+ * Reads one offline card's PaymentIntent, with its charge's card details, on
1491
+ * `account` (a direct-charge store's own, where its app's SDK made it) or
1492
+ * the platform.
1493
+ */ export async function retrievePosOfflineCardIntent(paymentIntentId, account = null) {
1494
+ const fetched = await posStripe('GET', `payment_intents/${encodeURIComponent(paymentIntentId)}`, _extends({
1226
1495
  params: {
1227
1496
  'expand[]': [
1228
1497
  'latest_charge'
1229
1498
  ]
1230
1499
  }
1231
- });
1500
+ }, onAccount(account)));
1232
1501
  if (!fetched.ok) return {
1233
1502
  ok: false,
1234
1503
  error: posStripeErrorMessage(fetched.body, 'The card payment could not be read.')
@@ -1238,9 +1507,10 @@ function offlineCardIntent(body) {
1238
1507
  intent: offlineCardIntent(fetched.body)
1239
1508
  };
1240
1509
  }
1241
- /** Captures one authorized offline card with the platform's fee; a repeat finds the first capture. */ export async function capturePosOfflineCardIntent(paymentIntentId, applicationFeeCents, idempotencyKey) {
1242
- const captured = await posStripe('POST', `payment_intents/${encodeURIComponent(paymentIntentId)}/capture`, {
1243
- idempotencyKey,
1510
+ /** Captures one authorized offline card with the platform's fee; a repeat finds the first capture. */ export async function capturePosOfflineCardIntent(paymentIntentId, applicationFeeCents, idempotencyKey, account = null) {
1511
+ const captured = await posStripe('POST', `payment_intents/${encodeURIComponent(paymentIntentId)}/capture`, _extends({
1512
+ idempotencyKey
1513
+ }, onAccount(account), {
1244
1514
  params: _extends({}, applicationFeeCents > 0 ? {
1245
1515
  application_fee_amount: applicationFeeCents
1246
1516
  } : {}, {
@@ -1248,7 +1518,7 @@ function offlineCardIntent(body) {
1248
1518
  'latest_charge'
1249
1519
  ]
1250
1520
  })
1251
- });
1521
+ }));
1252
1522
  // The status tells the sync whether this attempt definitely failed (AGL-4039).
1253
1523
  if (!captured.ok) {
1254
1524
  return {