@aglyn/plugins-commerce 1.29.1 → 1.29.3

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 (89) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/checkout-tax-blocked-notice.component.d.ts +18 -0
  3. package/src/lib/components/console/checkout-tax-blocked-notice.component.js +67 -0
  4. package/src/lib/components/console/checkout-tax-blocked-notice.component.js.map +1 -0
  5. package/src/lib/components/console/payments-settings-card.component.d.ts +2 -2
  6. package/src/lib/components/console/payments-settings-card.component.js +99 -5
  7. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  8. package/src/lib/components/console/product-editor-dialog.component.js +14 -3
  9. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  10. package/src/lib/components/console/products-hub-card.component.js +51 -14
  11. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  12. package/src/lib/components/console/stripe-tax-readiness.component.d.ts +45 -0
  13. package/src/lib/components/console/stripe-tax-readiness.component.js +276 -0
  14. package/src/lib/components/console/stripe-tax-readiness.component.js.map +1 -0
  15. package/src/lib/components/console/tax-settings-card.component.js +22 -8
  16. package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
  17. package/src/lib/constants/operator-alerts.d.ts +9 -0
  18. package/src/lib/constants/operator-alerts.js +22 -1
  19. package/src/lib/constants/operator-alerts.js.map +1 -1
  20. package/src/lib/declarations.server.js +11 -0
  21. package/src/lib/declarations.server.js.map +1 -1
  22. package/src/lib/model/commerce-record-routes.d.ts +13 -1
  23. package/src/lib/model/commerce-record-routes.js +22 -2
  24. package/src/lib/model/commerce-record-routes.js.map +1 -1
  25. package/src/lib/model/commerce-tax-readiness.d.ts +79 -0
  26. package/src/lib/model/commerce-tax-readiness.js +99 -0
  27. package/src/lib/model/commerce-tax-readiness.js.map +1 -0
  28. package/src/lib/model/commerce.d.ts +7 -0
  29. package/src/lib/model/commerce.js +17 -4
  30. package/src/lib/model/commerce.js.map +1 -1
  31. package/src/lib/model/payments-setup-status.d.ts +68 -0
  32. package/src/lib/model/payments-setup-status.js +103 -0
  33. package/src/lib/model/payments-setup-status.js.map +1 -0
  34. package/src/lib/plan-entitlements.d.ts +2 -2
  35. package/src/lib/plan-entitlements.js +4 -12
  36. package/src/lib/plan-entitlements.js.map +1 -1
  37. package/src/lib/server/cart-checkout.js +3 -0
  38. package/src/lib/server/cart-checkout.js.map +1 -1
  39. package/src/lib/server/checkout-tax-refusal.d.ts +51 -0
  40. package/src/lib/server/checkout-tax-refusal.js +133 -0
  41. package/src/lib/server/checkout-tax-refusal.js.map +1 -0
  42. package/src/lib/server/checkout.d.ts +2 -1
  43. package/src/lib/server/checkout.js +7 -2
  44. package/src/lib/server/checkout.js.map +1 -1
  45. package/src/lib/server/connect-prefill.d.ts +65 -0
  46. package/src/lib/server/connect-prefill.js +85 -0
  47. package/src/lib/server/connect-prefill.js.map +1 -0
  48. package/src/lib/server/connect.d.ts +4 -2
  49. package/src/lib/server/connect.js +117 -37
  50. package/src/lib/server/connect.js.map +1 -1
  51. package/src/lib/server/draft-order.js +4 -2
  52. package/src/lib/server/draft-order.js.map +1 -1
  53. package/src/lib/server/pos-order.js +1 -1
  54. package/src/lib/server/pos-order.js.map +1 -1
  55. package/src/lib/server/product-writer.d.ts +27 -0
  56. package/src/lib/server/product-writer.js +174 -4
  57. package/src/lib/server/product-writer.js.map +1 -1
  58. package/src/lib/server/quote-pay.d.ts +6 -0
  59. package/src/lib/server/quote-pay.js +8 -2
  60. package/src/lib/server/quote-pay.js.map +1 -1
  61. package/src/lib/server/seller-stripe-account.d.ts +19 -0
  62. package/src/lib/server/seller-stripe-account.js +40 -4
  63. package/src/lib/server/seller-stripe-account.js.map +1 -1
  64. package/src/lib/server/site-page-resolver.d.ts +11 -5
  65. package/src/lib/server/site-page-resolver.js +102 -19
  66. package/src/lib/server/site-page-resolver.js.map +1 -1
  67. package/src/lib/server/site-search.d.ts +43 -0
  68. package/src/lib/server/site-search.js +124 -0
  69. package/src/lib/server/site-search.js.map +1 -0
  70. package/src/lib/server/tax-readiness.d.ts +56 -0
  71. package/src/lib/server/tax-readiness.js +169 -0
  72. package/src/lib/server/tax-readiness.js.map +1 -0
  73. package/src/lib/server.js +10 -2
  74. package/src/lib/server.js.map +1 -1
  75. package/src/lib/transfer/product-image-copy.server.d.ts +77 -0
  76. package/src/lib/transfer/product-image-copy.server.js +307 -0
  77. package/src/lib/transfer/product-image-copy.server.js.map +1 -0
  78. package/src/lib/transfer/product-images.d.ts +62 -0
  79. package/src/lib/transfer/product-images.js +143 -0
  80. package/src/lib/transfer/product-images.js.map +1 -0
  81. package/src/lib/transfer/product-sources.d.ts +92 -0
  82. package/src/lib/transfer/product-sources.js +519 -0
  83. package/src/lib/transfer/product-sources.js.map +1 -0
  84. package/src/lib/transfer/product-transfer.d.ts +26 -1
  85. package/src/lib/transfer/product-transfer.js +283 -11
  86. package/src/lib/transfer/product-transfer.js.map +1 -1
  87. package/src/lib/transfer/products.server.d.ts +29 -3
  88. package/src/lib/transfer/products.server.js +289 -13
  89. package/src/lib/transfer/products.server.js.map +1 -1
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { BusinessDetailsHost } from '@aglyn/aglyn/app-utils/business-details';
18
+ import { type HostCustomDomainState } from '@aglyn/aglyn/app-utils/host-naming';
19
+ /**
20
+ * WHAT A NEW STRIPE ACCOUNT STARTS WITH (AGL-4245).
21
+ *
22
+ * The owner already typed their business name, email and phone on
23
+ * Setup → Business details, and the site already has a public address. Sent
24
+ * with the account create, Stripe's hosted onboarding shows them filled in,
25
+ * for the owner to confirm or change, instead of asking for each again.
26
+ *
27
+ * Every field is optional and checked here first: a value that is missing or
28
+ * does not look like what Stripe takes is left out, never sent half-formed.
29
+ * The connect route still retries the create without any of it when Stripe
30
+ * refuses a prefill field, so nothing here can stop a store from setting up
31
+ * payments.
32
+ *
33
+ * ONLY THE BUSINESS PROFILE. No country, no address, no `company`,
34
+ * `individual` or `business_type`. An owner who signs in to Stripe's form
35
+ * with an existing Stripe login is offered the business details and payout
36
+ * bank they already have there to reuse (networked onboarding), and anything
37
+ * the platform prefills on the legal entity narrows which of their existing
38
+ * businesses they can pick: a prefilled country limits them to that country
39
+ * and also locks it. That reuse is the easiest setup there is for someone who
40
+ * already has Stripe, so it is never narrowed. The business profile (name,
41
+ * site address, support email and phone) is what customers see, and the
42
+ * owner can still change any of it in Stripe's form.
43
+ *
44
+ * On this account shape `business_profile` stays writable by the platform
45
+ * after the first onboarding link, so the connect route also fills it in on
46
+ * re-entry for an account that has not finished onboarding
47
+ * ({@link missingBusinessProfilePrefill}).
48
+ */
49
+ /** The host fields the prefill reads: business details plus the site's public address. */
50
+ export type StripePrefillHost = BusinessDetailsHost & HostCustomDomainState;
51
+ /** The site's public https address: the live custom domain, else its platform address. */
52
+ export declare function prefillSiteUrl(host: StripePrefillHost | null | undefined, subdomain?: string | null): string;
53
+ /**
54
+ * The `/v1/accounts` prefill parameters for a site, as form fields. Empty
55
+ * when the site has nothing usable; each key appears only with a real value.
56
+ */
57
+ export declare function stripeAccountPrefill(host: StripePrefillHost | null | undefined, options?: {
58
+ subdomain?: string | null;
59
+ }): Record<string, string>;
60
+ /**
61
+ * The prefill for an account that already exists: only the fields its
62
+ * `business_profile` does not hold yet, so anything the owner already typed
63
+ * into Stripe's form is never overwritten. Empty when there is nothing to add.
64
+ */
65
+ export declare function missingBusinessProfilePrefill(prefill: Record<string, string>, account: unknown): Record<string, string>;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { hostPublicOrigin, liveCustomDomain } from "@aglyn/aglyn/app-utils/host-naming";
17
+ import { siteContactEmail } from "@aglyn/aglyn/app-utils/host-tokens";
18
+ const text = (value, max)=>typeof value === 'string' ? value.trim().slice(0, max) : '';
19
+ /** The site's public https address: the live custom domain, else its platform address. */ export function prefillSiteUrl(host, subdomain) {
20
+ var _liveCustomDomain;
21
+ const origin = hostPublicOrigin({
22
+ cname: (_liveCustomDomain = liveCustomDomain(host)) != null ? _liveCustomDomain : null,
23
+ subdomain: text(host == null ? void 0 : host.subdomain, 63) || text(subdomain, 63) || null
24
+ });
25
+ if (!origin) return '';
26
+ try {
27
+ const url = new URL(origin);
28
+ if (url.protocol !== 'https:') return '';
29
+ if (!url.hostname.includes('.') || url.hostname.endsWith('.localhost')) return '';
30
+ return url.origin;
31
+ } catch (unused) {
32
+ return '';
33
+ }
34
+ }
35
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
36
+ /**
37
+ * The `/v1/accounts` prefill parameters for a site, as form fields. Empty
38
+ * when the site has nothing usable; each key appears only with a real value.
39
+ */ export function stripeAccountPrefill(host, options = {}) {
40
+ var _ref, _siteContactEmail;
41
+ var _host_seo;
42
+ const params = {};
43
+ if (!host && !options.subdomain) return params;
44
+ const entity = (_ref = host == null ? void 0 : (_host_seo = host.seo) == null ? void 0 : _host_seo.entity) != null ? _ref : null;
45
+ const name = text(entity == null ? void 0 : entity.name, 200) || text(host == null ? void 0 : host.displayName, 200);
46
+ if (name) params['business_profile[name]'] = name;
47
+ const url = prefillSiteUrl(host, options.subdomain);
48
+ if (url) params['business_profile[url]'] = url;
49
+ const email = (_siteContactEmail = siteContactEmail(host != null ? host : null)) != null ? _siteContactEmail : '';
50
+ if (email && EMAIL.test(email)) params['business_profile[support_email]'] = email;
51
+ // A phone Stripe can read has at least seven digits and nothing but the
52
+ // usual punctuation around them; anything else is left for the owner to
53
+ // type in Stripe's form.
54
+ const phone = text(entity == null ? void 0 : entity.telephone, 64);
55
+ const digits = phone.replace(/\D/g, '');
56
+ if (phone && /^[+\d\s().-]+$/.test(phone) && digits.length >= 7 && digits.length <= 15) {
57
+ params['business_profile[support_phone]'] = phone;
58
+ }
59
+ return params;
60
+ }
61
+ /** The Stripe Account field each prefill parameter fills. */ const PREFILL_FIELDS = {
62
+ 'business_profile[name]': 'name',
63
+ 'business_profile[url]': 'url',
64
+ 'business_profile[support_email]': 'support_email',
65
+ 'business_profile[support_phone]': 'support_phone'
66
+ };
67
+ /**
68
+ * The prefill for an account that already exists: only the fields its
69
+ * `business_profile` does not hold yet, so anything the owner already typed
70
+ * into Stripe's form is never overwritten. Empty when there is nothing to add.
71
+ */ export function missingBusinessProfilePrefill(prefill, account) {
72
+ var _ref;
73
+ const profile = (_ref = account == null ? void 0 : account.business_profile) != null ? _ref : {};
74
+ const missing = {};
75
+ for (const [param, value] of Object.entries(prefill)){
76
+ const field = PREFILL_FIELDS[param];
77
+ if (!field) continue;
78
+ const current = profile == null ? void 0 : profile[field];
79
+ if (typeof current === 'string' && current.trim()) continue;
80
+ missing[param] = value;
81
+ }
82
+ return missing;
83
+ }
84
+
85
+ //# sourceMappingURL=connect-prefill.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/connect-prefill.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { BusinessDetailsHost } from '@aglyn/aglyn/app-utils/business-details'\nimport {\n hostPublicOrigin,\n liveCustomDomain,\n type HostCustomDomainState,\n} from '@aglyn/aglyn/app-utils/host-naming'\nimport { siteContactEmail } from '@aglyn/aglyn/app-utils/host-tokens'\n\n/**\n * WHAT A NEW STRIPE ACCOUNT STARTS WITH (AGL-4245).\n *\n * The owner already typed their business name, email and phone on\n * Setup → Business details, and the site already has a public address. Sent\n * with the account create, Stripe's hosted onboarding shows them filled in,\n * for the owner to confirm or change, instead of asking for each again.\n *\n * Every field is optional and checked here first: a value that is missing or\n * does not look like what Stripe takes is left out, never sent half-formed.\n * The connect route still retries the create without any of it when Stripe\n * refuses a prefill field, so nothing here can stop a store from setting up\n * payments.\n *\n * ONLY THE BUSINESS PROFILE. No country, no address, no `company`,\n * `individual` or `business_type`. An owner who signs in to Stripe's form\n * with an existing Stripe login is offered the business details and payout\n * bank they already have there to reuse (networked onboarding), and anything\n * the platform prefills on the legal entity narrows which of their existing\n * businesses they can pick: a prefilled country limits them to that country\n * and also locks it. That reuse is the easiest setup there is for someone who\n * already has Stripe, so it is never narrowed. The business profile (name,\n * site address, support email and phone) is what customers see, and the\n * owner can still change any of it in Stripe's form.\n *\n * On this account shape `business_profile` stays writable by the platform\n * after the first onboarding link, so the connect route also fills it in on\n * re-entry for an account that has not finished onboarding\n * ({@link missingBusinessProfilePrefill}).\n */\n\n/** The host fields the prefill reads: business details plus the site's public address. */\nexport type StripePrefillHost = BusinessDetailsHost & HostCustomDomainState\n\nconst text = (value: unknown, max: number): string =>\n typeof value === 'string' ? value.trim().slice(0, max) : ''\n\n/** The site's public https address: the live custom domain, else its platform address. */\nexport function prefillSiteUrl(\n host: StripePrefillHost | null | undefined,\n subdomain?: string | null,\n): string {\n const origin = hostPublicOrigin({\n cname: liveCustomDomain(host) ?? null,\n subdomain: text(host?.subdomain, 63) || text(subdomain, 63) || null,\n })\n if (!origin) return ''\n try {\n const url = new URL(origin)\n if (url.protocol !== 'https:') return ''\n if (!url.hostname.includes('.') || url.hostname.endsWith('.localhost')) return ''\n return url.origin\n } catch {\n return ''\n }\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * The `/v1/accounts` prefill parameters for a site, as form fields. Empty\n * when the site has nothing usable; each key appears only with a real value.\n */\nexport function stripeAccountPrefill(\n host: StripePrefillHost | null | undefined,\n options: { subdomain?: string | null } = {},\n): Record<string, string> {\n const params: Record<string, string> = {}\n if (!host && !options.subdomain) return params\n const entity = host?.seo?.entity ?? null\n\n const name = text(entity?.name, 200) || text(host?.displayName, 200)\n if (name) params['business_profile[name]'] = name\n\n const url = prefillSiteUrl(host, options.subdomain)\n if (url) params['business_profile[url]'] = url\n\n const email = siteContactEmail(host ?? null) ?? ''\n if (email && EMAIL.test(email)) params['business_profile[support_email]'] = email\n\n // A phone Stripe can read has at least seven digits and nothing but the\n // usual punctuation around them; anything else is left for the owner to\n // type in Stripe's form.\n const phone = text(entity?.telephone, 64)\n const digits = phone.replace(/\\D/g, '')\n if (phone && /^[+\\d\\s().-]+$/.test(phone) && digits.length >= 7 && digits.length <= 15) {\n params['business_profile[support_phone]'] = phone\n }\n\n return params\n}\n\n/** The Stripe Account field each prefill parameter fills. */\nconst PREFILL_FIELDS: Readonly<Record<string, string>> = {\n 'business_profile[name]': 'name',\n 'business_profile[url]': 'url',\n 'business_profile[support_email]': 'support_email',\n 'business_profile[support_phone]': 'support_phone',\n}\n\n/**\n * The prefill for an account that already exists: only the fields its\n * `business_profile` does not hold yet, so anything the owner already typed\n * into Stripe's form is never overwritten. Empty when there is nothing to add.\n */\nexport function missingBusinessProfilePrefill(\n prefill: Record<string, string>,\n account: unknown,\n): Record<string, string> {\n const profile = (account as any)?.business_profile ?? {}\n const missing: Record<string, string> = {}\n for (const [param, value] of Object.entries(prefill)) {\n const field = PREFILL_FIELDS[param]\n if (!field) continue\n const current = profile?.[field]\n if (typeof current === 'string' && current.trim()) continue\n missing[param] = value\n }\n return missing\n}\n"],"names":["hostPublicOrigin","liveCustomDomain","siteContactEmail","text","value","max","trim","slice","prefillSiteUrl","host","subdomain","origin","cname","url","URL","protocol","hostname","includes","endsWith","EMAIL","stripeAccountPrefill","options","params","entity","seo","name","displayName","email","test","phone","telephone","digits","replace","length","PREFILL_FIELDS","missingBusinessProfilePrefill","prefill","account","profile","business_profile","missing","param","Object","entries","field","current"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SACEA,gBAAgB,EAChBC,gBAAgB,QAEX,qCAAoC;AAC3C,SAASC,gBAAgB,QAAQ,qCAAoC;AAoCrE,MAAMC,OAAO,CAACC,OAAgBC,MAC5B,OAAOD,UAAU,WAAWA,MAAME,IAAI,GAAGC,KAAK,CAAC,GAAGF,OAAO;AAE3D,wFAAwF,GACxF,OAAO,SAASG,eACdC,IAA0C,EAC1CC,SAAyB;QAGhBT;IADT,MAAMU,SAASX,iBAAiB;QAC9BY,KAAK,GAAEX,oBAAAA,iBAAiBQ,iBAAjBR,oBAA0B;QACjCS,WAAWP,KAAKM,wBAAAA,KAAMC,SAAS,EAAE,OAAOP,KAAKO,WAAW,OAAO;IACjE;IACA,IAAI,CAACC,QAAQ,OAAO;IACpB,IAAI;QACF,MAAME,MAAM,IAAIC,IAAIH;QACpB,IAAIE,IAAIE,QAAQ,KAAK,UAAU,OAAO;QACtC,IAAI,CAACF,IAAIG,QAAQ,CAACC,QAAQ,CAAC,QAAQJ,IAAIG,QAAQ,CAACE,QAAQ,CAAC,eAAe,OAAO;QAC/E,OAAOL,IAAIF,MAAM;I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AAI,CAAC;IACvD,MAAMC,UAAkC,CAAC;IACzC,KAAK,MAAM,CAACC,OAAOrC,MAAM,IAAIsC,OAAOC,OAAO,CAACP,SAAU;QACpD,MAAMQ,QAAQV,cAAc,CAACO,MAAM;QACnC,IAAI,CAACG,OAAO;QACZ,MAAMC,UAAUP,2BAAAA,OAAS,CAACM,MAAM;QAChC,IAAI,OAAOC,YAAY,YAAYA,QAAQvC,IAAI,IAAI;QACnDkC,OAAO,CAACC,MAAM,GAAGrC;IACnB;IACA,OAAOoC;AACT"}
@@ -16,8 +16,10 @@
16
16
  */
