-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathindex.tsx
More file actions
301 lines (270 loc) · 9.79 KB
/
Copy pathindex.tsx
File metadata and controls
301 lines (270 loc) · 9.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import page from '@automattic/calypso-router';
import { StripeHookProvider } from '@automattic/calypso-stripe';
import { CheckoutErrorBoundary } from '@automattic/composite-checkout';
import { createRequestCartProduct, useShoppingCart } from '@automattic/shopping-cart';
import debugFactory from 'debug';
import { useTranslate } from 'i18n-calypso';
import { useEffect, useState } from 'react';
import A4ALogo from 'calypso/a8c-for-agencies/components/a4a-logo';
import { A4A_MARKETPLACE_LINK } from 'calypso/a8c-for-agencies/components/sidebar-menu/lib/constants';
import { getStripeConfiguration } from 'calypso/lib/store-transactions';
import CalypsoShoppingCartProvider from 'calypso/my-sites/checkout/calypso-shopping-cart-provider';
import CheckoutMain from 'calypso/my-sites/checkout/src/components/checkout-main';
import usePrepareProductsForCart from 'calypso/my-sites/checkout/src/hooks/use-prepare-products-for-cart';
import { useDispatch, useSelector } from 'calypso/state';
import { getActiveAgency } from 'calypso/state/a8c-for-agencies/agency/selectors';
import { getCurrentUserLocale } from 'calypso/state/current-user/selectors';
import hasLoadedSites from 'calypso/state/selectors/has-loaded-sites';
import getSite from 'calypso/state/sites/selectors/get-site';
import { setSelectedSiteId } from 'calypso/state/ui/actions';
import ClientCheckoutError from './checkout-error';
import ClientCheckoutPlaceholder from './checkout-placeholder';
import getPurchasedWPCOMPlanSlug from './lib/get-purchased-wpcom-plan-slug';
import getSuccessRedirectUrl from './lib/get-success-redirect-url';
import type { ShoppingCartItem } from '../types';
import './style.scss';
const debug = debugFactory( 'a4a:bd-checkout' );
/**
* A4A-BD Checkout Component using the WordPress.com checkout
*/
function BillingDragonCheckoutContent( {
cartItems,
withA8cLogo = true,
siteSlug,
planSlug,
shouldClearCartOnSuccess = false,
}: {
cartItems: ShoppingCartItem[];
withA8cLogo?: boolean;
siteSlug?: string;
planSlug?: string;
shouldClearCartOnSuccess?: boolean;
} ) {
const translate = useTranslate();
const [ isReady, setIsReady ] = useState( false );
const [ error, setError ] = useState< string | null >( null );
const dispatch = useDispatch();
const agency = useSelector( getActiveAgency );
const site = useSelector( ( state ) => ( siteSlug ? getSite( state, siteSlug ) : undefined ) );
const sitesLoaded = useSelector( hasLoadedSites );
const siteId = site?.ID;
const isPlanCheckout = !! planSlug;
useEffect( () => {
if ( siteId ) {
dispatch( setSelectedSiteId( siteId ) );
} else if ( ! isPlanCheckout ) {
// Clear selected site when navigating to siteless cart checkout
// This ensures the cart system uses the 'no-site' cart key
dispatch( setSelectedSiteId( null ) );
}
}, [ dispatch, siteId, isPlanCheckout ] );
// Use site's cart key when site exists, otherwise use 'no-site' for siteless checkout
const cartKey = siteId || 'no-site';
const { replaceProductsInCart, responseCart } = useShoppingCart( cartKey );
const {
productsForCart,
isLoading: areProductsPreparing,
error: productsError,
} = usePrepareProductsForCart( {
productAliasFromUrl: planSlug,
purchaseId: null,
usesJetpackProducts: false,
isPrivate: false,
siteSlug,
sitelessCheckoutType: 'a4a',
} );
debug( '[A4A Checkout] Cart items: ', cartItems );
// Plan Checkout Flow: This flow is used when a planSlug is provided in the URL (e.g., /checkout/:siteSlug/:planSlug).
// It handles direct plan purchases by:
// 1. Using usePrepareProductsForCart to convert the plan slug into products
// 2. Adding agency metadata to the products
// 3. Replacing the cart with the prepared products
useEffect( () => {
if ( ! isPlanCheckout || areProductsPreparing ) {
return;
}
// Check if user has access to the site when siteSlug is provided
if ( siteSlug && sitesLoaded && ! site ) {
debug( '[A4A Checkout] User does not have access to site:', siteSlug );
page( A4A_MARKETPLACE_LINK );
return;
}
if ( ! agency ) {
debug( '[A4A Checkout] Agency not loaded yet, waiting (plan checkout)...' );
return;
}
if ( ! productsForCart.length || productsError ) {
debug( '[A4A Checkout] No products created from plan slug' );
return;
}
const productsWithAgency = productsForCart.map( ( product ) => ( {
...product,
extra: {
...product.extra,
agency_id: agency.id,
isA4ADevSiteCheckout: true,
},
} ) );
debug( '[A4A Checkout] Replacing cart with products from plan slug', productsWithAgency );
replaceProductsInCart( productsWithAgency )
.then( () => {
debug( '[A4A Checkout] Products added to cart successfully (plan slug)' );
setIsReady( true );
} )
.catch( ( err ) => {
debug( '[A4A Checkout] Failed to add products to cart:', err );
} );
}, [
areProductsPreparing,
agency,
isPlanCheckout,
productsError,
productsForCart,
replaceProductsInCart,
site,
siteSlug,
sitesLoaded,
] );
// Cart Items Flow: This flow is used when cartItems are provided via props (the traditional A4A cart flow).
// It handles checkout for items already in the A4A shopping cart by:
// 1. Waiting for cartItems to be populated from the A4A cart
// 2. Converting A4A cart items into BD cart format
// 3. Replacing the cart with the converted products
// This is the original flow used when users add items to their cart first, then navigate to checkout.
useEffect( () => {
if ( isPlanCheckout ) {
return;
}
// Skip if we're already ready
if ( isReady ) {
debug( '[A4A Checkout] Already ready' );
return;
}
// Ensure agency is loaded before proceeding
if ( ! agency ) {
debug( '[A4A Checkout] Agency not loaded yet, waiting...' );
return;
}
// Wait for cartItems to be populated
if ( ! cartItems || cartItems.length === 0 ) {
debug( '[A4A Checkout] Cart items not loaded yet, waiting...' );
// Reset error state when waiting for cart items
if ( error ) {
setError( null );
}
return;
}
debug( '[A4A Checkout] Cart items inside useEffect: ', cartItems );
const productsToAdd = cartItems.flatMap( ( product ) => {
const productQuantity = product.quantity > 0 ? product.quantity : 1;
let cartItemIndex = 0;
// Add each product separately instead of using volume
// This ensures each site gets the correct tier pricing
return Array.from( { length: productQuantity }, () => {
const product_cart = {
// When using the wpcom checkout we use alternative a4a-specific billing product ids for wpcom and jetpack products.
product_id: product.alternative_product_id || product.product_id,
product_slug: product.slug,
extra: {
isA4ASitelessCheckout: true,
agency_id: agency.id,
cart_item_index: cartItemIndex++,
...( product.site_domain ? { a4a_pressable_site_domain: product.site_domain } : {} ),
},
};
debug( '[A4A Checkout] Processing product to add: ', product_cart );
return createRequestCartProduct( product_cart );
} );
} );
debug( '[A4A Checkout] Products to add', productsToAdd );
// Replace products in cart
if ( productsToAdd.length > 0 ) {
replaceProductsInCart( productsToAdd )
.then( () => {
debug( '[A4A Checkout] Products added to cart successfully' );
debug( '[A4A Checkout] Cart', responseCart );
setIsReady( true );
} )
.catch( ( err ) => {
debug( '[A4A Checkout] Failed to add products to cart:', err );
setError( 'Failed to add products to cart' );
} );
} else {
debug( '[A4A Checkout] No matching products found to add to cart' );
setError( 'Could not find the requested products' );
}
}, [ isReady, error, replaceProductsInCart, responseCart, agency, cartItems, isPlanCheckout ] );
// Debugging: Set a timeout to force showing the checkout after 2 seconds
// Todo: This was reduced from 10 seconds to 2 seconds to check if it works well. Better UX.
useEffect( () => {
if ( isReady || error ) {
return;
}
const timeoutId = setTimeout( () => {
debug( '[A4A Checkout] Timeout reached, showing checkout anyway' );
setIsReady( true );
}, 2000 );
return () => clearTimeout( timeoutId );
}, [ isReady, error ] );
if ( ! isReady ) {
return <ClientCheckoutPlaceholder />;
}
if ( error ) {
return <ClientCheckoutError title={ translate( 'Error' ) } message={ error } />;
}
return (
<div className="client-checkout-v2">
{ withA8cLogo && (
<div className="client-checkout-v2__top-bar">
<div className="client-checkout-v2__top-bar-logo">
<A4ALogo full size={ 14 } />
</div>
</div>
) }
<CheckoutMain
sitelessCheckoutType="a4a"
redirectTo={ getSuccessRedirectUrl(
window.location.origin,
shouldClearCartOnSuccess && ! isPlanCheckout,
isPlanCheckout ? null : getPurchasedWPCOMPlanSlug( cartItems )
) }
customizedPreviousPath="/marketplace"
siteSlug={ siteSlug ?? '' }
siteId={ siteId ?? 0 }
/>
</div>
);
}
export default function BillingDragonCheckout( {
cartItems,
withA8cLogo = true,
siteSlug,
planSlug,
shouldClearCartOnSuccess = false,
}: {
cartItems: ShoppingCartItem[];
withA8cLogo?: boolean;
siteSlug?: string;
planSlug?: string;
shouldClearCartOnSuccess?: boolean;
} ) {
const translate = useTranslate();
const locale = useSelector( getCurrentUserLocale );
return (
<CheckoutErrorBoundary
errorMessage={ translate( 'Sorry, there was an error loading the checkout page.' ) }
>
<CalypsoShoppingCartProvider shouldShowPersistentErrors>
<StripeHookProvider fetchStripeConfiguration={ getStripeConfiguration } locale={ locale }>
<BillingDragonCheckoutContent
cartItems={ cartItems }
withA8cLogo={ withA8cLogo }
siteSlug={ siteSlug }
planSlug={ planSlug }
shouldClearCartOnSuccess={ shouldClearCartOnSuccess }
/>
</StripeHookProvider>
</CalypsoShoppingCartProvider>
</CheckoutErrorBoundary>
);
}