@burdenoff/microfe-billing 2026.626.1 → 2026.708.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/billing/BillingAdminRoutes.js +74 -61
- package/dist/billing/BillingAdminRoutes.js.map +1 -1
- package/dist/billing/BillingRoot.js +84 -76
- package/dist/billing/BillingRoot.js.map +1 -1
- package/dist/billing/modules/checkout/hooks/useCheckout.js +0 -1
- package/dist/billing/modules/checkout/hooks/useCheckout.js.map +1 -1
- package/dist/billing/modules/earnings/api.js +67 -31
- package/dist/billing/modules/earnings/api.js.map +1 -1
- package/dist/billing/modules/earnings/index.js +4 -3
- package/dist/billing/modules/earnings/pages/DeveloperRevenueAdminPage.js +438 -0
- package/dist/billing/modules/earnings/pages/DeveloperRevenueAdminPage.js.map +1 -0
- package/dist/billing/modules/earnings/pages/PayoutAdminPage.js +106 -67
- package/dist/billing/modules/earnings/pages/PayoutAdminPage.js.map +1 -1
- package/dist/generated/global-operations.js +194 -111
- package/dist/generated/global-operations.js.map +1 -1
- package/dist/generated/global-types.js.map +1 -1
- package/package.json +1 -1
|
@@ -4,195 +4,203 @@ import { BillingAdminRoutes as n } from "./BillingAdminRoutes.js";
|
|
|
4
4
|
import { useCallback as r, useEffect as i } from "react";
|
|
5
5
|
import { ErrorBoundary as a } from "@burdenoff/fe-libs/shared/components";
|
|
6
6
|
import { FeatureFlagProvider as o } from "@burdenoff/fe-libs/shared/feature-flags";
|
|
7
|
-
import { Activity as s, Blocks as c, Coins as l,
|
|
8
|
-
import { jsx as
|
|
9
|
-
import { useI18n as
|
|
7
|
+
import { Activity as s, Blocks as c, Coins as l, DollarSign as u, Gauge as d, Gift as f, Landmark as p, LayoutDashboard as m, Package as h, RefreshCw as g, RotateCcw as _, Settings as v, Ticket as y, TicketCheck as b, TrendingUp as x } from "lucide-react";
|
|
8
|
+
import { jsx as S } from "react/jsx-runtime";
|
|
9
|
+
import { useI18n as C } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
|
|
10
10
|
//#region src/billing/BillingRoot.tsx
|
|
11
|
-
var
|
|
12
|
-
let { t:
|
|
13
|
-
let n =
|
|
11
|
+
var w = (w) => {
|
|
12
|
+
let { t: T } = C(), E = r((e, t) => {
|
|
13
|
+
let n = T(e);
|
|
14
14
|
return n === e ? t : n;
|
|
15
|
-
}, [
|
|
15
|
+
}, [T]), { registerNavItems: D, registerFooterItems: O, basePath: k = "/", mode: A = "user" } = w, j = (e, t) => (e.endsWith("/") ? e.slice(0, -1) : e) + (t.startsWith("/") ? t : `/${t}`);
|
|
16
16
|
return i(() => {
|
|
17
|
-
if (!
|
|
17
|
+
if (!D) return;
|
|
18
18
|
let e = [
|
|
19
19
|
{
|
|
20
20
|
id: "billing-overview",
|
|
21
|
-
label:
|
|
22
|
-
path:
|
|
23
|
-
icon: /* @__PURE__ */
|
|
21
|
+
label: E("billing.nav.billing", "Billing"),
|
|
22
|
+
path: k === "/" ? "/" : j(k, "overview"),
|
|
23
|
+
icon: /* @__PURE__ */ S(m, { size: 20 }),
|
|
24
24
|
order: 100,
|
|
25
25
|
group: "billing"
|
|
26
26
|
},
|
|
27
27
|
{
|
|
28
28
|
id: "billing-subscriptions",
|
|
29
|
-
label:
|
|
30
|
-
path:
|
|
31
|
-
icon: /* @__PURE__ */
|
|
29
|
+
label: E("billing.nav.subscriptions", "Subscriptions"),
|
|
30
|
+
path: j(k, "subscriptions"),
|
|
31
|
+
icon: /* @__PURE__ */ S(g, { size: 20 }),
|
|
32
32
|
order: 110,
|
|
33
33
|
group: "billing"
|
|
34
34
|
},
|
|
35
35
|
{
|
|
36
36
|
id: "billing-plans",
|
|
37
|
-
label:
|
|
38
|
-
path:
|
|
39
|
-
icon: /* @__PURE__ */
|
|
37
|
+
label: E("billing.nav.plans", "Plans"),
|
|
38
|
+
path: j(k, "plans"),
|
|
39
|
+
icon: /* @__PURE__ */ S(h, { size: 20 }),
|
|
40
40
|
order: 120,
|
|
41
41
|
group: "billing"
|
|
42
42
|
},
|
|
43
43
|
{
|
|
44
44
|
id: "billing-addons",
|
|
45
|
-
label:
|
|
46
|
-
path:
|
|
47
|
-
icon: /* @__PURE__ */
|
|
45
|
+
label: E("billing.nav.addons", "Addons"),
|
|
46
|
+
path: j(k, "addons"),
|
|
47
|
+
icon: /* @__PURE__ */ S(c, { size: 20 }),
|
|
48
48
|
order: 130,
|
|
49
49
|
group: "billing"
|
|
50
50
|
},
|
|
51
51
|
{
|
|
52
52
|
id: "billing-usage",
|
|
53
|
-
label:
|
|
54
|
-
path:
|
|
55
|
-
icon: /* @__PURE__ */
|
|
53
|
+
label: E("billing.nav.usage", "Usage"),
|
|
54
|
+
path: j(k, "usage"),
|
|
55
|
+
icon: /* @__PURE__ */ S(s, { size: 20 }),
|
|
56
56
|
order: 180,
|
|
57
57
|
group: "billing"
|
|
58
58
|
},
|
|
59
59
|
{
|
|
60
60
|
id: "billing-affiliate",
|
|
61
|
-
label:
|
|
62
|
-
path:
|
|
63
|
-
icon: /* @__PURE__ */
|
|
61
|
+
label: E("billing.nav.affiliate", "Affiliate"),
|
|
62
|
+
path: j(k, "affiliate"),
|
|
63
|
+
icon: /* @__PURE__ */ S(b, { size: 20 }),
|
|
64
64
|
order: 190,
|
|
65
65
|
group: "billing"
|
|
66
66
|
},
|
|
67
67
|
{
|
|
68
68
|
id: "billing-earnings",
|
|
69
|
-
label:
|
|
70
|
-
path:
|
|
71
|
-
icon: /* @__PURE__ */
|
|
69
|
+
label: E("billing.nav.earnings", "Earnings"),
|
|
70
|
+
path: j(k, "earnings"),
|
|
71
|
+
icon: /* @__PURE__ */ S(l, { size: 20 }),
|
|
72
72
|
order: 200,
|
|
73
73
|
group: "billing"
|
|
74
74
|
},
|
|
75
75
|
{
|
|
76
76
|
id: "billing-payouts",
|
|
77
|
-
label:
|
|
78
|
-
path:
|
|
79
|
-
icon: /* @__PURE__ */
|
|
77
|
+
label: E("billing.nav.payouts", "Payouts"),
|
|
78
|
+
path: j(k, "payouts"),
|
|
79
|
+
icon: /* @__PURE__ */ S(p, { size: 20 }),
|
|
80
80
|
order: 205,
|
|
81
81
|
group: "billing"
|
|
82
82
|
},
|
|
83
83
|
{
|
|
84
84
|
id: "billing-settings",
|
|
85
|
-
label:
|
|
86
|
-
path:
|
|
87
|
-
icon: /* @__PURE__ */
|
|
85
|
+
label: E("billing.nav.settings", "Settings"),
|
|
86
|
+
path: j(k, "settings"),
|
|
87
|
+
icon: /* @__PURE__ */ S(v, { size: 20 }),
|
|
88
88
|
order: 210,
|
|
89
89
|
group: "billing"
|
|
90
90
|
}
|
|
91
91
|
], t = [
|
|
92
92
|
{
|
|
93
93
|
id: "billing-plans",
|
|
94
|
-
label:
|
|
95
|
-
path:
|
|
96
|
-
icon: /* @__PURE__ */
|
|
94
|
+
label: E("billing.nav.plans", "Plans"),
|
|
95
|
+
path: j(k, "plans"),
|
|
96
|
+
icon: /* @__PURE__ */ S(h, { size: 20 }),
|
|
97
97
|
order: 100,
|
|
98
98
|
group: "billing"
|
|
99
99
|
},
|
|
100
100
|
{
|
|
101
101
|
id: "billing-addons",
|
|
102
|
-
label:
|
|
103
|
-
path:
|
|
104
|
-
icon: /* @__PURE__ */
|
|
102
|
+
label: E("billing.nav.addons", "Addons"),
|
|
103
|
+
path: j(k, "addons"),
|
|
104
|
+
icon: /* @__PURE__ */ S(c, { size: 20 }),
|
|
105
105
|
order: 110,
|
|
106
106
|
group: "billing"
|
|
107
107
|
},
|
|
108
108
|
{
|
|
109
109
|
id: "billing-quotas",
|
|
110
|
-
label:
|
|
111
|
-
path:
|
|
112
|
-
icon: /* @__PURE__ */
|
|
110
|
+
label: E("billing.nav.quotas", "Quotas"),
|
|
111
|
+
path: j(k, "quotas"),
|
|
112
|
+
icon: /* @__PURE__ */ S(d, { size: 20 }),
|
|
113
113
|
order: 120,
|
|
114
114
|
group: "billing"
|
|
115
115
|
},
|
|
116
116
|
{
|
|
117
117
|
id: "billing-coupons",
|
|
118
|
-
label:
|
|
119
|
-
path:
|
|
120
|
-
icon: /* @__PURE__ */
|
|
118
|
+
label: E("billing.nav.coupons", "Coupons"),
|
|
119
|
+
path: j(k, "coupons"),
|
|
120
|
+
icon: /* @__PURE__ */ S(y, { size: 20 }),
|
|
121
121
|
order: 130,
|
|
122
122
|
group: "billing"
|
|
123
123
|
},
|
|
124
124
|
{
|
|
125
125
|
id: "billing-promotions",
|
|
126
|
-
label:
|
|
127
|
-
path:
|
|
128
|
-
icon: /* @__PURE__ */
|
|
126
|
+
label: E("billing.nav.promotions", "Promotions"),
|
|
127
|
+
path: j(k, "promotions"),
|
|
128
|
+
icon: /* @__PURE__ */ S(f, { size: 20 }),
|
|
129
129
|
order: 135,
|
|
130
130
|
group: "billing"
|
|
131
131
|
},
|
|
132
132
|
{
|
|
133
133
|
id: "billing-credits-admin",
|
|
134
|
-
label:
|
|
135
|
-
path:
|
|
136
|
-
icon: /* @__PURE__ */
|
|
134
|
+
label: E("billing.nav.creditGrants", "Credit Grants"),
|
|
135
|
+
path: j(k, "credits"),
|
|
136
|
+
icon: /* @__PURE__ */ S(l, { size: 20 }),
|
|
137
137
|
order: 150,
|
|
138
138
|
group: "billing"
|
|
139
139
|
},
|
|
140
140
|
{
|
|
141
141
|
id: "billing-refunds",
|
|
142
|
-
label:
|
|
143
|
-
path:
|
|
144
|
-
icon: /* @__PURE__ */
|
|
142
|
+
label: E("billing.nav.refunds", "Refunds"),
|
|
143
|
+
path: j(k, "refunds"),
|
|
144
|
+
icon: /* @__PURE__ */ S(_, { size: 20 }),
|
|
145
145
|
order: 160,
|
|
146
146
|
group: "billing"
|
|
147
147
|
},
|
|
148
|
+
{
|
|
149
|
+
id: "billing-admin-developer-revenue",
|
|
150
|
+
label: E("billing.nav.developerRevenue", "Developer Revenue"),
|
|
151
|
+
path: j(k, "developer-revenue"),
|
|
152
|
+
icon: /* @__PURE__ */ S(u, { size: 20 }),
|
|
153
|
+
order: 164,
|
|
154
|
+
group: "billing"
|
|
155
|
+
},
|
|
148
156
|
{
|
|
149
157
|
id: "billing-admin-payouts",
|
|
150
|
-
label:
|
|
151
|
-
path:
|
|
152
|
-
icon: /* @__PURE__ */
|
|
158
|
+
label: E("billing.nav.payouts", "Payouts"),
|
|
159
|
+
path: j(k, "payouts"),
|
|
160
|
+
icon: /* @__PURE__ */ S(p, { size: 20 }),
|
|
153
161
|
order: 165,
|
|
154
162
|
group: "billing"
|
|
155
163
|
},
|
|
156
164
|
{
|
|
157
165
|
id: "billing-analytics",
|
|
158
|
-
label:
|
|
159
|
-
path:
|
|
160
|
-
icon: /* @__PURE__ */ x
|
|
166
|
+
label: E("billing.nav.analytics", "Analytics"),
|
|
167
|
+
path: j(k, "analytics"),
|
|
168
|
+
icon: /* @__PURE__ */ S(x, { size: 20 }),
|
|
161
169
|
order: 170,
|
|
162
170
|
group: "billing"
|
|
163
171
|
}
|
|
164
172
|
];
|
|
165
|
-
return
|
|
173
|
+
return D(A === "admin" ? t : e);
|
|
166
174
|
}, [
|
|
167
|
-
|
|
168
|
-
O,
|
|
175
|
+
D,
|
|
169
176
|
k,
|
|
170
|
-
|
|
177
|
+
A,
|
|
178
|
+
E
|
|
171
179
|
]), i(() => {
|
|
172
|
-
if (
|
|
180
|
+
if (O) return O([{
|
|
173
181
|
id: "billing-status",
|
|
174
|
-
label:
|
|
182
|
+
label: E("billing.nav.billingReady", "Billing Ready"),
|
|
175
183
|
type: "status",
|
|
176
184
|
order: 10,
|
|
177
185
|
section: "left"
|
|
178
186
|
}]);
|
|
179
|
-
}, [
|
|
180
|
-
fallback: /* @__PURE__ */
|
|
187
|
+
}, [O, E]), /* @__PURE__ */ S(a, {
|
|
188
|
+
fallback: /* @__PURE__ */ S("div", {
|
|
181
189
|
className: "flex min-h-[240px] items-center justify-center px-6 py-10 text-center text-sm text-text-secondary",
|
|
182
|
-
children:
|
|
190
|
+
children: E("billing.errorBoundary.message", "Something went wrong loading this module. Please refresh the page.")
|
|
183
191
|
}),
|
|
184
|
-
children: /* @__PURE__ */
|
|
192
|
+
children: /* @__PURE__ */ S(o, {
|
|
185
193
|
workspaceId: null,
|
|
186
194
|
gateway: "global",
|
|
187
195
|
defaultEnabled: !0,
|
|
188
|
-
children: /* @__PURE__ */
|
|
189
|
-
...
|
|
190
|
-
children:
|
|
196
|
+
children: /* @__PURE__ */ S(e, {
|
|
197
|
+
...w,
|
|
198
|
+
children: S(A === "admin" ? n : t, {})
|
|
191
199
|
})
|
|
192
200
|
})
|
|
193
201
|
});
|
|
194
202
|
};
|
|
195
203
|
//#endregion
|
|
196
|
-
export {
|
|
204
|
+
export { w as BillingRoot };
|
|
197
205
|
|
|
198
206
|
//# sourceMappingURL=BillingRoot.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BillingRoot.js","names":[],"sources":["../../src/billing/BillingRoot.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { useCallback, useEffect } from 'react';\nimport { ErrorBoundary } from '@burdenoff/fe-libs/shared/components';\nimport { FeatureFlagProvider } from '@burdenoff/fe-libs/shared/feature-flags';\nimport {\n LayoutDashboard,\n RefreshCw,\n Package,\n Blocks,\n Gauge,\n RotateCcw,\n Activity,\n TrendingUp,\n Settings,\n Ticket,\n Coins,\n TicketCheck,\n Landmark,\n Gift,\n} from 'lucide-react';\nimport { BillingProvider } from './providers/BillingProvider';\nimport type { NavItem, BillingRootProps } from './types';\nimport { BillingUserRoutes } from './BillingUserRoutes';\nimport { BillingAdminRoutes } from './BillingAdminRoutes';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\n/**\n * Root component for the Billing microfrontend.\n *\n * This is the main entry point that host applications import and render.\n * It sets up the necessary providers and renders the internal routing.\n * Automatically registers navigation items with the shell if registration functions are provided.\n *\n * @example\n * ```tsx\n * import { BillingRoot, type BillingRootProps } from '@burdenoff/microfe-billing';\n *\n * function App() {\n * const props: BillingRootProps = {\n * basePath: '/billing',\n * navigate: (path) => router.push(path),\n * currentUser: { id: '1', email: 'user@example.com', firstName: 'John', lastName: 'Doe' },\n * workspaceId: 'ws-123',\n * orgId: 'org-123',\n * apiGatewayUrl: 'https://api.example.com/tenant/graphql',\n * authToken: 'token',\n * stripePublishableKey: 'pk_test_...',\n * razorpayKey: 'rzp_test_...',\n * onSubscriptionCreate: (subscription) => console.log('Subscription created:', subscription),\n * onSubscriptionUpdate: (subscription) => console.log('Subscription updated:', subscription),\n * onPaymentProcess: (payment) => console.log('Payment processed:', payment),\n * registerNavItems: (items) => { return () => {}; },\n * };\n *\n * return <BillingRoot {...props} />;\n * }\n * ```\n */\nexport const BillingRoot: FC<BillingRootProps> = (props) => {\n const { t } = useI18n();\n const tr = useCallback(\n (key: string, fallback: string): string => {\n const translated = t(key);\n return translated === key ? fallback : translated;\n },\n [t]\n );\n const { registerNavItems, registerFooterItems, basePath = '/', mode = 'user' } = props;\n\n // Helper to join paths correctly, avoiding double slashes\n const joinPath = (base: string, path: string): string => {\n const cleanBase = base.endsWith('/') ? base.slice(0, -1) : base;\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n return cleanBase + cleanPath;\n };\n\n // Register navigation items with the shell based on mode\n useEffect(() => {\n if (!registerNavItems) return;\n\n const userNavItems: NavItem[] = [\n {\n id: 'billing-overview',\n label: tr('billing.nav.billing', 'Billing'),\n path: basePath === '/' ? '/' : joinPath(basePath, 'overview'),\n icon: <LayoutDashboard size={20} />,\n order: 100,\n group: 'billing',\n },\n {\n id: 'billing-subscriptions',\n label: tr('billing.nav.subscriptions', 'Subscriptions'),\n path: joinPath(basePath, 'subscriptions'),\n icon: <RefreshCw size={20} />,\n order: 110,\n group: 'billing',\n },\n {\n id: 'billing-plans',\n label: tr('billing.nav.plans', 'Plans'),\n path: joinPath(basePath, 'plans'),\n icon: <Package size={20} />,\n order: 120,\n group: 'billing',\n },\n {\n id: 'billing-addons',\n label: tr('billing.nav.addons', 'Addons'),\n path: joinPath(basePath, 'addons'),\n icon: <Blocks size={20} />,\n order: 130,\n group: 'billing',\n },\n {\n id: 'billing-usage',\n label: tr('billing.nav.usage', 'Usage'),\n path: joinPath(basePath, 'usage'),\n icon: <Activity size={20} />,\n order: 180,\n group: 'billing',\n },\n {\n id: 'billing-affiliate',\n label: tr('billing.nav.affiliate', 'Affiliate'),\n path: joinPath(basePath, 'affiliate'),\n icon: <TicketCheck size={20} />,\n order: 190,\n group: 'billing',\n },\n {\n id: 'billing-earnings',\n label: tr('billing.nav.earnings', 'Earnings'),\n path: joinPath(basePath, 'earnings'),\n icon: <Coins size={20} />,\n order: 200,\n group: 'billing',\n },\n {\n id: 'billing-payouts',\n label: tr('billing.nav.payouts', 'Payouts'),\n path: joinPath(basePath, 'payouts'),\n icon: <Landmark size={20} />,\n order: 205,\n group: 'billing',\n },\n {\n id: 'billing-settings',\n label: tr('billing.nav.settings', 'Settings'),\n path: joinPath(basePath, 'settings'),\n icon: <Settings size={20} />,\n order: 210,\n group: 'billing',\n },\n ];\n\n const adminNavItems: NavItem[] = [\n {\n id: 'billing-plans',\n label: tr('billing.nav.plans', 'Plans'),\n path: joinPath(basePath, 'plans'),\n icon: <Package size={20} />,\n order: 100,\n group: 'billing',\n },\n {\n id: 'billing-addons',\n label: tr('billing.nav.addons', 'Addons'),\n path: joinPath(basePath, 'addons'),\n icon: <Blocks size={20} />,\n order: 110,\n group: 'billing',\n },\n {\n id: 'billing-quotas',\n label: tr('billing.nav.quotas', 'Quotas'),\n path: joinPath(basePath, 'quotas'),\n icon: <Gauge size={20} />,\n order: 120,\n group: 'billing',\n },\n {\n id: 'billing-coupons',\n label: tr('billing.nav.coupons', 'Coupons'),\n path: joinPath(basePath, 'coupons'),\n icon: <Ticket size={20} />,\n order: 130,\n group: 'billing',\n },\n {\n id: 'billing-promotions',\n label: tr('billing.nav.promotions', 'Promotions'),\n path: joinPath(basePath, 'promotions'),\n icon: <Gift size={20} />,\n order: 135,\n group: 'billing',\n },\n\n {\n id: 'billing-credits-admin',\n label: tr('billing.nav.creditGrants', 'Credit Grants'),\n path: joinPath(basePath, 'credits'),\n icon: <Coins size={20} />,\n order: 150,\n group: 'billing',\n },\n {\n id: 'billing-refunds',\n label: tr('billing.nav.refunds', 'Refunds'),\n path: joinPath(basePath, 'refunds'),\n icon: <RotateCcw size={20} />,\n order: 160,\n group: 'billing',\n },\n {\n id: 'billing-admin-payouts',\n label: tr('billing.nav.payouts', 'Payouts'),\n path: joinPath(basePath, 'payouts'),\n icon: <Landmark size={20} />,\n order: 165,\n group: 'billing',\n },\n {\n id: 'billing-analytics',\n label: tr('billing.nav.analytics', 'Analytics'),\n path: joinPath(basePath, 'analytics'),\n icon: <TrendingUp size={20} />,\n order: 170,\n group: 'billing',\n },\n ];\n\n const navItems = mode === 'admin' ? adminNavItems : userNavItems;\n const cleanup = registerNavItems(navItems);\n return cleanup;\n }, [registerNavItems, basePath, mode, tr]);\n\n // Register footer items (example: billing status indicator in left section)\n useEffect(() => {\n if (!registerFooterItems) return;\n\n const footerItems = [\n {\n id: 'billing-status',\n label: tr('billing.nav.billingReady', 'Billing Ready'),\n type: 'status' as const,\n order: 10,\n section: 'left' as const,\n },\n ];\n\n const cleanup = registerFooterItems(footerItems);\n return cleanup;\n }, [registerFooterItems, tr]);\n\n return (\n <ErrorBoundary\n fallback={\n <div className=\"flex min-h-[240px] items-center justify-center px-6 py-10 text-center text-sm text-text-secondary\">\n {tr(\n 'billing.errorBoundary.message',\n 'Something went wrong loading this module. Please refresh the page.'\n )}\n </div>\n }\n >\n <FeatureFlagProvider workspaceId={null} gateway=\"global\" defaultEnabled={true}>\n <BillingProvider {...props}>\n {mode === 'admin' ? <BillingAdminRoutes /> : <BillingUserRoutes />}\n </BillingProvider>\n </FeatureFlagProvider>\n </ErrorBoundary>\n );\n};\n"],"mappings":";;;;;;;;;;AA0DA,IAAa,KAAqC,MAAU;CAC1D,IAAM,EAAE,SAAM,GAAS,EACjB,IAAK,GACR,GAAa,MAA6B;EACzC,IAAM,IAAa,EAAE,EAAI;AACzB,SAAO,MAAe,IAAM,IAAW;IAEzC,CAA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Root.js","names":[],"sources":["../../src/billing/BillingRoot.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { useCallback, useEffect } from 'react';\nimport { ErrorBoundary } from '@burdenoff/fe-libs/shared/components';\nimport { FeatureFlagProvider } from '@burdenoff/fe-libs/shared/feature-flags';\nimport {\n LayoutDashboard,\n RefreshCw,\n Package,\n Blocks,\n Gauge,\n RotateCcw,\n Activity,\n TrendingUp,\n Settings,\n Ticket,\n Coins,\n TicketCheck,\n Landmark,\n Gift,\n DollarSign,\n} from 'lucide-react';\nimport { BillingProvider } from './providers/BillingProvider';\nimport type { NavItem, BillingRootProps } from './types';\nimport { BillingUserRoutes } from './BillingUserRoutes';\nimport { BillingAdminRoutes } from './BillingAdminRoutes';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\n/**\n * Root component for the Billing microfrontend.\n *\n * This is the main entry point that host applications import and render.\n * It sets up the necessary providers and renders the internal routing.\n * Automatically registers navigation items with the shell if registration functions are provided.\n *\n * @example\n * ```tsx\n * import { BillingRoot, type BillingRootProps } from '@burdenoff/microfe-billing';\n *\n * function App() {\n * const props: BillingRootProps = {\n * basePath: '/billing',\n * navigate: (path) => router.push(path),\n * currentUser: { id: '1', email: 'user@example.com', firstName: 'John', lastName: 'Doe' },\n * workspaceId: 'ws-123',\n * orgId: 'org-123',\n * apiGatewayUrl: 'https://api.example.com/tenant/graphql',\n * authToken: 'token',\n * stripePublishableKey: 'pk_test_...',\n * razorpayKey: 'rzp_test_...',\n * onSubscriptionCreate: (subscription) => console.log('Subscription created:', subscription),\n * onSubscriptionUpdate: (subscription) => console.log('Subscription updated:', subscription),\n * onPaymentProcess: (payment) => console.log('Payment processed:', payment),\n * registerNavItems: (items) => { return () => {}; },\n * };\n *\n * return <BillingRoot {...props} />;\n * }\n * ```\n */\nexport const BillingRoot: FC<BillingRootProps> = (props) => {\n const { t } = useI18n();\n const tr = useCallback(\n (key: string, fallback: string): string => {\n const translated = t(key);\n return translated === key ? fallback : translated;\n },\n [t]\n );\n const { registerNavItems, registerFooterItems, basePath = '/', mode = 'user' } = props;\n\n // Helper to join paths correctly, avoiding double slashes\n const joinPath = (base: string, path: string): string => {\n const cleanBase = base.endsWith('/') ? base.slice(0, -1) : base;\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n return cleanBase + cleanPath;\n };\n\n // Register navigation items with the shell based on mode\n useEffect(() => {\n if (!registerNavItems) return;\n\n const userNavItems: NavItem[] = [\n {\n id: 'billing-overview',\n label: tr('billing.nav.billing', 'Billing'),\n path: basePath === '/' ? '/' : joinPath(basePath, 'overview'),\n icon: <LayoutDashboard size={20} />,\n order: 100,\n group: 'billing',\n },\n {\n id: 'billing-subscriptions',\n label: tr('billing.nav.subscriptions', 'Subscriptions'),\n path: joinPath(basePath, 'subscriptions'),\n icon: <RefreshCw size={20} />,\n order: 110,\n group: 'billing',\n },\n {\n id: 'billing-plans',\n label: tr('billing.nav.plans', 'Plans'),\n path: joinPath(basePath, 'plans'),\n icon: <Package size={20} />,\n order: 120,\n group: 'billing',\n },\n {\n id: 'billing-addons',\n label: tr('billing.nav.addons', 'Addons'),\n path: joinPath(basePath, 'addons'),\n icon: <Blocks size={20} />,\n order: 130,\n group: 'billing',\n },\n {\n id: 'billing-usage',\n label: tr('billing.nav.usage', 'Usage'),\n path: joinPath(basePath, 'usage'),\n icon: <Activity size={20} />,\n order: 180,\n group: 'billing',\n },\n {\n id: 'billing-affiliate',\n label: tr('billing.nav.affiliate', 'Affiliate'),\n path: joinPath(basePath, 'affiliate'),\n icon: <TicketCheck size={20} />,\n order: 190,\n group: 'billing',\n },\n {\n id: 'billing-earnings',\n label: tr('billing.nav.earnings', 'Earnings'),\n path: joinPath(basePath, 'earnings'),\n icon: <Coins size={20} />,\n order: 200,\n group: 'billing',\n },\n {\n id: 'billing-payouts',\n label: tr('billing.nav.payouts', 'Payouts'),\n path: joinPath(basePath, 'payouts'),\n icon: <Landmark size={20} />,\n order: 205,\n group: 'billing',\n },\n {\n id: 'billing-settings',\n label: tr('billing.nav.settings', 'Settings'),\n path: joinPath(basePath, 'settings'),\n icon: <Settings size={20} />,\n order: 210,\n group: 'billing',\n },\n ];\n\n const adminNavItems: NavItem[] = [\n {\n id: 'billing-plans',\n label: tr('billing.nav.plans', 'Plans'),\n path: joinPath(basePath, 'plans'),\n icon: <Package size={20} />,\n order: 100,\n group: 'billing',\n },\n {\n id: 'billing-addons',\n label: tr('billing.nav.addons', 'Addons'),\n path: joinPath(basePath, 'addons'),\n icon: <Blocks size={20} />,\n order: 110,\n group: 'billing',\n },\n {\n id: 'billing-quotas',\n label: tr('billing.nav.quotas', 'Quotas'),\n path: joinPath(basePath, 'quotas'),\n icon: <Gauge size={20} />,\n order: 120,\n group: 'billing',\n },\n {\n id: 'billing-coupons',\n label: tr('billing.nav.coupons', 'Coupons'),\n path: joinPath(basePath, 'coupons'),\n icon: <Ticket size={20} />,\n order: 130,\n group: 'billing',\n },\n {\n id: 'billing-promotions',\n label: tr('billing.nav.promotions', 'Promotions'),\n path: joinPath(basePath, 'promotions'),\n icon: <Gift size={20} />,\n order: 135,\n group: 'billing',\n },\n\n {\n id: 'billing-credits-admin',\n label: tr('billing.nav.creditGrants', 'Credit Grants'),\n path: joinPath(basePath, 'credits'),\n icon: <Coins size={20} />,\n order: 150,\n group: 'billing',\n },\n {\n id: 'billing-refunds',\n label: tr('billing.nav.refunds', 'Refunds'),\n path: joinPath(basePath, 'refunds'),\n icon: <RotateCcw size={20} />,\n order: 160,\n group: 'billing',\n },\n {\n id: 'billing-admin-developer-revenue',\n label: tr('billing.nav.developerRevenue', 'Developer Revenue'),\n path: joinPath(basePath, 'developer-revenue'),\n icon: <DollarSign size={20} />,\n order: 164,\n group: 'billing',\n },\n {\n id: 'billing-admin-payouts',\n label: tr('billing.nav.payouts', 'Payouts'),\n path: joinPath(basePath, 'payouts'),\n icon: <Landmark size={20} />,\n order: 165,\n group: 'billing',\n },\n {\n id: 'billing-analytics',\n label: tr('billing.nav.analytics', 'Analytics'),\n path: joinPath(basePath, 'analytics'),\n icon: <TrendingUp size={20} />,\n order: 170,\n group: 'billing',\n },\n ];\n\n const navItems = mode === 'admin' ? adminNavItems : userNavItems;\n const cleanup = registerNavItems(navItems);\n return cleanup;\n }, [registerNavItems, basePath, mode, tr]);\n\n // Register footer items (example: billing status indicator in left section)\n useEffect(() => {\n if (!registerFooterItems) return;\n\n const footerItems = [\n {\n id: 'billing-status',\n label: tr('billing.nav.billingReady', 'Billing Ready'),\n type: 'status' as const,\n order: 10,\n section: 'left' as const,\n },\n ];\n\n const cleanup = registerFooterItems(footerItems);\n return cleanup;\n }, [registerFooterItems, tr]);\n\n return (\n <ErrorBoundary\n fallback={\n <div className=\"flex min-h-[240px] items-center justify-center px-6 py-10 text-center text-sm text-text-secondary\">\n {tr(\n 'billing.errorBoundary.message',\n 'Something went wrong loading this module. Please refresh the page.'\n )}\n </div>\n }\n >\n <FeatureFlagProvider workspaceId={null} gateway=\"global\" defaultEnabled={true}>\n <BillingProvider {...props}>\n {mode === 'admin' ? <BillingAdminRoutes /> : <BillingUserRoutes />}\n </BillingProvider>\n </FeatureFlagProvider>\n </ErrorBoundary>\n );\n};\n"],"mappings":";;;;;;;;;;AA2DA,IAAa,KAAqC,MAAU;CAC1D,IAAM,EAAE,SAAM,GAAS,EACjB,IAAK,GACR,GAAa,MAA6B;EACzC,IAAM,IAAa,EAAE,EAAI;AACzB,SAAO,MAAe,IAAM,IAAW;IAEzC,CAAC,EAAE,CACJ,EACK,EAAE,qBAAkB,wBAAqB,cAAW,KAAK,UAAO,WAAW,GAG3E,KAAY,GAAc,OACZ,EAAK,SAAS,IAAI,GAAG,EAAK,MAAM,GAAG,GAAG,GAAG,MACzC,EAAK,WAAW,IAAI,GAAG,IAAO,IAAI;AA8LtD,QAzLA,QAAgB;AACd,MAAI,CAAC,EAAkB;EAEvB,IAAM,IAA0B;GAC9B;IACE,IAAI;IACJ,OAAO,EAAG,uBAAuB,UAAU;IAC3C,MAAM,MA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,CAAA;IAC7B,OAAO;IACP,OAAO;IACR;GACD;IACE,IAAI;IACJ,OAAO,EAAG,gCAAgC,oBAAoB;IAC9D,MAAM,EAAS,GAAU,oBAAoB;IAC7C,MAAM,kBAAC,GAAD,EAAY,MAAM,IAAM,CAAA;IAC9B,OAAO;IACP,OAAO;IACR;GACD;IACE,IAAI;IACJ,OAAO,EAAG,uBAAuB,UAAU;IAC3C,MAAM,EAAS,GAAU,UAAU;IACnC,MAAM,kBAAC,GAAD,EAAU,MAAM,IAAM,CAAA;IAC5B,OAAO;IACP,OAAO;IACR;GACD;IACE,IAAI;IACJ,OAAO,EAAG,yBAAyB,YAAY;IAC/C,MAAM,EAAS,GAAU,YAAY;IACrC,MAAM,kBAAC,GAAD,EAAY,MAAM,IAAM,CAAA;IAC9B,OAAO;IACP,OAAO;IACR;GACF;AAID,SADgB,EADC,MAAS,UAAU,IAAgB,EACV;IAEzC;EAAC;EAAkB;EAAU;EAAM;EAAG,CAAC,EAG1C,QAAgB;AACT,QAaL,QADgB,EAVI,CAClB;GACE,IAAI;GACJ,OAAO,EAAG,4BAA4B,gBAAgB;GACtD,MAAM;GACN,OAAO;GACP,SAAS;GACV,CACF,CAE+C;IAE/C,CAAC,GAAqB,EAAG,CAAC,EAG3B,kBAAC,GAAD;EACE,UACE,kBAAC,OAAD;GAAK,WAAU;aACZ,EACC,iCACA,qEACD;GACG,CAAA;YAGR,kBAAC,GAAD;GAAqB,aAAa;GAAM,SAAQ;GAAS,gBAAgB;aACvE,kBAAC,GAAD;IAAiB,GAAI;cACC,EAAnB,MAAS,UAAW,IAAyB,GAA1B,EAAsB,CAAwB;IAClD,CAAA;GACE,CAAA;EACR,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCheckout.js","names":[],"sources":["../../../../../src/billing/modules/checkout/hooks/useCheckout.ts"],"sourcesContent":["/**\n * Main checkout hook for managing checkout state and payment processing\n */\n\nimport { useState, useCallback, useMemo, useEffect } from 'react';\nimport {\n useInitiatePaymentCheckoutMutation,\n useSpendCreditsCheckoutMutation,\n useConvertCurrencyLazyQuery,\n useValidateCouponLazyQuery,\n useCreateBillingOrderCheckoutMutation,\n} from '../../../../generated/global-operations';\nimport { useBilling } from '../../../providers/BillingProvider';\nimport type {\n CheckoutItem,\n CheckoutBillingAccount,\n PaymentProvider,\n Currency,\n CheckoutState,\n PaymentInitResponse,\n PromoCodeResult,\n PurchaseType,\n} from '../types';\n\n/**\n * Credit conversion rate: How many credits equal 1 USD\n * This should match the backend creditRate.rateUSD (default 0.01 means 100 credits = $1)\n */\nconst CREDITS_PER_USD = 100;\n\ninterface UseCheckoutOptions {\n billingAccountId?: string;\n defaultCurrency?: Currency;\n defaultSaveCard?: boolean;\n upgradeFromSubscriptionId?: string;\n /** For plan downgrades — old sub auto-renewal cancelled, runs to natural expiry */\n downgradeFromSubscriptionId?: string;\n /** For addon purchases - pre-selected subscription ID */\n defaultSubscriptionId?: string;\n}\n\ninterface UseCheckoutResult {\n // State\n items: CheckoutItem[];\n billingAccount: CheckoutBillingAccount | null;\n selectedProvider: PaymentProvider;\n selectedCurrency: Currency;\n promoCode: string;\n promoDiscount: number;\n promoDiscountType: 'PERCENTAGE' | 'FIXED';\n useCredits: boolean;\n creditsToUse: number;\n checkoutState: CheckoutState;\n error: string | null;\n\n // Saved card state\n selectedPaymentMethodId: string | null;\n saveCard: boolean;\n\n // Auto-pay state (for subscription purchases)\n autoRenew: boolean;\n autoRenewPaymentMethodId: string | null;\n\n // Subscription state (for addon purchases)\n selectedSubscriptionId: string | null;\n\n // Computed values\n subtotal: number;\n subtotalUSD: number;\n discountAmount: number;\n taxAmount: number;\n taxRate: number;\n taxType: string;\n total: number;\n totalInSelectedCurrency: number;\n availableCredits: number;\n hasEnoughCredits: boolean;\n canPayWithCredits: boolean;\n isLoading: boolean;\n isProcessing: boolean;\n isCalculatingTax: boolean;\n\n // Currency conversion\n conversionRate: number;\n convertedAmount: number | null;\n\n // Actions\n addItem: (item: CheckoutItem) => void;\n removeItem: (itemId: string) => void;\n updateItemQuantity: (itemId: string, quantity: number) => void;\n updateItemPrice: (itemId: string, price: number, currency?: Currency) => void;\n clearItems: () => void;\n setBillingAccount: (account: CheckoutBillingAccount | null) => void;\n setPaymentProvider: (provider: PaymentProvider) => void;\n setCurrency: (currency: Currency) => void;\n setPromoCode: (code: string) => void;\n validatePromoCode: () => Promise<PromoCodeResult>;\n clearPromoCode: () => void;\n setUseCredits: (use: boolean) => void;\n setCreditsToUse: (amount: number) => void;\n setSelectedPaymentMethodId: (id: string | null) => void;\n setSaveCard: (save: boolean) => void;\n setAutoRenew: (enabled: boolean) => void;\n setAutoRenewPaymentMethodId: (id: string | null) => void;\n setSelectedSubscriptionId: (id: string | null) => void;\n initiatePayment: () => Promise<PaymentInitResponse>;\n reset: () => void;\n}\n\nexport function useCheckout(options: UseCheckoutOptions = {}): UseCheckoutResult {\n const { currentUser } = useBilling();\n const {\n defaultCurrency = 'USD',\n defaultSaveCard = false, // CRITICAL: Never save cards without explicit user consent\n upgradeFromSubscriptionId,\n downgradeFromSubscriptionId,\n defaultSubscriptionId,\n } = options;\n\n // Core state\n const [items, setItems] = useState<CheckoutItem[]>([]);\n const [billingAccount, setBillingAccount] = useState<CheckoutBillingAccount | null>(null);\n const [selectedProvider, setSelectedProvider] = useState<PaymentProvider>('AUTO');\n const [selectedCurrency, setSelectedCurrency] = useState<Currency>(defaultCurrency);\n const [promoCode, setPromoCode] = useState('');\n const [promoDiscount, setPromoDiscount] = useState(0);\n const [promoDiscountType, setPromoDiscountType] = useState<'PERCENTAGE' | 'FIXED'>('PERCENTAGE');\n const [useCredits, setUseCredits] = useState(false);\n const [creditsToUse, setCreditsToUse] = useState(0);\n const [checkoutState, setCheckoutState] = useState<CheckoutState>('idle');\n const [error, setError] = useState<string | null>(null);\n const [taxAmount, setTaxAmount] = useState(0);\n const [taxRate, setTaxRate] = useState(0);\n const [taxType, setTaxType] = useState<string>('NONE');\n\n // Saved card state\n const [selectedPaymentMethodId, setSelectedPaymentMethodId] = useState<string | null>(null);\n const [saveCard, setSaveCard] = useState(defaultSaveCard);\n\n // Auto-pay state (for subscription purchases)\n const [autoRenew, setAutoRenew] = useState(false);\n const [autoRenewPaymentMethodId, setAutoRenewPaymentMethodId] = useState<string | null>(null);\n\n // Subscription state (for addon purchases)\n const [selectedSubscriptionId, setSelectedSubscriptionId] = useState<string | null>(\n defaultSubscriptionId ?? null\n );\n\n // GraphQL mutations and queries\n const [initiatePaymentMutation] = useInitiatePaymentCheckoutMutation();\n const [createBillingOrderMutation] = useCreateBillingOrderCheckoutMutation();\n const [spendCreditsMutation] = useSpendCreditsCheckoutMutation();\n const [convertCurrency, { data: currencyData, loading: currencyLoading }] =\n useConvertCurrencyLazyQuery();\n const [validateCoupon] = useValidateCouponLazyQuery();\n\n // Computed values\n const subtotal = useMemo(() => {\n return items.reduce((sum, item) => sum + item.price * item.quantity, 0);\n }, [items]);\n\n // USD subtotal — always use priceUSD (base price) for credit calculations.\n // item.price may be in a local currency (INR, EUR, etc.) when currencyPrices is set.\n const subtotalUSD = useMemo(() => {\n return items.reduce((sum, item) => sum + (item.priceUSD ?? item.price) * item.quantity, 0);\n }, [items]);\n\n const discountAmount = useMemo(() => {\n if (!promoDiscount) return 0;\n // promoDiscount now contains the actual discount amount from backend validation\n // (not the percentage value), so use it directly\n return Math.min(promoDiscount, subtotal);\n }, [subtotal, promoDiscount]);\n\n // Total includes tax (calculated via calculateTax query)\n const total = useMemo(() => {\n const afterDiscount = subtotal - discountAmount;\n const withCredits = useCredits ? Math.max(0, afterDiscount - creditsToUse) : afterDiscount;\n return withCredits + taxAmount;\n }, [subtotal, discountAmount, useCredits, creditsToUse, taxAmount]);\n\n const availableCredits = billingAccount?.creditAmount ?? 0;\n\n const hasEnoughCredits = useMemo(() => {\n // Use subtotalUSD so this works correctly for any display currency\n const creditsRequired = subtotalUSD * CREDITS_PER_USD;\n return availableCredits >= creditsRequired;\n }, [availableCredits, subtotalUSD]);\n\n // Can only pay with credits if not buying credits\n const canPayWithCredits = useMemo(() => {\n const hasCreditsPurchase = items.some((item) => item.type === 'CREDITS');\n return !hasCreditsPurchase && availableCredits > 0;\n }, [items, availableCredits]);\n\n // Currency conversion result\n const convertedAmount = currencyData?.convertCurrency?.amount ?? null;\n const conversionRate = currencyData?.convertCurrency?.exchangeRate ?? 1;\n const totalInSelectedCurrency = convertedAmount ?? total;\n\n const isLoading = checkoutState === 'loading' || currencyLoading;\n const isProcessing = checkoutState === 'processing';\n\n // Effect to trigger currency conversion when total or currency changes\n // This ensures the converted amount is always up-to-date\n useEffect(() => {\n // Skip conversion for credit payments (no currency conversion needed)\n if (selectedProvider === 'CREDITS') {\n return;\n }\n\n // Skip if no items yet (cart is still loading)\n if (items.length === 0) {\n return;\n }\n\n // Skip conversion if items already have prices in selected currency\n // (Plans/Addons with multi-currency pricing have currencyPrices stored)\n const allItemsHaveLocalizedPrices = items.every(\n (item) => item.currency === selectedCurrency || item.type === 'CREDITS'\n );\n\n if (allItemsHaveLocalizedPrices) {\n // Items are already priced in the selected currency (from currencyPrices)\n // No conversion needed - subtotal and total are already correct!\n return;\n }\n\n // Only fetch if we have a valid total and non-USD currency\n if (total > 0 && selectedCurrency !== 'USD') {\n // For INR, wait until tax has been calculated (taxAmount > 0 or taxRate is set)\n // This prevents double API calls - one before tax, one after\n if (selectedCurrency === 'INR' && taxAmount === 0 && subtotal > 0) {\n // Tax hasn't been calculated yet, skip this conversion\n // The effect will run again when taxAmount changes\n return;\n }\n\n convertCurrency({\n variables: {\n amount: total,\n toCurrency: selectedCurrency,\n fromCurrency: 'USD',\n },\n });\n }\n }, [total, selectedCurrency, selectedProvider, convertCurrency, taxAmount, subtotal, items]);\n\n // Effect to calculate tax when billing account, subtotal, or currency changes\n // Tax is only applied for INR payments (18% GST)\n useEffect(() => {\n // Only calculate tax if we have a billing account and items\n if (!billingAccount || subtotal <= 0) {\n // Reset tax if no billing account or empty cart\n setTaxAmount(0);\n setTaxRate(0);\n setTaxType('NONE');\n return;\n }\n\n // Skip if paying with credits (no tax on credit payments)\n if (selectedProvider === 'CREDITS') {\n setTaxAmount(0);\n setTaxRate(0);\n setTaxType('NONE');\n return;\n }\n\n // Only apply tax for INR payments\n if (selectedCurrency !== 'INR') {\n setTaxAmount(0);\n setTaxRate(0);\n setTaxType('NONE');\n return;\n }\n\n // For INR: Calculate 18% GST on the USD amount, then we'll convert for display\n const afterDiscount = subtotal - discountAmount;\n const GST_RATE = 0.18;\n const taxInUSD = afterDiscount * GST_RATE;\n\n setTaxAmount(taxInUSD);\n setTaxRate(GST_RATE);\n setTaxType('GST');\n }, [billingAccount, subtotal, discountAmount, selectedCurrency, selectedProvider]);\n\n // Actions\n const addItem = useCallback((item: CheckoutItem) => {\n setItems((prev) => {\n // Plans can only be purchased once - quantity is always 1\n if (item.type === 'PLAN') {\n // Check if any plan already exists in cart\n const existingPlan = prev.find((i) => i.type === 'PLAN');\n if (existingPlan) {\n // Replace existing plan with new one (can only have 1 plan)\n return prev.map((i) => (i.type === 'PLAN' ? { ...item, quantity: 1 } : i));\n }\n // Add new plan with quantity forced to 1\n return [...prev, { ...item, quantity: 1 }];\n }\n\n // For addons and credits, allow quantity increment\n const existing = prev.find((i) => i.id === item.id);\n if (existing) {\n return prev.map((i) =>\n i.id === item.id ? { ...i, quantity: i.quantity + item.quantity } : i\n );\n }\n return [...prev, item];\n });\n }, []);\n\n const removeItem = useCallback((itemId: string) => {\n setItems((prev) => prev.filter((i) => i.id !== itemId));\n }, []);\n\n const updateItemQuantity = useCallback(\n (itemId: string, quantity: number) => {\n if (quantity <= 0) {\n removeItem(itemId);\n return;\n }\n setItems((prev) =>\n prev.map((i) => {\n if (i.id !== itemId) return i;\n // Plans can only have quantity 1\n if (i.type === 'PLAN') {\n return { ...i, quantity: 1 };\n }\n return { ...i, quantity };\n })\n );\n },\n [removeItem]\n );\n\n const updateItemPrice = useCallback((itemId: string, price: number, currency?: Currency) => {\n setItems((prev) =>\n prev.map((i) => {\n if (i.id !== itemId) return i;\n // Update price and optionally currency\n const updates: Partial<CheckoutItem> = { price };\n if (currency) {\n updates.currency = currency;\n }\n return { ...i, ...updates };\n })\n );\n }, []);\n\n const clearItems = useCallback(() => {\n setItems([]);\n }, []);\n\n const handleSetBillingAccount = useCallback((account: CheckoutBillingAccount | null) => {\n setBillingAccount(account);\n // Reset credits usage when billing account changes\n setUseCredits(false);\n setCreditsToUse(0);\n }, []);\n\n const handleSetCurrency = useCallback(\n (currency: Currency) => {\n setSelectedCurrency(currency);\n // Skip conversion if items already have localized prices\n // (Plans/Addons with multi-currency pricing don't need conversion)\n const allItemsHaveLocalizedPrices = items.every(\n (item) => item.currency === currency || item.type === 'CREDITS'\n );\n\n // Only fetch conversion rate if items don't have localized prices\n if (total > 0 && currency !== 'USD' && !allItemsHaveLocalizedPrices) {\n convertCurrency({\n variables: {\n amount: total,\n toCurrency: currency,\n fromCurrency: 'USD',\n },\n });\n }\n },\n [total, convertCurrency, items]\n );\n\n const handleSetPaymentProvider = useCallback(\n (provider: PaymentProvider) => {\n setSelectedProvider(provider);\n // Razorpay only supports INR\n if (provider === 'RAZORPAY' && selectedCurrency !== 'INR') {\n setSelectedCurrency('INR');\n }\n },\n [selectedCurrency]\n );\n\n const validatePromoCode = useCallback(async (): Promise<PromoCodeResult> => {\n if (!promoCode.trim()) {\n return {\n valid: false,\n code: '',\n discountType: 'PERCENTAGE',\n discountValue: 0,\n error: 'Please enter a promo code',\n };\n }\n\n try {\n setCheckoutState('loading');\n\n // Build validation input\n const validationInput = {\n code: promoCode.trim().toUpperCase(),\n userId: currentUser?.id ?? '',\n userEmail: currentUser?.email,\n amount: subtotal,\n currency: selectedCurrency,\n };\n\n const { data, error: queryError } = await validateCoupon({\n variables: {\n input: validationInput,\n },\n });\n\n if (queryError || !data?.validateCoupon) {\n setPromoDiscount(0);\n setCheckoutState('idle');\n return {\n valid: false,\n code: promoCode,\n discountType: 'PERCENTAGE',\n discountValue: 0,\n error: 'Failed to validate coupon',\n };\n }\n\n const response = data.validateCoupon;\n\n if (!response.valid) {\n setPromoDiscount(0);\n setCheckoutState('idle');\n return {\n valid: false,\n code: promoCode,\n discountType: 'PERCENTAGE',\n discountValue: 0,\n error: response.error || 'Invalid coupon code',\n };\n }\n\n // Extract discount details from coupon\n const coupon = response.coupon;\n if (!coupon) {\n setPromoDiscount(0);\n setCheckoutState('idle');\n return {\n valid: false,\n code: promoCode,\n discountType: 'PERCENTAGE',\n discountValue: 0,\n error: 'Coupon data not found',\n };\n }\n\n // Use the ACTUAL discount amount from validation (includes caps and currency conversion)\n const actualDiscountAmount = response.discountAmount || 0;\n\n const discountType = coupon.type === 'FIXED_AMOUNT' ? 'FIXED' : 'PERCENTAGE';\n setPromoDiscount(actualDiscountAmount); // Use actual discount, not coupon.value\n setPromoDiscountType(discountType);\n setCheckoutState('idle');\n\n return {\n valid: true,\n code: coupon.code,\n discountType,\n discountValue: actualDiscountAmount, // Use actual discount, not coupon.value\n };\n } catch {\n setPromoDiscount(0);\n setCheckoutState('idle');\n return {\n valid: false,\n code: promoCode,\n discountType: 'PERCENTAGE',\n discountValue: 0,\n error: 'Failed to validate coupon',\n };\n }\n }, [\n billingAccount?.id,\n currentUser?.email,\n currentUser?.id,\n promoCode,\n selectedCurrency,\n subtotal,\n validateCoupon,\n ]);\n\n const clearPromoCode = useCallback(() => {\n setPromoCode('');\n setPromoDiscount(0);\n setPromoDiscountType('PERCENTAGE');\n }, []);\n\n const handleSetCreditsToUse = useCallback(\n (amount: number) => {\n const maxCredits = Math.min(amount, availableCredits, subtotal - discountAmount);\n setCreditsToUse(Math.max(0, maxCredits));\n },\n [availableCredits, subtotal, discountAmount]\n );\n\n const initiatePayment = useCallback(async (): Promise<PaymentInitResponse> => {\n if (!billingAccount) {\n return {\n success: false,\n provider: 'AUTO',\n subtotal: 0,\n taxAmount: 0,\n taxRate: 0,\n total: 0,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: 'Please select a billing account',\n };\n }\n\n if (items.length === 0) {\n return {\n success: false,\n provider: 'AUTO',\n subtotal: 0,\n taxAmount: 0,\n taxRate: 0,\n total: 0,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: 'No items in checkout',\n };\n }\n\n try {\n setCheckoutState('processing');\n setError(null);\n\n // Determine purchase type from first item\n const firstItem = items[0];\n let purchaseType: PurchaseType = firstItem.type;\n\n // Check if this is a store order checkout (detect early)\n const storeOrderItem = items.find((item) => item.metadata?.storeOrderId);\n const storeOrderId = storeOrderItem?.metadata?.storeOrderId as string | undefined;\n let billingOrderId =\n (items.find((item) => item.metadata?.billingOrderId)?.metadata?.billingOrderId as\n | string\n | undefined) || undefined;\n\n // For store orders, use 'ORDER' purchase type\n if (storeOrderId) {\n purchaseType = 'ORDER' as PurchaseType;\n }\n\n // Calculate amount to charge\n const chargeAmount = subtotal - discountAmount;\n\n // Determine provider\n let provider = selectedProvider;\n if (provider === 'AUTO') {\n provider = selectedCurrency === 'INR' ? 'RAZORPAY' : 'STRIPE';\n }\n\n // If this is a store order without a billing order yet, create one now.\n // Pass callbackGraphQL so the billing service can call back to the store service\n // after payment completes to mark the order confirmed.\n if (purchaseType === 'ORDER' && !billingOrderId && storeOrderId && billingAccount) {\n const orderItems = items\n .filter((item) => item.type === 'ORDER')\n .map((item) => ({\n name: item.name,\n description: item.description ?? undefined,\n quantity: item.quantity,\n unitPrice: item.price,\n metadata: {\n productId: item.metadata?.productId ?? undefined,\n variantId: item.metadata?.variantId ?? undefined,\n },\n }));\n\n const { data: billingOrderResult } = await createBillingOrderMutation({\n variables: {\n input: {\n billingAccountId: billingAccount.id,\n externalOrderId: storeOrderId,\n externalService: 'STORE',\n currency: selectedCurrency,\n subtotal: chargeAmount,\n description: `Store order ${storeOrderId}`,\n items: orderItems,\n callbackGraphQL: {\n endpoint: 'http://global-int-gateway:4002/global/graphql',\n mutationName: 'updateStoreOrderPaymentStatus',\n },\n },\n },\n });\n\n if (billingOrderResult?.createBillingOrder?.success) {\n billingOrderId = billingOrderResult.createBillingOrder.order?.id;\n } else {\n const errMsg =\n billingOrderResult?.createBillingOrder?.error ?? 'Failed to create billing order';\n setCheckoutState('error');\n setError(errMsg);\n return {\n success: false,\n provider,\n subtotal: chargeAmount,\n taxAmount: 0,\n taxRate: 0,\n total: chargeAmount,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: errMsg,\n };\n }\n }\n\n // ========================================\n // CREDITS PAYMENT - use spendCredits mutation\n // Supports multiple addons\n // ========================================\n if (provider === 'CREDITS') {\n const addonItems = items.filter((item) => item.type === 'ADDON');\n const planItem = items.find((item) => item.type === 'PLAN');\n\n const { data } = await spendCreditsMutation({\n variables: {\n input: {\n billingAccountId: billingAccount.id,\n planId: planItem ? (planItem.metadata?.planId as string) || planItem.id : undefined,\n // Multiple addons supported via addOnIds array\n addOnIds:\n addonItems.length > 0\n ? addonItems.map((item) => ({\n id: (item.metadata?.addonId as string) || item.id,\n quantity: item.quantity,\n }))\n : undefined,\n isAnnual: planItem?.metadata?.duration === 'yearly',\n // Include upgrade context if changing plans\n upgradeFromSubscriptionId: upgradeFromSubscriptionId || undefined,\n // Include downgrade context if downgrading\n downgradeFromSubscriptionId: downgradeFromSubscriptionId || undefined,\n // For addon purchases - subscription to attach to\n subscriptionId: addonItems.length > 0 ? selectedSubscriptionId : undefined,\n // For PER_SEAT plans - pass seat count for credit calculation + subscription storage\n seatCount: planItem?.metadata?.seatCount as number | undefined,\n },\n },\n });\n\n const response = data?.spendCredits;\n\n if (!response?.creditTransactionID) {\n setCheckoutState('error');\n setError('Failed to process credit payment');\n return {\n success: false,\n provider: 'CREDITS',\n subtotal: chargeAmount,\n taxAmount: 0,\n taxRate: 0,\n total: chargeAmount,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: 'Failed to process credit payment',\n };\n }\n\n setCheckoutState('success');\n return {\n success: true,\n provider: 'CREDITS',\n subtotal: chargeAmount,\n taxAmount: 0,\n taxRate: 0,\n total: chargeAmount,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n // Return transaction ID for success handling\n orderId: response.creditTransactionID,\n };\n }\n\n // ========================================\n // CARD PAYMENT (Stripe/Razorpay) - use initiatePayment\n // Supports single or multiple addons\n // Supports store orders (via orderId parameter)\n // ========================================\n const addonItems = items.filter((item) => item.type === 'ADDON');\n\n // Build addon IDs and quantities for the mutation\n const addonIds =\n addonItems.length > 0\n ? addonItems.map((item) => (item.metadata?.addonId as string) || item.id)\n : undefined;\n const quantities =\n addonItems.length > 0 ? addonItems.map((item) => item.quantity) : undefined;\n\n // Determine if this is an annual plan purchase\n const planItem = items.find((item) => item.type === 'PLAN');\n const isAnnualPlan = planItem?.metadata?.duration === 'yearly';\n\n // Determine auto-renew payment method\n const autoRenewPMId =\n purchaseType === 'PLAN' && autoRenew\n ? autoRenewPaymentMethodId || selectedPaymentMethodId || undefined\n : undefined;\n\n const { data } = await initiatePaymentMutation({\n variables: {\n input: {\n billingAccountId: billingAccount.id,\n amount: chargeAmount, // Note: Backend IGNORES this and calculates from DB\n currency: selectedCurrency,\n purchaseType,\n provider: provider,\n // Store order - use orderId parameter (billing order ID)\n orderId: billingOrderId || undefined,\n creditAmount: purchaseType === 'CREDITS' ? firstItem.quantity : undefined,\n planId:\n purchaseType === 'PLAN'\n ? (firstItem.metadata?.planId as string) || firstItem.id\n : undefined,\n // Single addon (backwards compatible) - skip if store order\n addonId:\n purchaseType === 'ADDON' && addonItems.length === 1 && !billingOrderId\n ? (addonItems[0].metadata?.addonId as string) || addonItems[0].id\n : undefined,\n quantity:\n purchaseType === 'ADDON' && addonItems.length === 1 && !billingOrderId\n ? addonItems[0].quantity\n : undefined,\n // Multiple addons (cart checkout) - skip if store order\n addonIds:\n purchaseType === 'ADDON' && addonItems.length > 1 && !billingOrderId\n ? addonIds\n : undefined,\n quantities:\n purchaseType === 'ADDON' && addonItems.length > 1 && !billingOrderId\n ? quantities\n : undefined,\n // For addon purchases - subscription to attach to (skip for store orders)\n subscriptionId:\n purchaseType === 'ADDON' && !billingOrderId ? selectedSubscriptionId : undefined,\n // Saved card support\n paymentMethodId: selectedPaymentMethodId || undefined,\n // Save card if: user checked save card OR auto-renewal is enabled (which requires a saved card)\n // Only save if not using existing card (selectedPaymentMethodId is null)\n saveCard: !selectedPaymentMethodId ? saveCard || autoRenew : undefined,\n // Include upgrade context if changing plans\n upgradeFromSubscriptionId: upgradeFromSubscriptionId || undefined,\n // Include downgrade context if downgrading\n downgradeFromSubscriptionId: downgradeFromSubscriptionId || undefined,\n // Annual plan flag (for pricing calculation)\n isAnnual: isAnnualPlan || undefined,\n // Promo code (validated and applied on backend)\n promoCode: promoCode || undefined,\n // Auto-renewal (for plan purchases only)\n autoRenew: purchaseType === 'PLAN' && autoRenew ? true : undefined,\n autoRenewPaymentMethodId: autoRenewPMId,\n },\n },\n });\n\n const response = data?.initiatePayment;\n\n if (!response?.success) {\n setCheckoutState('error');\n setError(response?.error ?? 'Payment initiation failed');\n return {\n success: false,\n provider: provider,\n subtotal: chargeAmount,\n taxAmount: 0,\n taxRate: 0,\n total: chargeAmount,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: response?.error ?? 'Payment initiation failed',\n };\n }\n\n // Note: Tax is already calculated upfront in the effect, don't overwrite\n // The response tax is in converted currency which would mess up display\n setCheckoutState('success');\n\n return response;\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'An error occurred';\n setCheckoutState('error');\n setError(errorMessage);\n return {\n success: false,\n provider: 'AUTO',\n subtotal: 0,\n taxAmount: 0,\n taxRate: 0,\n total: 0,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: errorMessage,\n };\n }\n }, [\n billingAccount,\n items,\n selectedCurrency,\n selectedProvider,\n subtotal,\n discountAmount,\n promoCode,\n selectedPaymentMethodId,\n saveCard,\n autoRenew,\n autoRenewPaymentMethodId,\n selectedSubscriptionId,\n upgradeFromSubscriptionId,\n downgradeFromSubscriptionId,\n initiatePaymentMutation,\n createBillingOrderMutation,\n spendCreditsMutation,\n ]);\n\n const reset = useCallback(() => {\n setItems([]);\n setBillingAccount(null);\n setSelectedProvider('AUTO');\n setSelectedCurrency(defaultCurrency);\n setPromoCode('');\n setPromoDiscount(0);\n setPromoDiscountType('PERCENTAGE');\n setUseCredits(false);\n setCreditsToUse(0);\n setCheckoutState('idle');\n setError(null);\n setTaxAmount(0);\n setTaxRate(0);\n setTaxType('NONE');\n setSelectedPaymentMethodId(null);\n setSaveCard(defaultSaveCard);\n setAutoRenew(false);\n setAutoRenewPaymentMethodId(null);\n setSelectedSubscriptionId(defaultSubscriptionId ?? null);\n }, [defaultCurrency, defaultSaveCard, defaultSubscriptionId]);\n\n return {\n // State\n items,\n billingAccount,\n selectedProvider,\n selectedCurrency,\n promoCode,\n promoDiscount,\n promoDiscountType,\n useCredits,\n creditsToUse,\n checkoutState,\n error,\n\n // Saved card state\n selectedPaymentMethodId,\n saveCard,\n\n // Auto-pay state\n autoRenew,\n autoRenewPaymentMethodId,\n\n // Subscription state (for addon purchases)\n selectedSubscriptionId,\n\n // Computed\n subtotal,\n subtotalUSD,\n discountAmount,\n taxAmount,\n taxRate,\n taxType,\n total,\n totalInSelectedCurrency,\n availableCredits,\n hasEnoughCredits,\n canPayWithCredits,\n isLoading,\n isProcessing,\n isCalculatingTax: false, // Tax is calculated synchronously now\n conversionRate,\n convertedAmount,\n\n // Actions\n addItem,\n removeItem,\n updateItemQuantity,\n updateItemPrice,\n clearItems,\n setBillingAccount: handleSetBillingAccount,\n setPaymentProvider: handleSetPaymentProvider,\n setCurrency: handleSetCurrency,\n setPromoCode,\n validatePromoCode,\n clearPromoCode,\n setUseCredits,\n setCreditsToUse: handleSetCreditsToUse,\n setSelectedPaymentMethodId,\n setSaveCard,\n setAutoRenew,\n setAutoRenewPaymentMethodId,\n setSelected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V,UAAU;KACV,WAAW;KACX,SAAS;KACT,OAAO;KACP,SAAS;KACT,cAAc;KACd,UAAU;KACV,OAAO,GAAU,SAAS;KAC3B;YAQI,GAAK;IACZ,IAAM,IAAe,aAAe,QAAQ,EAAI,UAAU;AAG1D,WAFA,EAAiB,QAAQ,EACzB,EAAS,EAAa,EACf;KACL,SAAS;KACT,UAAU;KACV,UAAU;KACV,WAAW;KACX,SAAS;KACT,OAAO;KACP,SAAS;KACT,cAAc;KACd,UAAU;KACV,OAAO;KACR;;KAEF;GACD;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC;EAuFA,OArFY,QAAkB;AAmB9B,GAlBA,EAAS,EAAE,CAAC,EACZ,GAAkB,KAAK,EACvB,EAAoB,OAAO,EAC3B,EAAoB,EAAgB,EACpC,EAAa,GAAG,EAChB,EAAiB,EAAE,EACnB,EAAqB,aAAa,EAClC,EAAc,GAAM,EACpB,EAAgB,EAAE,EAClB,EAAiB,OAAO,EACxB,EAAS,KAAK,EACd,EAAa,EAAE,EACf,EAAW,EAAE,EACb,EAAW,OAAO,EAClB,EAA2B,KAAK,EAChC,GAAY,EAAgB,EAC5B,GAAa,GAAM,EACnB,EAA4B,KAAK,EACjC,GAA0B,KAAyB,KAAK;KACvD;GAAC;GAAiB;GAAiB;GAAsB,CAAC;EAkE5D"}
|
|
1
|
+
{"version":3,"file":"useCheckout.js","names":[],"sources":["../../../../../src/billing/modules/checkout/hooks/useCheckout.ts"],"sourcesContent":["/**\n * Main checkout hook for managing checkout state and payment processing\n */\n\nimport { useState, useCallback, useMemo, useEffect } from 'react';\nimport {\n useInitiatePaymentCheckoutMutation,\n useSpendCreditsCheckoutMutation,\n useConvertCurrencyLazyQuery,\n useValidateCouponLazyQuery,\n useCreateBillingOrderCheckoutMutation,\n} from '../../../../generated/global-operations';\nimport { useBilling } from '../../../providers/BillingProvider';\nimport type {\n CheckoutItem,\n CheckoutBillingAccount,\n PaymentProvider,\n Currency,\n CheckoutState,\n PaymentInitResponse,\n PromoCodeResult,\n PurchaseType,\n} from '../types';\n\n/**\n * Credit conversion rate: How many credits equal 1 USD\n * This should match the backend creditRate.rateUSD (default 0.01 means 100 credits = $1)\n */\nconst CREDITS_PER_USD = 100;\n\ninterface UseCheckoutOptions {\n billingAccountId?: string;\n defaultCurrency?: Currency;\n defaultSaveCard?: boolean;\n upgradeFromSubscriptionId?: string;\n /** For plan downgrades — old sub auto-renewal cancelled, runs to natural expiry */\n downgradeFromSubscriptionId?: string;\n /** For addon purchases - pre-selected subscription ID */\n defaultSubscriptionId?: string;\n}\n\ninterface UseCheckoutResult {\n // State\n items: CheckoutItem[];\n billingAccount: CheckoutBillingAccount | null;\n selectedProvider: PaymentProvider;\n selectedCurrency: Currency;\n promoCode: string;\n promoDiscount: number;\n promoDiscountType: 'PERCENTAGE' | 'FIXED';\n useCredits: boolean;\n creditsToUse: number;\n checkoutState: CheckoutState;\n error: string | null;\n\n // Saved card state\n selectedPaymentMethodId: string | null;\n saveCard: boolean;\n\n // Auto-pay state (for subscription purchases)\n autoRenew: boolean;\n autoRenewPaymentMethodId: string | null;\n\n // Subscription state (for addon purchases)\n selectedSubscriptionId: string | null;\n\n // Computed values\n subtotal: number;\n subtotalUSD: number;\n discountAmount: number;\n taxAmount: number;\n taxRate: number;\n taxType: string;\n total: number;\n totalInSelectedCurrency: number;\n availableCredits: number;\n hasEnoughCredits: boolean;\n canPayWithCredits: boolean;\n isLoading: boolean;\n isProcessing: boolean;\n isCalculatingTax: boolean;\n\n // Currency conversion\n conversionRate: number;\n convertedAmount: number | null;\n\n // Actions\n addItem: (item: CheckoutItem) => void;\n removeItem: (itemId: string) => void;\n updateItemQuantity: (itemId: string, quantity: number) => void;\n updateItemPrice: (itemId: string, price: number, currency?: Currency) => void;\n clearItems: () => void;\n setBillingAccount: (account: CheckoutBillingAccount | null) => void;\n setPaymentProvider: (provider: PaymentProvider) => void;\n setCurrency: (currency: Currency) => void;\n setPromoCode: (code: string) => void;\n validatePromoCode: () => Promise<PromoCodeResult>;\n clearPromoCode: () => void;\n setUseCredits: (use: boolean) => void;\n setCreditsToUse: (amount: number) => void;\n setSelectedPaymentMethodId: (id: string | null) => void;\n setSaveCard: (save: boolean) => void;\n setAutoRenew: (enabled: boolean) => void;\n setAutoRenewPaymentMethodId: (id: string | null) => void;\n setSelectedSubscriptionId: (id: string | null) => void;\n initiatePayment: () => Promise<PaymentInitResponse>;\n reset: () => void;\n}\n\nexport function useCheckout(options: UseCheckoutOptions = {}): UseCheckoutResult {\n const { currentUser } = useBilling();\n const {\n defaultCurrency = 'USD',\n defaultSaveCard = false, // CRITICAL: Never save cards without explicit user consent\n upgradeFromSubscriptionId,\n downgradeFromSubscriptionId,\n defaultSubscriptionId,\n } = options;\n\n // Core state\n const [items, setItems] = useState<CheckoutItem[]>([]);\n const [billingAccount, setBillingAccount] = useState<CheckoutBillingAccount | null>(null);\n const [selectedProvider, setSelectedProvider] = useState<PaymentProvider>('AUTO');\n const [selectedCurrency, setSelectedCurrency] = useState<Currency>(defaultCurrency);\n const [promoCode, setPromoCode] = useState('');\n const [promoDiscount, setPromoDiscount] = useState(0);\n const [promoDiscountType, setPromoDiscountType] = useState<'PERCENTAGE' | 'FIXED'>('PERCENTAGE');\n const [useCredits, setUseCredits] = useState(false);\n const [creditsToUse, setCreditsToUse] = useState(0);\n const [checkoutState, setCheckoutState] = useState<CheckoutState>('idle');\n const [error, setError] = useState<string | null>(null);\n const [taxAmount, setTaxAmount] = useState(0);\n const [taxRate, setTaxRate] = useState(0);\n const [taxType, setTaxType] = useState<string>('NONE');\n\n // Saved card state\n const [selectedPaymentMethodId, setSelectedPaymentMethodId] = useState<string | null>(null);\n const [saveCard, setSaveCard] = useState(defaultSaveCard);\n\n // Auto-pay state (for subscription purchases)\n const [autoRenew, setAutoRenew] = useState(false);\n const [autoRenewPaymentMethodId, setAutoRenewPaymentMethodId] = useState<string | null>(null);\n\n // Subscription state (for addon purchases)\n const [selectedSubscriptionId, setSelectedSubscriptionId] = useState<string | null>(\n defaultSubscriptionId ?? null\n );\n\n // GraphQL mutations and queries\n const [initiatePaymentMutation] = useInitiatePaymentCheckoutMutation();\n const [createBillingOrderMutation] = useCreateBillingOrderCheckoutMutation();\n const [spendCreditsMutation] = useSpendCreditsCheckoutMutation();\n const [convertCurrency, { data: currencyData, loading: currencyLoading }] =\n useConvertCurrencyLazyQuery();\n const [validateCoupon] = useValidateCouponLazyQuery();\n\n // Computed values\n const subtotal = useMemo(() => {\n return items.reduce((sum, item) => sum + item.price * item.quantity, 0);\n }, [items]);\n\n // USD subtotal — always use priceUSD (base price) for credit calculations.\n // item.price may be in a local currency (INR, EUR, etc.) when currencyPrices is set.\n const subtotalUSD = useMemo(() => {\n return items.reduce((sum, item) => sum + (item.priceUSD ?? item.price) * item.quantity, 0);\n }, [items]);\n\n const discountAmount = useMemo(() => {\n if (!promoDiscount) return 0;\n // promoDiscount now contains the actual discount amount from backend validation\n // (not the percentage value), so use it directly\n return Math.min(promoDiscount, subtotal);\n }, [subtotal, promoDiscount]);\n\n // Total includes tax (calculated via calculateTax query)\n const total = useMemo(() => {\n const afterDiscount = subtotal - discountAmount;\n const withCredits = useCredits ? Math.max(0, afterDiscount - creditsToUse) : afterDiscount;\n return withCredits + taxAmount;\n }, [subtotal, discountAmount, useCredits, creditsToUse, taxAmount]);\n\n const availableCredits = billingAccount?.creditAmount ?? 0;\n\n const hasEnoughCredits = useMemo(() => {\n // Use subtotalUSD so this works correctly for any display currency\n const creditsRequired = subtotalUSD * CREDITS_PER_USD;\n return availableCredits >= creditsRequired;\n }, [availableCredits, subtotalUSD]);\n\n // Can only pay with credits if not buying credits\n const canPayWithCredits = useMemo(() => {\n const hasCreditsPurchase = items.some((item) => item.type === 'CREDITS');\n return !hasCreditsPurchase && availableCredits > 0;\n }, [items, availableCredits]);\n\n // Currency conversion result\n const convertedAmount = currencyData?.convertCurrency?.amount ?? null;\n const conversionRate = currencyData?.convertCurrency?.exchangeRate ?? 1;\n const totalInSelectedCurrency = convertedAmount ?? total;\n\n const isLoading = checkoutState === 'loading' || currencyLoading;\n const isProcessing = checkoutState === 'processing';\n\n // Effect to trigger currency conversion when total or currency changes\n // This ensures the converted amount is always up-to-date\n useEffect(() => {\n // Skip conversion for credit payments (no currency conversion needed)\n if (selectedProvider === 'CREDITS') {\n return;\n }\n\n // Skip if no items yet (cart is still loading)\n if (items.length === 0) {\n return;\n }\n\n // Skip conversion if items already have prices in selected currency\n // (Plans/Addons with multi-currency pricing have currencyPrices stored)\n const allItemsHaveLocalizedPrices = items.every(\n (item) => item.currency === selectedCurrency || item.type === 'CREDITS'\n );\n\n if (allItemsHaveLocalizedPrices) {\n // Items are already priced in the selected currency (from currencyPrices)\n // No conversion needed - subtotal and total are already correct!\n return;\n }\n\n // Only fetch if we have a valid total and non-USD currency\n if (total > 0 && selectedCurrency !== 'USD') {\n // For INR, wait until tax has been calculated (taxAmount > 0 or taxRate is set)\n // This prevents double API calls - one before tax, one after\n if (selectedCurrency === 'INR' && taxAmount === 0 && subtotal > 0) {\n // Tax hasn't been calculated yet, skip this conversion\n // The effect will run again when taxAmount changes\n return;\n }\n\n convertCurrency({\n variables: {\n amount: total,\n toCurrency: selectedCurrency,\n fromCurrency: 'USD',\n },\n });\n }\n }, [total, selectedCurrency, selectedProvider, convertCurrency, taxAmount, subtotal, items]);\n\n // Effect to calculate tax when billing account, subtotal, or currency changes\n // Tax is only applied for INR payments (18% GST)\n useEffect(() => {\n // Only calculate tax if we have a billing account and items\n if (!billingAccount || subtotal <= 0) {\n // Reset tax if no billing account or empty cart\n setTaxAmount(0);\n setTaxRate(0);\n setTaxType('NONE');\n return;\n }\n\n // Skip if paying with credits (no tax on credit payments)\n if (selectedProvider === 'CREDITS') {\n setTaxAmount(0);\n setTaxRate(0);\n setTaxType('NONE');\n return;\n }\n\n // Only apply tax for INR payments\n if (selectedCurrency !== 'INR') {\n setTaxAmount(0);\n setTaxRate(0);\n setTaxType('NONE');\n return;\n }\n\n // For INR: Calculate 18% GST on the USD amount, then we'll convert for display\n const afterDiscount = subtotal - discountAmount;\n const GST_RATE = 0.18;\n const taxInUSD = afterDiscount * GST_RATE;\n\n setTaxAmount(taxInUSD);\n setTaxRate(GST_RATE);\n setTaxType('GST');\n }, [billingAccount, subtotal, discountAmount, selectedCurrency, selectedProvider]);\n\n // Actions\n const addItem = useCallback((item: CheckoutItem) => {\n setItems((prev) => {\n // Plans can only be purchased once - quantity is always 1\n if (item.type === 'PLAN') {\n // Check if any plan already exists in cart\n const existingPlan = prev.find((i) => i.type === 'PLAN');\n if (existingPlan) {\n // Replace existing plan with new one (can only have 1 plan)\n return prev.map((i) => (i.type === 'PLAN' ? { ...item, quantity: 1 } : i));\n }\n // Add new plan with quantity forced to 1\n return [...prev, { ...item, quantity: 1 }];\n }\n\n // For addons and credits, allow quantity increment\n const existing = prev.find((i) => i.id === item.id);\n if (existing) {\n return prev.map((i) =>\n i.id === item.id ? { ...i, quantity: i.quantity + item.quantity } : i\n );\n }\n return [...prev, item];\n });\n }, []);\n\n const removeItem = useCallback((itemId: string) => {\n setItems((prev) => prev.filter((i) => i.id !== itemId));\n }, []);\n\n const updateItemQuantity = useCallback(\n (itemId: string, quantity: number) => {\n if (quantity <= 0) {\n removeItem(itemId);\n return;\n }\n setItems((prev) =>\n prev.map((i) => {\n if (i.id !== itemId) return i;\n // Plans can only have quantity 1\n if (i.type === 'PLAN') {\n return { ...i, quantity: 1 };\n }\n return { ...i, quantity };\n })\n );\n },\n [removeItem]\n );\n\n const updateItemPrice = useCallback((itemId: string, price: number, currency?: Currency) => {\n setItems((prev) =>\n prev.map((i) => {\n if (i.id !== itemId) return i;\n // Update price and optionally currency\n const updates: Partial<CheckoutItem> = { price };\n if (currency) {\n updates.currency = currency;\n }\n return { ...i, ...updates };\n })\n );\n }, []);\n\n const clearItems = useCallback(() => {\n setItems([]);\n }, []);\n\n const handleSetBillingAccount = useCallback((account: CheckoutBillingAccount | null) => {\n setBillingAccount(account);\n // Reset credits usage when billing account changes\n setUseCredits(false);\n setCreditsToUse(0);\n }, []);\n\n const handleSetCurrency = useCallback(\n (currency: Currency) => {\n setSelectedCurrency(currency);\n // Skip conversion if items already have localized prices\n // (Plans/Addons with multi-currency pricing don't need conversion)\n const allItemsHaveLocalizedPrices = items.every(\n (item) => item.currency === currency || item.type === 'CREDITS'\n );\n\n // Only fetch conversion rate if items don't have localized prices\n if (total > 0 && currency !== 'USD' && !allItemsHaveLocalizedPrices) {\n convertCurrency({\n variables: {\n amount: total,\n toCurrency: currency,\n fromCurrency: 'USD',\n },\n });\n }\n },\n [total, convertCurrency, items]\n );\n\n const handleSetPaymentProvider = useCallback(\n (provider: PaymentProvider) => {\n setSelectedProvider(provider);\n // Razorpay only supports INR\n if (provider === 'RAZORPAY' && selectedCurrency !== 'INR') {\n setSelectedCurrency('INR');\n }\n },\n [selectedCurrency]\n );\n\n const validatePromoCode = useCallback(async (): Promise<PromoCodeResult> => {\n if (!promoCode.trim()) {\n return {\n valid: false,\n code: '',\n discountType: 'PERCENTAGE',\n discountValue: 0,\n error: 'Please enter a promo code',\n };\n }\n\n try {\n setCheckoutState('loading');\n\n // Build validation input\n const validationInput = {\n code: promoCode.trim().toUpperCase(),\n userId: currentUser?.id ?? '',\n userEmail: currentUser?.email,\n amount: subtotal,\n currency: selectedCurrency,\n };\n\n const { data, error: queryError } = await validateCoupon({\n variables: {\n input: validationInput,\n },\n });\n\n if (queryError || !data?.validateCoupon) {\n setPromoDiscount(0);\n setCheckoutState('idle');\n return {\n valid: false,\n code: promoCode,\n discountType: 'PERCENTAGE',\n discountValue: 0,\n error: 'Failed to validate coupon',\n };\n }\n\n const response = data.validateCoupon;\n\n if (!response.valid) {\n setPromoDiscount(0);\n setCheckoutState('idle');\n return {\n valid: false,\n code: promoCode,\n discountType: 'PERCENTAGE',\n discountValue: 0,\n error: response.error || 'Invalid coupon code',\n };\n }\n\n // Extract discount details from coupon\n const coupon = response.coupon;\n if (!coupon) {\n setPromoDiscount(0);\n setCheckoutState('idle');\n return {\n valid: false,\n code: promoCode,\n discountType: 'PERCENTAGE',\n discountValue: 0,\n error: 'Coupon data not found',\n };\n }\n\n // Use the ACTUAL discount amount from validation (includes caps and currency conversion)\n const actualDiscountAmount = response.discountAmount || 0;\n\n const discountType = coupon.type === 'FIXED_AMOUNT' ? 'FIXED' : 'PERCENTAGE';\n setPromoDiscount(actualDiscountAmount); // Use actual discount, not coupon.value\n setPromoDiscountType(discountType);\n setCheckoutState('idle');\n\n return {\n valid: true,\n code: coupon.code,\n discountType,\n discountValue: actualDiscountAmount, // Use actual discount, not coupon.value\n };\n } catch {\n setPromoDiscount(0);\n setCheckoutState('idle');\n return {\n valid: false,\n code: promoCode,\n discountType: 'PERCENTAGE',\n discountValue: 0,\n error: 'Failed to validate coupon',\n };\n }\n }, [\n billingAccount?.id,\n currentUser?.email,\n currentUser?.id,\n promoCode,\n selectedCurrency,\n subtotal,\n validateCoupon,\n ]);\n\n const clearPromoCode = useCallback(() => {\n setPromoCode('');\n setPromoDiscount(0);\n setPromoDiscountType('PERCENTAGE');\n }, []);\n\n const handleSetCreditsToUse = useCallback(\n (amount: number) => {\n const maxCredits = Math.min(amount, availableCredits, subtotal - discountAmount);\n setCreditsToUse(Math.max(0, maxCredits));\n },\n [availableCredits, subtotal, discountAmount]\n );\n\n const initiatePayment = useCallback(async (): Promise<PaymentInitResponse> => {\n if (!billingAccount) {\n return {\n success: false,\n provider: 'AUTO',\n subtotal: 0,\n taxAmount: 0,\n taxRate: 0,\n total: 0,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: 'Please select a billing account',\n };\n }\n\n if (items.length === 0) {\n return {\n success: false,\n provider: 'AUTO',\n subtotal: 0,\n taxAmount: 0,\n taxRate: 0,\n total: 0,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: 'No items in checkout',\n };\n }\n\n try {\n setCheckoutState('processing');\n setError(null);\n\n // Determine purchase type from first item\n const firstItem = items[0];\n let purchaseType: PurchaseType = firstItem.type;\n\n // Check if this is a store order checkout (detect early)\n const storeOrderItem = items.find((item) => item.metadata?.storeOrderId);\n const storeOrderId = storeOrderItem?.metadata?.storeOrderId as string | undefined;\n let billingOrderId =\n (items.find((item) => item.metadata?.billingOrderId)?.metadata?.billingOrderId as\n | string\n | undefined) || undefined;\n\n // For store orders, use 'ORDER' purchase type\n if (storeOrderId) {\n purchaseType = 'ORDER' as PurchaseType;\n }\n\n // Calculate amount to charge\n const chargeAmount = subtotal - discountAmount;\n\n // Determine provider\n let provider = selectedProvider;\n if (provider === 'AUTO') {\n provider = selectedCurrency === 'INR' ? 'RAZORPAY' : 'STRIPE';\n }\n\n // If this is a store order without a billing order yet, create one now.\n // Pass callbackGraphQL so the billing service can call back to the store service\n // after payment completes to mark the order confirmed.\n if (purchaseType === 'ORDER' && !billingOrderId && storeOrderId && billingAccount) {\n const orderItems = items\n .filter((item) => item.type === 'ORDER')\n .map((item) => ({\n name: item.name,\n description: item.description ?? undefined,\n quantity: item.quantity,\n unitPrice: item.price,\n metadata: {\n productId: item.metadata?.productId ?? undefined,\n variantId: item.metadata?.variantId ?? undefined,\n },\n }));\n\n const { data: billingOrderResult } = await createBillingOrderMutation({\n variables: {\n input: {\n // billingAccountId intentionally not set here — it gets\n // linked at initiatePayment time so the user can switch\n // billing accounts before confirming payment.\n externalOrderId: storeOrderId,\n externalService: 'STORE',\n currency: selectedCurrency,\n subtotal: chargeAmount,\n description: `Store order ${storeOrderId}`,\n items: orderItems,\n callbackGraphQL: {\n endpoint: 'http://global-int-gateway:4002/global/graphql',\n mutationName: 'updateStoreOrderPaymentStatus',\n },\n },\n },\n });\n\n if (billingOrderResult?.createBillingOrder?.success) {\n billingOrderId = billingOrderResult.createBillingOrder.order?.id;\n } else {\n const errMsg =\n billingOrderResult?.createBillingOrder?.error ?? 'Failed to create billing order';\n setCheckoutState('error');\n setError(errMsg);\n return {\n success: false,\n provider,\n subtotal: chargeAmount,\n taxAmount: 0,\n taxRate: 0,\n total: chargeAmount,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: errMsg,\n };\n }\n }\n\n // ========================================\n // CREDITS PAYMENT - use spendCredits mutation\n // Supports multiple addons\n // ========================================\n if (provider === 'CREDITS') {\n const addonItems = items.filter((item) => item.type === 'ADDON');\n const planItem = items.find((item) => item.type === 'PLAN');\n\n const { data } = await spendCreditsMutation({\n variables: {\n input: {\n billingAccountId: billingAccount.id,\n planId: planItem ? (planItem.metadata?.planId as string) || planItem.id : undefined,\n // Multiple addons supported via addOnIds array\n addOnIds:\n addonItems.length > 0\n ? addonItems.map((item) => ({\n id: (item.metadata?.addonId as string) || item.id,\n quantity: item.quantity,\n }))\n : undefined,\n isAnnual: planItem?.metadata?.duration === 'yearly',\n // Include upgrade context if changing plans\n upgradeFromSubscriptionId: upgradeFromSubscriptionId || undefined,\n // Include downgrade context if downgrading\n downgradeFromSubscriptionId: downgradeFromSubscriptionId || undefined,\n // For addon purchases - subscription to attach to\n subscriptionId: addonItems.length > 0 ? selectedSubscriptionId : undefined,\n // For PER_SEAT plans - pass seat count for credit calculation + subscription storage\n seatCount: planItem?.metadata?.seatCount as number | undefined,\n },\n },\n });\n\n const response = data?.spendCredits;\n\n if (!response?.creditTransactionID) {\n setCheckoutState('error');\n setError('Failed to process credit payment');\n return {\n success: false,\n provider: 'CREDITS',\n subtotal: chargeAmount,\n taxAmount: 0,\n taxRate: 0,\n total: chargeAmount,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: 'Failed to process credit payment',\n };\n }\n\n setCheckoutState('success');\n return {\n success: true,\n provider: 'CREDITS',\n subtotal: chargeAmount,\n taxAmount: 0,\n taxRate: 0,\n total: chargeAmount,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n // Return transaction ID for success handling\n orderId: response.creditTransactionID,\n };\n }\n\n // ========================================\n // CARD PAYMENT (Stripe/Razorpay) - use initiatePayment\n // Supports single or multiple addons\n // Supports store orders (via orderId parameter)\n // ========================================\n const addonItems = items.filter((item) => item.type === 'ADDON');\n\n // Build addon IDs and quantities for the mutation\n const addonIds =\n addonItems.length > 0\n ? addonItems.map((item) => (item.metadata?.addonId as string) || item.id)\n : undefined;\n const quantities =\n addonItems.length > 0 ? addonItems.map((item) => item.quantity) : undefined;\n\n // Determine if this is an annual plan purchase\n const planItem = items.find((item) => item.type === 'PLAN');\n const isAnnualPlan = planItem?.metadata?.duration === 'yearly';\n\n // Determine auto-renew payment method\n const autoRenewPMId =\n purchaseType === 'PLAN' && autoRenew\n ? autoRenewPaymentMethodId || selectedPaymentMethodId || undefined\n : undefined;\n\n const { data } = await initiatePaymentMutation({\n variables: {\n input: {\n billingAccountId: billingAccount.id,\n amount: chargeAmount, // Note: Backend IGNORES this and calculates from DB\n currency: selectedCurrency,\n purchaseType,\n provider: provider,\n // Store order - use orderId parameter (billing order ID)\n orderId: billingOrderId || undefined,\n creditAmount: purchaseType === 'CREDITS' ? firstItem.quantity : undefined,\n planId:\n purchaseType === 'PLAN'\n ? (firstItem.metadata?.planId as string) || firstItem.id\n : undefined,\n // Single addon (backwards compatible) - skip if store order\n addonId:\n purchaseType === 'ADDON' && addonItems.length === 1 && !billingOrderId\n ? (addonItems[0].metadata?.addonId as string) || addonItems[0].id\n : undefined,\n quantity:\n purchaseType === 'ADDON' && addonItems.length === 1 && !billingOrderId\n ? addonItems[0].quantity\n : undefined,\n // Multiple addons (cart checkout) - skip if store order\n addonIds:\n purchaseType === 'ADDON' && addonItems.length > 1 && !billingOrderId\n ? addonIds\n : undefined,\n quantities:\n purchaseType === 'ADDON' && addonItems.length > 1 && !billingOrderId\n ? quantities\n : undefined,\n // For addon purchases - subscription to attach to (skip for store orders)\n subscriptionId:\n purchaseType === 'ADDON' && !billingOrderId ? selectedSubscriptionId : undefined,\n // Saved card support\n paymentMethodId: selectedPaymentMethodId || undefined,\n // Save card if: user checked save card OR auto-renewal is enabled (which requires a saved card)\n // Only save if not using existing card (selectedPaymentMethodId is null)\n saveCard: !selectedPaymentMethodId ? saveCard || autoRenew : undefined,\n // Include upgrade context if changing plans\n upgradeFromSubscriptionId: upgradeFromSubscriptionId || undefined,\n // Include downgrade context if downgrading\n downgradeFromSubscriptionId: downgradeFromSubscriptionId || undefined,\n // Annual plan flag (for pricing calculation)\n isAnnual: isAnnualPlan || undefined,\n // Promo code (validated and applied on backend)\n promoCode: promoCode || undefined,\n // Auto-renewal (for plan purchases only)\n autoRenew: purchaseType === 'PLAN' && autoRenew ? true : undefined,\n autoRenewPaymentMethodId: autoRenewPMId,\n },\n },\n });\n\n const response = data?.initiatePayment;\n\n if (!response?.success) {\n setCheckoutState('error');\n setError(response?.error ?? 'Payment initiation failed');\n return {\n success: false,\n provider: provider,\n subtotal: chargeAmount,\n taxAmount: 0,\n taxRate: 0,\n total: chargeAmount,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: response?.error ?? 'Payment initiation failed',\n };\n }\n\n // Note: Tax is already calculated upfront in the effect, don't overwrite\n // The response tax is in converted currency which would mess up display\n setCheckoutState('success');\n\n return response;\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'An error occurred';\n setCheckoutState('error');\n setError(errorMessage);\n return {\n success: false,\n provider: 'AUTO',\n subtotal: 0,\n taxAmount: 0,\n taxRate: 0,\n total: 0,\n taxType: 'NONE',\n jurisdiction: 'UNKNOWN',\n currency: selectedCurrency,\n error: errorMessage,\n };\n }\n }, [\n billingAccount,\n items,\n selectedCurrency,\n selectedProvider,\n subtotal,\n discountAmount,\n promoCode,\n selectedPaymentMethodId,\n saveCard,\n autoRenew,\n autoRenewPaymentMethodId,\n selectedSubscriptionId,\n upgradeFromSubscriptionId,\n downgradeFromSubscriptionId,\n initiatePaymentMutation,\n createBillingOrderMutation,\n spendCreditsMutation,\n ]);\n\n const reset = useCallback(() => {\n setItems([]);\n setBillingAccount(null);\n setSelectedProvider('AUTO');\n setSelectedCurrency(defaultCurrency);\n setPromoCode('');\n setPromoDiscount(0);\n setPromoDiscountType('PERCENTAGE');\n setUseCredits(false);\n setCreditsToUse(0);\n setCheckoutState('idle');\n setError(null);\n setTaxAmount(0);\n setTaxRate(0);\n setTaxType('NONE');\n setSelectedPaymentMethodId(null);\n setSaveCard(defaultSaveCard);\n setAutoRenew(false);\n setAutoRenewPaymentMethodId(null);\n setSelectedSubscriptionId(defaultSubscriptionId ?? null);\n }, [defaultCurrency, defaultSaveCard, defaultSubscriptionId]);\n\n return {\n // State\n items,\n billingAccount,\n selectedProvider,\n selectedCurrency,\n promoCode,\n promoDiscount,\n promoDiscountType,\n useCredits,\n creditsToUse,\n checkoutState,\n error,\n\n // Saved card state\n selectedPaymentMethodId,\n saveCard,\n\n // Auto-pay state\n autoRenew,\n autoRenewPaymentMethodId,\n\n // Subscription state (for addon purchases)\n selectedSubscriptionId,\n\n // Computed\n subtotal,\n subtotalUSD,\n discountAmount,\n taxAmount,\n taxRate,\n taxType,\n total,\n totalInSelectedCurrency,\n availableCredits,\n hasEnoughCredits,\n canPayWithCredits,\n isLoading,\n isProcessing,\n isCalculatingTax: false, // Tax is calculated synchronously now\n conversionRate,\n convertedAmount,\n\n // Actions\n addItem,\n removeItem,\n updateItemQuantity,\n updateItemPrice,\n clearItems,\n setBillingAccount: handleSetBillingAccount,\n setPaymentProvider: handleSetPaymentProvider,\n setCurrency: handleSetCurrency,\n setPromoCode,\n validatePromoCode,\n clearPromoCode,\n setUseCredits,\n setCreditsToUse: handleSetCreditsToUse,\n setSelectedPaymentMethodId,\n setSaveCard,\n setAutoRenew,\n setAutoRenewPaymentMethodId,\n setSelectedSubscriptionId,\n initiatePayment,\n reset,\n };\n}\n"],"mappings":";;;;AA4BA,IAAM,KAAkB;AAiFxB,SAAgB,EAAY,IAA8B,EAAE,EAAqB;CAC/E,IAAM,EAAE,mBAAgB,GAAY,EAC9B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