Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ECE initialization when no shipping rates are provided #10169

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog/fix-tokenized-ece-with-no-address-on-initialization
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: fix

fix: avoid ECE error when no address is provided on initialization
39 changes: 29 additions & 10 deletions client/express-checkout/blocks/hooks/use-express-checkout.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import { useCallback } from '@wordpress/element';
import { useStripe, useElements } from '@stripe/react-stripe-js';
import { __ } from '@wordpress/i18n';

/**
* Internal dependencies
Expand Down Expand Up @@ -58,22 +59,40 @@ export const useExpressCheckout = ( {
return;
}

const shippingAddressRequired = shippingData?.needsShipping;
const shippingRatesMap = shippingData?.shippingRates[ 0 ]?.shipping_rates?.map(
( r ) => {
return {
id: r.rate_id,
amount: parseInt( r.price, 10 ),
displayName: r.name,
};
}
);
const shippingRates =
shippingAddressRequired &&
( ! shippingRatesMap || shippingRatesMap.length === 0 )
? [
// fallback for initialization (and initialization _only_), before an address is provided by the ECE.
{
id: 'pending',
displayName: __(
'Pending',
'woocommerce-payments'
),
amount: 0,
},
]
: undefined;

const options = {
lineItems: normalizeLineItems( billing?.cartTotalItems ),
emailRequired: true,
shippingAddressRequired: shippingData?.needsShipping,
shippingAddressRequired,
phoneNumberRequired:
getExpressCheckoutData( 'checkout' )?.needs_payer_phone ??
false,
shippingRates: shippingData?.shippingRates[ 0 ]?.shipping_rates?.map(
( r ) => {
return {
id: r.rate_id,
amount: parseInt( r.price, 10 ),
displayName: r.name,
};
}
),
shippingRates,
allowedShippingCountries: getExpressCheckoutData( 'checkout' )
.allowed_shipping_countries,
};
Expand Down
4 changes: 2 additions & 2 deletions client/express-checkout/event-handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {
let lastSelectedAddress = null;

export const shippingAddressChangeHandler = async ( api, event, elements ) => {
lastSelectedAddress = event.address;

try {
const response = await api.expressCheckoutECECalculateShippingOptions(
normalizeShippingAddress( event.address )
Expand All @@ -33,8 +35,6 @@ export const shippingAddressChangeHandler = async ( api, event, elements ) => {
amount: response.total.amount,
} );

lastSelectedAddress = event.address;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved above, so that the newly selected address is saved regardless of the error.
This makes the behavior consistent between block-based and shortcode-based checkout.


event.resolve( {
shippingRates: response.shipping_options,
lineItems: normalizeLineItems( response.displayItems ),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/**
* External dependencies
*/
import { renderHook } from '@testing-library/react-hooks';

/**
* Internal dependencies
*/
import { useExpressCheckout } from '../use-express-checkout';

jest.mock( '@stripe/react-stripe-js', () => ( {
useElements: jest.fn(),
useStripe: jest.fn(),
} ) );
jest.mock( 'tracks', () => ( {
recordUserEvent: jest.fn(),
} ) );

const jQueryMock = ( selector ) => {
if ( typeof selector === 'function' ) {
return selector( jQueryMock );
}

return {
on: () => null,
val: () => null,
is: () => null,
remove: () => null,
};
};
jQueryMock.blockUI = () => null;

window.wcpayExpressCheckoutParams = {};
window.wcpayExpressCheckoutParams.checkout = {};

describe( 'useExpressCheckout', () => {
beforeEach( () => {
global.$ = jQueryMock;
global.jQuery = jQueryMock;
} );

it( 'should provide no shipping rates when not required on click', () => {
const onClickMock = jest.fn();
const event = { resolve: jest.fn() };
const { result } = renderHook( () =>
useExpressCheckout( {
billing: {
cartTotalItems: [],
},
shippingData: {
needsShipping: false,
shippingRates: [],
},
onClick: onClickMock,
onClose: {},
setExpressPaymentError: {},
} )
);

expect( onClickMock ).not.toHaveBeenCalled();

result.current.onButtonClick( event );

expect( event.resolve ).toHaveBeenCalledWith(
expect.objectContaining( {
shippingRates: undefined,
shippingAddressRequired: false,
} )
);
expect( onClickMock ).toHaveBeenCalled();
} );

it( 'should provide the shipping rates on click', () => {
const event = { resolve: jest.fn() };
const { result } = renderHook( () =>
useExpressCheckout( {
billing: {
cartTotalItems: [],
},
shippingData: {
needsShipping: true,
shippingRates: [
{
shipping_rates: [
{
rate_id: '1',
price: '10',
name: 'Fake shipping rate',
},
],
},
],
},
onClick: jest.fn(),
onClose: {},
setExpressPaymentError: {},
} )
);

result.current.onButtonClick( event );

expect( event.resolve ).toHaveBeenCalledWith(
expect.objectContaining( {
shippingRates: expect.arrayContaining( [
{
id: '1',
displayName: 'Fake shipping rate',
amount: 10,
},
] ),
shippingAddressRequired: true,
} )
);
} );

it( 'should provide the shipping rates with fallback on click', () => {
const event = { resolve: jest.fn() };
const { result } = renderHook( () =>
useExpressCheckout( {
billing: {
cartTotalItems: [],
},
shippingData: {
needsShipping: true,
shippingRates: [],
},
onClick: jest.fn(),
onClose: {},
setExpressPaymentError: {},
} )
);

result.current.onButtonClick( event );

expect( event.resolve ).toHaveBeenCalledWith(
expect.objectContaining( {
shippingRates: expect.arrayContaining( [
{
id: 'pending',
displayName: 'Pending',
amount: 0,
},
] ),
shippingAddressRequired: true,
} )
);
} );
} );
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import { useCallback } from '@wordpress/element';
import { useStripe, useElements } from '@stripe/react-stripe-js';
import { __ } from '@wordpress/i18n';

