@solvapay/react 1.0.0-preview.2 → 1.0.0-preview.20
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/LICENSE.md +21 -0
- package/README.md +306 -16
- package/dist/adapters/auth.cjs +49 -0
- package/dist/adapters/auth.d.cts +44 -0
- package/dist/adapters/auth.d.ts +44 -0
- package/dist/adapters/auth.js +6 -0
- package/dist/chunk-OUSEQRCT.js +25 -0
- package/dist/index.cjs +1213 -174
- package/dist/index.d.cts +869 -45
- package/dist/index.d.ts +869 -45
- package/dist/index.js +1177 -174
- package/package.json +28 -7
package/dist/index.cjs
CHANGED
|
@@ -21,201 +21,711 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
PaymentForm: () => PaymentForm,
|
|
24
|
-
|
|
24
|
+
PlanBadge: () => PlanBadge,
|
|
25
|
+
PlanSelector: () => PlanSelector,
|
|
26
|
+
PurchaseGate: () => PurchaseGate,
|
|
27
|
+
SolvaPayProvider: () => SolvaPayProvider,
|
|
28
|
+
Spinner: () => Spinner,
|
|
29
|
+
StripePaymentFormWrapper: () => StripePaymentFormWrapper,
|
|
30
|
+
defaultAuthAdapter: () => defaultAuthAdapter,
|
|
31
|
+
filterPurchases: () => filterPurchases,
|
|
32
|
+
getActivePurchases: () => getActivePurchases,
|
|
33
|
+
getCancelledPurchasesWithEndDate: () => getCancelledPurchasesWithEndDate,
|
|
34
|
+
getMostRecentPurchase: () => getMostRecentPurchase,
|
|
35
|
+
getPrimaryPurchase: () => getPrimaryPurchase,
|
|
36
|
+
isPaidPurchase: () => isPaidPurchase,
|
|
37
|
+
useCheckout: () => useCheckout,
|
|
38
|
+
useCustomer: () => useCustomer,
|
|
39
|
+
usePlans: () => usePlans,
|
|
40
|
+
usePurchase: () => usePurchase,
|
|
41
|
+
usePurchaseStatus: () => usePurchaseStatus,
|
|
42
|
+
useSolvaPay: () => useSolvaPay
|
|
25
43
|
});
|
|
26
44
|
module.exports = __toCommonJS(index_exports);
|
|
27
45
|
|
|
28
46
|
// src/SolvaPayProvider.tsx
|
|
29
47
|
var import_react = require("react");
|
|
30
|
-
|
|
31
|
-
|
|
48
|
+
|
|
49
|
+
// src/utils/purchases.ts
|
|
50
|
+
function filterPurchases(purchases) {
|
|
51
|
+
return purchases.filter((purchase) => purchase.status === "active");
|
|
52
|
+
}
|
|
53
|
+
function getActivePurchases(purchases) {
|
|
54
|
+
return purchases.filter((purchase) => purchase.status === "active");
|
|
55
|
+
}
|
|
56
|
+
function getCancelledPurchasesWithEndDate(purchases) {
|
|
57
|
+
const now = /* @__PURE__ */ new Date();
|
|
58
|
+
return purchases.filter((purchase) => {
|
|
59
|
+
return purchase.status === "active" && purchase.cancelledAt && purchase.endDate && new Date(purchase.endDate) > now;
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
function getMostRecentPurchase(purchases) {
|
|
63
|
+
if (purchases.length === 0) return null;
|
|
64
|
+
return purchases.reduce((latest, current) => {
|
|
65
|
+
return new Date(current.startDate) > new Date(latest.startDate) ? current : latest;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function getPrimaryPurchase(purchases) {
|
|
69
|
+
const filtered = filterPurchases(purchases);
|
|
70
|
+
if (filtered.length > 0) {
|
|
71
|
+
return getMostRecentPurchase(filtered);
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
function isPaidPurchase(purchase) {
|
|
76
|
+
return (purchase.amount ?? 0) > 0;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/adapters/auth.ts
|
|
80
|
+
var defaultAuthAdapter = {
|
|
81
|
+
async getToken() {
|
|
82
|
+
if (typeof window === "undefined") return null;
|
|
83
|
+
const token = localStorage.getItem("auth_token");
|
|
84
|
+
return token || null;
|
|
85
|
+
},
|
|
86
|
+
async getUserId() {
|
|
87
|
+
const token = await this.getToken();
|
|
88
|
+
if (!token) return null;
|
|
89
|
+
try {
|
|
90
|
+
const parts = token.split(".");
|
|
91
|
+
if (parts.length === 3) {
|
|
92
|
+
const payload = JSON.parse(atob(parts[1]));
|
|
93
|
+
return payload.sub || payload.user_id || null;
|
|
94
|
+
}
|
|
95
|
+
} catch {
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// src/SolvaPayProvider.tsx
|
|
32
102
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
103
|
+
var SolvaPayContext = (0, import_react.createContext)(null);
|
|
104
|
+
var CUSTOMER_REF_KEY = "solvapay_customerRef";
|
|
105
|
+
var CUSTOMER_REF_EXPIRY = "solvapay_customerRef_expiry";
|
|
106
|
+
var CUSTOMER_REF_USER_ID_KEY = "solvapay_customerRef_userId";
|
|
107
|
+
var CACHE_DURATION = 24 * 60 * 60 * 1e3;
|
|
108
|
+
function getCachedCustomerRef(userId) {
|
|
109
|
+
if (typeof window === "undefined") return null;
|
|
110
|
+
const cached = localStorage.getItem(CUSTOMER_REF_KEY);
|
|
111
|
+
const expiry = localStorage.getItem(CUSTOMER_REF_EXPIRY);
|
|
112
|
+
const cachedUserId = localStorage.getItem(CUSTOMER_REF_USER_ID_KEY);
|
|
113
|
+
if (!cached || !expiry) return null;
|
|
114
|
+
if (Date.now() > parseInt(expiry)) {
|
|
115
|
+
localStorage.removeItem(CUSTOMER_REF_KEY);
|
|
116
|
+
localStorage.removeItem(CUSTOMER_REF_EXPIRY);
|
|
117
|
+
localStorage.removeItem(CUSTOMER_REF_USER_ID_KEY);
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
if (userId !== void 0 && userId !== null) {
|
|
121
|
+
if (cachedUserId !== userId) {
|
|
122
|
+
clearCachedCustomerRef();
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return cached;
|
|
127
|
+
}
|
|
128
|
+
function setCachedCustomerRef(customerRef, userId) {
|
|
129
|
+
if (typeof window === "undefined") return;
|
|
130
|
+
if (userId === void 0 || userId === null) {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
localStorage.setItem(CUSTOMER_REF_KEY, customerRef);
|
|
134
|
+
localStorage.setItem(CUSTOMER_REF_EXPIRY, String(Date.now() + CACHE_DURATION));
|
|
135
|
+
localStorage.setItem(CUSTOMER_REF_USER_ID_KEY, userId);
|
|
136
|
+
}
|
|
137
|
+
function clearCachedCustomerRef() {
|
|
138
|
+
if (typeof window === "undefined") return;
|
|
139
|
+
localStorage.removeItem(CUSTOMER_REF_KEY);
|
|
140
|
+
localStorage.removeItem(CUSTOMER_REF_EXPIRY);
|
|
141
|
+
localStorage.removeItem(CUSTOMER_REF_USER_ID_KEY);
|
|
142
|
+
}
|
|
143
|
+
function getAuthAdapter(config) {
|
|
144
|
+
if (config?.auth?.adapter) {
|
|
145
|
+
return config.auth.adapter;
|
|
146
|
+
}
|
|
147
|
+
if (config?.auth?.getToken || config?.auth?.getUserId) {
|
|
148
|
+
return {
|
|
149
|
+
async getToken() {
|
|
150
|
+
return config?.auth?.getToken?.() || null;
|
|
151
|
+
},
|
|
152
|
+
async getUserId() {
|
|
153
|
+
return config?.auth?.getUserId?.() || null;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
return defaultAuthAdapter;
|
|
158
|
+
}
|
|
33
159
|
var SolvaPayProvider = ({
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
agentRef,
|
|
40
|
-
apiBaseUrl = "/api/solvapay",
|
|
41
|
-
onPaymentReady
|
|
160
|
+
config,
|
|
161
|
+
createPayment: customCreatePayment,
|
|
162
|
+
checkPurchase: customCheckPurchase,
|
|
163
|
+
processPayment: customProcessPayment,
|
|
164
|
+
children
|
|
42
165
|
}) => {
|
|
43
|
-
const [
|
|
44
|
-
|
|
166
|
+
const [purchaseData, setPurchaseData] = (0, import_react.useState)({
|
|
167
|
+
purchases: []
|
|
168
|
+
});
|
|
45
169
|
const [loading, setLoading] = (0, import_react.useState)(false);
|
|
46
|
-
const [
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
170
|
+
const [internalCustomerRef, setInternalCustomerRef] = (0, import_react.useState)(void 0);
|
|
171
|
+
const [userId, setUserId] = (0, import_react.useState)(null);
|
|
172
|
+
const [isAuthenticated, setIsAuthenticated] = (0, import_react.useState)(false);
|
|
173
|
+
const inFlightRef = (0, import_react.useRef)(null);
|
|
174
|
+
const lastFetchedRef = (0, import_react.useRef)(null);
|
|
175
|
+
const checkPurchaseRef = (0, import_react.useRef)(null);
|
|
176
|
+
const createPaymentRef = (0, import_react.useRef)(null);
|
|
177
|
+
const processPaymentRef = (0, import_react.useRef)(null);
|
|
178
|
+
const configRef = (0, import_react.useRef)(config);
|
|
179
|
+
const buildDefaultCheckPurchaseRef = (0, import_react.useRef)(
|
|
180
|
+
null
|
|
181
|
+
);
|
|
182
|
+
(0, import_react.useEffect)(() => {
|
|
183
|
+
configRef.current = config;
|
|
184
|
+
}, [config]);
|
|
185
|
+
(0, import_react.useEffect)(() => {
|
|
186
|
+
checkPurchaseRef.current = customCheckPurchase || null;
|
|
187
|
+
}, [customCheckPurchase]);
|
|
188
|
+
(0, import_react.useEffect)(() => {
|
|
189
|
+
createPaymentRef.current = customCreatePayment || null;
|
|
190
|
+
}, [customCreatePayment]);
|
|
191
|
+
(0, import_react.useEffect)(() => {
|
|
192
|
+
processPaymentRef.current = customProcessPayment || null;
|
|
193
|
+
}, [customProcessPayment]);
|
|
194
|
+
const buildDefaultCheckPurchase = (0, import_react.useCallback)(async () => {
|
|
195
|
+
const currentConfig = configRef.current;
|
|
196
|
+
const adapter = getAuthAdapter(currentConfig);
|
|
197
|
+
const token = await adapter.getToken();
|
|
198
|
+
const detectedUserId = await adapter.getUserId();
|
|
199
|
+
const route = currentConfig?.api?.checkPurchase || "/api/check-purchase";
|
|
200
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
201
|
+
const cachedRef = getCachedCustomerRef(detectedUserId);
|
|
202
|
+
const headers = {
|
|
203
|
+
"Content-Type": "application/json"
|
|
204
|
+
};
|
|
205
|
+
if (token) {
|
|
206
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
207
|
+
}
|
|
208
|
+
if (cachedRef) {
|
|
209
|
+
headers["x-solvapay-customer-ref"] = cachedRef;
|
|
210
|
+
}
|
|
211
|
+
if (currentConfig?.headers) {
|
|
212
|
+
const customHeaders = typeof currentConfig.headers === "function" ? await currentConfig.headers() : currentConfig.headers;
|
|
213
|
+
Object.assign(headers, customHeaders);
|
|
214
|
+
}
|
|
215
|
+
const res = await fetchFn(route, {
|
|
216
|
+
method: "GET",
|
|
217
|
+
headers
|
|
218
|
+
});
|
|
219
|
+
if (!res.ok) {
|
|
220
|
+
const error = new Error(`Failed to check purchase: ${res.statusText}`);
|
|
221
|
+
currentConfig?.onError?.(error, "checkPurchase");
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
return res.json();
|
|
225
|
+
}, []);
|
|
226
|
+
(0, import_react.useEffect)(() => {
|
|
227
|
+
buildDefaultCheckPurchaseRef.current = buildDefaultCheckPurchase;
|
|
228
|
+
}, [buildDefaultCheckPurchase]);
|
|
229
|
+
const buildDefaultCreatePayment = (0, import_react.useCallback)(
|
|
230
|
+
async (params) => {
|
|
231
|
+
const currentConfig = configRef.current;
|
|
232
|
+
const adapter = getAuthAdapter(currentConfig);
|
|
233
|
+
const token = await adapter.getToken();
|
|
234
|
+
const detectedUserId = await adapter.getUserId();
|
|
235
|
+
const route = currentConfig?.api?.createPayment || "/api/create-payment-intent";
|
|
236
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
237
|
+
const cachedRef = getCachedCustomerRef(detectedUserId);
|
|
238
|
+
const headers = {
|
|
239
|
+
"Content-Type": "application/json"
|
|
240
|
+
};
|
|
241
|
+
if (token) {
|
|
242
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
243
|
+
}
|
|
244
|
+
if (cachedRef) {
|
|
245
|
+
headers["x-solvapay-customer-ref"] = cachedRef;
|
|
246
|
+
}
|
|
247
|
+
if (currentConfig?.headers) {
|
|
248
|
+
const customHeaders = typeof currentConfig.headers === "function" ? await currentConfig.headers() : currentConfig.headers;
|
|
249
|
+
Object.assign(headers, customHeaders);
|
|
250
|
+
}
|
|
251
|
+
const body = { planRef: params.planRef };
|
|
252
|
+
if (params.productRef) {
|
|
253
|
+
body.productRef = params.productRef;
|
|
254
|
+
}
|
|
255
|
+
const res = await fetchFn(route, {
|
|
53
256
|
method: "POST",
|
|
54
|
-
headers
|
|
55
|
-
|
|
56
|
-
},
|
|
57
|
-
body: JSON.stringify({
|
|
58
|
-
planRef,
|
|
59
|
-
agentRef,
|
|
60
|
-
amount: paymentAmount,
|
|
61
|
-
currency,
|
|
62
|
-
description: "SolvaPay - Plan Purchase"
|
|
63
|
-
})
|
|
257
|
+
headers,
|
|
258
|
+
body: JSON.stringify(body)
|
|
64
259
|
});
|
|
65
|
-
if (!
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
260
|
+
if (!res.ok) {
|
|
261
|
+
const error = new Error(`Failed to create payment: ${res.statusText}`);
|
|
262
|
+
currentConfig?.onError?.(error, "createPayment");
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
return res.json();
|
|
266
|
+
},
|
|
267
|
+
[]
|
|
268
|
+
);
|
|
269
|
+
const buildDefaultProcessPayment = (0, import_react.useCallback)(
|
|
270
|
+
async (params) => {
|
|
271
|
+
const currentConfig = configRef.current;
|
|
272
|
+
const adapter = getAuthAdapter(currentConfig);
|
|
273
|
+
const token = await adapter.getToken();
|
|
274
|
+
const detectedUserId = await adapter.getUserId();
|
|
275
|
+
const route = currentConfig?.api?.processPayment || "/api/process-payment";
|
|
276
|
+
const fetchFn = currentConfig?.fetch || fetch;
|
|
277
|
+
const cachedRef = getCachedCustomerRef(detectedUserId);
|
|
278
|
+
const headers = {
|
|
279
|
+
"Content-Type": "application/json"
|
|
280
|
+
};
|
|
281
|
+
if (token) {
|
|
282
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
283
|
+
}
|
|
284
|
+
if (cachedRef) {
|
|
285
|
+
headers["x-solvapay-customer-ref"] = cachedRef;
|
|
286
|
+
}
|
|
287
|
+
if (currentConfig?.headers) {
|
|
288
|
+
const customHeaders = typeof currentConfig.headers === "function" ? await currentConfig.headers() : currentConfig.headers;
|
|
289
|
+
Object.assign(headers, customHeaders);
|
|
290
|
+
}
|
|
291
|
+
const res = await fetchFn(route, {
|
|
292
|
+
method: "POST",
|
|
293
|
+
headers,
|
|
294
|
+
body: JSON.stringify(params)
|
|
79
295
|
});
|
|
296
|
+
if (!res.ok) {
|
|
297
|
+
const error = new Error(`Failed to process payment: ${res.statusText}`);
|
|
298
|
+
currentConfig?.onError?.(error, "processPayment");
|
|
299
|
+
throw error;
|
|
300
|
+
}
|
|
301
|
+
return res.json();
|
|
302
|
+
},
|
|
303
|
+
[]
|
|
304
|
+
);
|
|
305
|
+
const _checkPurchase = (0, import_react.useCallback)(async () => {
|
|
306
|
+
if (checkPurchaseRef.current) {
|
|
307
|
+
return checkPurchaseRef.current();
|
|
308
|
+
}
|
|
309
|
+
if (buildDefaultCheckPurchaseRef.current) {
|
|
310
|
+
return buildDefaultCheckPurchaseRef.current();
|
|
311
|
+
}
|
|
312
|
+
return buildDefaultCheckPurchase();
|
|
313
|
+
}, [buildDefaultCheckPurchase]);
|
|
314
|
+
const createPayment = (0, import_react.useCallback)(
|
|
315
|
+
async (params) => {
|
|
316
|
+
if (createPaymentRef.current) {
|
|
317
|
+
return createPaymentRef.current(params);
|
|
318
|
+
}
|
|
319
|
+
return buildDefaultCreatePayment(params);
|
|
320
|
+
},
|
|
321
|
+
[buildDefaultCreatePayment]
|
|
322
|
+
);
|
|
323
|
+
const processPayment = (0, import_react.useCallback)(
|
|
324
|
+
async (params) => {
|
|
325
|
+
if (processPaymentRef.current) {
|
|
326
|
+
return processPaymentRef.current(params);
|
|
327
|
+
}
|
|
328
|
+
return buildDefaultProcessPayment(params);
|
|
329
|
+
},
|
|
330
|
+
[buildDefaultProcessPayment]
|
|
331
|
+
);
|
|
332
|
+
(0, import_react.useEffect)(() => {
|
|
333
|
+
const detectAuth = async () => {
|
|
334
|
+
const currentConfig = configRef.current;
|
|
335
|
+
const adapter = getAuthAdapter(currentConfig);
|
|
336
|
+
const token = await adapter.getToken();
|
|
337
|
+
const detectedUserId = await adapter.getUserId();
|
|
338
|
+
const prevUserId = userId;
|
|
339
|
+
setIsAuthenticated(!!token);
|
|
340
|
+
setUserId(detectedUserId);
|
|
341
|
+
if (prevUserId !== null && detectedUserId !== prevUserId) {
|
|
342
|
+
clearCachedCustomerRef();
|
|
343
|
+
setInternalCustomerRef(void 0);
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const cachedRef = getCachedCustomerRef(detectedUserId);
|
|
347
|
+
if (cachedRef && token) {
|
|
348
|
+
setInternalCustomerRef(cachedRef);
|
|
349
|
+
} else if (!token) {
|
|
350
|
+
clearCachedCustomerRef();
|
|
351
|
+
setInternalCustomerRef(void 0);
|
|
352
|
+
} else if (token && !cachedRef) {
|
|
353
|
+
setInternalCustomerRef(void 0);
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
detectAuth();
|
|
357
|
+
const interval = setInterval(detectAuth, 5e3);
|
|
358
|
+
return () => clearInterval(interval);
|
|
359
|
+
}, [userId]);
|
|
360
|
+
const fetchPurchase = (0, import_react.useCallback)(
|
|
361
|
+
async (force = false) => {
|
|
362
|
+
if (!isAuthenticated && !internalCustomerRef) {
|
|
363
|
+
setPurchaseData({ purchases: [] });
|
|
364
|
+
setLoading(false);
|
|
365
|
+
inFlightRef.current = null;
|
|
366
|
+
lastFetchedRef.current = null;
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
const cacheKey = internalCustomerRef || userId || "anonymous";
|
|
370
|
+
if (!force && lastFetchedRef.current === cacheKey && inFlightRef.current !== cacheKey) {
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
if (inFlightRef.current === cacheKey) {
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
inFlightRef.current = cacheKey;
|
|
377
|
+
setLoading(true);
|
|
378
|
+
try {
|
|
379
|
+
const checkFn = checkPurchaseRef.current || buildDefaultCheckPurchaseRef.current;
|
|
380
|
+
if (!checkFn) {
|
|
381
|
+
throw new Error("checkPurchase function not available");
|
|
382
|
+
}
|
|
383
|
+
const data = await checkFn();
|
|
384
|
+
if (data.customerRef) {
|
|
385
|
+
setInternalCustomerRef(data.customerRef);
|
|
386
|
+
const currentAdapter = getAuthAdapter(configRef.current);
|
|
387
|
+
const currentUserId = await currentAdapter.getUserId();
|
|
388
|
+
setCachedCustomerRef(data.customerRef, currentUserId);
|
|
389
|
+
}
|
|
390
|
+
if (inFlightRef.current === cacheKey) {
|
|
391
|
+
const filteredData = {
|
|
392
|
+
...data,
|
|
393
|
+
purchases: filterPurchases(data.purchases || [])
|
|
394
|
+
};
|
|
395
|
+
setPurchaseData(filteredData);
|
|
396
|
+
lastFetchedRef.current = cacheKey;
|
|
397
|
+
}
|
|
398
|
+
} catch (error) {
|
|
399
|
+
console.error("[SolvaPayProvider] Failed to fetch purchase:", error);
|
|
400
|
+
if (inFlightRef.current === cacheKey) {
|
|
401
|
+
setPurchaseData({
|
|
402
|
+
purchases: []
|
|
403
|
+
});
|
|
404
|
+
lastFetchedRef.current = cacheKey;
|
|
405
|
+
}
|
|
406
|
+
} finally {
|
|
407
|
+
if (inFlightRef.current === cacheKey) {
|
|
408
|
+
setLoading(false);
|
|
409
|
+
inFlightRef.current = null;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
},
|
|
413
|
+
[isAuthenticated, internalCustomerRef, userId]
|
|
414
|
+
);
|
|
415
|
+
const fetchPurchaseRef = (0, import_react.useRef)(fetchPurchase);
|
|
416
|
+
(0, import_react.useEffect)(() => {
|
|
417
|
+
fetchPurchaseRef.current = fetchPurchase;
|
|
418
|
+
}, [fetchPurchase]);
|
|
419
|
+
const refetchPurchase = (0, import_react.useCallback)(async () => {
|
|
420
|
+
lastFetchedRef.current = null;
|
|
421
|
+
inFlightRef.current = null;
|
|
422
|
+
setPurchaseData({ purchases: [] });
|
|
423
|
+
await fetchPurchaseRef.current(true);
|
|
424
|
+
}, []);
|
|
425
|
+
(0, import_react.useEffect)(() => {
|
|
426
|
+
lastFetchedRef.current = null;
|
|
427
|
+
inFlightRef.current = null;
|
|
428
|
+
if (isAuthenticated || internalCustomerRef) {
|
|
429
|
+
fetchPurchase();
|
|
430
|
+
} else {
|
|
431
|
+
setPurchaseData({ purchases: [] });
|
|
432
|
+
setLoading(false);
|
|
433
|
+
}
|
|
434
|
+
}, [isAuthenticated, internalCustomerRef, userId]);
|
|
435
|
+
const updateCustomerRef = (0, import_react.useCallback)(
|
|
436
|
+
(newCustomerRef) => {
|
|
437
|
+
setInternalCustomerRef(newCustomerRef);
|
|
438
|
+
setCachedCustomerRef(newCustomerRef, userId);
|
|
439
|
+
fetchPurchase(true);
|
|
440
|
+
},
|
|
441
|
+
[fetchPurchase, userId]
|
|
442
|
+
);
|
|
443
|
+
const purchase = (0, import_react.useMemo)(() => {
|
|
444
|
+
const activePurchase = getPrimaryPurchase(purchaseData.purchases);
|
|
445
|
+
const activePaidPurchases = purchaseData.purchases.filter(
|
|
446
|
+
(p) => p.status === "active" && isPaidPurchase(p)
|
|
447
|
+
);
|
|
448
|
+
const activePaidPurchase = activePaidPurchases.sort(
|
|
449
|
+
(a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
|
|
450
|
+
)[0] || null;
|
|
451
|
+
return {
|
|
452
|
+
loading,
|
|
453
|
+
customerRef: purchaseData.customerRef || internalCustomerRef,
|
|
454
|
+
email: purchaseData.email,
|
|
455
|
+
name: purchaseData.name,
|
|
456
|
+
purchases: purchaseData.purchases,
|
|
457
|
+
hasPlan: (planName) => {
|
|
458
|
+
return purchaseData.purchases.some(
|
|
459
|
+
(p) => p.planName.toLowerCase() === planName.toLowerCase() && p.status === "active"
|
|
460
|
+
);
|
|
461
|
+
},
|
|
462
|
+
activePurchase,
|
|
463
|
+
hasPaidPurchase: activePaidPurchases.length > 0,
|
|
464
|
+
activePaidPurchase
|
|
465
|
+
};
|
|
466
|
+
}, [loading, purchaseData, internalCustomerRef]);
|
|
467
|
+
const contextValue = (0, import_react.useMemo)(
|
|
468
|
+
() => ({
|
|
469
|
+
purchase,
|
|
470
|
+
refetchPurchase,
|
|
471
|
+
createPayment,
|
|
472
|
+
processPayment,
|
|
473
|
+
customerRef: purchaseData.customerRef || internalCustomerRef,
|
|
474
|
+
updateCustomerRef
|
|
475
|
+
}),
|
|
476
|
+
[
|
|
477
|
+
purchase,
|
|
478
|
+
refetchPurchase,
|
|
479
|
+
createPayment,
|
|
480
|
+
processPayment,
|
|
481
|
+
purchaseData.customerRef,
|
|
482
|
+
internalCustomerRef,
|
|
483
|
+
updateCustomerRef
|
|
484
|
+
]
|
|
485
|
+
);
|
|
486
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SolvaPayContext.Provider, { value: contextValue, children });
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
// src/PaymentForm.tsx
|
|
490
|
+
var import_react5 = require("react");
|
|
491
|
+
var import_react_stripe_js2 = require("@stripe/react-stripe-js");
|
|
492
|
+
|
|
493
|
+
// src/hooks/useCheckout.ts
|
|
494
|
+
var import_react3 = require("react");
|
|
495
|
+
var import_stripe_js = require("@stripe/stripe-js");
|
|
496
|
+
|
|
497
|
+
// src/hooks/useSolvaPay.ts
|
|
498
|
+
var import_react2 = require("react");
|
|
499
|
+
function useSolvaPay() {
|
|
500
|
+
const context = (0, import_react2.useContext)(SolvaPayContext);
|
|
501
|
+
if (!context) {
|
|
502
|
+
throw new Error(
|
|
503
|
+
"useSolvaPay must be used within a SolvaPayProvider. Wrap your component tree with <SolvaPayProvider> to use this hook."
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
return context;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// src/hooks/useCheckout.ts
|
|
510
|
+
var stripePromiseCache = /* @__PURE__ */ new Map();
|
|
511
|
+
function getStripeCacheKey(publishableKey, accountId) {
|
|
512
|
+
return accountId ? `${publishableKey}:${accountId}` : publishableKey;
|
|
513
|
+
}
|
|
514
|
+
function useCheckout(options) {
|
|
515
|
+
const { planRef, productRef } = options;
|
|
516
|
+
const { createPayment, customerRef, updateCustomerRef } = useSolvaPay();
|
|
517
|
+
const [loading, setLoading] = (0, import_react3.useState)(false);
|
|
518
|
+
const [error, setError] = (0, import_react3.useState)(
|
|
519
|
+
!planRef || typeof planRef !== "string" ? new Error("useCheckout: planRef parameter is required and must be a string") : null
|
|
520
|
+
);
|
|
521
|
+
const [stripePromise, setStripePromise] = (0, import_react3.useState)(null);
|
|
522
|
+
const [clientSecret, setClientSecret] = (0, import_react3.useState)(null);
|
|
523
|
+
const isStartingRef = (0, import_react3.useRef)(false);
|
|
524
|
+
const startCheckout = (0, import_react3.useCallback)(async () => {
|
|
525
|
+
if (isStartingRef.current || loading) {
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
if (!planRef || typeof planRef !== "string") {
|
|
529
|
+
setError(new Error("useCheckout: planRef parameter is required and must be a string"));
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
isStartingRef.current = true;
|
|
533
|
+
setLoading(true);
|
|
534
|
+
setError(null);
|
|
535
|
+
try {
|
|
536
|
+
const result = await createPayment({ planRef, productRef });
|
|
537
|
+
if (!result || typeof result !== "object") {
|
|
538
|
+
throw new Error("Invalid payment intent response from server");
|
|
539
|
+
}
|
|
540
|
+
if (!result.clientSecret || typeof result.clientSecret !== "string") {
|
|
541
|
+
throw new Error("Invalid client secret in payment intent response");
|
|
542
|
+
}
|
|
543
|
+
if (!result.publishableKey || typeof result.publishableKey !== "string") {
|
|
544
|
+
throw new Error("Invalid publishable key in payment intent response");
|
|
545
|
+
}
|
|
546
|
+
if (result.customerRef && result.customerRef !== customerRef && updateCustomerRef) {
|
|
547
|
+
updateCustomerRef(result.customerRef);
|
|
548
|
+
}
|
|
80
549
|
const stripeOptions = result.accountId ? { stripeAccount: result.accountId } : {};
|
|
81
|
-
const
|
|
550
|
+
const cacheKey = getStripeCacheKey(result.publishableKey, result.accountId);
|
|
551
|
+
let stripe = stripePromiseCache.get(cacheKey);
|
|
82
552
|
if (!stripe) {
|
|
83
|
-
|
|
553
|
+
stripe = (0, import_stripe_js.loadStripe)(result.publishableKey, stripeOptions);
|
|
554
|
+
stripePromiseCache.set(cacheKey, stripe);
|
|
84
555
|
}
|
|
85
556
|
setStripePromise(stripe);
|
|
86
557
|
setClientSecret(result.clientSecret);
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
} catch (error2) {
|
|
91
|
-
console.error("Failed to create payment:", error2);
|
|
92
|
-
let errorMessage = "Payment creation failed";
|
|
93
|
-
if (error2 instanceof Error) {
|
|
94
|
-
if (error2.message.includes("publishable key")) {
|
|
95
|
-
errorMessage = "Server configuration error: Missing Stripe publishable key";
|
|
96
|
-
} else if (error2.message.includes("client secret")) {
|
|
97
|
-
errorMessage = "Server error: Payment intent creation failed";
|
|
98
|
-
} else if (error2.message.includes("Failed to initialize Stripe")) {
|
|
99
|
-
errorMessage = "Stripe initialization failed. Please check your configuration.";
|
|
100
|
-
} else {
|
|
101
|
-
errorMessage = error2.message;
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
setError(errorMessage);
|
|
558
|
+
} catch (err) {
|
|
559
|
+
const error2 = err instanceof Error ? err : new Error("Failed to start checkout");
|
|
560
|
+
setError(error2);
|
|
105
561
|
} finally {
|
|
106
562
|
setLoading(false);
|
|
563
|
+
isStartingRef.current = false;
|
|
107
564
|
}
|
|
565
|
+
}, [planRef, productRef, createPayment, updateCustomerRef, loading]);
|
|
566
|
+
const reset = (0, import_react3.useCallback)(() => {
|
|
567
|
+
isStartingRef.current = false;
|
|
568
|
+
setLoading(false);
|
|
569
|
+
setError(null);
|
|
570
|
+
setStripePromise(null);
|
|
571
|
+
setClientSecret(null);
|
|
572
|
+
}, []);
|
|
573
|
+
return {
|
|
574
|
+
loading,
|
|
575
|
+
error,
|
|
576
|
+
stripePromise,
|
|
577
|
+
clientSecret,
|
|
578
|
+
startCheckout,
|
|
579
|
+
reset
|
|
108
580
|
};
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// src/hooks/usePurchase.ts
|
|
584
|
+
function usePurchase() {
|
|
585
|
+
const { purchase, refetchPurchase } = useSolvaPay();
|
|
586
|
+
return {
|
|
587
|
+
...purchase,
|
|
588
|
+
refetch: refetchPurchase
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// src/components/Spinner.tsx
|
|
593
|
+
var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
594
|
+
var Spinner = ({
|
|
595
|
+
className = "",
|
|
596
|
+
size = "md"
|
|
597
|
+
}) => {
|
|
598
|
+
const sizeClasses = {
|
|
599
|
+
sm: "h-4 w-4",
|
|
600
|
+
md: "h-5 w-5",
|
|
601
|
+
lg: "h-6 w-6"
|
|
602
|
+
};
|
|
603
|
+
return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
|
|
604
|
+
"svg",
|
|
605
|
+
{
|
|
606
|
+
className: `animate-spin ${sizeClasses[size]} ${className}`,
|
|
607
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
608
|
+
fill: "none",
|
|
609
|
+
viewBox: "0 0 24 24",
|
|
610
|
+
role: "status",
|
|
611
|
+
"aria-busy": "true",
|
|
612
|
+
children: [
|
|
613
|
+
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }),
|
|
614
|
+
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
|
|
615
|
+
"path",
|
|
616
|
+
{
|
|
617
|
+
className: "opacity-75",
|
|
618
|
+
fill: "currentColor",
|
|
619
|
+
d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
|
620
|
+
}
|
|
621
|
+
)
|
|
622
|
+
]
|
|
112
623
|
}
|
|
113
|
-
|
|
114
|
-
if (error) {
|
|
115
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: {
|
|
116
|
-
padding: "1rem",
|
|
117
|
-
backgroundColor: "#fed7d7",
|
|
118
|
-
color: "#742a2a",
|
|
119
|
-
borderRadius: "0.375rem",
|
|
120
|
-
marginBottom: "1rem"
|
|
121
|
-
}, children: [
|
|
122
|
-
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: "Payment Setup Error:" }),
|
|
123
|
-
" ",
|
|
124
|
-
error,
|
|
125
|
-
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
126
|
-
"button",
|
|
127
|
-
{
|
|
128
|
-
onClick: () => createPayment(amount),
|
|
129
|
-
style: {
|
|
130
|
-
marginLeft: "1rem",
|
|
131
|
-
padding: "0.5rem 1rem",
|
|
132
|
-
backgroundColor: "#742a2a",
|
|
133
|
-
color: "white",
|
|
134
|
-
border: "none",
|
|
135
|
-
borderRadius: "0.25rem",
|
|
136
|
-
cursor: "pointer"
|
|
137
|
-
},
|
|
138
|
-
children: "Retry"
|
|
139
|
-
}
|
|
140
|
-
)
|
|
141
|
-
] });
|
|
142
|
-
}
|
|
143
|
-
if (loading) {
|
|
144
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: {
|
|
145
|
-
padding: "1rem",
|
|
146
|
-
textAlign: "center",
|
|
147
|
-
color: "#4a5568"
|
|
148
|
-
}, children: "Setting up payment..." });
|
|
149
|
-
}
|
|
150
|
-
if (!stripePromise || !clientSecret) {
|
|
151
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { style: {
|
|
152
|
-
padding: "1rem",
|
|
153
|
-
textAlign: "center",
|
|
154
|
-
color: "#4a5568"
|
|
155
|
-
}, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
156
|
-
"button",
|
|
157
|
-
{
|
|
158
|
-
onClick: () => createPayment(amount),
|
|
159
|
-
style: {
|
|
160
|
-
padding: "0.75rem 1.5rem",
|
|
161
|
-
backgroundColor: "#3182ce",
|
|
162
|
-
color: "white",
|
|
163
|
-
border: "none",
|
|
164
|
-
borderRadius: "0.375rem",
|
|
165
|
-
cursor: "pointer",
|
|
166
|
-
fontSize: "1rem"
|
|
167
|
-
},
|
|
168
|
-
children: "Initialize Payment"
|
|
169
|
-
}
|
|
170
|
-
) });
|
|
171
|
-
}
|
|
172
|
-
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_stripe_js.Elements, { stripe: stripePromise, options: { clientSecret }, children });
|
|
624
|
+
);
|
|
173
625
|
};
|
|
174
626
|
|
|
175
|
-
// src/
|
|
176
|
-
var
|
|
177
|
-
var
|
|
178
|
-
|
|
179
|
-
|
|
627
|
+
// src/components/StripePaymentFormWrapper.tsx
|
|
628
|
+
var import_react4 = require("react");
|
|
629
|
+
var import_react_stripe_js = require("@stripe/react-stripe-js");
|
|
630
|
+
|
|
631
|
+
// src/hooks/useCustomer.ts
|
|
632
|
+
function useCustomer() {
|
|
633
|
+
const { purchase, customerRef } = useSolvaPay();
|
|
634
|
+
return {
|
|
635
|
+
customerRef: purchase.customerRef || customerRef,
|
|
636
|
+
email: purchase.email,
|
|
637
|
+
name: purchase.name,
|
|
638
|
+
loading: purchase.loading
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// src/components/StripePaymentFormWrapper.tsx
|
|
643
|
+
var import_jsx_runtime3 = require("react/jsx-runtime");
|
|
644
|
+
var StripePaymentFormWrapper = ({
|
|
180
645
|
onSuccess,
|
|
181
646
|
onError,
|
|
182
|
-
returnUrl,
|
|
647
|
+
returnUrl: _returnUrl,
|
|
183
648
|
submitButtonText = "Pay Now",
|
|
184
|
-
|
|
649
|
+
buttonClassName,
|
|
650
|
+
clientSecret
|
|
185
651
|
}) => {
|
|
186
|
-
const stripe = (0,
|
|
187
|
-
const elements = (0,
|
|
188
|
-
const
|
|
189
|
-
const [
|
|
652
|
+
const stripe = (0, import_react_stripe_js.useStripe)();
|
|
653
|
+
const elements = (0, import_react_stripe_js.useElements)();
|
|
654
|
+
const customer = useCustomer();
|
|
655
|
+
const [isProcessing, setIsProcessing] = (0, import_react4.useState)(false);
|
|
656
|
+
const [message, setMessage] = (0, import_react4.useState)(null);
|
|
657
|
+
const [cardComplete, setCardComplete] = (0, import_react4.useState)(false);
|
|
190
658
|
const handleSubmit = async (event) => {
|
|
191
659
|
event.preventDefault();
|
|
192
660
|
if (!stripe || !elements) {
|
|
661
|
+
const errorMessage = "Stripe is not available. Please refresh the page.";
|
|
662
|
+
setMessage(errorMessage);
|
|
663
|
+
if (onError) {
|
|
664
|
+
onError(new Error(errorMessage));
|
|
665
|
+
}
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
if (!clientSecret) {
|
|
669
|
+
const errorMessage = "Payment intent not available. Please refresh the page.";
|
|
670
|
+
setMessage(errorMessage);
|
|
671
|
+
if (onError) {
|
|
672
|
+
onError(new Error(errorMessage));
|
|
673
|
+
}
|
|
193
674
|
return;
|
|
194
675
|
}
|
|
195
676
|
setIsProcessing(true);
|
|
196
677
|
setMessage(null);
|
|
197
678
|
try {
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
679
|
+
const cardElement = elements.getElement(import_react_stripe_js.CardElement);
|
|
680
|
+
if (!cardElement) {
|
|
681
|
+
const errorMessage = "Card element not found";
|
|
682
|
+
setMessage(errorMessage);
|
|
683
|
+
setIsProcessing(false);
|
|
684
|
+
if (onError) {
|
|
685
|
+
onError(new Error(errorMessage));
|
|
686
|
+
}
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
const { error, paymentIntent } = await stripe.confirmCardPayment(clientSecret, {
|
|
690
|
+
payment_method: {
|
|
691
|
+
card: cardElement,
|
|
692
|
+
billing_details: {
|
|
693
|
+
email: customer.email,
|
|
694
|
+
name: customer.name
|
|
695
|
+
}
|
|
696
|
+
}
|
|
205
697
|
});
|
|
206
698
|
if (error) {
|
|
207
699
|
const errorMessage = error.message || "An unexpected error occurred.";
|
|
208
700
|
setMessage(errorMessage);
|
|
701
|
+
setIsProcessing(false);
|
|
209
702
|
if (onError) {
|
|
210
703
|
onError(new Error(errorMessage));
|
|
211
704
|
}
|
|
212
705
|
} else if (paymentIntent && paymentIntent.status === "succeeded") {
|
|
213
|
-
setMessage(
|
|
706
|
+
setMessage(null);
|
|
214
707
|
if (onSuccess) {
|
|
215
|
-
|
|
708
|
+
try {
|
|
709
|
+
await onSuccess(paymentIntent);
|
|
710
|
+
setMessage("Payment successful!");
|
|
711
|
+
} catch (err) {
|
|
712
|
+
const error2 = err instanceof Error ? err : new Error("Payment processing failed");
|
|
713
|
+
setMessage("Payment processing failed. Please try again or contact support.");
|
|
714
|
+
setIsProcessing(false);
|
|
715
|
+
if (onError) {
|
|
716
|
+
onError(error2);
|
|
717
|
+
}
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
} else {
|
|
721
|
+
setMessage("Payment successful!");
|
|
216
722
|
}
|
|
217
|
-
} else {
|
|
218
|
-
setMessage(
|
|
723
|
+
} else if (paymentIntent && paymentIntent.status === "requires_action") {
|
|
724
|
+
setMessage("Payment requires additional authentication. Please complete the verification.");
|
|
725
|
+
setIsProcessing(false);
|
|
726
|
+
} else if (paymentIntent) {
|
|
727
|
+
setMessage(`Payment status: ${paymentIntent.status || "processing"}`);
|
|
728
|
+
setIsProcessing(false);
|
|
219
729
|
}
|
|
220
730
|
} catch (err) {
|
|
221
731
|
const error = err instanceof Error ? err : new Error("Unknown error occurred");
|
|
@@ -227,46 +737,575 @@ var PaymentForm = ({
|
|
|
227
737
|
setIsProcessing(false);
|
|
228
738
|
}
|
|
229
739
|
};
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
740
|
+
const isSuccess = message?.includes("successful") ?? false;
|
|
741
|
+
const isReady = !!(stripe && elements);
|
|
742
|
+
const cardElementOptions = {
|
|
743
|
+
style: {
|
|
744
|
+
base: {
|
|
745
|
+
fontSize: "16px",
|
|
746
|
+
color: "#424770",
|
|
747
|
+
"::placeholder": {
|
|
748
|
+
color: "#aab7c4"
|
|
749
|
+
}
|
|
750
|
+
},
|
|
751
|
+
invalid: {
|
|
752
|
+
color: "#9e2146"
|
|
753
|
+
}
|
|
754
|
+
},
|
|
755
|
+
hidePostalCode: true
|
|
756
|
+
};
|
|
757
|
+
return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
|
|
758
|
+
isReady ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
|
|
759
|
+
import_react_stripe_js.CardElement,
|
|
760
|
+
{
|
|
761
|
+
options: cardElementOptions,
|
|
762
|
+
onChange: (e) => {
|
|
763
|
+
if (e.error) {
|
|
764
|
+
setMessage(e.error.message);
|
|
765
|
+
setCardComplete(false);
|
|
766
|
+
} else {
|
|
767
|
+
setMessage(null);
|
|
768
|
+
setCardComplete(e.complete);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
|
|
233
773
|
"div",
|
|
234
774
|
{
|
|
235
775
|
style: {
|
|
236
|
-
|
|
237
|
-
|
|
776
|
+
padding: "12px",
|
|
777
|
+
border: "1px solid #cbd5e1",
|
|
238
778
|
borderRadius: "0.375rem",
|
|
239
|
-
backgroundColor:
|
|
240
|
-
|
|
779
|
+
backgroundColor: "white",
|
|
780
|
+
display: "flex",
|
|
781
|
+
alignItems: "center",
|
|
782
|
+
justifyContent: "center",
|
|
783
|
+
minHeight: "40px"
|
|
241
784
|
},
|
|
242
|
-
children:
|
|
785
|
+
children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Spinner, { size: "sm" })
|
|
243
786
|
}
|
|
244
787
|
),
|
|
245
|
-
/* @__PURE__ */ (0,
|
|
788
|
+
message && !isSuccess && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { role: "alert", "aria-live": "assertive", "aria-atomic": "true", children: message }),
|
|
789
|
+
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
|
|
246
790
|
"button",
|
|
247
791
|
{
|
|
248
792
|
type: "submit",
|
|
249
|
-
disabled: !
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
fontSize: "1rem",
|
|
259
|
-
fontWeight: "500",
|
|
260
|
-
cursor: isProcessing || !stripe ? "not-allowed" : "pointer",
|
|
261
|
-
transition: "background-color 0.2s"
|
|
262
|
-
},
|
|
263
|
-
children: isProcessing ? "Processing..." : submitButtonText
|
|
793
|
+
disabled: !isReady || !cardComplete || isProcessing || !clientSecret,
|
|
794
|
+
className: buttonClassName,
|
|
795
|
+
"aria-busy": isProcessing,
|
|
796
|
+
"aria-disabled": !isReady || !cardComplete || isProcessing || !clientSecret,
|
|
797
|
+
onClick: handleSubmit,
|
|
798
|
+
children: isProcessing ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
|
|
799
|
+
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Spinner, { size: "sm" }),
|
|
800
|
+
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: "Processing..." })
|
|
801
|
+
] }) : submitButtonText
|
|
264
802
|
}
|
|
265
803
|
)
|
|
266
804
|
] });
|
|
267
805
|
};
|
|
806
|
+
|
|
807
|
+
// src/PaymentForm.tsx
|
|
808
|
+
var import_jsx_runtime4 = require("react/jsx-runtime");
|
|
809
|
+
var PaymentForm = ({
|
|
810
|
+
planRef,
|
|
811
|
+
productRef,
|
|
812
|
+
onSuccess,
|
|
813
|
+
onError,
|
|
814
|
+
returnUrl,
|
|
815
|
+
submitButtonText = "Pay Now",
|
|
816
|
+
className,
|
|
817
|
+
buttonClassName
|
|
818
|
+
}) => {
|
|
819
|
+
const validPlanRef = planRef && typeof planRef === "string" ? planRef : "";
|
|
820
|
+
const {
|
|
821
|
+
loading: checkoutLoading,
|
|
822
|
+
error: checkoutError,
|
|
823
|
+
clientSecret,
|
|
824
|
+
startCheckout,
|
|
825
|
+
stripePromise
|
|
826
|
+
} = useCheckout({ planRef: validPlanRef, productRef });
|
|
827
|
+
const { refetch } = usePurchase();
|
|
828
|
+
const { processPayment } = useSolvaPay();
|
|
829
|
+
const hasInitializedRef = (0, import_react5.useRef)(false);
|
|
830
|
+
(0, import_react5.useEffect)(() => {
|
|
831
|
+
if (!hasInitializedRef.current && validPlanRef && !checkoutLoading && !checkoutError && !clientSecret) {
|
|
832
|
+
hasInitializedRef.current = true;
|
|
833
|
+
startCheckout().catch(() => {
|
|
834
|
+
hasInitializedRef.current = false;
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
if (validPlanRef && clientSecret) {
|
|
838
|
+
hasInitializedRef.current = true;
|
|
839
|
+
}
|
|
840
|
+
}, [validPlanRef, checkoutLoading, checkoutError, clientSecret, startCheckout]);
|
|
841
|
+
const handleSuccess = (0, import_react5.useCallback)(
|
|
842
|
+
async (paymentIntent) => {
|
|
843
|
+
let processingTimeout = false;
|
|
844
|
+
let processingResult = null;
|
|
845
|
+
const paymentIntentAny = paymentIntent;
|
|
846
|
+
if (processPayment && productRef) {
|
|
847
|
+
try {
|
|
848
|
+
const result = await processPayment({
|
|
849
|
+
paymentIntentId: paymentIntentAny.id,
|
|
850
|
+
productRef,
|
|
851
|
+
planRef
|
|
852
|
+
});
|
|
853
|
+
processingResult = result;
|
|
854
|
+
const isTimeout = result?.status === "timeout";
|
|
855
|
+
processingTimeout = isTimeout;
|
|
856
|
+
if (isTimeout) {
|
|
857
|
+
for (let attempt = 1; attempt <= 5; attempt++) {
|
|
858
|
+
const delay = attempt * 1e3;
|
|
859
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
860
|
+
await refetch();
|
|
861
|
+
}
|
|
862
|
+
if (onSuccess) {
|
|
863
|
+
await onSuccess({
|
|
864
|
+
...paymentIntentAny,
|
|
865
|
+
_processingTimeout: processingTimeout,
|
|
866
|
+
_processingResult: processingResult
|
|
867
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
throw new Error("Payment processing timed out");
|
|
871
|
+
} else {
|
|
872
|
+
await refetch();
|
|
873
|
+
}
|
|
874
|
+
} catch (error) {
|
|
875
|
+
console.error("[PaymentForm] Failed to process payment:", error);
|
|
876
|
+
if (onSuccess) {
|
|
877
|
+
try {
|
|
878
|
+
await onSuccess({
|
|
879
|
+
...paymentIntentAny,
|
|
880
|
+
_processingError: error
|
|
881
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
882
|
+
});
|
|
883
|
+
} catch {
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
throw error;
|
|
887
|
+
}
|
|
888
|
+
} else {
|
|
889
|
+
await refetch();
|
|
890
|
+
}
|
|
891
|
+
if (onSuccess && !processingTimeout) {
|
|
892
|
+
await onSuccess({
|
|
893
|
+
...paymentIntentAny,
|
|
894
|
+
_processingTimeout: processingTimeout,
|
|
895
|
+
_processingResult: processingResult
|
|
896
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
897
|
+
});
|
|
898
|
+
}
|
|
899
|
+
},
|
|
900
|
+
[processPayment, productRef, planRef, refetch, onSuccess]
|
|
901
|
+
);
|
|
902
|
+
const handleError = (0, import_react5.useCallback)(
|
|
903
|
+
(err) => {
|
|
904
|
+
if (onError) {
|
|
905
|
+
onError(err);
|
|
906
|
+
}
|
|
907
|
+
},
|
|
908
|
+
[onError]
|
|
909
|
+
);
|
|
910
|
+
const finalReturnUrl = returnUrl || (typeof window !== "undefined" ? window.location.href : "/");
|
|
911
|
+
const isValidPlanRef = planRef && typeof planRef === "string";
|
|
912
|
+
const hasError = !!checkoutError;
|
|
913
|
+
const hasStripeData = !!(stripePromise && clientSecret);
|
|
914
|
+
const elementsOptions = (0, import_react5.useMemo)(() => {
|
|
915
|
+
if (!clientSecret) return void 0;
|
|
916
|
+
return { clientSecret };
|
|
917
|
+
}, [clientSecret]);
|
|
918
|
+
const [hasMountedElements, setHasMountedElements] = (0, import_react5.useState)(false);
|
|
919
|
+
(0, import_react5.useEffect)(() => {
|
|
920
|
+
if (hasStripeData) {
|
|
921
|
+
setHasMountedElements(true);
|
|
922
|
+
}
|
|
923
|
+
}, [hasStripeData]);
|
|
924
|
+
const shouldRenderElements = hasStripeData || hasMountedElements && stripePromise && clientSecret;
|
|
925
|
+
return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className, children: !isValidPlanRef ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: "PaymentForm: planRef is required and must be a string" }) : hasError ? /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { children: [
|
|
926
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: "Payment initialization failed" }),
|
|
927
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: checkoutError?.message || "Unknown error" })
|
|
928
|
+
] }) : shouldRenderElements && elementsOptions ? (
|
|
929
|
+
// Once we have Stripe data, always render Elements to maintain hook consistency
|
|
930
|
+
// This prevents hook count mismatches when transitioning between states
|
|
931
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
932
|
+
import_react_stripe_js2.Elements,
|
|
933
|
+
{
|
|
934
|
+
stripe: stripePromise,
|
|
935
|
+
options: elementsOptions,
|
|
936
|
+
children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
937
|
+
StripePaymentFormWrapper,
|
|
938
|
+
{
|
|
939
|
+
onSuccess: handleSuccess,
|
|
940
|
+
onError: handleError,
|
|
941
|
+
returnUrl: finalReturnUrl,
|
|
942
|
+
submitButtonText,
|
|
943
|
+
buttonClassName,
|
|
944
|
+
clientSecret
|
|
945
|
+
}
|
|
946
|
+
)
|
|
947
|
+
},
|
|
948
|
+
clientSecret
|
|
949
|
+
)
|
|
950
|
+
) : (
|
|
951
|
+
// Loading state before Stripe data is available
|
|
952
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { children: [
|
|
953
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
954
|
+
"div",
|
|
955
|
+
{
|
|
956
|
+
style: {
|
|
957
|
+
minHeight: "40px",
|
|
958
|
+
display: "flex",
|
|
959
|
+
alignItems: "center",
|
|
960
|
+
justifyContent: "center"
|
|
961
|
+
},
|
|
962
|
+
children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Spinner, { size: "md" })
|
|
963
|
+
}
|
|
964
|
+
),
|
|
965
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
966
|
+
"button",
|
|
967
|
+
{
|
|
968
|
+
type: "submit",
|
|
969
|
+
disabled: true,
|
|
970
|
+
className: buttonClassName,
|
|
971
|
+
"aria-busy": "false",
|
|
972
|
+
"aria-disabled": "true",
|
|
973
|
+
children: submitButtonText
|
|
974
|
+
}
|
|
975
|
+
)
|
|
976
|
+
] })
|
|
977
|
+
) });
|
|
978
|
+
};
|
|
979
|
+
|
|
980
|
+
// src/components/PlanBadge.tsx
|
|
981
|
+
var import_react6 = require("react");
|
|
982
|
+
var import_jsx_runtime5 = require("react/jsx-runtime");
|
|
983
|
+
var PlanBadge = ({
|
|
984
|
+
children,
|
|
985
|
+
as: Component = "div",
|
|
986
|
+
className
|
|
987
|
+
}) => {
|
|
988
|
+
const { purchases, loading, hasPaidPurchase, activePurchase } = usePurchase();
|
|
989
|
+
const [displayPlan, setDisplayPlan] = (0, import_react6.useState)(null);
|
|
990
|
+
const [hasLoadedOnce, setHasLoadedOnce] = (0, import_react6.useState)(false);
|
|
991
|
+
const lastPlanRef = (0, import_react6.useRef)(null);
|
|
992
|
+
const lastLoadingRef = (0, import_react6.useRef)(true);
|
|
993
|
+
const previousPurchasesRef = (0, import_react6.useRef)(purchases);
|
|
994
|
+
const currentPlanName = activePurchase?.planName || null;
|
|
995
|
+
const effectivePlanName = currentPlanName;
|
|
996
|
+
(0, import_react6.useEffect)(() => {
|
|
997
|
+
if (!loading && !hasLoadedOnce) {
|
|
998
|
+
setHasLoadedOnce(true);
|
|
999
|
+
}
|
|
1000
|
+
lastLoadingRef.current = loading;
|
|
1001
|
+
}, [loading, hasLoadedOnce]);
|
|
1002
|
+
(0, import_react6.useEffect)(() => {
|
|
1003
|
+
const previousPurchases = previousPurchasesRef.current;
|
|
1004
|
+
if (previousPurchases !== purchases) {
|
|
1005
|
+
if (loading) {
|
|
1006
|
+
setHasLoadedOnce(false);
|
|
1007
|
+
}
|
|
1008
|
+
setDisplayPlan(null);
|
|
1009
|
+
lastPlanRef.current = null;
|
|
1010
|
+
previousPurchasesRef.current = purchases;
|
|
1011
|
+
}
|
|
1012
|
+
}, [purchases, loading]);
|
|
1013
|
+
(0, import_react6.useEffect)(() => {
|
|
1014
|
+
const currentPlan = effectivePlanName;
|
|
1015
|
+
const previousPlan = lastPlanRef.current;
|
|
1016
|
+
if (currentPlan !== previousPlan) {
|
|
1017
|
+
if (currentPlan !== null) {
|
|
1018
|
+
lastPlanRef.current = currentPlan;
|
|
1019
|
+
setDisplayPlan(currentPlan);
|
|
1020
|
+
} else {
|
|
1021
|
+
lastPlanRef.current = null;
|
|
1022
|
+
setDisplayPlan(null);
|
|
1023
|
+
}
|
|
1024
|
+
} else if (currentPlan !== null && displayPlan === null) {
|
|
1025
|
+
setDisplayPlan(currentPlan);
|
|
1026
|
+
}
|
|
1027
|
+
}, [effectivePlanName, displayPlan]);
|
|
1028
|
+
const shouldShow = effectivePlanName !== null && hasLoadedOnce;
|
|
1029
|
+
const planToDisplay = displayPlan ?? effectivePlanName;
|
|
1030
|
+
if (children) {
|
|
1031
|
+
return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_jsx_runtime5.Fragment, { children: children({ purchases, loading, displayPlan: planToDisplay, shouldShow }) });
|
|
1032
|
+
}
|
|
1033
|
+
if (!shouldShow) {
|
|
1034
|
+
return null;
|
|
1035
|
+
}
|
|
1036
|
+
const computedClassName = typeof className === "function" ? className({ purchases }) : className;
|
|
1037
|
+
return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
|
|
1038
|
+
Component,
|
|
1039
|
+
{
|
|
1040
|
+
className: computedClassName,
|
|
1041
|
+
"data-loading": loading,
|
|
1042
|
+
"data-has-purchase": !!activePurchase,
|
|
1043
|
+
"data-has-paid-purchase": hasPaidPurchase,
|
|
1044
|
+
role: "status",
|
|
1045
|
+
"aria-live": "polite",
|
|
1046
|
+
"aria-busy": loading,
|
|
1047
|
+
"aria-label": `Current plan: ${planToDisplay}`,
|
|
1048
|
+
children: planToDisplay
|
|
1049
|
+
}
|
|
1050
|
+
);
|
|
1051
|
+
};
|
|
1052
|
+
|
|
1053
|
+
// src/components/PurchaseGate.tsx
|
|
1054
|
+
var import_jsx_runtime6 = require("react/jsx-runtime");
|
|
1055
|
+
var PurchaseGate = ({ requirePlan, requireProduct, children }) => {
|
|
1056
|
+
const { purchases, loading, hasPlan } = usePurchase();
|
|
1057
|
+
const hasAccess = requirePlan ? hasPlan(requirePlan) : requireProduct ? purchases.some((p) => p.status === "active" && (p.productName === requireProduct || p.productReference === requireProduct)) : purchases.some((p) => p.status === "active");
|
|
1058
|
+
return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: children({
|
|
1059
|
+
hasAccess,
|
|
1060
|
+
purchases,
|
|
1061
|
+
loading
|
|
1062
|
+
}) });
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
// src/components/PlanSelector.tsx
|
|
1066
|
+
var import_react8 = require("react");
|
|
1067
|
+
|
|
1068
|
+
// src/hooks/usePlans.ts
|
|
1069
|
+
var import_react7 = require("react");
|
|
1070
|
+
var plansCache = /* @__PURE__ */ new Map();
|
|
1071
|
+
var CACHE_DURATION2 = 5 * 60 * 1e3;
|
|
1072
|
+
function usePlans(options) {
|
|
1073
|
+
const { fetcher, productRef, filter, sortBy, autoSelectFirstPaid = false } = options;
|
|
1074
|
+
const [plans, setPlans] = (0, import_react7.useState)([]);
|
|
1075
|
+
const [loading, setLoading] = (0, import_react7.useState)(true);
|
|
1076
|
+
const [error, setError] = (0, import_react7.useState)(null);
|
|
1077
|
+
const [selectedPlanIndex, setSelectedPlanIndex] = (0, import_react7.useState)(0);
|
|
1078
|
+
const fetcherRef = (0, import_react7.useRef)(fetcher);
|
|
1079
|
+
const filterRef = (0, import_react7.useRef)(filter);
|
|
1080
|
+
const sortByRef = (0, import_react7.useRef)(sortBy);
|
|
1081
|
+
const autoSelectFirstPaidRef = (0, import_react7.useRef)(autoSelectFirstPaid);
|
|
1082
|
+
(0, import_react7.useEffect)(() => {
|
|
1083
|
+
fetcherRef.current = fetcher;
|
|
1084
|
+
}, [fetcher]);
|
|
1085
|
+
(0, import_react7.useEffect)(() => {
|
|
1086
|
+
filterRef.current = filter;
|
|
1087
|
+
}, [filter]);
|
|
1088
|
+
(0, import_react7.useEffect)(() => {
|
|
1089
|
+
sortByRef.current = sortBy;
|
|
1090
|
+
}, [sortBy]);
|
|
1091
|
+
(0, import_react7.useEffect)(() => {
|
|
1092
|
+
autoSelectFirstPaidRef.current = autoSelectFirstPaid;
|
|
1093
|
+
}, [autoSelectFirstPaid]);
|
|
1094
|
+
const fetchPlans = (0, import_react7.useCallback)(
|
|
1095
|
+
async (force = false) => {
|
|
1096
|
+
if (!productRef) {
|
|
1097
|
+
setError(new Error("Product reference not configured"));
|
|
1098
|
+
setLoading(false);
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
const cached = plansCache.get(productRef);
|
|
1102
|
+
const now = Date.now();
|
|
1103
|
+
if (!force && cached && now - cached.timestamp < CACHE_DURATION2) {
|
|
1104
|
+
const cachedPlans = cached.plans;
|
|
1105
|
+
let processedPlans = filterRef.current ? cachedPlans.filter(filterRef.current) : cachedPlans;
|
|
1106
|
+
if (sortByRef.current) {
|
|
1107
|
+
processedPlans = [...processedPlans].sort(sortByRef.current);
|
|
1108
|
+
}
|
|
1109
|
+
setPlans(processedPlans);
|
|
1110
|
+
setLoading(false);
|
|
1111
|
+
setError(null);
|
|
1112
|
+
if (autoSelectFirstPaidRef.current && processedPlans.length > 0) {
|
|
1113
|
+
const firstPaidIndex = processedPlans.findIndex((plan) => plan.price && plan.price > 0);
|
|
1114
|
+
setSelectedPlanIndex(firstPaidIndex >= 0 ? firstPaidIndex : 0);
|
|
1115
|
+
}
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
if (cached?.promise) {
|
|
1119
|
+
try {
|
|
1120
|
+
setLoading(true);
|
|
1121
|
+
const fetchedPlans = await cached.promise;
|
|
1122
|
+
let processedPlans = filterRef.current ? fetchedPlans.filter(filterRef.current) : fetchedPlans;
|
|
1123
|
+
if (sortByRef.current) {
|
|
1124
|
+
processedPlans = [...processedPlans].sort(sortByRef.current);
|
|
1125
|
+
}
|
|
1126
|
+
setPlans(processedPlans);
|
|
1127
|
+
setError(null);
|
|
1128
|
+
if (autoSelectFirstPaidRef.current && processedPlans.length > 0) {
|
|
1129
|
+
const firstPaidIndex = processedPlans.findIndex((plan) => plan.price && plan.price > 0);
|
|
1130
|
+
setSelectedPlanIndex(firstPaidIndex >= 0 ? firstPaidIndex : 0);
|
|
1131
|
+
}
|
|
1132
|
+
} catch (err) {
|
|
1133
|
+
setError(err instanceof Error ? err : new Error("Failed to load plans"));
|
|
1134
|
+
} finally {
|
|
1135
|
+
setLoading(false);
|
|
1136
|
+
}
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
try {
|
|
1140
|
+
setLoading(true);
|
|
1141
|
+
setError(null);
|
|
1142
|
+
const fetchPromise = fetcherRef.current(productRef);
|
|
1143
|
+
plansCache.set(productRef, {
|
|
1144
|
+
plans: [],
|
|
1145
|
+
timestamp: now,
|
|
1146
|
+
promise: fetchPromise
|
|
1147
|
+
});
|
|
1148
|
+
const fetchedPlans = await fetchPromise;
|
|
1149
|
+
plansCache.set(productRef, {
|
|
1150
|
+
plans: fetchedPlans,
|
|
1151
|
+
timestamp: now,
|
|
1152
|
+
promise: null
|
|
1153
|
+
});
|
|
1154
|
+
let processedPlans = filterRef.current ? fetchedPlans.filter(filterRef.current) : fetchedPlans;
|
|
1155
|
+
if (sortByRef.current) {
|
|
1156
|
+
processedPlans = [...processedPlans].sort(sortByRef.current);
|
|
1157
|
+
}
|
|
1158
|
+
setPlans(processedPlans);
|
|
1159
|
+
if (autoSelectFirstPaidRef.current && processedPlans.length > 0) {
|
|
1160
|
+
const firstPaidIndex = processedPlans.findIndex((plan) => plan.price && plan.price > 0);
|
|
1161
|
+
setSelectedPlanIndex(firstPaidIndex >= 0 ? firstPaidIndex : 0);
|
|
1162
|
+
}
|
|
1163
|
+
} catch (err) {
|
|
1164
|
+
plansCache.delete(productRef);
|
|
1165
|
+
setError(err instanceof Error ? err : new Error("Failed to load plans"));
|
|
1166
|
+
} finally {
|
|
1167
|
+
setLoading(false);
|
|
1168
|
+
}
|
|
1169
|
+
},
|
|
1170
|
+
[productRef]
|
|
1171
|
+
);
|
|
1172
|
+
(0, import_react7.useEffect)(() => {
|
|
1173
|
+
fetchPlans();
|
|
1174
|
+
}, [fetchPlans]);
|
|
1175
|
+
const selectedPlan = (0, import_react7.useMemo)(() => {
|
|
1176
|
+
return plans[selectedPlanIndex] || null;
|
|
1177
|
+
}, [plans, selectedPlanIndex]);
|
|
1178
|
+
const selectPlan = (0, import_react7.useCallback)(
|
|
1179
|
+
(planRef) => {
|
|
1180
|
+
const index = plans.findIndex((p) => p.reference === planRef);
|
|
1181
|
+
if (index >= 0) {
|
|
1182
|
+
setSelectedPlanIndex(index);
|
|
1183
|
+
}
|
|
1184
|
+
},
|
|
1185
|
+
[plans]
|
|
1186
|
+
);
|
|
1187
|
+
return {
|
|
1188
|
+
plans,
|
|
1189
|
+
loading,
|
|
1190
|
+
error,
|
|
1191
|
+
selectedPlanIndex,
|
|
1192
|
+
selectedPlan,
|
|
1193
|
+
setSelectedPlanIndex,
|
|
1194
|
+
selectPlan,
|
|
1195
|
+
refetch: () => fetchPlans(true)
|
|
1196
|
+
// Force refetch
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
// src/components/PlanSelector.tsx
|
|
1201
|
+
var import_jsx_runtime7 = require("react/jsx-runtime");
|
|
1202
|
+
var PlanSelector = ({
|
|
1203
|
+
productRef,
|
|
1204
|
+
fetcher,
|
|
1205
|
+
filter,
|
|
1206
|
+
sortBy,
|
|
1207
|
+
autoSelectFirstPaid,
|
|
1208
|
+
children
|
|
1209
|
+
}) => {
|
|
1210
|
+
const { purchases } = usePurchase();
|
|
1211
|
+
const plansHook = usePlans({
|
|
1212
|
+
productRef,
|
|
1213
|
+
fetcher,
|
|
1214
|
+
filter,
|
|
1215
|
+
sortBy,
|
|
1216
|
+
autoSelectFirstPaid
|
|
1217
|
+
});
|
|
1218
|
+
const { plans } = plansHook;
|
|
1219
|
+
const isPaidPlan = (0, import_react8.useCallback)(
|
|
1220
|
+
(planName) => {
|
|
1221
|
+
const plan = plans.find((p) => p.name === planName);
|
|
1222
|
+
return plan ? (plan.price ?? 0) > 0 && !plan.isFreeTier : true;
|
|
1223
|
+
},
|
|
1224
|
+
[plans]
|
|
1225
|
+
);
|
|
1226
|
+
const activePurchase = (0, import_react8.useMemo)(() => {
|
|
1227
|
+
const activePurchases = purchases.filter((p) => p.status === "active");
|
|
1228
|
+
return activePurchases.sort(
|
|
1229
|
+
(a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
|
|
1230
|
+
)[0] || null;
|
|
1231
|
+
}, [purchases]);
|
|
1232
|
+
const isCurrentPlan = (0, import_react8.useCallback)(
|
|
1233
|
+
(planName) => {
|
|
1234
|
+
return activePurchase?.planName === planName;
|
|
1235
|
+
},
|
|
1236
|
+
[activePurchase]
|
|
1237
|
+
);
|
|
1238
|
+
return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_jsx_runtime7.Fragment, { children: children({
|
|
1239
|
+
...plansHook,
|
|
1240
|
+
purchases,
|
|
1241
|
+
isPaidPlan,
|
|
1242
|
+
isCurrentPlan
|
|
1243
|
+
}) });
|
|
1244
|
+
};
|
|
1245
|
+
|
|
1246
|
+
// src/hooks/usePurchaseStatus.ts
|
|
1247
|
+
var import_react9 = require("react");
|
|
1248
|
+
function usePurchaseStatus() {
|
|
1249
|
+
const { purchases } = usePurchase();
|
|
1250
|
+
const isPaidPurchase2 = (0, import_react9.useCallback)((p) => {
|
|
1251
|
+
return (p.amount ?? 0) > 0;
|
|
1252
|
+
}, []);
|
|
1253
|
+
const purchaseData = (0, import_react9.useMemo)(() => {
|
|
1254
|
+
const cancelledPaidPurchases = purchases.filter((p) => {
|
|
1255
|
+
return p.status === "active" && p.cancelledAt && isPaidPurchase2(p);
|
|
1256
|
+
});
|
|
1257
|
+
const cancelledPurchase = cancelledPaidPurchases.sort(
|
|
1258
|
+
(a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()
|
|
1259
|
+
)[0] || null;
|
|
1260
|
+
const shouldShowCancelledNotice = !!cancelledPurchase;
|
|
1261
|
+
return {
|
|
1262
|
+
cancelledPurchase,
|
|
1263
|
+
shouldShowCancelledNotice
|
|
1264
|
+
};
|
|
1265
|
+
}, [purchases, isPaidPurchase2]);
|
|
1266
|
+
const formatDate = (0, import_react9.useCallback)((dateString) => {
|
|
1267
|
+
if (!dateString) return null;
|
|
1268
|
+
return new Date(dateString).toLocaleDateString("en-US", {
|
|
1269
|
+
year: "numeric",
|
|
1270
|
+
month: "long",
|
|
1271
|
+
day: "numeric"
|
|
1272
|
+
});
|
|
1273
|
+
}, []);
|
|
1274
|
+
const getDaysUntilExpiration = (0, import_react9.useCallback)((endDate) => {
|
|
1275
|
+
if (!endDate) return null;
|
|
1276
|
+
const now = /* @__PURE__ */ new Date();
|
|
1277
|
+
const expiration = new Date(endDate);
|
|
1278
|
+
const diffTime = expiration.getTime() - now.getTime();
|
|
1279
|
+
const diffDays = Math.ceil(diffTime / (1e3 * 60 * 60 * 24));
|
|
1280
|
+
return diffDays > 0 ? diffDays : 0;
|
|
1281
|
+
}, []);
|
|
1282
|
+
return {
|
|
1283
|
+
cancelledPurchase: purchaseData.cancelledPurchase,
|
|
1284
|
+
shouldShowCancelledNotice: purchaseData.shouldShowCancelledNotice,
|
|
1285
|
+
formatDate,
|
|
1286
|
+
getDaysUntilExpiration
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
268
1289
|
// Annotate the CommonJS export names for ESM import in node:
|
|
269
1290
|
0 && (module.exports = {
|
|
270
1291
|
PaymentForm,
|
|
271
|
-
|
|
1292
|
+
PlanBadge,
|
|
1293
|
+
PlanSelector,
|
|
1294
|
+
PurchaseGate,
|
|
1295
|
+
SolvaPayProvider,
|
|
1296
|
+
Spinner,
|
|
1297
|
+
StripePaymentFormWrapper,
|
|
1298
|
+
defaultAuthAdapter,
|
|
1299
|
+
filterPurchases,
|
|
1300
|
+
getActivePurchases,
|
|
1301
|
+
getCancelledPurchasesWithEndDate,
|
|
1302
|
+
getMostRecentPurchase,
|
|
1303
|
+
getPrimaryPurchase,
|
|
1304
|
+
isPaidPurchase,
|
|
1305
|
+
useCheckout,
|
|
1306
|
+
useCustomer,
|
|
1307
|
+
usePlans,
|
|
1308
|
+
usePurchase,
|
|
1309
|
+
usePurchaseStatus,
|
|
1310
|
+
useSolvaPay
|
|
272
1311
|
});
|