17
17
  import { type PluginApiHandler } from '@aglyn/aglyn/server';
18
18
  /**
19
- * Merchant payments onboarding (AGL-284): Stripe Connect Express for
20
- * storefront selling. Same account storage the checkout reads
19
+ * Merchant payments onboarding (AGL-284): a Stripe account for storefront
20
+ * selling, the store's own full Stripe account for every new setup
21
+ * (`DIRECT_CHARGE_ACCOUNT_PARAMS`, AGL-4245 for the prefill). Same account
22
+ * storage the checkout reads
21
23
  * (`profiles/{ownerUid}.stripeAccountId`, AGL-46) but without the
22
24
  * marketplace-profile prerequisite — commerce merchants aren't necessarily
23
25
  * publishers. Only the owning org's owner may onboard (payouts land on
@@ -15,8 +15,15 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import { firebaseAdmin, getOrgForHost, isServerReleaseFlagOnForOrg } from "@aglyn/tenant-data-admin";
18
- import { accountChargeModel, DIRECT_CHARGE_ACCOUNT_PARAMS, merchantAccountInOtherMode, merchantAccountReplacement, paymentProvider, PREVIOUS_MERCHANT_ACCOUNTS_FIELD } from "@aglyn/tenant-data-admin/server/payment-provider";
18
+ import { accountChargeModel, DIRECT_CHARGE_ACCOUNT_PARAMS, merchantAccountInOtherMode, merchantAccountReplacement, merchantRequirementsSummary, paymentProvider, PREVIOUS_MERCHANT_ACCOUNTS_FIELD } from "@aglyn/tenant-data-admin/server/payment-provider";
19
19
  import { buildRoute, Route } from "@aglyn/aglyn/server";
20
+ import { CONNECT_RETURN_PARAM } from "../model/payments-setup-status.js";
21
+ import { missingBusinessProfilePrefill, stripeAccountPrefill } from "./connect-prefill.js";
22
+ /** A Stripe refusal, carrying the HTTP status so a caller can tell a bad parameter from an outage. */ let StripeRequestError = class StripeRequestError extends Error {
23
+ constructor(message, status){
24
+ super(message), this.status = status;
25
+ }
26
+ };
20
27
  async function stripe(path, params) {
21
28
  const response = await fetch(`https://api.stripe.com/v1/${path}`, _extends({
22
29
  method: params ? 'POST' : 'GET',
@@ -32,13 +39,15 @@ async function stripe(path, params) {
32
39
  if (!response.ok) {
33
40
  var _ref;
34
41
  var _payload_error;
35
- throw new Error((_ref = payload == null ? void 0 : (_payload_error = payload.error) == null ? void 0 : _payload_error.message) != null ? _ref : `Stripe ${path} failed`);
42
+ throw new StripeRequestError((_ref = payload == null ? void 0 : (_payload_error = payload.error) == null ? void 0 : _payload_error.message) != null ? _ref : `Stripe ${path} failed`, response.status);
36
43
  }
37
44
  return payload;
38
45
  }
39
46
  /**
40
- * Merchant payments onboarding (AGL-284): Stripe Connect Express for
41
- * storefront selling. Same account storage the checkout reads
47
+ * Merchant payments onboarding (AGL-284): a Stripe account for storefront
48
+ * selling, the store's own full Stripe account for every new setup
49
+ * (`DIRECT_CHARGE_ACCOUNT_PARAMS`, AGL-4245 for the prefill). Same account
50
+ * storage the checkout reads
42
51
  * (`profiles/{ownerUid}.stripeAccountId`, AGL-46) but without the
43
52
  * marketplace-profile prerequisite — commerce merchants aren't necessarily
44
53
  * publishers. Only the owning org's owner may onboard (payouts land on
@@ -83,6 +92,25 @@ async function stripe(path, params) {
83
92
  }
84
93
  const firestore = firebaseAdmin.app().firestore();
85
94
  const profileRef = firestore.collection('profiles').doc(decoded.uid);
95
+ // The site's platform SUBDOMAIN, read once: the return links below need
96
+ // it, and so does the prefill's site address.
97
+ let subdomainRead;
98
+ const hostSubdomain = ()=>subdomainRead != null ? subdomainRead : subdomainRead = firestore.collection('hostIndex').doc(hostId).get().then((index)=>index.get('subdomain'));
99
+ // WHAT THE OWNER ALREADY TOLD US (AGL-4245): the site's business details
100
+ // and public address as Stripe `business_profile` fields, so Stripe's form
101
+ // opens filled in. Read from the site the owner is setting up from; a read
102
+ // that fails is no prefill, never a failed setup.
103
+ const readPrefill = async ()=>{
104
+ try {
105
+ const hostSnapshot = await firestore.collection('hosts').doc(hostId).get();
106
+ return stripeAccountPrefill((hostSnapshot == null ? void 0 : hostSnapshot.exists) ? hostSnapshot.data() : null, {
107
+ subdomain: await hostSubdomain()
108
+ });
109
+ } catch (error) {
110
+ console.warn('[AGL-4245] Stripe prefill skipped: the site could not be read', error);
111
+ return {};
112
+ }
113
+ };
86
114
  const profileSnapshot = await profileRef.get();
87
115
  // This deployment's Stripe mode, asked first: whether the stored account
88
116
  // can be used here at all depends on it (AGL-2471).
@@ -121,18 +149,35 @@ async function stripe(path, params) {
121
149
  }
122
150
  replacedAccountId = accountId;
123
151
  }
152
+ // RE-ENTRY BEFORE ONBOARDING IS FINISHED (AGL-4245). `business_profile`
153
+ // stays writable by the platform on this account shape after the first
154
+ // onboarding link, so an owner who left Stripe's form part way gets the
155
+ // site's details on the way back in. Only the fields the account does
156
+ // not hold yet, so nothing typed in Stripe is overwritten, and any
157
+ // failure is logged and setup carries on.
158
+ if (account && account.details_submitted !== true) {
159
+ const missing = missingBusinessProfilePrefill(await readPrefill(), account);
160
+ if (Object.keys(missing).length) {
161
+ try {
162
+ account = await stripe(`accounts/${accountId}`, new URLSearchParams(missing));
163
+ } catch (error) {
164
+ console.warn(`[AGL-4245] Stripe refused the business profile update for ` + `profiles/${decoded.uid} (${error == null ? void 0 : error.message}); ` + `continuing setup without it.`);
165
+ }
166
+ }
167
+ }
124
168
  }
125
169
  if (!accountId || replacedAccountId) {
126
170
  // The seller's OWN Stripe account (direct charges): Stripe bills it,
127
171
  // underwrites it and gives it the full Stripe Dashboard, so the seller
128
172
  // is the merchant of record on every site sale and can refund, answer
129
173
  // a dispute and manage tax registrations there. See
130
- // `DIRECT_CHARGE_ACCOUNT_PARAMS`. Behind `release_direct_charges` until
131
- // the Terms say so; off, the platform-managed Express account and its
132
- // destination charges, exactly as before. The shape cannot be changed
133
- // once the account exists, so this is the one place it is decided.
134
- // Any failure to read the flag is OFF: the account it would create is
135
- // the one every store had before, never a shape nobody chose.
174
+ // `DIRECT_CHARGE_ACCOUNT_PARAMS`. `release_direct_charges` is on for
175
+ // every store (default on, and on in Remote Config), so this is the
176
+ // account every new setup gets. The flag is still read so it can be
177
+ // turned off: off, or unreadable, gives the platform-managed Express
178
+ // account and its destination charges, the shape stores had before.
179
+ // The shape cannot be changed once the account exists, so this is the
180
+ // one place it is decided.
136
181
  let ownsAccount = false;
137
182
  try {
138
183
  var _ref, _ref1;
@@ -141,13 +186,16 @@ async function stripe(path, params) {
141
186
  } catch (unused) {
142
187
  ownsAccount = false;
143
188
  }
144
- const created = await stripe('accounts', new URLSearchParams(_extends({}, ownsAccount ? DIRECT_CHARGE_ACCOUNT_PARAMS : {
189
+ // Everything the account is created with except the prefill: the
190
+ // shape, the capabilities and the bookkeeping. Kept apart so a create
191
+ // Stripe refuses over a prefill field can be sent again without it.
192
+ const accountParams = _extends({}, ownsAccount ? DIRECT_CHARGE_ACCOUNT_PARAMS : {
145
193
  type: 'express'
146
194
  }, {
147
195
  // Explicit capabilities (AGL-1994): `card_payments` for the
148
- // charges, and `transfers` because a destination charge (every
149
- // sale on an Express account, and the register and Tap to Pay on
150
- // either kind) requires the destination to hold it.
196
+ // charges, and `transfers` because a destination charge (every sale
197
+ // on an Express account, and the register and Tap to Pay on one)
198
+ // requires the destination to hold it.
151
199
  'capabilities[card_payments][requested]': 'true',
152
200
  'capabilities[transfers][requested]': 'true',
153
201
  'metadata[profileId]': decoded.uid,
@@ -156,7 +204,22 @@ async function stripe(path, params) {
156
204
  'metadata[replacesAccount]': replacedAccountId
157
205
  } : {}, decoded.email ? {
158
206
  email: decoded.email
159
- } : {})));
207
+ } : {});
208
+ const prefill = await readPrefill();
209
+ let created;
210
+ try {
211
+ created = await stripe('accounts', new URLSearchParams(_extends({}, prefill, accountParams)));
212
+ } catch (error) {
213
+ // A prefill field Stripe will not take (a phone it cannot parse, a
214
+ // site address it will not accept) must not stop setup: the owner can type
215
+ // it in Stripe's own form. Only a 400 with a prefill sent is retried;
216
+ // anything else is the 502 it always was.
217
+ if (!Object.keys(prefill).length || !(error instanceof StripeRequestError) || error.status !== 400) {
218
+ throw error;
219
+ }
220
+ console.warn(`[AGL-4245] Stripe refused the account prefill for ` + `profiles/${decoded.uid} (${error.message}); creating the ` + `account without it.`);
221
+ created = await stripe('accounts', new URLSearchParams(accountParams));
222
+ }
160
223
  accountId = String(created.id);
161
224
  if (replacedAccountId) {
162
225
  console.warn(`[AGL-2471] Replacing Stripe account ${replacedAccountId} on ` + `profiles/${decoded.uid}: it belongs to the other Stripe mode ` + `from this ${platformMode != null ? platformMode : 'unknown'}-mode deployment. New ` + `account ${accountId}.`);
@@ -203,7 +266,11 @@ async function stripe(path, params) {
203
266
  // every time, so a re-onboarded seller can never inherit the last
204
267
  // account's answer.
205
268
  const chargeModel = accountChargeModel(account);
206
- await profileRef.set({
269
+ // What Stripe still needs, read off the same account (AGL-4245): the
270
+ // Payments card warns from it before a deadline stops anything.
271
+ const requirements = merchantRequirementsSummary(account);
272
+ const needsDetails = Boolean(requirements && (requirements.stripeRequirementsDueCount > 0 || requirements.stripeRequirementsPastDueCount > 0));
273
+ await profileRef.set(_extends({}, requirements != null ? requirements : {}, {
207
274
  stripeChargesEnabled: chargesEnabled,
208
275
  stripeChargeModel: chargeModel,
209
276
  stripePayoutsEnabled: payoutsEnabled,
@@ -214,7 +281,7 @@ async function stripe(path, params) {
214
281
  // boolean, so the gate reads it as `mode-unverified` and refuses —
215
282
  // never a fabricated `true`.
216
283
  stripeAccountLivemode: platformMode ? platformMode === 'live' : null
217
- }, {
284
+ }), {
218
285
  merge: true
219
286
  });
220
287
  const origin = (_req_headers_origin = req.headers.origin) != null ? _req_headers_origin : `https://${req.headers.host}`;
@@ -224,17 +291,26 @@ async function stripe(path, params) {
224
291
  // (AGL-685). Console products is the plugin route under the org slug and
225
292
  // the host SUBDOMAIN, both of which have to be resolved here; the client
226
293
  // hook (useConsoleHostRoute) is not available to server code.
227
- const index = await firebaseAdmin.app().firestore().collection('hostIndex').doc(hostId).get();
228
- const subdomain = index.get('subdomain');
294
+ const subdomain = await hostSubdomain();
229
295
  const orgSlug = ownerOrg == null ? void 0 : (_ownerOrg_org1 = ownerOrg.org) == null ? void 0 : _ownerOrg_org1.slug;
230
296
  // No slug/subdomain means no route to send them to; Stripe requires
231
297
  // both URLs, so fall back to the origin root rather than a fabricated
232
298
  // path that 404s.
233
- const productsUrl = orgSlug && subdomain ? `${origin}${buildRoute(Route.HOST_PLUGIN, {
299
+ //
300
+ // The PAYMENTS section, not bare `/products` (AGL-4245): the bare hub
301
+ // redirects to the first section, Catalog, where nothing read the
302
+ // parameter, so an owner back from Stripe saw no result at all.
303
+ const paymentsUrl = orgSlug && subdomain ? `${origin}${buildRoute(Route.HOST_PLUGIN, {
234
304
  orgSlug,
235
305
  host: subdomain,
236
306
  pluginSlug: 'products'
237
- })}` : origin;
307
+ })}/payments` : origin;
308
+ const onboardingLink = ()=>stripe('account_links', new URLSearchParams({
309
+ account: accountId,
310
+ type: 'account_onboarding',
311
+ refresh_url: `${paymentsUrl}?${CONNECT_RETURN_PARAM}=refresh`,
312
+ return_url: `${paymentsUrl}?${CONNECT_RETURN_PARAM}=done`
313
+ }));
238
314
  // A CONNECTED MERCHANT STILL NEEDS A DOOR INTO STRIPE.
239
315
  //
240
316
  // This route used to return here the moment `charges_enabled` was true,
@@ -247,25 +323,33 @@ async function stripe(path, params) {
247
323
  // a link minted here is the merchant's ONLY way in; without one the money
248
324
  // is unreachable and no surface says why.
249
325
  if (chargesEnabled) {
326
+ var _ref2;
327
+ var _this;
250
328
  if (!payoutsEnabled) {
251
329
  // The remediation flow, which is what Stripe points an account with
252
330
  // outstanding requirements at. Failures are NOT swallowed: answering
253
331
  // 200 with no link is precisely the dead end being closed here, so a
254
332
  // mint that fails surfaces as the handler's 502 and the merchant is
255
333
  // told to try again rather than left pressing a dead button.
256
- const fix = await stripe('account_links', new URLSearchParams({
257
- account: accountId,
258
- type: 'account_onboarding',
259
- refresh_url: `${productsUrl}?connect=refresh`,
260
- return_url: `${productsUrl}?connect=done`
261
- }));
334
+ const fix = await onboardingLink();
262
335
  return res.status(200).json({
263
336
  accountId,
264
337
  chargesEnabled: true,
265
338
  payoutsEnabled,
339
+ needsDetails,
266
340
  url: fix.url
267
341
  });
268
342
  }
343
+ // Payouts flowing, and Stripe asking for more before a deadline
344
+ // (AGL-4245): the same onboarding form fixes it, so the answer carries
345
+ // its link beside the dashboard. The card follows it only when the
346
+ // owner pressed "Continue setup"; a status check stays a status check.
347
+ const fixUrl = needsDetails ? String((_ref2 = (_this = await onboardingLink()) == null ? void 0 : _this.url) != null ? _ref2 : '') || undefined : undefined;
348
+ const detailsLink = _extends({
349
+ needsDetails
350
+ }, fixUrl ? {
351
+ url: fixUrl
352
+ } : {});
269
353
  // Payouts are flowing, so this is the VIEW: balance, payout schedule,
270
354
  // and the reason a payout failed — none of which Aglyn records and none
271
355
  // of which the merchant could otherwise reach. Best-effort on purpose:
@@ -275,12 +359,13 @@ async function stripe(path, params) {
275
359
  if (chargeModel === 'direct') {
276
360
  // A full Stripe account signs in to Stripe itself; login links exist
277
361
  // only for Express accounts.
278
- return res.status(200).json({
362
+ return res.status(200).json(_extends({
279
363
  accountId,
280
364
  chargesEnabled: true,
281
- payoutsEnabled,
365
+ payoutsEnabled
366
+ }, detailsLink, {
282
367
  dashboardUrl: 'https://dashboard.stripe.com/'
283
- });
368
+ }));
284
369
  }
285
370
  try {
286
371
  const login = await stripe(`accounts/${accountId}/login_links`, new URLSearchParams());
@@ -292,16 +377,11 @@ async function stripe(path, params) {
292
377
  accountId,
293
378
  chargesEnabled: true,
294
379
  payoutsEnabled
295
- }, dashboardUrl ? {
380
+ }, detailsLink, dashboardUrl ? {
296
381
  dashboardUrl
297
382
  } : {}));
298
383
  }
299
- const link = await stripe('account_links', new URLSearchParams({
300
- account: accountId,
301
- type: 'account_onboarding',
302
- refresh_url: `${productsUrl}?connect=refresh`,
303
- return_url: `${productsUrl}?connect=done`
304
- }));
384
+ const link = await onboardingLink();
305
385
  return res.status(200).json({
306
386
  accountId,
307
387
  chargesEnabled: false,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/connect.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n firebaseAdmin,\n getOrgForHost,\n isServerReleaseFlagOnForOrg,\n} from '@aglyn/tenant-data-admin'\nimport {\n accountChargeModel,\n DIRECT_CHARGE_ACCOUNT_PARAMS,\n merchantAccountInOtherMode,\n merchantAccountReplacement,\n paymentProvider,\n PREVIOUS_MERCHANT_ACCOUNTS_FIELD,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\n\nasync function stripe(path: string, params?: URLSearchParams) {\n const response = await fetch(`https://api.stripe.com/v1/${path}`, {\n method: params ? 'POST' : 'GET',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(params && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n },\n ...(params && { body: params.toString() }),\n })\n const payload = await response.json()\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed`)\n }\n return payload\n}\n\n/**\n * Merchant payments onboarding (AGL-284): Stripe Connect Express for\n * storefront selling. Same account storage the checkout reads\n * (`profiles/{ownerUid}.stripeAccountId`, AGL-46) but without the\n * marketplace-profile prerequisite — commerce merchants aren't necessarily\n * publishers. Only the owning org's owner may onboard (payouts land on\n * their account). 501 without Stripe env.\n */\nexport const connectHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res\n .status(501)\n .json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const ownerOrg = await getOrgForHost(hostId)\n const ownerUid = ownerOrg?.org?.ownerUid\n if (!ownerUid) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n if (String(ownerUid) !== decoded.uid) {\n return res\n .status(403)\n .json({ error: 'Only the organization owner can set up payments' })\n }\n const firestore = firebaseAdmin.app().firestore()\n const profileRef = firestore.collection('profiles').doc(decoded.uid)\n const profileSnapshot = await profileRef.get()\n\n // This deployment's Stripe mode, asked first: whether the stored account\n // can be used here at all depends on it (AGL-2471).\n const platformMode = await paymentProvider().resolvePlatformMode()\n let accountId = profileSnapshot.get('stripeAccountId') as\n | string\n | undefined\n // AN ACCOUNT FROM THE OTHER STRIPE MODE IS REPLACED, NEVER RESUMED.\n //\n // A test account on a live deployment (a localhost session onboarded with\n // the test key while writing production Firestore, see\n // `payment-provider-stripe-connect.ts`) can never take a live payment, and\n // a live key cannot even read it: Stripe refuses the retrieve. This route\n // used to retrieve it anyway, so the owner pressing \"Set up payments\" got\n // \"Payment setup failed\" every time and the store could not sell. Two\n // ways in:\n //\n // - `mode-mismatch`: the profile RECORDS the other mode. Not read at all,\n // since the read cannot succeed.\n // - `mode-unverified` (and any recorded mode Stripe contradicts): the\n // account is read, and a read that succeeds is the proof it is in this\n // mode, recorded below exactly as before. Only Stripe's own cross-mode\n // refusal retires it; any other failure is the 502 it always was.\n //\n // A new account is then created in this mode, of the shape every new\n // setup takes (direct charges, below), and the replaced id is kept on the\n // profile (`merchantAccountReplacement`).\n let account: any\n let replacedAccountId: string | undefined\n if (\n accountId &&\n merchantAccountInOtherMode(\n profileSnapshot.get('stripeAccountLivemode'),\n platformMode,\n )\n ) {\n replacedAccountId = accountId\n } else if (accountId) {\n try {\n account = await stripe(`accounts/${accountId}`)\n } catch (error) {\n if (!paymentProvider().refusedAsOtherMode((error as Error)?.message)) {\n throw error\n }\n replacedAccountId = accountId\n }\n }\n if (!accountId || replacedAccountId) {\n // The seller's OWN Stripe account (direct charges): Stripe bills it,\n // underwrites it and gives it the full Stripe Dashboard, so the seller\n // is the merchant of record on every site sale and can refund, answer\n // a dispute and manage tax registrations there. See\n // `DIRECT_CHARGE_ACCOUNT_PARAMS`. Behind `release_direct_charges` until\n // the Terms say so; off, the platform-managed Express account and its\n // destination charges, exactly as before. The shape cannot be changed\n // once the account exists, so this is the one place it is decided.\n // Any failure to read the flag is OFF: the account it would create is\n // the one every store had before, never a shape nobody chose.\n let ownsAccount = false\n try {\n ownsAccount = await isServerReleaseFlagOnForOrg(\n 'release_direct_charges',\n String(ownerOrg?.org?.id ?? ownerOrg?.orgId ?? '') || null,\n )\n } catch {\n ownsAccount = false\n }\n const created = await stripe(\n 'accounts',\n new URLSearchParams({\n ...(ownsAccount\n ? DIRECT_CHARGE_ACCOUNT_PARAMS\n : { type: 'express' }),\n // Explicit capabilities (AGL-1994): `card_payments` for the\n // charges, and `transfers` because a destination charge (every\n // sale on an Express account, and the register and Tap to Pay on\n // either kind) requires the destination to hold it.\n 'capabilities[card_payments][requested]': 'true',\n 'capabilities[transfers][requested]': 'true',\n 'metadata[profileId]': decoded.uid,\n 'metadata[purpose]': 'commerce',\n ...(replacedAccountId\n ? { 'metadata[replacesAccount]': replacedAccountId }\n : {}),\n ...(decoded.email ? { email: decoded.email } : {}),\n }),\n )\n accountId = String(created.id)\n if (replacedAccountId) {\n console.warn(\n `[AGL-2471] Replacing Stripe account ${replacedAccountId} on ` +\n `profiles/${decoded.uid}: it belongs to the other Stripe mode ` +\n `from this ${platformMode ?? 'unknown'}-mode deployment. New ` +\n `account ${accountId}.`,\n )\n await profileRef.set(\n merchantAccountReplacement({\n previousAccountIds: profileSnapshot.get(\n PREVIOUS_MERCHANT_ACCOUNTS_FIELD,\n ),\n replacedAccountId,\n newAccountId: accountId,\n }),\n { merge: true },\n )\n } else {\n await profileRef.set(\n { stripeAccountId: accountId, stripeChargesEnabled: false },\n { merge: true },\n )\n }\n account = await stripe(`accounts/${accountId}`)\n }\n\n const chargesEnabled = Boolean(account?.charges_enabled)\n // WHICH STRIPE WORLD THIS ACCOUNT LIVES IN (AGL-2471).\n //\n // Three production linkages named TEST-mode accounts, one of them with\n // `stripeChargesEnabled: true`, so its storefronts read as payments-ready\n // and could not take a payment. Nothing recorded the mode, and nothing\n // could recover it later: the Account object carries no `livemode` field\n // and an `acct_…` id is the same shape in both worlds.\n //\n // The retrieve above IS the proof. Stripe refuses cross-mode account\n // access outright — \"was a test account created with a testmode key\" —\n // so an account this key just fetched is in this key's mode, and the\n // payment provider asks Stripe (`/v1/balance.livemode`) what that mode is\n // rather than reading the key string (`platformMode`, asked first).\n // Payout readiness rides along (AGL-1994): the sale gate stays on\n // charges_enabled — that is what Stripe checks at charge time — but\n // charges-yes/payouts-no was invisible to the storefront, because\n // commerce wrote only `stripeChargesEnabled`. Recording\n // `payouts_enabled` is what lets a console surface warn a merchant\n // BEFORE the first sale strands funds in a Connect account that\n // cannot pay them out.\n const payoutsEnabled = Boolean(account?.payouts_enabled)\n // Which charge shape this account takes, read off the account itself\n // every time, so a re-onboarded seller can never inherit the last\n // account's answer.\n const chargeModel = accountChargeModel(account)\n await profileRef.set(\n {\n stripeChargesEnabled: chargesEnabled,\n stripeChargeModel: chargeModel,\n stripePayoutsEnabled: payoutsEnabled,\n // ALWAYS written, and `null` when Stripe would not say (AGL-2471).\n // Writing unconditionally is what makes re-onboarding safe: a fresh\n // `stripeAccountId` on a document that still carried the PREVIOUS\n // account's verdict would otherwise inherit it. `null` is not a\n // boolean, so the gate reads it as `mode-unverified` and refuses —\n // never a fabricated `true`.\n stripeAccountLivemode: platformMode ? platformMode === 'live' : null,\n },\n { merge: true },\n )\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n // Stripe bakes these into the onboarding link, so they have to be real\n // console paths. They were `/{hostDocId}/products` — the pre-AGL-621/622\n // shape — so finishing Connect onboarding dropped the seller on a 404\n // (AGL-685). Console products is the plugin route under the org slug and\n // the host SUBDOMAIN, both of which have to be resolved here; the client\n // hook (useConsoleHostRoute) is not available to server code.\n const index = await firebaseAdmin\n .app()\n .firestore()\n .collection('hostIndex')\n .doc(hostId)\n .get()\n const subdomain = index.get('subdomain') as string | undefined\n const orgSlug = ownerOrg?.org?.slug as string | undefined\n // No slug/subdomain means no route to send them to; Stripe requires\n // both URLs, so fall back to the origin root rather than a fabricated\n // path that 404s.\n const productsUrl =\n orgSlug && subdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug,\n host: subdomain,\n pluginSlug: 'products',\n })}`\n : origin\n // A CONNECTED MERCHANT STILL NEEDS A DOOR INTO STRIPE.\n //\n // This route used to return here the moment `charges_enabled` was true,\n // with a status and no link of any kind, and both console cards read the\n // `chargesEnabled` flag before they ever looked for a url. So the one\n // state that most needs Stripe — charges on, payouts NOT released, funds\n // accumulating in a Connect account that cannot pay them out — offered a\n // button labelled \"Finish payout setup in Stripe\" that raised a toast and\n // went nowhere. An Express account has no password and no direct login, so\n // a link minted here is the merchant's ONLY way in; without one the money\n // is unreachable and no surface says why.\n if (chargesEnabled) {\n if (!payoutsEnabled) {\n // The remediation flow, which is what Stripe points an account with\n // outstanding requirements at. Failures are NOT swallowed: answering\n // 200 with no link is precisely the dead end being closed here, so a\n // mint that fails surfaces as the handler's 502 and the merchant is\n // told to try again rather than left pressing a dead button.\n const fix = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${productsUrl}?connect=refresh`,\n return_url: `${productsUrl}?connect=done`,\n }),\n )\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n url: fix.url,\n })\n }\n // Payouts are flowing, so this is the VIEW: balance, payout schedule,\n // and the reason a payout failed — none of which Aglyn records and none\n // of which the merchant could otherwise reach. Best-effort on purpose:\n // a login link is a convenience, and failing to mint one must never turn\n // a working status check into an error.\n let dashboardUrl: string | undefined\n if (chargeModel === 'direct') {\n // A full Stripe account signs in to Stripe itself; login links exist\n // only for Express accounts.\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n dashboardUrl: 'https://dashboard.stripe.com/',\n })\n }\n try {\n const login = await stripe(\n `accounts/${accountId}/login_links`,\n new URLSearchParams(),\n )\n dashboardUrl = typeof login?.url === 'string' ? login.url : undefined\n } catch (error) {\n console.error('Stripe Express dashboard link failed', error)\n }\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n ...(dashboardUrl ? { dashboardUrl } : {}),\n })\n }\n\n const link = await stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${productsUrl}?connect=refresh`,\n return_url: `${productsUrl}?connect=done`,\n }),\n )\n return res\n .status(200)\n .json({ accountId, chargesEnabled: false, url: link.url })\n } catch (error) {\n console.error(error)\n return res.status(502).json({ error: 'Payment setup failed' })\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","isServerReleaseFlagOnForOrg","accountChargeModel","DIRECT_CHARGE_ACCOUNT_PARAMS","merchantAccountInOtherMode","merchantAccountReplacement","paymentProvider","PREVIOUS_MERCHANT_ACCOUNTS_FIELD","buildRoute","Route","stripe","path","params","response","fetch","method","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","ok","Error","error","message","connectHandler","req","res","status","authorization","String","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","ownerOrg","decoded","app","auth","verifyIdToken","ownerUid","org","uid","firestore","profileRef","collection","doc","profileSnapshot","get","platformMode","resolvePlatformMode","accountId","account","replacedAccountId","refusedAsOtherMode","ownsAccount","id","orgId","created","URLSearchParams","type","email","console","warn","set","previousAccountIds","newAccountId","merge","stripeAccountId","stripeChargesEnabled","chargesEnabled","Boolean","charges_enabled","payoutsEnabled","payouts_enabled","chargeModel","stripeChargeModel","stripePayoutsEnabled","stripeAccountLivemode","origin","host","index","subdomain","orgSlug","slug","productsUrl","HOST_PLUGIN","pluginSlug","fix","refresh_url","return_url","url","dashboardUrl","login","link"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,aAAa,EACbC,aAAa,EACbC,2BAA2B,QACtB,2BAA0B;AACjC,SACEC,kBAAkB,EAClBC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,0BAA0B,EAC1BC,eAAe,EACfC,gCAAgC,QAC3B,mDAAkD;AACzD,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAE9E,eAAeC,OAAOC,IAAY,EAAEC,MAAwB;IAC1D,MAAMC,WAAW,MAAMC,MAAM,CAAC,0BAA0B,EAAEH,MAAM,EAAE;QAChEI,QAAQH,SAAS,SAAS;QAC1BI,SAAS;YACPC,eAAe,CAAC,OAAO,EAAEC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;WACpDR,UAAU;YACZ,gBAAgB;QAClB;OAEEA,UAAU;QAAES,MAAMT,OAAOU,QAAQ;IAAG;IAE1C,MAAMC,UAAU,MAAMV,SAASW,IAAI;IACnC,IAAI,CA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BAAAA,MAAOF,GAAG,MAAK,WAAWE,MAAMF,GAAG,GAAG5D;YAC9D,EAAE,OAAOZ,OAAO;gBACd2C,QAAQ3C,KAAK,CAAC,wCAAwCA;YACxD;YACA,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;gBAC1BmC;gBACAmB,gBAAgB;gBAChBG;eACImB,eAAe;gBAAEA;YAAa,IAAI,CAAC;QAE3C;QAEA,MAAME,OAAO,MAAM5F,OACjB,iBACA,IAAIyD,gBAAgB;YAClBP,SAASD;YACTS,MAAM;YACN6B,aAAa,GAAGJ,YAAY,gBAAgB,CAAC;YAC7CK,YAAY,GAAGL,YAAY,aAAa,CAAC;QAC3C;QAEF,OAAO9D,IACJC,MAAM,CAAC,KACPR,IAAI,CAAC;YAAEmC;YAAWmB,gBAAgB;YAAOqB,KAAKG,KAAKH,GAAG;QAAC;IAC5D,EAAE,OAAOxE,OAAO;QACd2C,QAAQ3C,KAAK,CAACA;QACd,OAAOI,IAAIC,MAAM,CAAC,KAAKR,IAAI,CAAC;YAAEG,OAAO;QAAuB;IAC9D;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/connect.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n firebaseAdmin,\n getOrgForHost,\n isServerReleaseFlagOnForOrg,\n} from '@aglyn/tenant-data-admin'\nimport {\n accountChargeModel,\n DIRECT_CHARGE_ACCOUNT_PARAMS,\n merchantAccountInOtherMode,\n merchantAccountReplacement,\n merchantRequirementsSummary,\n paymentProvider,\n PREVIOUS_MERCHANT_ACCOUNTS_FIELD,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { CONNECT_RETURN_PARAM } from '../model/payments-setup-status'\nimport {\n missingBusinessProfilePrefill,\n stripeAccountPrefill,\n type StripePrefillHost,\n} from './connect-prefill'\n\n/** A Stripe refusal, carrying the HTTP status so a caller can tell a bad parameter from an outage. */\nclass StripeRequestError extends Error {\n constructor(\n message: string,\n readonly status: number,\n ) {\n super(message)\n }\n}\n\nasync function stripe(path: string, params?: URLSearchParams) {\n const response = await fetch(`https://api.stripe.com/v1/${path}`, {\n method: params ? 'POST' : 'GET',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(params && {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }),\n },\n ...(params && { body: params.toString() }),\n })\n const payload = await response.json()\n if (!response.ok) {\n throw new StripeRequestError(\n payload?.error?.message ?? `Stripe ${path} failed`,\n response.status,\n )\n }\n return payload\n}\n\n/**\n * Merchant payments onboarding (AGL-284): a Stripe account for storefront\n * selling, the store's own full Stripe account for every new setup\n * (`DIRECT_CHARGE_ACCOUNT_PARAMS`, AGL-4245 for the prefill). Same account\n * storage the checkout reads\n * (`profiles/{ownerUid}.stripeAccountId`, AGL-46) but without the\n * marketplace-profile prerequisite — commerce merchants aren't necessarily\n * publishers. Only the owning org's owner may onboard (payouts land on\n * their account). 501 without Stripe env.\n */\nexport const connectHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res\n .status(501)\n .json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const ownerOrg = await getOrgForHost(hostId)\n const ownerUid = ownerOrg?.org?.ownerUid\n if (!ownerUid) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n if (String(ownerUid) !== decoded.uid) {\n return res\n .status(403)\n .json({ error: 'Only the organization owner can set up payments' })\n }\n const firestore = firebaseAdmin.app().firestore()\n const profileRef = firestore.collection('profiles').doc(decoded.uid)\n // The site's platform SUBDOMAIN, read once: the return links below need\n // it, and so does the prefill's site address.\n let subdomainRead: Promise<string | undefined> | undefined\n const hostSubdomain = () =>\n (subdomainRead ??= firestore\n .collection('hostIndex')\n .doc(hostId)\n .get()\n .then((index) => index.get('subdomain') as string | undefined))\n // WHAT THE OWNER ALREADY TOLD US (AGL-4245): the site's business details\n // and public address as Stripe `business_profile` fields, so Stripe's form\n // opens filled in. Read from the site the owner is setting up from; a read\n // that fails is no prefill, never a failed setup.\n const readPrefill = async (): Promise<Record<string, string>> => {\n try {\n const hostSnapshot = await firestore.collection('hosts').doc(hostId).get()\n return stripeAccountPrefill(\n (hostSnapshot?.exists ? hostSnapshot.data() : null) as StripePrefillHost | null,\n { subdomain: await hostSubdomain() },\n )\n } catch (error) {\n console.warn('[AGL-4245] Stripe prefill skipped: the site could not be read', error)\n return {}\n }\n }\n const profileSnapshot = await profileRef.get()\n\n // This deployment's Stripe mode, asked first: whether the stored account\n // can be used here at all depends on it (AGL-2471).\n const platformMode = await paymentProvider().resolvePlatformMode()\n let accountId = profileSnapshot.get('stripeAccountId') as\n | string\n | undefined\n // AN ACCOUNT FROM THE OTHER STRIPE MODE IS REPLACED, NEVER RESUMED.\n //\n // A test account on a live deployment (a localhost session onboarded with\n // the test key while writing production Firestore, see\n // `payment-provider-stripe-connect.ts`) can never take a live payment, and\n // a live key cannot even read it: Stripe refuses the retrieve. This route\n // used to retrieve it anyway, so the owner pressing \"Set up payments\" got\n // \"Payment setup failed\" every time and the store could not sell. Two\n // ways in:\n //\n // - `mode-mismatch`: the profile RECORDS the other mode. Not read at all,\n // since the read cannot succeed.\n // - `mode-unverified` (and any recorded mode Stripe contradicts): the\n // account is read, and a read that succeeds is the proof it is in this\n // mode, recorded below exactly as before. Only Stripe's own cross-mode\n // refusal retires it; any other failure is the 502 it always was.\n //\n // A new account is then created in this mode, of the shape every new\n // setup takes (direct charges, below), and the replaced id is kept on the\n // profile (`merchantAccountReplacement`).\n let account: any\n let replacedAccountId: string | undefined\n if (\n accountId &&\n merchantAccountInOtherMode(\n profileSnapshot.get('stripeAccountLivemode'),\n platformMode,\n )\n ) {\n replacedAccountId = accountId\n } else if (accountId) {\n try {\n account = await stripe(`accounts/${accountId}`)\n } catch (error) {\n if (!paymentProvider().refusedAsOtherMode((error as Error)?.message)) {\n throw error\n }\n replacedAccountId = accountId\n }\n // RE-ENTRY BEFORE ONBOARDING IS FINISHED (AGL-4245). `business_profile`\n // stays writable by the platform on this account shape after the first\n // onboarding link, so an owner who left Stripe's form part way gets the\n // site's details on the way back in. Only the fields the account does\n // not hold yet, so nothing typed in Stripe is overwritten, and any\n // failure is logged and setup carries on.\n if (account && account.details_submitted !== true) {\n const missing = missingBusinessProfilePrefill(await readPrefill(), account)\n if (Object.keys(missing).length) {\n try {\n account = await stripe(`accounts/${accountId}`, new URLSearchParams(missing))\n } catch (error) {\n console.warn(\n `[AGL-4245] Stripe refused the business profile update for ` +\n `profiles/${decoded.uid} (${(error as Error)?.message}); ` +\n `continuing setup without it.`,\n )\n }\n }\n }\n }\n if (!accountId || replacedAccountId) {\n // The seller's OWN Stripe account (direct charges): Stripe bills it,\n // underwrites it and gives it the full Stripe Dashboard, so the seller\n // is the merchant of record on every site sale and can refund, answer\n // a dispute and manage tax registrations there. See\n // `DIRECT_CHARGE_ACCOUNT_PARAMS`. `release_direct_charges` is on for\n // every store (default on, and on in Remote Config), so this is the\n // account every new setup gets. The flag is still read so it can be\n // turned off: off, or unreadable, gives the platform-managed Express\n // account and its destination charges, the shape stores had before.\n // The shape cannot be changed once the account exists, so this is the\n // one place it is decided.\n let ownsAccount = false\n try {\n ownsAccount = await isServerReleaseFlagOnForOrg(\n 'release_direct_charges',\n String(ownerOrg?.org?.id ?? ownerOrg?.orgId ?? '') || null,\n )\n } catch {\n ownsAccount = false\n }\n // Everything the account is created with except the prefill: the\n // shape, the capabilities and the bookkeeping. Kept apart so a create\n // Stripe refuses over a prefill field can be sent again without it.\n const accountParams: Record<string, string> = {\n ...(ownsAccount ? DIRECT_CHARGE_ACCOUNT_PARAMS : { type: 'express' }),\n // Explicit capabilities (AGL-1994): `card_payments` for the\n // charges, and `transfers` because a destination charge (every sale\n // on an Express account, and the register and Tap to Pay on one)\n // requires the destination to hold it.\n 'capabilities[card_payments][requested]': 'true',\n 'capabilities[transfers][requested]': 'true',\n 'metadata[profileId]': decoded.uid,\n 'metadata[purpose]': 'commerce',\n ...(replacedAccountId\n ? { 'metadata[replacesAccount]': replacedAccountId }\n : {}),\n ...(decoded.email ? { email: decoded.email } : {}),\n }\n const prefill = await readPrefill()\n let created: any\n try {\n created = await stripe(\n 'accounts',\n new URLSearchParams({ ...prefill, ...accountParams }),\n )\n } catch (error) {\n // A prefill field Stripe will not take (a phone it cannot parse, a\n // site address it will not accept) must not stop setup: the owner can type\n // it in Stripe's own form. Only a 400 with a prefill sent is retried;\n // anything else is the 502 it always was.\n if (\n !Object.keys(prefill).length ||\n !(error instanceof StripeRequestError) ||\n error.status !== 400\n ) {\n throw error\n }\n console.warn(\n `[AGL-4245] Stripe refused the account prefill for ` +\n `profiles/${decoded.uid} (${error.message}); creating the ` +\n `account without it.`,\n )\n created = await stripe('accounts', new URLSearchParams(accountParams))\n }\n accountId = String(created.id)\n if (replacedAccountId) {\n console.warn(\n `[AGL-2471] Replacing Stripe account ${replacedAccountId} on ` +\n `profiles/${decoded.uid}: it belongs to the other Stripe mode ` +\n `from this ${platformMode ?? 'unknown'}-mode deployment. New ` +\n `account ${accountId}.`,\n )\n await profileRef.set(\n merchantAccountReplacement({\n previousAccountIds: profileSnapshot.get(\n PREVIOUS_MERCHANT_ACCOUNTS_FIELD,\n ),\n replacedAccountId,\n newAccountId: accountId,\n }),\n { merge: true },\n )\n } else {\n await profileRef.set(\n { stripeAccountId: accountId, stripeChargesEnabled: false },\n { merge: true },\n )\n }\n account = await stripe(`accounts/${accountId}`)\n }\n\n const chargesEnabled = Boolean(account?.charges_enabled)\n // WHICH STRIPE WORLD THIS ACCOUNT LIVES IN (AGL-2471).\n //\n // Three production linkages named TEST-mode accounts, one of them with\n // `stripeChargesEnabled: true`, so its storefronts read as payments-ready\n // and could not take a payment. Nothing recorded the mode, and nothing\n // could recover it later: the Account object carries no `livemode` field\n // and an `acct_…` id is the same shape in both worlds.\n //\n // The retrieve above IS the proof. Stripe refuses cross-mode account\n // access outright — \"was a test account created with a testmode key\" —\n // so an account this key just fetched is in this key's mode, and the\n // payment provider asks Stripe (`/v1/balance.livemode`) what that mode is\n // rather than reading the key string (`platformMode`, asked first).\n // Payout readiness rides along (AGL-1994): the sale gate stays on\n // charges_enabled — that is what Stripe checks at charge time — but\n // charges-yes/payouts-no was invisible to the storefront, because\n // commerce wrote only `stripeChargesEnabled`. Recording\n // `payouts_enabled` is what lets a console surface warn a merchant\n // BEFORE the first sale strands funds in a Connect account that\n // cannot pay them out.\n const payoutsEnabled = Boolean(account?.payouts_enabled)\n // Which charge shape this account takes, read off the account itself\n // every time, so a re-onboarded seller can never inherit the last\n // account's answer.\n const chargeModel = accountChargeModel(account)\n // What Stripe still needs, read off the same account (AGL-4245): the\n // Payments card warns from it before a deadline stops anything.\n const requirements = merchantRequirementsSummary(account)\n const needsDetails = Boolean(\n requirements &&\n (requirements.stripeRequirementsDueCount > 0 ||\n requirements.stripeRequirementsPastDueCount > 0),\n )\n await profileRef.set(\n {\n ...(requirements ?? {}),\n stripeChargesEnabled: chargesEnabled,\n stripeChargeModel: chargeModel,\n stripePayoutsEnabled: payoutsEnabled,\n // ALWAYS written, and `null` when Stripe would not say (AGL-2471).\n // Writing unconditionally is what makes re-onboarding safe: a fresh\n // `stripeAccountId` on a document that still carried the PREVIOUS\n // account's verdict would otherwise inherit it. `null` is not a\n // boolean, so the gate reads it as `mode-unverified` and refuses —\n // never a fabricated `true`.\n stripeAccountLivemode: platformMode ? platformMode === 'live' : null,\n },\n { merge: true },\n )\n const origin = req.headers.origin ?? `https://${req.headers.host}`\n // Stripe bakes these into the onboarding link, so they have to be real\n // console paths. They were `/{hostDocId}/products` — the pre-AGL-621/622\n // shape — so finishing Connect onboarding dropped the seller on a 404\n // (AGL-685). Console products is the plugin route under the org slug and\n // the host SUBDOMAIN, both of which have to be resolved here; the client\n // hook (useConsoleHostRoute) is not available to server code.\n const subdomain = await hostSubdomain()\n const orgSlug = ownerOrg?.org?.slug as string | undefined\n // No slug/subdomain means no route to send them to; Stripe requires\n // both URLs, so fall back to the origin root rather than a fabricated\n // path that 404s.\n //\n // The PAYMENTS section, not bare `/products` (AGL-4245): the bare hub\n // redirects to the first section, Catalog, where nothing read the\n // parameter, so an owner back from Stripe saw no result at all.\n const paymentsUrl =\n orgSlug && subdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug,\n host: subdomain,\n pluginSlug: 'products',\n })}/payments`\n : origin\n const onboardingLink = () =>\n stripe(\n 'account_links',\n new URLSearchParams({\n account: accountId as string,\n type: 'account_onboarding',\n refresh_url: `${paymentsUrl}?${CONNECT_RETURN_PARAM}=refresh`,\n return_url: `${paymentsUrl}?${CONNECT_RETURN_PARAM}=done`,\n }),\n )\n // A CONNECTED MERCHANT STILL NEEDS A DOOR INTO STRIPE.\n //\n // This route used to return here the moment `charges_enabled` was true,\n // with a status and no link of any kind, and both console cards read the\n // `chargesEnabled` flag before they ever looked for a url. So the one\n // state that most needs Stripe — charges on, payouts NOT released, funds\n // accumulating in a Connect account that cannot pay them out — offered a\n // button labelled \"Finish payout setup in Stripe\" that raised a toast and\n // went nowhere. An Express account has no password and no direct login, so\n // a link minted here is the merchant's ONLY way in; without one the money\n // is unreachable and no surface says why.\n if (chargesEnabled) {\n if (!payoutsEnabled) {\n // The remediation flow, which is what Stripe points an account with\n // outstanding requirements at. Failures are NOT swallowed: answering\n // 200 with no link is precisely the dead end being closed here, so a\n // mint that fails surfaces as the handler's 502 and the merchant is\n // told to try again rather than left pressing a dead button.\n const fix = await onboardingLink()\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n needsDetails,\n url: fix.url,\n })\n }\n // Payouts flowing, and Stripe asking for more before a deadline\n // (AGL-4245): the same onboarding form fixes it, so the answer carries\n // its link beside the dashboard. The card follows it only when the\n // owner pressed \"Continue setup\"; a status check stays a status check.\n const fixUrl = needsDetails\n ? String((await onboardingLink())?.url ?? '') || undefined\n : undefined\n const detailsLink = {\n needsDetails,\n ...(fixUrl ? { url: fixUrl } : {}),\n }\n // Payouts are flowing, so this is the VIEW: balance, payout schedule,\n // and the reason a payout failed — none of which Aglyn records and none\n // of which the merchant could otherwise reach. Best-effort on purpose:\n // a login link is a convenience, and failing to mint one must never turn\n // a working status check into an error.\n let dashboardUrl: string | undefined\n if (chargeModel === 'direct') {\n // A full Stripe account signs in to Stripe itself; login links exist\n // only for Express accounts.\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n ...detailsLink,\n dashboardUrl: 'https://dashboard.stripe.com/',\n })\n }\n try {\n const login = await stripe(\n `accounts/${accountId}/login_links`,\n new URLSearchParams(),\n )\n dashboardUrl = typeof login?.url === 'string' ? login.url : undefined\n } catch (error) {\n console.error('Stripe Express dashboard link failed', error)\n }\n return res.status(200).json({\n accountId,\n chargesEnabled: true,\n payoutsEnabled,\n ...detailsLink,\n ...(dashboardUrl ? { dashboardUrl } : {}),\n })\n }\n\n const link = await onboardingLink()\n return res\n .status(200)\n .json({ accountId, chargesEnabled: false, url: link.url })\n } catch (error) {\n console.error(error)\n return res.status(502).json({ error: 'Payment setup failed' })\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","isServerReleaseFlagOnForOrg","accountChargeModel","DIRECT_CHARGE_ACCOUNT_PARAMS","merchantAccountInOtherMode","merchantAccountReplacement","merchantRequirementsSummary","paymentProvider","PREVIOUS_MERCHANT_ACCOUNTS_FIELD","buildRoute","Route","CONNECT_RETURN_PARAM","missingBusinessProfilePrefill","stripeAccountPrefill","StripeRequestError","Error","message","status","stripe","path","params","response","fetch","method","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","ok","error","connectHandler","req","res","authorization","String","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","ownerOrg","decoded","app","auth","verifyIdToken","ownerUid","org","uid","firestore","profileRef","collection","doc","subdomainRead","hostSubdomain","get","then","index","readPrefill","hostSnapshot","exists","data","subdomain","console","warn","profileSnapshot","platformMode","resolvePlatformMode","accountId","account","replacedAccountId","refusedAsOtherMode","details_submitted","missing","Object","keys","URLSearchParams","ownsAccount","id","orgId","accountParams","type","email","prefill","created","set","previousAccountIds","newAccountId","merge","stripeAccountId","stripeChargesEnabled","chargesEnabled","Boolean","charges_enabled","payoutsEnabled","payouts_enabled","chargeModel","requirements","needsDetails","stripeRequirementsDueCount","stripeRequirementsPastDueCount","stripeChargeModel","stripePayoutsEnabled","stripeAccountLivemode","origin","host","orgSlug","slug","paymentsUrl","HOST_PLUGIN","pluginSlug","onboardingLink","refresh_url","return_url","fix","url","fixUrl","detailsLink","dashboardUrl","login","link"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,aAAa,EACbC,aAAa,EACbC,2BAA2B,QACtB,2BAA0B;AACjC,SACEC,kBAAkB,EAClBC,4BAA4B,EAC5BC,0BAA0B,EAC1BC,0BAA0B,EAC1BC,2BAA2B,EAC3BC,eAAe,EACfC,gCAAgC,QAC3B,mDAAkD;AACzD,SAASC,UAAU,EAAEC,KA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YAAO,IAAI,CAAC;YAElC,sEAAsE;YACtE,wEAAwE;YACxE,uEAAuE;YACvE,yEAAyE;YACzE,wCAAwC;YACxC,IAAIE;YACJ,IAAItB,gBAAgB,UAAU;gBAC5B,qEAAqE;gBACrE,6BAA6B;gBAC7B,OAAOlE,IAAIpB,MAAM,CAAC,KAAKe,IAAI,CAAC;oBAC1B2C;oBACAuB,gBAAgB;oBAChBG;mBACGuB;oBACHC,cAAc;;YAElB;YACA,IAAI;gBACF,MAAMC,QAAQ,MAAM5G,OAClB,CAAC,SAAS,EAAEyD,UAAU,YAAY,CAAC,EACnC,IAAIQ;gBAEN0C,eAAe,QAAOC,yBAAAA,MAAOJ,GAAG,MAAK,WAAWI,MAAMJ,GAAG,GAAG9E;YAC9D,EAAE,OAAOV,OAAO;gBACdoC,QAAQpC,KAAK,CAAC,wCAAwCA;YACxD;YACA,OAAOG,IAAIpB,MAAM,CAAC,KAAKe,IAAI,CAAC;gBAC1B2C;gBACAuB,gBAAgB;gBAChBG;eACGuB,aACCC,eAAe;gBAAEA;YAAa,IAAI,CAAC;QAE3C;QAEA,MAAME,OAAO,MAAMT;QACnB,OAAOjF,IACJpB,MAAM,CAAC,KACPe,IAAI,CAAC;YAAE2C;YAAWuB,gBAAgB;YAAOwB,KAAKK,KAAKL,GAAG;QAAC;IAC5D,EAAE,OAAOxF,OAAO;QACdoC,QAAQpC,KAAK,CAACA;QACd,OAAOG,IAAIpB,MAAM,CAAC,KAAKe,IAAI,CAAC;YAAEE,OAAO;QAAuB;IAC9D;AACF,EAAC"}
@@ -23,7 +23,7 @@ import { connectedAccountHeader, directChargeParams, merchantAccountIsReady, sal
23
23
  import { checkoutSessionCardAuthenticationParams } from "@aglyn/tenant-data-admin/server/stripe-card-authentication";
24
24
  import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
25
25
  import { resolveManualTaxRateId } from "./manual-tax-rate.js";
26
- import { SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE, sellerStripeTaxActive } from "./seller-stripe-account.js";
26
+ import { SELLER_STRIPE_TAX_NOT_SET_UP_MANAGER_MESSAGE, sellerStripeTaxActive } from "./seller-stripe-account.js";
27
27
  import { orderStatusUrl } from "./order-status-token.js";
28
28
  import { holdPromotionSlot, promotionHoldKey } from "./promotion-hold.js";
29
29
  import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
@@ -372,8 +372,10 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
372
372
  // not set up, and a store that chose it must not sell untaxed. Above the
373
373
  // claim and the order write with the other tax refusals.
374
374
  if (direct && useStripeTax && !await sellerStripeTaxActive(String(accountId))) {
375
+ // The manager making the link reads this, not a shopper (AGL-4245), so
376
+ // it says what to do rather than "try again later".
375
377
  return res.status(409).json({
376
- error: SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE
378
+ error: SELLER_STRIPE_TAX_NOT_SET_UP_MANAGER_MESSAGE
377
379
  });
378
380
  }
379
381
  const manualRate = taxDecision.kind === 'manual' && !taxSettings.pricesIncludeTax ? CommerceModel.resolveTaxRate(taxSettings, (_taxSettings_origin = taxSettings.origin) != null ? _taxSettings_origin : {}) : null;