2021-09-15 16:36:02 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import type { CanMakePaymentCallback } from '@woocommerce/type-defs/payments';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import type {
|
|
|
|
NamespacedCanMakePaymentExtensionsCallbacks,
|
|
|
|
PaymentMethodName,
|
|
|
|
ExtensionNamespace,
|
|
|
|
} from './extensions-config';
|
|
|
|
|
2021-01-29 06:28:44 +00:00
|
|
|
// Filter out payment methods by supported features and cart requirement.
|
2021-09-15 16:36:02 +00:00
|
|
|
export const canMakePaymentWithFeaturesCheck = (
|
|
|
|
canMakePayment: CanMakePaymentCallback,
|
|
|
|
features: string[]
|
|
|
|
): CanMakePaymentCallback => ( canPayArgument ) => {
|
2021-01-29 06:28:44 +00:00
|
|
|
const requirements = canPayArgument.paymentRequirements || [];
|
|
|
|
const featuresSupportRequirements = requirements.every( ( requirement ) =>
|
|
|
|
features.includes( requirement )
|
|
|
|
);
|
|
|
|
return featuresSupportRequirements && canMakePayment( canPayArgument );
|
|
|
|
};
|
2021-09-08 11:29:29 +00:00
|
|
|
|
|
|
|
// Filter out payment methods by callbacks registered by extensions.
|
|
|
|
export const canMakePaymentWithExtensions = (
|
2021-09-15 16:36:02 +00:00
|
|
|
canMakePayment: CanMakePaymentCallback,
|
|
|
|
extensionsCallbacks: NamespacedCanMakePaymentExtensionsCallbacks,
|
|
|
|
paymentMethodName: PaymentMethodName
|
|
|
|
): CanMakePaymentCallback => ( canPayArgument ) => {
|
2021-09-08 11:29:29 +00:00
|
|
|
// Validate whether the payment method is available based on its own criteria first.
|
|
|
|
let canPay = canMakePayment( canPayArgument );
|
|
|
|
|
|
|
|
if ( canPay ) {
|
2021-09-15 16:36:02 +00:00
|
|
|
// Gather all callbacks for paymentMethodName.
|
|
|
|
const namespacedCallbacks: Record<
|
|
|
|
ExtensionNamespace,
|
|
|
|
CanMakePaymentCallback
|
|
|
|
> = {};
|
|
|
|
|
2021-09-08 11:29:29 +00:00
|
|
|
Object.entries( extensionsCallbacks ).forEach(
|
|
|
|
( [ namespace, callbacks ] ) => {
|
2021-09-15 16:36:02 +00:00
|
|
|
namespacedCallbacks[ namespace ] =
|
|
|
|
callbacks[ paymentMethodName ];
|
2021-09-08 11:29:29 +00:00
|
|
|
}
|
|
|
|
);
|
2021-09-15 16:36:02 +00:00
|
|
|
|
2021-09-08 11:29:29 +00:00
|
|
|
canPay = Object.keys( namespacedCallbacks ).every( ( namespace ) => {
|
|
|
|
try {
|
|
|
|
return namespacedCallbacks[ namespace ]( canPayArgument );
|
|
|
|
} catch ( err ) {
|
|
|
|
// eslint-disable-next-line no-console
|
|
|
|
console.error(
|
|
|
|
`Error when executing callback for ${ paymentMethodName } in ${ namespace }`,
|
|
|
|
err
|
|
|
|
);
|
2021-09-15 16:36:02 +00:00
|
|
|
// .every() expects a return value at the end of every arrow function and
|
2021-09-08 11:29:29 +00:00
|
|
|
// this ensures that the error is ignored when computing the whole result.
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
} );
|
|
|
|
}
|
|
|
|
|
|
|
|
return canPay;
|
|
|
|
};
|