woocommerce/plugins/woocommerce-blocks/assets/js/base/context/cart-checkout/checkout-state/index.js

218 lines
6.2 KiB
JavaScript
Raw Normal View History

/**
* External dependencies
*/
import {
createContext,
useContext,
useReducer,
useRef,
useMemo,
useEffect,
} from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { useStoreNotices } from '@woocommerce/base-hooks';
/**
* Internal dependencies
*/
import { actions } from './actions';
import { reducer } from './reducer';
import { DEFAULT_STATE, STATUS } from './constants';
import {
EMIT_TYPES,
emitterSubscribers,
emitEvent,
reducer as emitReducer,
} from './event-emit';
import { useValidationContext } from '../validation';
/**
* @typedef {import('@woocommerce/type-defs/checkout').CheckoutDispatchActions} CheckoutDispatchActions
* @typedef {import('@woocommerce/type-defs/contexts').CheckoutDataContext} CheckoutDataContext
*/
const CheckoutContext = createContext( {
submitLabel: '',
onSubmit: () => void null,
isComplete: false,
isIdle: false,
isCalculating: false,
isProcessing: false,
isProcessingComplete: false,
hasError: false,
redirectUrl: '',
orderId: 0,
onCheckoutCompleteSuccess: ( callback ) => void callback,
onCheckoutCompleteError: ( callback ) => void callback,
onCheckoutProcessing: ( callback ) => void callback,
dispatchActions: {
resetCheckout: () => void null,
setRedirectUrl: ( url ) => void url,
setHasError: ( hasError ) => void hasError,
setComplete: () => void null,
incrementCalculating: () => void null,
decrementCalculating: () => void null,
setOrderId: ( id ) => void id,
},
hasOrder: false,
isCart: false,
} );
/**
* @return {CheckoutDataContext} Returns the checkout data context value
*/
export const useCheckoutContext = () => {
return useContext( CheckoutContext );
};
/**
* Checkout state provider
* This provides provides an api interface exposing checkout state for use with
* cart or checkout blocks.
*
* @param {Object} props Incoming props for the provider.
* @param {Object} props.children The children being wrapped.
* @param {string} props.redirectUrl Initialize what the checkout will
* redirect to after successful
* submit.
* @param {string} props.submitLabel What will be used for the checkout
* submit button label.
* @param {boolean} props.isCart If context provider is being used
* in cart context.
*/
export const CheckoutStateProvider = ( {
children,
redirectUrl,
isCart = false,
submitLabel = __( 'Place Order', 'woo-gutenberg-product-block' ),
} ) => {
// note, this is done intentionally so that the default state now has
// the redirectUrl for when checkout is reset to PRISTINE state.
DEFAULT_STATE.redirectUrl = redirectUrl;
const [ checkoutState, dispatch ] = useReducer( reducer, DEFAULT_STATE );
const [ observers, subscriber ] = useReducer( emitReducer, {} );
const currentObservers = useRef( observers );
const { setValidationErrors } = useValidationContext();
const { addErrorNotice, removeNotices } = useStoreNotices();
const isCalculating = checkoutState.calculatingCount > 0;
// set observers on ref so it's always current.
useEffect( () => {
currentObservers.current = observers;
}, [ observers ] );
const onCheckoutCompleteSuccess = useMemo(
() => emitterSubscribers( subscriber ).onCheckoutCompleteSuccess,
[ subscriber ]
);
const onCheckoutCompleteError = useMemo(
() => emitterSubscribers( subscriber ).onCheckoutCompleteError,
[ subscriber ]
);
const onCheckoutProcessing = useMemo(
() => emitterSubscribers( subscriber ).onCheckoutProcessing,
[ subscriber ]
);
/**
* @type {CheckoutDispatchActions}
*/
const dispatchActions = useMemo(
() => ( {
resetCheckout: () => void dispatch( actions.setPristine() ),
setRedirectUrl: ( url ) =>
void dispatch( actions.setRedirectUrl( url ) ),
setHasError: ( hasError ) =>
void dispatch( actions.setHasError( hasError ) ),
incrementCalculating: () =>
void dispatch( actions.incrementCalculating() ),
decrementCalculating: () =>
void dispatch( actions.decrementCalculating() ),
setOrderId: ( orderId ) =>
void dispatch( actions.setOrderId( orderId ) ),
setComplete: () => {
void dispatch( actions.setComplete() );
},
} ),
[]
);
// emit events.
useEffect( () => {
Convert apple pay integration to payment request integration and finish implementation (https://github.com/woocommerce/woocommerce-blocks/pull/2127) * add logic allowing payment method to be overridden via payment data in request * hook in to trigger server side processing of stripe payment request * improvements to shipping data context - memoize event emitters - split up emitted events (reduces how often events trigger) - Include whether rate is being selected in exported data. * expose `isSelectingRate` value to payment method interface * fix typo in shipping emitters for emitter type * include setting of shipping data in payment method success status call - this also requires changing the nested order of providers in checkout provider * fix priority logic for event emitters. - lower priority is supposed to fire before higher priority. * normalize postal code for comparisons * move normalize functions into stripe-utils folder * refactor stripePromise so that it provides a specific instance to each payment method. This also provides it as a prop to the pm components. * renadme apple pay express to payment request express This adds full support for the stripe payment request api instead of just applePay (so GooglePay, MicrosoftPay and ApplePay are now supported). Also adds numerous fixes to internal logic. * add handling to skip core checkout validation logic if express payment method is handling payment Express payment methods have their own internal validation so this removes the need for checkout validating fields. This is also necessary because checkout validation breaks the flow when making a payment using express payment methods because of the order of the flow for these methods. * splitting out emmitter effects for checkout and improving logic Splitting up effects limits the potential for firing off emitters more than needed. * remove unnecessary ref definitions * fix on cancel action erroring for payment request modal * ensure unique stripe object for component and canPay * set default total label if one isn’t configured on the server * fix order of state changes * simplify condition * remove unnecessary dependency * normalize to uppercase too * simplify can make payment conditional * update comment blocks
2020-04-08 16:36:04 +00:00
const { status } = checkoutState;
if ( status === STATUS.PROCESSING ) {
removeNotices( 'error' );
emitEvent(
currentObservers.current,
EMIT_TYPES.CHECKOUT_PROCESSING,
{}
).then( ( response ) => {
Convert apple pay integration to payment request integration and finish implementation (https://github.com/woocommerce/woocommerce-blocks/pull/2127) * add logic allowing payment method to be overridden via payment data in request * hook in to trigger server side processing of stripe payment request * improvements to shipping data context - memoize event emitters - split up emitted events (reduces how often events trigger) - Include whether rate is being selected in exported data. * expose `isSelectingRate` value to payment method interface * fix typo in shipping emitters for emitter type * include setting of shipping data in payment method success status call - this also requires changing the nested order of providers in checkout provider * fix priority logic for event emitters. - lower priority is supposed to fire before higher priority. * normalize postal code for comparisons * move normalize functions into stripe-utils folder * refactor stripePromise so that it provides a specific instance to each payment method. This also provides it as a prop to the pm components. * renadme apple pay express to payment request express This adds full support for the stripe payment request api instead of just applePay (so GooglePay, MicrosoftPay and ApplePay are now supported). Also adds numerous fixes to internal logic. * add handling to skip core checkout validation logic if express payment method is handling payment Express payment methods have their own internal validation so this removes the need for checkout validating fields. This is also necessary because checkout validation breaks the flow when making a payment using express payment methods because of the order of the flow for these methods. * splitting out emmitter effects for checkout and improving logic Splitting up effects limits the potential for firing off emitters more than needed. * remove unnecessary ref definitions * fix on cancel action erroring for payment request modal * ensure unique stripe object for component and canPay * set default total label if one isn’t configured on the server * fix order of state changes * simplify condition * remove unnecessary dependency * normalize to uppercase too * simplify can make payment conditional * update comment blocks
2020-04-08 16:36:04 +00:00
if ( response !== true ) {
if ( Array.isArray( response ) ) {
response.forEach(
( { errorMessage, validationErrors } ) => {
addErrorNotice( errorMessage );
setValidationErrors( validationErrors );
}
);
}
dispatch( actions.setComplete() );
} else {
dispatch( actions.setProcessingComplete() );
}
} );
}
Convert apple pay integration to payment request integration and finish implementation (https://github.com/woocommerce/woocommerce-blocks/pull/2127) * add logic allowing payment method to be overridden via payment data in request * hook in to trigger server side processing of stripe payment request * improvements to shipping data context - memoize event emitters - split up emitted events (reduces how often events trigger) - Include whether rate is being selected in exported data. * expose `isSelectingRate` value to payment method interface * fix typo in shipping emitters for emitter type * include setting of shipping data in payment method success status call - this also requires changing the nested order of providers in checkout provider * fix priority logic for event emitters. - lower priority is supposed to fire before higher priority. * normalize postal code for comparisons * move normalize functions into stripe-utils folder * refactor stripePromise so that it provides a specific instance to each payment method. This also provides it as a prop to the pm components. * renadme apple pay express to payment request express This adds full support for the stripe payment request api instead of just applePay (so GooglePay, MicrosoftPay and ApplePay are now supported). Also adds numerous fixes to internal logic. * add handling to skip core checkout validation logic if express payment method is handling payment Express payment methods have their own internal validation so this removes the need for checkout validating fields. This is also necessary because checkout validation breaks the flow when making a payment using express payment methods because of the order of the flow for these methods. * splitting out emmitter effects for checkout and improving logic Splitting up effects limits the potential for firing off emitters more than needed. * remove unnecessary ref definitions * fix on cancel action erroring for payment request modal * ensure unique stripe object for component and canPay * set default total label if one isn’t configured on the server * fix order of state changes * simplify condition * remove unnecessary dependency * normalize to uppercase too * simplify can make payment conditional * update comment blocks
2020-04-08 16:36:04 +00:00
}, [ checkoutState.status, setValidationErrors ] );
useEffect( () => {
if ( checkoutState.status === STATUS.COMPLETE ) {
if ( checkoutState.hasError ) {
emitEvent(
currentObservers.current,
EMIT_TYPES.CHECKOUT_COMPLETE_WITH_ERROR,
{}
);
} else {
emitEvent(
currentObservers.current,
EMIT_TYPES.CHECKOUT_COMPLETE_WITH_SUCCESS,
{}
);
}
}
Convert apple pay integration to payment request integration and finish implementation (https://github.com/woocommerce/woocommerce-blocks/pull/2127) * add logic allowing payment method to be overridden via payment data in request * hook in to trigger server side processing of stripe payment request * improvements to shipping data context - memoize event emitters - split up emitted events (reduces how often events trigger) - Include whether rate is being selected in exported data. * expose `isSelectingRate` value to payment method interface * fix typo in shipping emitters for emitter type * include setting of shipping data in payment method success status call - this also requires changing the nested order of providers in checkout provider * fix priority logic for event emitters. - lower priority is supposed to fire before higher priority. * normalize postal code for comparisons * move normalize functions into stripe-utils folder * refactor stripePromise so that it provides a specific instance to each payment method. This also provides it as a prop to the pm components. * renadme apple pay express to payment request express This adds full support for the stripe payment request api instead of just applePay (so GooglePay, MicrosoftPay and ApplePay are now supported). Also adds numerous fixes to internal logic. * add handling to skip core checkout validation logic if express payment method is handling payment Express payment methods have their own internal validation so this removes the need for checkout validating fields. This is also necessary because checkout validation breaks the flow when making a payment using express payment methods because of the order of the flow for these methods. * splitting out emmitter effects for checkout and improving logic Splitting up effects limits the potential for firing off emitters more than needed. * remove unnecessary ref definitions * fix on cancel action erroring for payment request modal * ensure unique stripe object for component and canPay * set default total label if one isn’t configured on the server * fix order of state changes * simplify condition * remove unnecessary dependency * normalize to uppercase too * simplify can make payment conditional * update comment blocks
2020-04-08 16:36:04 +00:00
}, [ checkoutState.status, checkoutState.hasError ] );
const onSubmit = () => {
dispatch( actions.setProcessing() );
};
/**
* @type {CheckoutDataContext}
*/
const checkoutData = {
submitLabel,
onSubmit,
isComplete: checkoutState.status === STATUS.COMPLETE,
isIdle: checkoutState.status === STATUS.IDLE,
isCalculating,
isProcessing: checkoutState.status === STATUS.PROCESSING,
isProcessingComplete:
checkoutState.status === STATUS.PROCESSING_COMPLETE,
hasError: checkoutState.hasError,
redirectUrl: checkoutState.redirectUrl,
onCheckoutCompleteSuccess,
onCheckoutCompleteError,
onCheckoutProcessing,
dispatchActions,
isCart,
orderId: checkoutState.orderId,
hasOrder: !! checkoutState.orderId,
customerId: checkoutState.customerId,
};
return (
<CheckoutContext.Provider value={ checkoutData }>
{ children }
</CheckoutContext.Provider>
);
};