/**
* Internal dependencies
Expand Down Expand Up @@ -58,22 +59,43 @@ export const useExpressCheckout = ( {
return;
}

const shippingAddressRequired = shippingData?.needsShipping;

const shippingRatesMap = shippingData?.shippingRates[ 0 ]?.shipping_rates?.map(
( r ) => {
return {
id: r.rate_id,
amount: parseInt( r.price, 10 ),
displayName: r.name,
};
}
);
const shippingOptionsWithFallback =
// the variable could be undefined or it could just be an array without values.
! shippingRatesMap || shippingRatesMap.length === 0
? [
// fallback for initialization (and initialization _only_), before an address is provided by the ECE.
{
id: 'pending',
displayName: __(
'Pending',
'woocommerce-payments'
),
amount: 0,
},
]
: shippingRatesMap;

const options = {
lineItems: normalizeLineItems( billing?.cartTotalItems ),
emailRequired: true,
shippingAddressRequired: shippingData?.needsShipping,
shippingAddressRequired,
phoneNumberRequired:
getExpressCheckoutData( 'checkout' )?.needs_payer_phone ??
false,
shippingRates: shippingData?.shippingRates[ 0 ]?.shipping_rates?.map(
( r ) => {
return {
id: r.rate_id,
amount: parseInt( r.price, 10 ),
displayName: r.name,
};
}
),
shippingRates: shippingAddressRequired
? shippingOptionsWithFallback
: undefined,
allowedShippingCountries: getExpressCheckoutData( 'checkout' )
.allowed_shipping_countries,
};
Expand Down
4 changes: 2 additions & 2 deletions client/tokenized-express-checkout/event-handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export const setCartApiHandler = ( handler ) => ( cartApi = handler );
export const getCartApiHandler = () => cartApi;

export const shippingAddressChangeHandler = async ( event, elements ) => {
lastSelectedAddress = event.address;

try {
// Please note that the `event.address` might not contain all the fields.
// Some fields might not be present (like `line_1` or `line_2`) due to semi-anonymized data.
Expand Down Expand Up @@ -62,8 +64,6 @@ export const shippingAddressChangeHandler = async ( event, elements ) => {
),
} );

lastSelectedAddress = event.address;

event.resolve( {
shippingRates: transformCartDataForShippingRates( cartData ),
lineItems: transformCartDataForDisplayItems( cartData ),
Expand Down
35 changes: 21 additions & 14 deletions client/tokenized-express-checkout/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,29 +65,18 @@ const fetchNewCartData = async () => {
};

const getServerSideExpressCheckoutProductData = () => {
const requestShipping =
getExpressCheckoutData( 'product' )?.needs_shipping ?? false;
const displayItems = (
getExpressCheckoutData( 'product' )?.displayItems ?? []
).map( ( { label, amount } ) => ( {
name: label,
amount,
} ) );
const shippingRates = requestShipping
? [
{
id: 'pending',
displayName: __( 'Pending', 'woocommerce-payments' ),
amount: 0,
},
]
: undefined;
Comment on lines -76 to -84
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This "Pending" rate is now consistently added on initialization. Before, it was added only on the product pages.


return {
total: getExpressCheckoutData( 'product' )?.total.amount,
currency: getExpressCheckoutData( 'product' )?.currency,
requestShipping,
shippingRates,
requestShipping:
getExpressCheckoutData( 'product' )?.needs_shipping ?? false,
requestPhone:
getExpressCheckoutData( 'checkout' )?.needs_payer_phone ?? false,
displayItems,
Expand Down Expand Up @@ -258,6 +247,22 @@ jQuery( ( $ ) => {
} );
}

const shippingOptionsWithFallback =
! options.shippingRates || // server-side data on the product page initialization doesn't provide any shipping rates.
options.shippingRates.length === 0 // but it can also happen that there are no rates in the array.
? [
// fallback for initialization (and initialization _only_), before an address is provided by the ECE.
{
id: 'pending',
displayName: __(
'Pending',
'woocommerce-payments'
),
amount: 0,
},
]
: options.shippingRates;

const clickOptions = {
// `options.displayItems`, `options.requestShipping`, `options.requestPhone`, `options.shippingRates`,
// are all coming from prior of the initialization.
Expand All @@ -268,7 +273,9 @@ jQuery( ( $ ) => {
emailRequired: true,
shippingAddressRequired: options.requestShipping,
phoneNumberRequired: options.requestPhone,
shippingRates: options.shippingRates,
shippingRates: options.requestShipping
? shippingOptionsWithFallback
: undefined,
allowedShippingCountries: getExpressCheckoutData(
'checkout'
).allowed_shipping_countries,
Expand Down
Loading