@aglyn/plugins-commerce 1.33.1 → 1.34.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.
- package/package.json +13 -13
- package/src/lib/components/cart.js +3 -1
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js +82 -69
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +46 -25
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/gift-cards-card.component.js +81 -55
- package/src/lib/components/console/gift-cards-card.component.js.map +1 -1
- package/src/lib/components/console/host-coupons-card.component.js +36 -25
- package/src/lib/components/console/host-coupons-card.component.js.map +1 -1
- package/src/lib/components/console/locations-card.component.js +53 -32
- package/src/lib/components/console/locations-card.component.js.map +1 -1
- package/src/lib/components/console/member-posts-card.component.js +35 -32
- package/src/lib/components/console/member-posts-card.component.js.map +1 -1
- package/src/lib/components/console/new-store-tax-question.component.d.ts +17 -0
- package/src/lib/components/console/new-store-tax-question.component.js +197 -0
- package/src/lib/components/console/new-store-tax-question.component.js.map +1 -0
- package/src/lib/components/console/payments-settings-card.component.js +132 -5
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-api.d.ts +6 -0
- package/src/lib/components/console/pos/pos-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-tax-notice.component.d.ts +21 -0
- package/src/lib/components/console/pos/pos-tax-notice.component.js +59 -0
- package/src/lib/components/console/pos/pos-tax-notice.component.js.map +1 -0
- package/src/lib/components/console/pos-page.component.js +65 -17
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/registers-card.component.js +21 -13
- package/src/lib/components/console/registers-card.component.js.map +1 -1
- package/src/lib/components/console/reviews-moderation-card.component.js +108 -68
- package/src/lib/components/console/reviews-moderation-card.component.js.map +1 -1
- package/src/lib/components/console/site-member-purchases.component.js +5 -3
- package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +2 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscriptions-card.component.js +13 -5
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +47 -40
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/product-choice-cards.js +2 -1
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/components/product-detail.js +9 -4
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.js +3 -1
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/related-products.js +2 -1
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/store-image-sizing.d.ts +46 -0
- package/src/lib/components/store-image-sizing.js +53 -0
- package/src/lib/components/store-image-sizing.js.map +1 -0
- package/src/lib/components/wishlist.js +2 -1
- package/src/lib/components/wishlist.js.map +1 -1
- package/src/lib/declarations.console-server.js +10 -0
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/model/commerce-tax-step.d.ts +123 -0
- package/src/lib/model/commerce-tax-step.js +185 -0
- package/src/lib/model/commerce-tax-step.js.map +1 -0
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/payments-setup-status.d.ts +40 -0
- package/src/lib/model/payments-setup-status.js +63 -0
- package/src/lib/model/payments-setup-status.js.map +1 -1
- package/src/lib/model/subscription-view.d.ts +19 -0
- package/src/lib/model/subscription-view.js +16 -0
- package/src/lib/model/subscription-view.js.map +1 -1
- package/src/lib/model/tap-to-pay-launch.d.ts +103 -0
- package/src/lib/model/tap-to-pay-launch.js +148 -0
- package/src/lib/model/tap-to-pay-launch.js.map +1 -0
- package/src/lib/plugin.js +12 -0
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/billing-webhook.js +140 -116
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/checkout.js +15 -4
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect-return.d.ts +83 -0
- package/src/lib/server/connect-return.js +105 -0
- package/src/lib/server/connect-return.js.map +1 -0
- package/src/lib/server/connect.d.ts +18 -0
- package/src/lib/server/connect.js +60 -6
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/new-store-tax.d.ts +10 -0
- package/src/lib/server/new-store-tax.js +43 -0
- package/src/lib/server/new-store-tax.js.map +1 -0
- package/src/lib/server/pos-payment.js +3 -2
- package/src/lib/server/pos-payment.js.map +1 -1
- package/src/lib/server/pos-tax-step.d.ts +43 -0
- package/src/lib/server/pos-tax-step.js +55 -0
- package/src/lib/server/pos-tax-step.js.map +1 -0
- package/src/lib/server/pos-terminal-connection-token.d.ts +10 -1
- package/src/lib/server/pos-terminal-connection-token.js +18 -7
- package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +9 -0
- package/src/lib/server/pos-terminal.js +17 -1
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/tap-to-pay-launch-admin.d.ts +18 -0
- package/src/lib/server/tap-to-pay-launch-admin.js +204 -0
- package/src/lib/server/tap-to-pay-launch-admin.js.map +1 -0
- package/src/lib/server/tap-to-pay-launch.d.ts +114 -0
- package/src/lib/server/tap-to-pay-launch.js +408 -0
- package/src/lib/server/tap-to-pay-launch.js.map +1 -0
- package/src/lib/server.js +15 -0
- package/src/lib/server.js.map +1 -1
|
@@ -0,0 +1,83 @@
|
|
|
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 { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server';
|
|
18
|
+
/**
|
|
19
|
+
* STRIPE'S ONBOARDING HANDS BACK TO THE APP THAT OPENED IT (AGL-4061).
|
|
20
|
+
*
|
|
21
|
+
* The apps open Stripe's hosted onboarding in the platform's secure browser,
|
|
22
|
+
* which closes by itself the moment a page sends it to the app's own scheme.
|
|
23
|
+
* Stripe only returns to an https address in live mode, so the onboarding
|
|
24
|
+
* link names this console route, and the route sends the browser on to the
|
|
25
|
+
* app. The app asks for it explicitly with `returnTo` on the connect route;
|
|
26
|
+
* the console's web card keeps returning to its own page.
|
|
27
|
+
*
|
|
28
|
+
* Which scheme: an Apple secure browser hears any scheme it is told to
|
|
29
|
+
* (`aglyn://`, both apps), but an Android Custom Tab hands a page over only
|
|
30
|
+
* to an app that claims the address, and both Android apps may be on one
|
|
31
|
+
* device. So Aglyn POS on Android asks for `returnTo: 'pos-app'`, its links
|
|
32
|
+
* carry `app=pos`, and the route answers with its own `aglyn-pos://`.
|
|
33
|
+
*
|
|
34
|
+
* Not an open redirect: the schemes and path are fixed here, chosen from a
|
|
35
|
+
* closed list ({@link CONNECT_APP_RETURNS}); the only things carried over are
|
|
36
|
+
* which of the two apps (`app=pos`, anything else is Aglyn) and the one-word
|
|
37
|
+
* result Stripe returned for (`done` or `refresh`, anything else is `done`).
|
|
38
|
+
*/
|
|
39
|
+
/** The path Stripe returns an app's onboarding to. */
|
|
40
|
+
export declare const CONNECT_APP_RETURN_PATH = "/api/commerce/connect-return";
|
|
41
|
+
/** Where the route sends the app's secure browser: the Aglyn app's own scheme (and both Apple apps'), a fixed path. */
|
|
42
|
+
export declare const CONNECT_APP_CALLBACK = "aglyn://payments/setup";
|
|
43
|
+
/** Aglyn POS on Android: its own scheme, the one address its Custom Tab hands back to it. */
|
|
44
|
+
export declare const CONNECT_POS_APP_CALLBACK = "aglyn-pos://payments/setup";
|
|
45
|
+
/** The query parameter an app's return links name the app by. */
|
|
46
|
+
export declare const CONNECT_RETURN_APP_PARAM = "app";
|
|
47
|
+
/**
|
|
48
|
+
* The connect route's `returnTo` values, each with the `app` value its links
|
|
49
|
+
* carry and where the return route then sends the browser. Nothing outside
|
|
50
|
+
* this list is accepted, and nothing a caller sends becomes an address.
|
|
51
|
+
*/
|
|
52
|
+
export declare const CONNECT_APP_RETURNS: {
|
|
53
|
+
readonly app: {
|
|
54
|
+
readonly app: any;
|
|
55
|
+
readonly callback: "aglyn://payments/setup";
|
|
56
|
+
};
|
|
57
|
+
readonly 'pos-app': {
|
|
58
|
+
readonly app: "pos";
|
|
59
|
+
readonly callback: "aglyn-pos://payments/setup";
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
export type ConnectAppReturn = keyof typeof CONNECT_APP_RETURNS;
|
|
63
|
+
/** A `returnTo` the connect route accepts, else null. */
|
|
64
|
+
export declare function connectAppReturn(value: unknown): ConnectAppReturn | null;
|
|
65
|
+
/** The fixed address the return route sends the browser to for the `app` value its link carried. */
|
|
66
|
+
export declare function connectAppCallback(value: unknown): string;
|
|
67
|
+
/** The return parameter's two values, `done` for anything that is not `refresh`. */
|
|
68
|
+
export declare function connectReturnResult(value: unknown): 'done' | 'refresh';
|
|
69
|
+
/**
|
|
70
|
+
* The console origin Stripe's return links name: the page's own origin for
|
|
71
|
+
* the web console, which sends one; for an app, which does not, the host the
|
|
72
|
+
* request was addressed to, over https. Only outside a production build (the
|
|
73
|
+
* local stack an app talks to over http, where Stripe's test mode takes an
|
|
74
|
+
* http return) does the proxy's stated protocol, or plain http, decide.
|
|
75
|
+
*/
|
|
76
|
+
export declare function connectRequestOrigin(req: Pick<PluginApiRequest, 'headers'>, env?: Record<string, string | undefined>): string;
|
|
77
|
+
/** The return and refresh links an app's onboarding is minted with. */
|
|
78
|
+
export declare function connectAppReturnUrls(origin: string, returnTo?: ConnectAppReturn): {
|
|
79
|
+
return_url: string;
|
|
80
|
+
refresh_url: string;
|
|
81
|
+
};
|
|
82
|
+
/** `GET /api/commerce/connect-return`: on to the app, with the one-word result. */
|
|
83
|
+
export declare const connectReturnHandler: PluginApiHandler;
|
|
@@ -0,0 +1,105 @@
|
|
|
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 { CONNECT_RETURN_PARAM } from "../model/payments-setup-status.js";
|
|
17
|
+
/**
|
|
18
|
+
* STRIPE'S ONBOARDING HANDS BACK TO THE APP THAT OPENED IT (AGL-4061).
|
|
19
|
+
*
|
|
20
|
+
* The apps open Stripe's hosted onboarding in the platform's secure browser,
|
|
21
|
+
* which closes by itself the moment a page sends it to the app's own scheme.
|
|
22
|
+
* Stripe only returns to an https address in live mode, so the onboarding
|
|
23
|
+
* link names this console route, and the route sends the browser on to the
|
|
24
|
+
* app. The app asks for it explicitly with `returnTo` on the connect route;
|
|
25
|
+
* the console's web card keeps returning to its own page.
|
|
26
|
+
*
|
|
27
|
+
* Which scheme: an Apple secure browser hears any scheme it is told to
|
|
28
|
+
* (`aglyn://`, both apps), but an Android Custom Tab hands a page over only
|
|
29
|
+
* to an app that claims the address, and both Android apps may be on one
|
|
30
|
+
* device. So Aglyn POS on Android asks for `returnTo: 'pos-app'`, its links
|
|
31
|
+
* carry `app=pos`, and the route answers with its own `aglyn-pos://`.
|
|
32
|
+
*
|
|
33
|
+
* Not an open redirect: the schemes and path are fixed here, chosen from a
|
|
34
|
+
* closed list ({@link CONNECT_APP_RETURNS}); the only things carried over are
|
|
35
|
+
* which of the two apps (`app=pos`, anything else is Aglyn) and the one-word
|
|
36
|
+
* result Stripe returned for (`done` or `refresh`, anything else is `done`).
|
|
37
|
+
*/ /** The path Stripe returns an app's onboarding to. */ export const CONNECT_APP_RETURN_PATH = '/api/commerce/connect-return';
|
|
38
|
+
/** Where the route sends the app's secure browser: the Aglyn app's own scheme (and both Apple apps'), a fixed path. */ export const CONNECT_APP_CALLBACK = 'aglyn://payments/setup';
|
|
39
|
+
/** Aglyn POS on Android: its own scheme, the one address its Custom Tab hands back to it. */ export const CONNECT_POS_APP_CALLBACK = 'aglyn-pos://payments/setup';
|
|
40
|
+
/** The query parameter an app's return links name the app by. */ export const CONNECT_RETURN_APP_PARAM = 'app';
|
|
41
|
+
/**
|
|
42
|
+
* The connect route's `returnTo` values, each with the `app` value its links
|
|
43
|
+
* carry and where the return route then sends the browser. Nothing outside
|
|
44
|
+
* this list is accepted, and nothing a caller sends becomes an address.
|
|
45
|
+
*/ export const CONNECT_APP_RETURNS = {
|
|
46
|
+
app: {
|
|
47
|
+
app: null,
|
|
48
|
+
callback: CONNECT_APP_CALLBACK
|
|
49
|
+
},
|
|
50
|
+
'pos-app': {
|
|
51
|
+
app: 'pos',
|
|
52
|
+
callback: CONNECT_POS_APP_CALLBACK
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
/** A `returnTo` the connect route accepts, else null. */ export function connectAppReturn(value) {
|
|
56
|
+
return value === 'app' || value === 'pos-app' ? value : null;
|
|
57
|
+
}
|
|
58
|
+
/** The fixed address the return route sends the browser to for the `app` value its link carried. */ export function connectAppCallback(value) {
|
|
59
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
60
|
+
return raw === CONNECT_APP_RETURNS['pos-app'].app ? CONNECT_APP_RETURNS['pos-app'].callback : CONNECT_APP_RETURNS.app.callback;
|
|
61
|
+
}
|
|
62
|
+
/** The return parameter's two values, `done` for anything that is not `refresh`. */ export function connectReturnResult(value) {
|
|
63
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
64
|
+
return raw === 'refresh' ? 'refresh' : 'done';
|
|
65
|
+
}
|
|
66
|
+
const firstHeader = (value)=>{
|
|
67
|
+
var _ref;
|
|
68
|
+
return String((_ref = Array.isArray(value) ? value[0] : value) != null ? _ref : '').split(',')[0].trim();
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* The console origin Stripe's return links name: the page's own origin for
|
|
72
|
+
* the web console, which sends one; for an app, which does not, the host the
|
|
73
|
+
* request was addressed to, over https. Only outside a production build (the
|
|
74
|
+
* local stack an app talks to over http, where Stripe's test mode takes an
|
|
75
|
+
* http return) does the proxy's stated protocol, or plain http, decide.
|
|
76
|
+
*/ export function connectRequestOrigin(req, env = process.env) {
|
|
77
|
+
const origin = firstHeader(req.headers.origin);
|
|
78
|
+
if (origin) return origin;
|
|
79
|
+
const host = firstHeader(req.headers.host);
|
|
80
|
+
if (env['NODE_ENV'] === 'production') return `https://${host}`;
|
|
81
|
+
const proto = firstHeader(req.headers['x-forwarded-proto']).toLowerCase();
|
|
82
|
+
return `${proto === 'https' ? 'https' : 'http'}://${host}`;
|
|
83
|
+
}
|
|
84
|
+
/** The return and refresh links an app's onboarding is minted with. */ export function connectAppReturnUrls(origin, returnTo = 'app') {
|
|
85
|
+
const app = CONNECT_APP_RETURNS[returnTo].app;
|
|
86
|
+
const named = app ? `&${CONNECT_RETURN_APP_PARAM}=${app}` : '';
|
|
87
|
+
const base = `${origin}${CONNECT_APP_RETURN_PATH}?${CONNECT_RETURN_PARAM}=`;
|
|
88
|
+
return {
|
|
89
|
+
return_url: `${base}done${named}`,
|
|
90
|
+
refresh_url: `${base}refresh${named}`
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/** `GET /api/commerce/connect-return`: on to the app, with the one-word result. */ export const connectReturnHandler = async (req, res)=>{
|
|
94
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
95
|
+
return res.status(405).json({
|
|
96
|
+
error: 'Method not allowed'
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const result = connectReturnResult(req.query[CONNECT_RETURN_PARAM]);
|
|
100
|
+
const callback = connectAppCallback(req.query[CONNECT_RETURN_APP_PARAM]);
|
|
101
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
102
|
+
return res.redirect(302, `${callback}?${CONNECT_RETURN_PARAM}=${result}`);
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
//# sourceMappingURL=connect-return.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/connect-return.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 { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport { CONNECT_RETURN_PARAM } from '../model/payments-setup-status'\n\n/**\n * STRIPE'S ONBOARDING HANDS BACK TO THE APP THAT OPENED IT (AGL-4061).\n *\n * The apps open Stripe's hosted onboarding in the platform's secure browser,\n * which closes by itself the moment a page sends it to the app's own scheme.\n * Stripe only returns to an https address in live mode, so the onboarding\n * link names this console route, and the route sends the browser on to the\n * app. The app asks for it explicitly with `returnTo` on the connect route;\n * the console's web card keeps returning to its own page.\n *\n * Which scheme: an Apple secure browser hears any scheme it is told to\n * (`aglyn://`, both apps), but an Android Custom Tab hands a page over only\n * to an app that claims the address, and both Android apps may be on one\n * device. So Aglyn POS on Android asks for `returnTo: 'pos-app'`, its links\n * carry `app=pos`, and the route answers with its own `aglyn-pos://`.\n *\n * Not an open redirect: the schemes and path are fixed here, chosen from a\n * closed list ({@link CONNECT_APP_RETURNS}); the only things carried over are\n * which of the two apps (`app=pos`, anything else is Aglyn) and the one-word\n * result Stripe returned for (`done` or `refresh`, anything else is `done`).\n */\n\n/** The path Stripe returns an app's onboarding to. */\nexport const CONNECT_APP_RETURN_PATH = '/api/commerce/connect-return'\n\n/** Where the route sends the app's secure browser: the Aglyn app's own scheme (and both Apple apps'), a fixed path. */\nexport const CONNECT_APP_CALLBACK = 'aglyn://payments/setup'\n\n/** Aglyn POS on Android: its own scheme, the one address its Custom Tab hands back to it. */\nexport const CONNECT_POS_APP_CALLBACK = 'aglyn-pos://payments/setup'\n\n/** The query parameter an app's return links name the app by. */\nexport const CONNECT_RETURN_APP_PARAM = 'app'\n\n/**\n * The connect route's `returnTo` values, each with the `app` value its links\n * carry and where the return route then sends the browser. Nothing outside\n * this list is accepted, and nothing a caller sends becomes an address.\n */\nexport const CONNECT_APP_RETURNS = {\n app: { app: null, callback: CONNECT_APP_CALLBACK },\n 'pos-app': { app: 'pos', callback: CONNECT_POS_APP_CALLBACK },\n} as const\n\nexport type ConnectAppReturn = keyof typeof CONNECT_APP_RETURNS\n\n/** A `returnTo` the connect route accepts, else null. */\nexport function connectAppReturn(value: unknown): ConnectAppReturn | null {\n return value === 'app' || value === 'pos-app' ? value : null\n}\n\n/** The fixed address the return route sends the browser to for the `app` value its link carried. */\nexport function connectAppCallback(value: unknown): string {\n const raw = Array.isArray(value) ? value[0] : value\n return raw === CONNECT_APP_RETURNS['pos-app'].app\n ? CONNECT_APP_RETURNS['pos-app'].callback\n : CONNECT_APP_RETURNS.app.callback\n}\n\n/** The return parameter's two values, `done` for anything that is not `refresh`. */\nexport function connectReturnResult(value: unknown): 'done' | 'refresh' {\n const raw = Array.isArray(value) ? value[0] : value\n return raw === 'refresh' ? 'refresh' : 'done'\n}\n\nconst firstHeader = (value: string | string[] | undefined): string =>\n String((Array.isArray(value) ? value[0] : value) ?? '')\n .split(',')[0]\n .trim()\n\n/**\n * The console origin Stripe's return links name: the page's own origin for\n * the web console, which sends one; for an app, which does not, the host the\n * request was addressed to, over https. Only outside a production build (the\n * local stack an app talks to over http, where Stripe's test mode takes an\n * http return) does the proxy's stated protocol, or plain http, decide.\n */\nexport function connectRequestOrigin(\n req: Pick<PluginApiRequest, 'headers'>,\n env: Record<string, string | undefined> = process.env,\n): string {\n const origin = firstHeader(req.headers.origin)\n if (origin) return origin\n const host = firstHeader(req.headers.host)\n if (env['NODE_ENV'] === 'production') return `https://${host}`\n const proto = firstHeader(req.headers['x-forwarded-proto']).toLowerCase()\n return `${proto === 'https' ? 'https' : 'http'}://${host}`\n}\n\n/** The return and refresh links an app's onboarding is minted with. */\nexport function connectAppReturnUrls(\n origin: string,\n returnTo: ConnectAppReturn = 'app',\n): {\n return_url: string\n refresh_url: string\n} {\n const app = CONNECT_APP_RETURNS[returnTo].app\n const named = app ? `&${CONNECT_RETURN_APP_PARAM}=${app}` : ''\n const base = `${origin}${CONNECT_APP_RETURN_PATH}?${CONNECT_RETURN_PARAM}=`\n return { return_url: `${base}done${named}`, refresh_url: `${base}refresh${named}` }\n}\n\n/** `GET /api/commerce/connect-return`: on to the app, with the one-word result. */\nexport const connectReturnHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const result = connectReturnResult(req.query[CONNECT_RETURN_PARAM])\n const callback = connectAppCallback(req.query[CONNECT_RETURN_APP_PARAM])\n res.setHeader('Cache-Control', 'no-store')\n return res.redirect(302, `${callback}?${CONNECT_RETURN_PARAM}=${result}`)\n}\n"],"names":["CONNECT_RETURN_PARAM","CONNECT_APP_RETURN_PATH","CONNECT_APP_CALLBACK","CONNECT_POS_APP_CALLBACK","CONNECT_RETURN_APP_PARAM","CONNECT_APP_RETURNS","app","callback","connectAppReturn","value","connectAppCallback","raw","Array","isArray","connectReturnResult","firstHeader","String","split","trim","connectRequestOrigin","req","env","process","origin","headers","host","proto","toLowerCase","connectAppReturnUrls","returnTo","named","base","return_url","refresh_url","connectReturnHandler","res","method","status","json","error","result","query","setHeader","redirect"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,oBAAoB,QAAQ,oCAAgC;AAErE;;;;;;;;;;;;;;;;;;;;CAoBC,GAED,oDAAoD,GACpD,OAAO,MAAMC,0BAA0B,+BAA8B;AAErE,qHAAqH,GACrH,OAAO,MAAMC,uBAAuB,yBAAwB;AAE5D,2FAA2F,GAC3F,OAAO,MAAMC,2BAA2B,6BAA4B;AAEpE,+DAA+D,GAC/D,OAAO,MAAMC,2BAA2B,MAAK;AAE7C;;;;CAIC,GACD,OAAO,MAAMC,sBAAsB;IACjCC,KAAK;QAAEA,KAAK;QAAMC,UAAUL;IAAqB;IACjD,WAAW;QAAEI,KAAK;QAAOC,UAAUJ;IAAyB;AAC9D,EAAU;AAIV,uDAAuD,GACvD,OAAO,SAASK,iBAAiBC,KAAc;IAC7C,OAAOA,UAAU,SAASA,UAAU,YAAYA,QAAQ;AAC1D;AAEA,kGAAkG,GAClG,OAAO,SAASC,mBAAmBD,KAAc;IAC/C,MAAME,MAAMC,MAAMC,OAAO,CAACJ,SAASA,KAAK,CAAC,EAAE,GAAGA;IAC9C,OAAOE,QAAQN,mBAAmB,CAAC,UAAU,CAACC,GAAG,GAC7CD,mBAAmB,CAAC,UAAU,CAACE,QAAQ,GACvCF,oBAAoBC,GAAG,CAACC,QAAQ;AAC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AAM,KAAK,SAAShB,IAAIgB,MAAM,KAAK,QAAQ;QACjD,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAAS1B,oBAAoBM,IAAIqB,KAAK,CAACzC,qBAAqB;IAClE,MAAMO,WAAWG,mBAAmBU,IAAIqB,KAAK,CAACrC,yBAAyB;IACvE+B,IAAIO,SAAS,CAAC,iBAAiB;IAC/B,OAAOP,IAAIQ,QAAQ,CAAC,KAAK,GAAGpC,SAAS,CAAC,EAAEP,qBAAqB,CAAC,EAAEwC,QAAQ;AAC1E,EAAC"}
|
|
@@ -15,6 +15,12 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import { type PluginApiHandler } from '@aglyn/aglyn/server';
|
|
18
|
+
/**
|
|
19
|
+
* Stripe is still checking what the owner submitted (AGL-4061): the account
|
|
20
|
+
* names fields under `pending_verification`, or Stripe disabled it for that
|
|
21
|
+
* reason. Says nothing about whether the owner has more to do.
|
|
22
|
+
*/
|
|
23
|
+
export declare function stripeIsVerifying(account: unknown): boolean;
|
|
18
24
|
/**
|
|
19
25
|
* Merchant payments onboarding (AGL-284): a Stripe account for storefront
|
|
20
26
|
* selling, the store's own full Stripe account for every new setup
|
|
@@ -24,5 +30,17 @@ import { type PluginApiHandler } from '@aglyn/aglyn/server';
|
|
|
24
30
|
* marketplace-profile prerequisite — commerce merchants aren't necessarily
|
|
25
31
|
* publishers. Only the owning org's owner may onboard (payouts land on
|
|
26
32
|
* their account). 501 without Stripe env.
|
|
33
|
+
*
|
|
34
|
+
* Two optional body fields (AGL-4061), each refused unless it is the one
|
|
35
|
+
* value it may be:
|
|
36
|
+
* - `sync: true` re-reads the account from Stripe and records what it says,
|
|
37
|
+
* as a status check always has, but creates no account, writes nothing to
|
|
38
|
+
* Stripe and mints no link. An app asks it whenever the owner may have
|
|
39
|
+
* just finished Stripe's form, so a store's readiness never waits on the
|
|
40
|
+
* `account.updated` webhook.
|
|
41
|
+
* - `returnTo: 'app'` (or `'pos-app'`, Aglyn POS on Android) mints the
|
|
42
|
+
* onboarding link with this route's app return (`connect-return.ts`),
|
|
43
|
+
* which closes the app's secure browser, instead of the console's
|
|
44
|
+
* Payments page.
|
|
27
45
|
*/
|
|
28
46
|
export declare const connectHandler: PluginApiHandler;
|
|
@@ -19,6 +19,7 @@ import { accountChargeModel, DIRECT_CHARGE_ACCOUNT_PARAMS, merchantAccountInOthe
|
|
|
19
19
|
import { buildRoute, Route } from "@aglyn/aglyn/server";
|
|
20
20
|
import { CONNECT_RETURN_PARAM } from "../model/payments-setup-status.js";
|
|
21
21
|
import { missingBusinessProfilePrefill, stripeAccountPrefill } from "./connect-prefill.js";
|
|
22
|
+
import { connectAppReturn, connectAppReturnUrls, connectRequestOrigin } from "./connect-return.js";
|
|
22
23
|
/** 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
24
|
constructor(message, status){
|
|
24
25
|
super(message), this.status = status;
|
|
@@ -43,6 +44,14 @@ async function stripe(path, params) {
|
|
|
43
44
|
}
|
|
44
45
|
return payload;
|
|
45
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Stripe is still checking what the owner submitted (AGL-4061): the account
|
|
49
|
+
* names fields under `pending_verification`, or Stripe disabled it for that
|
|
50
|
+
* reason. Says nothing about whether the owner has more to do.
|
|
51
|
+
*/ export function stripeIsVerifying(account) {
|
|
52
|
+
const requirements = account == null ? void 0 : account.requirements;
|
|
53
|
+
return Array.isArray(requirements == null ? void 0 : requirements.pending_verification) && requirements.pending_verification.length > 0 || (requirements == null ? void 0 : requirements.disabled_reason) === 'requirements.pending_verification';
|
|
54
|
+
}
|
|
46
55
|
/**
|
|
47
56
|
* Merchant payments onboarding (AGL-284): a Stripe account for storefront
|
|
48
57
|
* selling, the store's own full Stripe account for every new setup
|
|
@@ -52,6 +61,18 @@ async function stripe(path, params) {
|
|
|
52
61
|
* marketplace-profile prerequisite — commerce merchants aren't necessarily
|
|
53
62
|
* publishers. Only the owning org's owner may onboard (payouts land on
|
|
54
63
|
* their account). 501 without Stripe env.
|
|
64
|
+
*
|
|
65
|
+
* Two optional body fields (AGL-4061), each refused unless it is the one
|
|
66
|
+
* value it may be:
|
|
67
|
+
* - `sync: true` re-reads the account from Stripe and records what it says,
|
|
68
|
+
* as a status check always has, but creates no account, writes nothing to
|
|
69
|
+
* Stripe and mints no link. An app asks it whenever the owner may have
|
|
70
|
+
* just finished Stripe's form, so a store's readiness never waits on the
|
|
71
|
+
* `account.updated` webhook.
|
|
72
|
+
* - `returnTo: 'app'` (or `'pos-app'`, Aglyn POS on Android) mints the
|
|
73
|
+
* onboarding link with this route's app return (`connect-return.ts`),
|
|
74
|
+
* which closes the app's secure browser, instead of the console's
|
|
75
|
+
* Payments page.
|
|
55
76
|
*/ export const connectHandler = async (req, res)=>{
|
|
56
77
|
var _req_headers_authorization, _req_body, _body_hostId;
|
|
57
78
|
if (req.method !== 'POST') {
|
|
@@ -74,8 +95,19 @@ async function stripe(path, params) {
|
|
|
74
95
|
if (!hostId) return res.status(400).json({
|
|
75
96
|
error: 'Missing hostId'
|
|
76
97
|
});
|
|
98
|
+
if (body.sync !== undefined && body.sync !== true) {
|
|
99
|
+
return res.status(400).json({
|
|
100
|
+
error: 'Unknown sync'
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
const returnTo = connectAppReturn(body.returnTo);
|
|
104
|
+
if (body.returnTo !== undefined && !returnTo) {
|
|
105
|
+
return res.status(400).json({
|
|
106
|
+
error: 'Unknown returnTo'
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
const sync = body.sync === true;
|
|
77
110
|
try {
|
|
78
|
-
var _req_headers_origin;
|
|
79
111
|
var _ownerOrg_org, _ownerOrg_org1;
|
|
80
112
|
const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
|
|
81
113
|
const ownerOrg = await getOrgForHost(hostId);
|
|
@@ -155,7 +187,7 @@ async function stripe(path, params) {
|
|
|
155
187
|
// site's details on the way back in. Only the fields the account does
|
|
156
188
|
// not hold yet, so nothing typed in Stripe is overwritten, and any
|
|
157
189
|
// failure is logged and setup carries on.
|
|
158
|
-
if (account && account.details_submitted !== true) {
|
|
190
|
+
if (account && account.details_submitted !== true && !sync) {
|
|
159
191
|
const missing = missingBusinessProfilePrefill(await readPrefill(), account);
|
|
160
192
|
if (Object.keys(missing).length) {
|
|
161
193
|
try {
|
|
@@ -166,6 +198,17 @@ async function stripe(path, params) {
|
|
|
166
198
|
}
|
|
167
199
|
}
|
|
168
200
|
}
|
|
201
|
+
if (sync && (!accountId || replacedAccountId)) {
|
|
202
|
+
// Nothing in this mode to read: a status check never creates one.
|
|
203
|
+
return res.status(200).json({
|
|
204
|
+
accountId: null,
|
|
205
|
+
chargesEnabled: false,
|
|
206
|
+
payoutsEnabled: false,
|
|
207
|
+
needsDetails: false,
|
|
208
|
+
detailsSubmitted: false,
|
|
209
|
+
verifying: false
|
|
210
|
+
});
|
|
211
|
+
}
|
|
169
212
|
if (!accountId || replacedAccountId) {
|
|
170
213
|
// The seller's OWN Stripe account (direct charges): Stripe bills it,
|
|
171
214
|
// underwrites it and gives it the full Stripe Dashboard, so the seller
|
|
@@ -284,7 +327,17 @@ async function stripe(path, params) {
|
|
|
284
327
|
}), {
|
|
285
328
|
merge: true
|
|
286
329
|
});
|
|
287
|
-
|
|
330
|
+
if (sync) {
|
|
331
|
+
return res.status(200).json({
|
|
332
|
+
accountId,
|
|
333
|
+
chargesEnabled,
|
|
334
|
+
payoutsEnabled,
|
|
335
|
+
needsDetails,
|
|
336
|
+
detailsSubmitted: (account == null ? void 0 : account.details_submitted) === true,
|
|
337
|
+
verifying: stripeIsVerifying(account)
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
const origin = connectRequestOrigin(req);
|
|
288
341
|
// Stripe bakes these into the onboarding link, so they have to be real
|
|
289
342
|
// console paths. They were `/{hostDocId}/products` — the pre-AGL-621/622
|
|
290
343
|
// shape — so finishing Connect onboarding dropped the seller on a 404
|
|
@@ -305,12 +358,13 @@ async function stripe(path, params) {
|
|
|
305
358
|
host: subdomain,
|
|
306
359
|
pluginSlug: 'products'
|
|
307
360
|
})}/payments` : origin;
|
|
308
|
-
const onboardingLink = ()=>stripe('account_links', new URLSearchParams({
|
|
361
|
+
const onboardingLink = ()=>stripe('account_links', new URLSearchParams(_extends({
|
|
309
362
|
account: accountId,
|
|
310
|
-
type: 'account_onboarding'
|
|
363
|
+
type: 'account_onboarding'
|
|
364
|
+
}, returnTo ? connectAppReturnUrls(origin, returnTo) : {
|
|
311
365
|
refresh_url: `${paymentsUrl}?${CONNECT_RETURN_PARAM}=refresh`,
|
|
312
366
|
return_url: `${paymentsUrl}?${CONNECT_RETURN_PARAM}=done`
|
|
313
|
-
}));
|
|
367
|
+
})));
|
|
314
368
|
// A CONNECTED MERCHANT STILL NEEDS A DOOR INTO STRIPE.
|
|
315
369
|
//
|
|
316
370
|
// This route used to return here the moment `charges_enabled` was true,
|
|
@@ -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 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,EA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KAAKC;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"}
|
|
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'\nimport { connectAppReturn, connectAppReturnUrls, connectRequestOrigin } from './connect-return'\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 * Stripe is still checking what the owner submitted (AGL-4061): the account\n * names fields under `pending_verification`, or Stripe disabled it for that\n * reason. Says nothing about whether the owner has more to do.\n */\nexport function stripeIsVerifying(account: unknown): boolean {\n const requirements = (account as any)?.requirements\n return (\n (Array.isArray(requirements?.pending_verification) &&\n requirements.pending_verification.length > 0) ||\n requirements?.disabled_reason === 'requirements.pending_verification'\n )\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 *\n * Two optional body fields (AGL-4061), each refused unless it is the one\n * value it may be:\n * - `sync: true` re-reads the account from Stripe and records what it says,\n * as a status check always has, but creates no account, writes nothing to\n * Stripe and mints no link. An app asks it whenever the owner may have\n * just finished Stripe's form, so a store's readiness never waits on the\n * `account.updated` webhook.\n * - `returnTo: 'app'` (or `'pos-app'`, Aglyn POS on Android) mints the\n * onboarding link with this route's app return (`connect-return.ts`),\n * which closes the app's secure browser, instead of the console's\n * Payments page.\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 if (body.sync !== undefined && body.sync !== true) {\n return res.status(400).json({ error: 'Unknown sync' })\n }\n const returnTo = connectAppReturn(body.returnTo)\n if (body.returnTo !== undefined && !returnTo) {\n return res.status(400).json({ error: 'Unknown returnTo' })\n }\n const sync = body.sync === true\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 && !sync) {\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 (sync && (!accountId || replacedAccountId)) {\n // Nothing in this mode to read: a status check never creates one.\n return res.status(200).json({\n accountId: null,\n chargesEnabled: false,\n payoutsEnabled: false,\n needsDetails: false,\n detailsSubmitted: false,\n verifying: false,\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 if (sync) {\n return res.status(200).json({\n accountId,\n chargesEnabled,\n payoutsEnabled,\n needsDetails,\n detailsSubmitted: account?.details_submitted === true,\n verifying: stripeIsVerifying(account),\n })\n }\n const origin = connectRequestOrigin(req)\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 ...(returnTo\n ? connectAppReturnUrls(origin, returnTo)\n : {\n refresh_url: `${paymentsUrl}?${CONNECT_RETURN_PARAM}=refresh`,\n return_url: `${paymentsUrl}?${CONNECT_RETURN_PARAM}=done`,\n }),\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","connectAppReturn","connectAppReturnUrls","connectRequestOrigin","StripeRequestError","Error","message","status","stripe","path","params","response","fetch","method","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","ok","error","stripeIsVerifying","account","requirements","Array","isArray","pending_verification","length","disabled_reason","connectHandler","req","res","authorization","String","idToken","startsWith","slice","undefined","JSON","parse","hostId","sync","returnTo","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","replacedAccountId","refusedAsOtherMode","details_submitted","missing","Object","keys","URLSearchParams","chargesEnabled","payoutsEnabled","needsDetails","detailsSubmitted","verifying","ownsAccount","id","orgId","accountParams","type","email","prefill","created","set","previousAccountIds","newAccountId","merge","stripeAccountId","stripeChargesEnabled","Boolean","charges_enabled","payouts_enabled","chargeModel","stripeRequirementsDueCount","stripeRequirementsPastDueCount","stripeChargeModel","stripePayoutsEnabled","stripeAccountLivemode","origin","orgSlug","slug","paymentsUrl","HOST_PLUGIN","host","pluginSlug","onboardingLink","refresh_url","return_url","fix","url","fixUrl","detailsLink","dashboardUrl","login","link"],"mappings":";AAAA;;;;;;;;;;;;;;;CAe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gF,qCAAP,AAAC,MAAyBI,GAAG,oBAAI,OAAOhF,YAC/CA;YACJ,MAAMkF,cAAc;gBAClBvC;eACIsC,SAAS;gBAAED,KAAKC;YAAO,IAAI,CAAC;YAElC,sEAAsE;YACtE,wEAAwE;YACxE,uEAAuE;YACvE,yEAAyE;YACzE,wCAAwC;YACxC,IAAIE;YACJ,IAAIpB,gBAAgB,UAAU;gBAC5B,qEAAqE;gBACrE,6BAA6B;gBAC7B,OAAOrE,IAAI5B,MAAM,CAAC,KAAKe,IAAI,CAAC;oBAC1BoD;oBACAQ,gBAAgB;oBAChBC;mBACGwC;oBACHC,cAAc;;YAElB;YACA,IAAI;gBACF,MAAMC,QAAQ,MAAMrH,OAClB,CAAC,SAAS,EAAEkE,UAAU,YAAY,CAAC,EACnC,IAAIO;gBAEN2C,eAAe,QAAOC,yBAAAA,MAAOJ,GAAG,MAAK,WAAWI,MAAMJ,GAAG,GAAGhF;YAC9D,EAAE,OAAOjB,OAAO;gBACd6C,QAAQ7C,KAAK,CAAC,wCAAwCA;YACxD;YACA,OAAOW,IAAI5B,MAAM,CAAC,KAAKe,IAAI,CAAC;gBAC1BoD;gBACAQ,gBAAgB;gBAChBC;eACGwC,aACCC,eAAe;gBAAEA;YAAa,IAAI,CAAC;QAE3C;QAEA,MAAME,OAAO,MAAMT;QACnB,OAAOlF,IACJ5B,MAAM,CAAC,KACPe,IAAI,CAAC;YAAEoD;YAAWQ,gBAAgB;YAAOuC,KAAKK,KAAKL,GAAG;QAAC;IAC5D,EAAE,OAAOjG,OAAO;QACd6C,QAAQ7C,KAAK,CAACA;QACd,OAAOW,IAAI5B,MAAM,CAAC,KAAKe,IAAI,CAAC;YAAEE,OAAO;QAAuB;IAC9D;AACF,EAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SiteCreateAnswerSite } from '@aglyn/aglyn/plugin-manager/plugin-site-create-answers';
|
|
2
|
+
/**
|
|
3
|
+
* Saves the answer to "Do you charge sales tax?" from Create site (AGL-4061)
|
|
4
|
+
* on the site just created: `hosts/{hostId}/settings/store.tax`, as the Taxes
|
|
5
|
+
* editor saves it. Only onto a store that has not decided: a site that
|
|
6
|
+
* already holds an answer (a create resumed after one was saved) keeps it.
|
|
7
|
+
* No answer, or one that is not one, writes nothing, and the store decides
|
|
8
|
+
* later. Returns whether it wrote.
|
|
9
|
+
*/
|
|
10
|
+
export declare function applyNewStoreTaxAnswer(answer: unknown, site: SiteCreateAnswerSite): Promise<boolean>;
|
|
@@ -0,0 +1,43 @@
|
|
|
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 { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
17
|
+
import { newStoreTaxSettings } from "../model/commerce-tax-step.js";
|
|
18
|
+
/**
|
|
19
|
+
* Saves the answer to "Do you charge sales tax?" from Create site (AGL-4061)
|
|
20
|
+
* on the site just created: `hosts/{hostId}/settings/store.tax`, as the Taxes
|
|
21
|
+
* editor saves it. Only onto a store that has not decided: a site that
|
|
22
|
+
* already holds an answer (a create resumed after one was saved) keeps it.
|
|
23
|
+
* No answer, or one that is not one, writes nothing, and the store decides
|
|
24
|
+
* later. Returns whether it wrote.
|
|
25
|
+
*/ export async function applyNewStoreTaxAnswer(answer, site) {
|
|
26
|
+
const tax = newStoreTaxSettings(answer);
|
|
27
|
+
if (!tax) return false;
|
|
28
|
+
const firestore = firebaseAdmin.app().firestore();
|
|
29
|
+
const ref = firestore.collection('hosts').doc(site.hostId).collection('settings').doc('store');
|
|
30
|
+
return firestore.runTransaction(async (transaction)=>{
|
|
31
|
+
var _current_get;
|
|
32
|
+
const current = await transaction.get(ref);
|
|
33
|
+
if (current.exists && typeof ((_current_get = current.get('tax')) == null ? void 0 : _current_get.mode) === 'string') return false;
|
|
34
|
+
transaction.set(ref, {
|
|
35
|
+
tax
|
|
36
|
+
}, {
|
|
37
|
+
merge: true
|
|
38
|
+
});
|
|
39
|
+
return true;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
//# sourceMappingURL=new-store-tax.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/new-store-tax.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 */\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport type { SiteCreateAnswerSite } from '@aglyn/aglyn/plugin-manager/plugin-site-create-answers'\nimport { newStoreTaxSettings } from '../model/commerce-tax-step'\n\n/**\n * Saves the answer to \"Do you charge sales tax?\" from Create site (AGL-4061)\n * on the site just created: `hosts/{hostId}/settings/store.tax`, as the Taxes\n * editor saves it. Only onto a store that has not decided: a site that\n * already holds an answer (a create resumed after one was saved) keeps it.\n * No answer, or one that is not one, writes nothing, and the store decides\n * later. Returns whether it wrote.\n */\nexport async function applyNewStoreTaxAnswer(answer: unknown, site: SiteCreateAnswerSite): Promise<boolean> {\n const tax = newStoreTaxSettings(answer)\n if (!tax) return false\n const firestore = firebaseAdmin.app().firestore()\n const ref = firestore.collection('hosts').doc(site.hostId).collection('settings').doc('store')\n return firestore.runTransaction(async (transaction: any) => {\n const current = await transaction.get(ref)\n if (current.exists && typeof current.get('tax')?.mode === 'string') return false\n transaction.set(ref, { tax }, { merge: true })\n return true\n })\n}\n"],"names":["firebaseAdmin","newStoreTaxSettings","applyNewStoreTaxAnswer","answer","site","tax","firestore","app","ref","collection","doc","hostId","runTransaction","transaction","current","get","exists","mode","set","merge"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD,SAASA,aAAa,QAAQ,2BAA0B;AAExD,SAASC,mBAAmB,QAAQ,gCAA4B;AAEhE;;;;;;;CAOC,GACD,OAAO,eAAeC,uBAAuBC,MAAe,EAAEC,IAA0B;IACtF,MAAMC,MAAMJ,oBAAoBE;IAChC,IAAI,CAACE,KAAK,OAAO;IACjB,MAAMC,YAAYN,cAAcO,GAAG,GAAGD,SAAS;IAC/C,MAAME,MAAMF,UAAUG,UAAU,CAAC,SAASC,GAAG,CAACN,KAAKO,MAAM,EAAEF,UAAU,CAAC,YAAYC,GAAG,CAAC;IACtF,OAAOJ,UAAUM,cAAc,CAAC,OAAOC;YAERC;QAD7B,MAAMA,UAAU,MAAMD,YAAYE,GAAG,CAACP;QACtC,IAAIM,QAAQE,MAAM,IAAI,SAAOF,eAAAA,QAAQC,GAAG,CAAC,2BAAZD,aAAoBG,IAAI,MAAK,UAAU,OAAO;QAC3EJ,YAAYK,GAAG,CAACV,KAAK;YAAEH;QAAI,GAAG;YAAEc,OAAO;QAAK;QAC5C,OAAO;IACT;AACF"}
|
|
@@ -26,6 +26,7 @@ import { posOpsSettings } from "../pos-ops-config.js";
|
|
|
26
26
|
import { authorizePosStaff, posIdempotencyKey, posQueryBody, posRequestBody } from "./pos-auth.js";
|
|
27
27
|
import { applyPosPayment, deliverChosenPosReceipt, posPaymentId, posSaleSummary, readPosSale, releasePosSaleDiscount } from "./pos-sale.js";
|
|
28
28
|
import { posPaymentCashierId } from "./pos-sale-stamp.js";
|
|
29
|
+
import { posTaxStep } from "./pos-tax-step.js";
|
|
29
30
|
import { printPosSaleReceipt } from "./pos-print.js";
|
|
30
31
|
import { POS_CURRENCY, posStripe, posStripeErrorMessage, posStripeTestMode, posTerminalAvailable } from "./pos-stripe.js";
|
|
31
32
|
import { cancelPosCardPayment, createCardPresentIntent, posPaymentAccount, refreshPosCardPayment, retryCardPresentPayment, simulatePosReaderTap, startCardKeyedPayment, startCardLinkPayment, startCardPresentPayment } from "./pos-terminal.js";
|
|
@@ -83,7 +84,7 @@ import { isNoApplicationFeeToRefund } from "./stripe-refund.js";
|
|
|
83
84
|
const config = await getPluginConfig(staff.orgId || undefined, 'commerce', {
|
|
84
85
|
hostId
|
|
85
86
|
});
|
|
86
|
-
return res.status(200).json({
|
|
87
|
+
return res.status(200).json(_extends({
|
|
87
88
|
settings: posRegisterSettings(config),
|
|
88
89
|
// The register's own rules (AGL-3609): the shift it requires, the
|
|
89
90
|
// idle lock and the refund limit. The console reads the same config
|
|
@@ -102,7 +103,7 @@ import { isNoApplicationFeeToRefund } from "./stripe-refund.js";
|
|
|
102
103
|
hostId,
|
|
103
104
|
channel: 'pos'
|
|
104
105
|
})
|
|
105
|
-
});
|
|
106
|
+
}, await posTaxStep(staff)));
|
|
106
107
|
}
|
|
107
108
|
if (!orderId) return res.status(400).json({
|
|
108
109
|
error: 'Missing orderId'
|