/**
* External dependencies
*/
import { select, dispatch } from '@wordpress/data';
import { PaymentMethods } from '@woocommerce/type-defs/payments';
* Internal dependencies
import { STORE_KEY as PAYMENT_METHOD_DATA_STORE_KEY } from './constants';
export const setDefaultPaymentMethod = async (
paymentMethods: PaymentMethods
) => {
const paymentMethodKeys = Object.keys( paymentMethods );
const expressPaymentMethodKeys = Object.keys(
select(
PAYMENT_METHOD_DATA_STORE_KEY
).getAvailableExpressPaymentMethods()
);
const allPaymentMethodKeys = [
...paymentMethodKeys,
...expressPaymentMethodKeys,
];
const savedPaymentMethods = select(
).getSavedPaymentMethods();
const savedPaymentMethod =
Object.keys( savedPaymentMethods ).flatMap(
( type ) => savedPaymentMethods[ type ]
)[ 0 ] || undefined;
if ( savedPaymentMethod ) {
const token = savedPaymentMethod.tokenId.toString();
const paymentMethodSlug = savedPaymentMethod.method.gateway;
const savedTokenKey = `wc-${ paymentMethodSlug }-payment-token`;
dispatch(
).__internalSetActivePaymentMethod( paymentMethodSlug, {
token,
payment_method: paymentMethodSlug,
[ savedTokenKey ]: token,
isSavedToken: true,
} );
return;
}
const activePaymentMethod = select(
).getActivePaymentMethod();
// Return if current method is valid.
if (
activePaymentMethod &&
allPaymentMethodKeys.includes( activePaymentMethod )
) {
dispatch( PAYMENT_METHOD_DATA_STORE_KEY ).__internalSetPaymentStatus( {
isPristine: true,
dispatch( PAYMENT_METHOD_DATA_STORE_KEY ).__internalSetActivePaymentMethod(
paymentMethodKeys[ 0 ]
};