@tagadapay/plugin-sdk 2.8.7 → 2.8.9
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/react/config/environment.d.ts +1 -22
- package/dist/react/config/environment.js +1 -132
- package/dist/react/utils/deviceInfo.d.ts +1 -39
- package/dist/react/utils/deviceInfo.js +1 -163
- package/dist/react/utils/jwtDecoder.d.ts +1 -14
- package/dist/react/utils/jwtDecoder.js +1 -86
- package/dist/react/utils/tokenStorage.d.ts +1 -16
- package/dist/react/utils/tokenStorage.js +1 -53
- package/dist/v2/core/client.d.ts +92 -0
- package/dist/v2/core/client.js +386 -0
- package/dist/v2/core/config/environment.d.ts +22 -0
- package/dist/v2/core/config/environment.js +140 -0
- package/dist/v2/core/pathRemapping.js +61 -3
- package/dist/v2/core/resources/apiClient.d.ts +8 -0
- package/dist/v2/core/resources/apiClient.js +30 -9
- package/dist/v2/core/resources/funnel.d.ts +253 -16
- package/dist/v2/core/resources/payments.d.ts +23 -0
- package/dist/v2/core/types.d.ts +271 -0
- package/dist/v2/core/types.js +4 -0
- package/dist/v2/core/utils/deviceInfo.d.ts +39 -0
- package/dist/v2/core/utils/deviceInfo.js +162 -0
- package/dist/v2/core/utils/eventDispatcher.d.ts +10 -0
- package/dist/v2/core/utils/eventDispatcher.js +24 -0
- package/dist/v2/core/utils/jwtDecoder.d.ts +14 -0
- package/dist/v2/core/utils/jwtDecoder.js +85 -0
- package/dist/v2/core/utils/pluginConfig.js +6 -0
- package/dist/v2/core/utils/tokenStorage.d.ts +19 -0
- package/dist/v2/core/utils/tokenStorage.js +52 -0
- package/dist/v2/index.d.ts +2 -1
- package/dist/v2/index.js +1 -1
- package/dist/v2/react/components/DebugDrawer.js +90 -1
- package/dist/v2/react/hooks/__examples__/FunnelContextExample.d.ts +12 -0
- package/dist/v2/react/hooks/__examples__/FunnelContextExample.js +54 -0
- package/dist/v2/react/hooks/useFunnel.d.ts +2 -2
- package/dist/v2/react/hooks/useFunnel.js +209 -32
- package/dist/v2/react/hooks/useGoogleAutocomplete.js +26 -18
- package/dist/v2/react/hooks/useISOData.js +4 -2
- package/dist/v2/react/hooks/useOffersQuery.d.ts +24 -29
- package/dist/v2/react/hooks/useOffersQuery.js +164 -204
- package/dist/v2/react/hooks/usePaymentQuery.js +99 -6
- package/dist/v2/react/providers/TagadaProvider.d.ts +8 -21
- package/dist/v2/react/providers/TagadaProvider.js +79 -673
- package/package.json +1 -1
|
@@ -15,6 +15,7 @@ export function useGoogleAutocomplete(options) {
|
|
|
15
15
|
const autocompleteServiceRef = useRef(null);
|
|
16
16
|
const placesServiceRef = useRef(null);
|
|
17
17
|
const scriptLoadedRef = useRef(false);
|
|
18
|
+
const debounceTimeoutRef = useRef(null);
|
|
18
19
|
// Inject Google Maps script
|
|
19
20
|
useEffect(() => {
|
|
20
21
|
if (!apiKey) {
|
|
@@ -97,25 +98,32 @@ export function useGoogleAutocomplete(options) {
|
|
|
97
98
|
setPredictions([]);
|
|
98
99
|
return;
|
|
99
100
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
101
|
+
// Clear existing timeout
|
|
102
|
+
if (debounceTimeoutRef.current) {
|
|
103
|
+
clearTimeout(debounceTimeoutRef.current);
|
|
104
|
+
}
|
|
105
|
+
// Set new timeout
|
|
106
|
+
debounceTimeoutRef.current = setTimeout(() => {
|
|
107
|
+
setIsLoading(true);
|
|
108
|
+
const request = {
|
|
109
|
+
input,
|
|
110
|
+
...(countryRestriction && {
|
|
111
|
+
componentRestrictions: { country: countryRestriction.toLowerCase() },
|
|
112
|
+
}),
|
|
113
|
+
};
|
|
114
|
+
autocompleteServiceRef.current.getPlacePredictions(request, (results, status) => {
|
|
115
|
+
setIsLoading(false);
|
|
116
|
+
if (status === window.google.maps.places.PlacesServiceStatus.OK && results) {
|
|
117
|
+
setPredictions(results);
|
|
116
118
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
+
else {
|
|
120
|
+
setPredictions([]);
|
|
121
|
+
if (status !== window.google.maps.places.PlacesServiceStatus.ZERO_RESULTS) {
|
|
122
|
+
// Prediction failed but not zero results
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
}, 300); // 300ms debounce
|
|
119
127
|
}, [initializeServices, isScriptLoaded]);
|
|
120
128
|
// Get detailed place information
|
|
121
129
|
const getPlaceDetails = useCallback((placeId) => {
|
|
@@ -25,8 +25,10 @@ export function useISOData(language = 'en', autoImport = true, disputeSetting =
|
|
|
25
25
|
}, [language, autoImport]);
|
|
26
26
|
const data = useMemo(() => {
|
|
27
27
|
try {
|
|
28
|
+
console.log('[SDK] Loading ISO data for language:', language, 'autoImport:', autoImport);
|
|
28
29
|
// Get countries from pre-built data with language support
|
|
29
30
|
const countriesArray = getCountries(language);
|
|
31
|
+
console.log('[SDK] Loaded countries count:', countriesArray.length);
|
|
30
32
|
// Transform to our expected format (Record<string, ISOCountry>)
|
|
31
33
|
const countries = {};
|
|
32
34
|
countriesArray.forEach((country) => {
|
|
@@ -85,8 +87,8 @@ export function useISOData(language = 'en', autoImport = true, disputeSetting =
|
|
|
85
87
|
registeredLanguages,
|
|
86
88
|
};
|
|
87
89
|
}
|
|
88
|
-
catch (
|
|
89
|
-
|
|
90
|
+
catch (error) {
|
|
91
|
+
console.error('[SDK] Error loading ISO data:', error);
|
|
90
92
|
return {
|
|
91
93
|
countries: {},
|
|
92
94
|
getRegions: () => [],
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* Offers Hook using TanStack Query
|
|
3
3
|
* Handles offers with automatic caching
|
|
4
4
|
*/
|
|
5
|
-
import { Offer } from '../../core/resources/offers';
|
|
6
|
-
import {
|
|
5
|
+
import { Offer, OfferSummary } from '../../core/resources/offers';
|
|
6
|
+
import { CurrencyOptions, OrderSummary } from '../../core/resources/postPurchases';
|
|
7
7
|
export interface UseOffersQueryOptions {
|
|
8
8
|
/**
|
|
9
9
|
* Array of offer IDs to fetch
|
|
@@ -18,32 +18,27 @@ export interface UseOffersQueryOptions {
|
|
|
18
18
|
* Return URL for checkout sessions
|
|
19
19
|
*/
|
|
20
20
|
returnUrl?: string;
|
|
21
|
+
/**
|
|
22
|
+
* Order ID to associate with the offers (required for payments)
|
|
23
|
+
*/
|
|
24
|
+
orderId?: string;
|
|
21
25
|
}
|
|
22
26
|
export interface UseOffersQueryResult {
|
|
23
27
|
offers: Offer[];
|
|
24
28
|
isLoading: boolean;
|
|
25
29
|
error: Error | null;
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
checkoutUrl: string;
|
|
31
|
-
}>;
|
|
30
|
+
/**
|
|
31
|
+
* Pay for an offer
|
|
32
|
+
* Initializes a checkout session and pays it
|
|
33
|
+
*/
|
|
32
34
|
payOffer: (offerId: string, orderId?: string) => Promise<void>;
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
getTotalSavings: () => number;
|
|
41
|
-
payWithCheckoutSession: (checkoutSessionId: string, orderId?: string) => Promise<void>;
|
|
42
|
-
initCheckoutSession: (offerId: string, orderId: string, customerId?: string) => Promise<{
|
|
43
|
-
checkoutSessionId: string;
|
|
44
|
-
}>;
|
|
45
|
-
getCheckoutSessionState: (offerId: string) => CheckoutSessionState | null;
|
|
46
|
-
initializeOfferCheckout: (offerId: string) => Promise<void>;
|
|
35
|
+
/**
|
|
36
|
+
* Preview an offer's price/summary
|
|
37
|
+
*/
|
|
38
|
+
preview: (offerId: string) => Promise<OrderSummary | OfferSummary | null>;
|
|
39
|
+
/**
|
|
40
|
+
* Get available variants for a product in an offer
|
|
41
|
+
*/
|
|
47
42
|
getAvailableVariants: (offerId: string, productId: string) => {
|
|
48
43
|
variantId: string;
|
|
49
44
|
variantName: string;
|
|
@@ -53,13 +48,13 @@ export interface UseOffersQueryResult {
|
|
|
53
48
|
priceId: string;
|
|
54
49
|
currencyOptions: CurrencyOptions;
|
|
55
50
|
}[];
|
|
56
|
-
|
|
57
|
-
|
|
51
|
+
/**
|
|
52
|
+
* Select a variant for a product in an offer
|
|
53
|
+
*/
|
|
54
|
+
selectVariant: (offerId: string, productId: string, variantId: string) => Promise<OrderSummary | null>;
|
|
55
|
+
/**
|
|
56
|
+
* Check if variants are loading for a product
|
|
57
|
+
*/
|
|
58
58
|
isLoadingVariants: (offerId: string, productId: string) => boolean;
|
|
59
|
-
isUpdatingOrderSummary: (offerId: string) => boolean;
|
|
60
|
-
confirmPurchase: (offerId: string, options?: {
|
|
61
|
-
draft?: boolean;
|
|
62
|
-
returnUrl?: string;
|
|
63
|
-
}) => Promise<void>;
|
|
64
59
|
}
|
|
65
60
|
export declare function useOffersQuery(options?: UseOffersQueryOptions): UseOffersQueryResult;
|
|
@@ -2,19 +2,23 @@
|
|
|
2
2
|
* Offers Hook using TanStack Query
|
|
3
3
|
* Handles offers with automatic caching
|
|
4
4
|
*/
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
6
|
+
import { useCallback, useMemo, useRef, useState } from 'react';
|
|
7
7
|
import { OffersResource } from '../../core/resources/offers';
|
|
8
8
|
import { useTagadaContext } from '../providers/TagadaProvider';
|
|
9
|
-
import { usePluginConfig } from './usePluginConfig';
|
|
10
9
|
import { getGlobalApiClient } from './useApiQuery';
|
|
10
|
+
import { usePluginConfig } from './usePluginConfig';
|
|
11
11
|
export function useOffersQuery(options = {}) {
|
|
12
|
-
const { offerIds = [], enabled = true, returnUrl } = options;
|
|
12
|
+
const { offerIds = [], enabled = true, returnUrl, orderId: defaultOrderId } = options;
|
|
13
13
|
const { storeId } = usePluginConfig();
|
|
14
14
|
const { isSessionInitialized, session } = useTagadaContext();
|
|
15
15
|
const _queryClient = useQueryClient();
|
|
16
16
|
// State for checkout sessions per offer (similar to postPurchases)
|
|
17
17
|
const [checkoutSessions, setCheckoutSessions] = useState({});
|
|
18
|
+
// Use ref to break dependency cycles in callbacks
|
|
19
|
+
const checkoutSessionsRef = useRef(checkoutSessions);
|
|
20
|
+
// Update ref on every render
|
|
21
|
+
checkoutSessionsRef.current = checkoutSessions;
|
|
18
22
|
// Create offers resource client
|
|
19
23
|
const offersResource = useMemo(() => {
|
|
20
24
|
try {
|
|
@@ -59,7 +63,9 @@ export function useOffersQuery(options = {}) {
|
|
|
59
63
|
isUpdatingSummary: false,
|
|
60
64
|
}
|
|
61
65
|
}));
|
|
66
|
+
return orderSummary;
|
|
62
67
|
}
|
|
68
|
+
return null;
|
|
63
69
|
}
|
|
64
70
|
catch (error) {
|
|
65
71
|
setCheckoutSessions(prev => ({
|
|
@@ -75,7 +81,7 @@ export function useOffersQuery(options = {}) {
|
|
|
75
81
|
// Create query key based on options
|
|
76
82
|
const queryKey = useMemo(() => ['offers', { storeId, offerIds }], [storeId, offerIds]);
|
|
77
83
|
// Use TanStack Query for fetching offers
|
|
78
|
-
const { data: offers = [], isLoading, error
|
|
84
|
+
const { data: offers = [], isLoading, error } = useQuery({
|
|
79
85
|
queryKey,
|
|
80
86
|
enabled: enabled && !!storeId && isSessionInitialized,
|
|
81
87
|
queryFn: async () => {
|
|
@@ -94,32 +100,7 @@ export function useOffersQuery(options = {}) {
|
|
|
94
100
|
staleTime: 5 * 60 * 1000, // 5 minutes
|
|
95
101
|
refetchOnWindowFocus: false,
|
|
96
102
|
});
|
|
97
|
-
|
|
98
|
-
const createCheckoutSessionMutation = useMutation({
|
|
99
|
-
mutationFn: async ({ offerId, returnUrl }) => {
|
|
100
|
-
return await offersResource.createCheckoutSession(offerId, returnUrl);
|
|
101
|
-
},
|
|
102
|
-
onError: (_error) => {
|
|
103
|
-
// Error handling removed
|
|
104
|
-
},
|
|
105
|
-
});
|
|
106
|
-
const payOfferMutation = useMutation({
|
|
107
|
-
mutationFn: async ({ offerId, orderId }) => {
|
|
108
|
-
return await offersResource.payOffer(offerId, orderId);
|
|
109
|
-
},
|
|
110
|
-
onError: (_error) => {
|
|
111
|
-
// Error handling removed
|
|
112
|
-
},
|
|
113
|
-
});
|
|
114
|
-
const transformToCheckoutMutation = useMutation({
|
|
115
|
-
mutationFn: async ({ offerId, returnUrl }) => {
|
|
116
|
-
return await offersResource.transformToCheckout(offerId, returnUrl);
|
|
117
|
-
},
|
|
118
|
-
onError: (_error) => {
|
|
119
|
-
// Error handling removed
|
|
120
|
-
},
|
|
121
|
-
});
|
|
122
|
-
const payWithCheckoutSessionMutation = useMutation({
|
|
103
|
+
const { mutateAsync: payWithCheckoutSessionAsync } = useMutation({
|
|
123
104
|
mutationFn: async ({ checkoutSessionId, orderId }) => {
|
|
124
105
|
return await offersResource.payWithCheckoutSession(checkoutSessionId, orderId);
|
|
125
106
|
},
|
|
@@ -127,7 +108,7 @@ export function useOffersQuery(options = {}) {
|
|
|
127
108
|
// Error handling removed
|
|
128
109
|
},
|
|
129
110
|
});
|
|
130
|
-
const
|
|
111
|
+
const { mutateAsync: initCheckoutSessionAsync } = useMutation({
|
|
131
112
|
mutationFn: async ({ offerId, orderId, customerId }) => {
|
|
132
113
|
return await offersResource.initCheckoutSession(offerId, orderId, customerId);
|
|
133
114
|
},
|
|
@@ -135,108 +116,125 @@ export function useOffersQuery(options = {}) {
|
|
|
135
116
|
// Error handling removed
|
|
136
117
|
},
|
|
137
118
|
});
|
|
138
|
-
// Helper functions (matching V1 useOffers exactly)
|
|
139
|
-
const getOffer = useCallback((offerId) => {
|
|
140
|
-
return offers.find((offer) => offer.id === offerId);
|
|
141
|
-
}, [offers]);
|
|
142
|
-
const getTotalValue = useCallback(() => {
|
|
143
|
-
return offers.reduce((total, offer) => {
|
|
144
|
-
const firstSummary = offer.summaries[0];
|
|
145
|
-
return total + (firstSummary?.totalAdjustedAmount || 0);
|
|
146
|
-
}, 0);
|
|
147
|
-
}, [offers]);
|
|
148
|
-
const getTotalSavings = useCallback(() => {
|
|
149
|
-
return offers.reduce((total, offer) => {
|
|
150
|
-
const firstSummary = offer.summaries[0];
|
|
151
|
-
return total + (firstSummary?.totalPromotionAmount || 0);
|
|
152
|
-
}, 0);
|
|
153
|
-
}, [offers]);
|
|
154
|
-
// Action functions
|
|
155
|
-
const createCheckoutSession = useCallback(async (offerId, options) => {
|
|
156
|
-
return await createCheckoutSessionMutation.mutateAsync({
|
|
157
|
-
offerId,
|
|
158
|
-
returnUrl: options?.returnUrl || returnUrl,
|
|
159
|
-
});
|
|
160
|
-
}, [createCheckoutSessionMutation, returnUrl]);
|
|
161
|
-
const payOffer = useCallback(async (offerId, orderId) => {
|
|
162
|
-
return await payOfferMutation.mutateAsync({ offerId, orderId });
|
|
163
|
-
}, [payOfferMutation]);
|
|
164
|
-
const transformToCheckout = useCallback(async (offerId, options) => {
|
|
165
|
-
return await transformToCheckoutMutation.mutateAsync({
|
|
166
|
-
offerId,
|
|
167
|
-
returnUrl: options?.returnUrl || returnUrl,
|
|
168
|
-
});
|
|
169
|
-
}, [transformToCheckoutMutation, returnUrl]);
|
|
170
119
|
const payWithCheckoutSession = useCallback(async (checkoutSessionId, orderId) => {
|
|
171
|
-
return await
|
|
172
|
-
}, [
|
|
120
|
+
return await payWithCheckoutSessionAsync({ checkoutSessionId, orderId });
|
|
121
|
+
}, [payWithCheckoutSessionAsync]);
|
|
173
122
|
const initCheckoutSession = useCallback(async (offerId, orderId, customerId) => {
|
|
174
123
|
// Use customerId from session context if not provided
|
|
175
124
|
const effectiveCustomerId = customerId || session?.customerId;
|
|
176
125
|
if (!effectiveCustomerId) {
|
|
177
126
|
throw new Error('Customer ID is required. Make sure the session is properly initialized.');
|
|
178
127
|
}
|
|
179
|
-
return await
|
|
128
|
+
return await initCheckoutSessionAsync({
|
|
180
129
|
offerId,
|
|
181
130
|
orderId,
|
|
182
131
|
customerId: effectiveCustomerId
|
|
183
132
|
});
|
|
184
|
-
}, [
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
}
|
|
194
|
-
//
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
//
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
133
|
+
}, [initCheckoutSessionAsync, session?.customerId]);
|
|
134
|
+
const payOffer = useCallback(async (offerId, orderId) => {
|
|
135
|
+
const effectiveOrderId = orderId || defaultOrderId;
|
|
136
|
+
const effectiveCustomerId = session?.customerId;
|
|
137
|
+
if (!effectiveOrderId) {
|
|
138
|
+
throw new Error('Order ID is required for payment. Please provide it in the hook options or the function call.');
|
|
139
|
+
}
|
|
140
|
+
if (!effectiveCustomerId) {
|
|
141
|
+
throw new Error('Customer ID is required. Make sure the session is properly initialized.');
|
|
142
|
+
}
|
|
143
|
+
// 1. Init session
|
|
144
|
+
const { checkoutSessionId } = await initCheckoutSession(offerId, effectiveOrderId, effectiveCustomerId);
|
|
145
|
+
// 2. Pay
|
|
146
|
+
await payWithCheckoutSession(checkoutSessionId, effectiveOrderId);
|
|
147
|
+
}, [initCheckoutSession, payWithCheckoutSession, defaultOrderId, session?.customerId]);
|
|
148
|
+
const preview = useCallback(async (offerId) => {
|
|
149
|
+
const effectiveOrderId = defaultOrderId;
|
|
150
|
+
const effectiveCustomerId = session?.customerId;
|
|
151
|
+
// Use ref to check current state without creating dependency
|
|
152
|
+
const currentSessions = checkoutSessionsRef.current;
|
|
153
|
+
// If we already have a summary in state, return it
|
|
154
|
+
if (currentSessions[offerId]?.orderSummary) {
|
|
155
|
+
return currentSessions[offerId].orderSummary;
|
|
156
|
+
}
|
|
157
|
+
// Prevent duplicate initialization if already has a session and is updating
|
|
158
|
+
if (currentSessions[offerId]?.checkoutSessionId && currentSessions[offerId]?.isUpdatingSummary) {
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
// If we don't have orderId, fallback to static summary from offer object
|
|
162
|
+
// as we can't initialize a checkout session properly without orderId (for upsells)
|
|
163
|
+
if (!effectiveOrderId || !effectiveCustomerId) {
|
|
164
|
+
const offer = offers.find(o => o.id === offerId);
|
|
165
|
+
return offer?.summaries?.[0] || null;
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
// If we already have a session ID, reuse it instead of creating a new one
|
|
169
|
+
let sessionId = currentSessions[offerId]?.checkoutSessionId;
|
|
170
|
+
if (!sessionId) {
|
|
171
|
+
const { checkoutSessionId } = await initCheckoutSession(offerId, effectiveOrderId, effectiveCustomerId);
|
|
172
|
+
sessionId = checkoutSessionId;
|
|
173
|
+
// Update state with session ID
|
|
174
|
+
setCheckoutSessions(prev => ({
|
|
175
|
+
...prev,
|
|
176
|
+
[offerId]: {
|
|
177
|
+
checkoutSessionId: sessionId,
|
|
178
|
+
orderSummary: null,
|
|
179
|
+
selectedVariants: {},
|
|
180
|
+
loadingVariants: {},
|
|
181
|
+
isUpdatingSummary: false,
|
|
182
|
+
}
|
|
183
|
+
}));
|
|
218
184
|
}
|
|
219
|
-
//
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
185
|
+
// Fetch and return summary
|
|
186
|
+
return await fetchOrderSummary(offerId, sessionId);
|
|
187
|
+
}
|
|
188
|
+
catch (e) {
|
|
189
|
+
console.error("Failed to preview offer", e);
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
}, [offers, defaultOrderId, session?.customerId, initCheckoutSession, fetchOrderSummary]); // Removed checkoutSessions dependency
|
|
193
|
+
const getAvailableVariants = useCallback((offerId, productId) => {
|
|
194
|
+
const sessionState = checkoutSessions[offerId]; // This hook needs to react to state changes
|
|
195
|
+
if (!sessionState?.orderSummary?.options?.[productId])
|
|
196
|
+
return [];
|
|
197
|
+
return sessionState.orderSummary.options[productId].map((variant) => ({
|
|
198
|
+
variantId: variant.id,
|
|
199
|
+
variantName: variant.name,
|
|
200
|
+
variantSku: variant.sku,
|
|
201
|
+
variantDefault: variant.default,
|
|
202
|
+
variantExternalId: variant.externalVariantId,
|
|
203
|
+
priceId: variant.prices[0]?.id,
|
|
204
|
+
currencyOptions: variant.prices[0]?.currencyOptions,
|
|
205
|
+
}));
|
|
206
|
+
}, [checkoutSessions]);
|
|
207
|
+
const isLoadingVariants = useCallback((offerId, productId) => {
|
|
208
|
+
return checkoutSessions[offerId]?.loadingVariants?.[productId] ?? false;
|
|
209
|
+
}, [checkoutSessions]);
|
|
210
|
+
const selectVariant = useCallback(async (offerId, productId, variantId) => {
|
|
211
|
+
// Use ref for initial check to avoid dependency but we might need latest state for logic
|
|
212
|
+
// Actually for actions it's better to use ref or just dependency if action is not called in useEffect
|
|
213
|
+
const currentSessions = checkoutSessionsRef.current;
|
|
214
|
+
const sessionState = currentSessions[offerId];
|
|
215
|
+
if (!sessionState?.checkoutSessionId || !sessionState.orderSummary) {
|
|
216
|
+
throw new Error('Checkout session not initialized for this offer');
|
|
217
|
+
}
|
|
218
|
+
const sessionId = sessionState.checkoutSessionId;
|
|
219
|
+
// Set loading state for this specific variant
|
|
220
|
+
setCheckoutSessions(prev => ({
|
|
221
|
+
...prev,
|
|
222
|
+
[offerId]: {
|
|
223
|
+
...prev[offerId],
|
|
224
|
+
loadingVariants: {
|
|
225
|
+
...prev[offerId].loadingVariants,
|
|
226
|
+
[productId]: true,
|
|
230
227
|
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
const sessionState =
|
|
237
|
-
if (!sessionState?.orderSummary?.options?.[productId])
|
|
238
|
-
|
|
239
|
-
|
|
228
|
+
}
|
|
229
|
+
}));
|
|
230
|
+
try {
|
|
231
|
+
// We need to use the state from the ref to ensure we have the latest data without causing infinite loops
|
|
232
|
+
// if selectVariant was in a dependency array that triggered effects
|
|
233
|
+
const sessionState = checkoutSessionsRef.current[offerId];
|
|
234
|
+
if (!sessionState?.orderSummary?.options?.[productId]) {
|
|
235
|
+
throw new Error('No variants available for this product');
|
|
236
|
+
}
|
|
237
|
+
const availableVariants = sessionState.orderSummary.options[productId].map((variant) => ({
|
|
240
238
|
variantId: variant.id,
|
|
241
239
|
variantName: variant.name,
|
|
242
240
|
variantSku: variant.sku,
|
|
@@ -245,98 +243,60 @@ export function useOffersQuery(options = {}) {
|
|
|
245
243
|
priceId: variant.prices[0]?.id,
|
|
246
244
|
currencyOptions: variant.prices[0]?.currencyOptions,
|
|
247
245
|
}));
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
246
|
+
const selectedVariant = availableVariants.find(v => v.variantId === variantId);
|
|
247
|
+
if (!selectedVariant) {
|
|
248
|
+
throw new Error('Selected variant not found');
|
|
249
|
+
}
|
|
250
|
+
// Find the current item to get its quantity
|
|
251
|
+
const currentItem = sessionState.orderSummary.items.find(item => item.productId === productId);
|
|
252
|
+
if (!currentItem) {
|
|
253
|
+
throw new Error('Current item not found');
|
|
253
254
|
}
|
|
254
|
-
|
|
255
|
-
|
|
255
|
+
// Update selected variants state
|
|
256
|
+
setCheckoutSessions(prev => ({
|
|
257
|
+
...prev,
|
|
258
|
+
[offerId]: {
|
|
259
|
+
...prev[offerId],
|
|
260
|
+
selectedVariants: {
|
|
261
|
+
...prev[offerId].selectedVariants,
|
|
262
|
+
[productId]: variantId,
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}));
|
|
266
|
+
// Update line items on the server
|
|
267
|
+
await offersResource.updateLineItems(sessionId, [
|
|
268
|
+
{
|
|
269
|
+
variantId: selectedVariant.variantId,
|
|
270
|
+
quantity: currentItem.quantity,
|
|
271
|
+
},
|
|
272
|
+
]);
|
|
273
|
+
// Refetch order summary after successful line item update
|
|
274
|
+
return await fetchOrderSummary(offerId, sessionId);
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
// Clear loading state for this specific variant
|
|
256
278
|
setCheckoutSessions(prev => ({
|
|
257
279
|
...prev,
|
|
258
280
|
[offerId]: {
|
|
259
281
|
...prev[offerId],
|
|
260
282
|
loadingVariants: {
|
|
261
283
|
...prev[offerId].loadingVariants,
|
|
262
|
-
[productId]:
|
|
284
|
+
[productId]: false,
|
|
263
285
|
}
|
|
264
286
|
}
|
|
265
287
|
}));
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
}));
|
|
280
|
-
const selectedVariant = availableVariants.find(v => v.variantId === variantId);
|
|
281
|
-
if (!selectedVariant) {
|
|
282
|
-
throw new Error('Selected variant not found');
|
|
283
|
-
}
|
|
284
|
-
// Find the current item to get its quantity
|
|
285
|
-
const currentItem = sessionState.orderSummary.items.find(item => item.productId === productId);
|
|
286
|
-
if (!currentItem) {
|
|
287
|
-
throw new Error('Current item not found');
|
|
288
|
-
}
|
|
289
|
-
// Update selected variants state
|
|
290
|
-
setCheckoutSessions(prev => ({
|
|
291
|
-
...prev,
|
|
292
|
-
[offerId]: {
|
|
293
|
-
...prev[offerId],
|
|
294
|
-
selectedVariants: {
|
|
295
|
-
...prev[offerId].selectedVariants,
|
|
296
|
-
[productId]: variantId,
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
}));
|
|
300
|
-
// Update line items on the server
|
|
301
|
-
await offersResource.updateLineItems(sessionId, [
|
|
302
|
-
{
|
|
303
|
-
variantId: selectedVariant.variantId,
|
|
304
|
-
quantity: currentItem.quantity,
|
|
305
|
-
},
|
|
306
|
-
]);
|
|
307
|
-
// Refetch order summary after successful line item update
|
|
308
|
-
await fetchOrderSummary(offerId, sessionId);
|
|
309
|
-
}
|
|
310
|
-
finally {
|
|
311
|
-
// Clear loading state for this specific variant
|
|
312
|
-
setCheckoutSessions(prev => ({
|
|
313
|
-
...prev,
|
|
314
|
-
[offerId]: {
|
|
315
|
-
...prev[offerId],
|
|
316
|
-
loadingVariants: {
|
|
317
|
-
...prev[offerId].loadingVariants,
|
|
318
|
-
[productId]: false,
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
}));
|
|
322
|
-
}
|
|
323
|
-
},
|
|
324
|
-
getOrderSummary: (offerId) => {
|
|
325
|
-
return checkoutSessions[offerId]?.orderSummary ?? null;
|
|
326
|
-
},
|
|
327
|
-
isLoadingVariants: (offerId, productId) => {
|
|
328
|
-
return checkoutSessions[offerId]?.loadingVariants?.[productId] ?? false;
|
|
329
|
-
},
|
|
330
|
-
isUpdatingOrderSummary: (offerId) => {
|
|
331
|
-
return checkoutSessions[offerId]?.isUpdatingSummary || false;
|
|
332
|
-
},
|
|
333
|
-
confirmPurchase: async (offerId, _options) => {
|
|
334
|
-
const sessionState = checkoutSessions[offerId];
|
|
335
|
-
if (!sessionState?.checkoutSessionId) {
|
|
336
|
-
throw new Error('Checkout session not initialized for this offer');
|
|
337
|
-
}
|
|
338
|
-
// Use the enhanced payWithCheckoutSession with proper metadata
|
|
339
|
-
await offersResource.payWithCheckoutSession(sessionState.checkoutSessionId);
|
|
340
|
-
},
|
|
288
|
+
}
|
|
289
|
+
}, [offersResource, fetchOrderSummary]); // Removed checkoutSessions dependency
|
|
290
|
+
return {
|
|
291
|
+
// Query data
|
|
292
|
+
offers,
|
|
293
|
+
isLoading,
|
|
294
|
+
error,
|
|
295
|
+
// Actions
|
|
296
|
+
payOffer,
|
|
297
|
+
preview,
|
|
298
|
+
getAvailableVariants,
|
|
299
|
+
selectVariant,
|
|
300
|
+
isLoadingVariants,
|
|
341
301
|
};
|
|
342
302
|
}
|