woocommerce/plugins/woocommerce-blocks/docs/internal-developers/block-client-apis/checkout/checkout-flow-and-events.md

499 lines
32 KiB
Markdown
Raw Normal View History

# Checkout Flow and Events <!-- omit in toc -->
## Table of Contents <!-- omit in toc -->
- [General Concepts](#general-concepts)
- [Tracking flow through status](#tracking-flow-through-status)
- [Checkout Data Store Status](#checkout-data-store-status)
- [Special States:](#special-states)
- [`ShippingProvider` Exposed Statuses](#shippingprovider-exposed-statuses)
- [Payment Method Data Store Status](#payment-method-data-store-status)
- [Emitting Events](#emitting-events)
- [`onCheckoutValidationBeforeProcessing`](#oncheckoutvalidationbeforeprocessing)
- [`onPaymentProcessing`](#onpaymentprocessing)
- [Success](#success)
- [Fail](#fail)
- [Error](#error)
- [`onCheckoutAfterProcessingWithSuccess`](#oncheckoutafterprocessingwithsuccess)
- [`onCheckoutAfterProcessingWithError`](#oncheckoutafterprocessingwitherror)
- [`onShippingRateSuccess`](#onshippingratesuccess)
- [`onShippingRateFail`](#onshippingratefail)
- [`onShippingRateSelectSuccess`](#onshippingrateselectsuccess)
- [`onShippingRateSelectFail`](#onshippingrateselectfail)
This document gives an overview of the flow for the checkout in the WooCommerce checkout block, and some general architectural overviews.
The architecture of the Checkout Block is derived from the following principles:
- A single source of truth for data within the checkout flow.
- Provide a consistent interface for extension integrations (eg Payment methods). This interface protects the integrity of the checkout process and isolates extension logic from checkout logic. The checkout block handles _all_ communication with the server for processing the order. Extensions are able to react to and communicate with the checkout block via the provided interface.
- Checkout flow state is tracked by checkout status.
- Extensions are able to interact with the checkout flow via subscribing to emitted events.
Here's a high level overview of the flow:
![checkout flow diagram](https://user-images.githubusercontent.com/1628454/113739726-f8c9df00-96f7-11eb-80f1-78e25ccc88cb.png)
## General Concepts
### Tracking flow through status
At any point in the checkout lifecycle, components should be able to accurately detect the state of the checkout flow. This includes things like:
- Is something loading? What is loading?
- Is there an error? What is the error?
- is the checkout calculating totals?
Using simple booleans can be fine in some cases, but in others it can lead to complicated conditionals and bug prone code (especially for logic behaviour that reacts to various flow state).
To surface the flow state, the block uses statuses that are tracked in the various contexts. _As much as possible_ these statuses are set internally in reaction to various actions so there's no implementation needed in children components (components just have to _consume_ the status not set status).
The following statuses exist in the Checkout.
#### Checkout Data Store Status
Convert checkout context to data store - part 1 (https://github.com/woocommerce/woocommerce-blocks/pull/6232) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Delete empty types.ts file * remove merge conflict from docs * Correct linting in docs Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>
2022-06-10 16:33:15 +00:00
There are various statuses that are exposed on the Checkout data store via selectors. All the selectors are detailed below and in the [Checkout API docs](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/trunk/docs/block-client-apis/checkout/checkout-api.md).
Convert checkout context to data store - part 1 (https://github.com/woocommerce/woocommerce-blocks/pull/6232) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Delete empty types.ts file * remove merge conflict from docs * Correct linting in docs Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>
2022-06-10 16:33:15 +00:00
You can use them in your component like so
```jsx
Convert checkout context to data store - part 1 (https://github.com/woocommerce/woocommerce-blocks/pull/6232) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Delete empty types.ts file * remove merge conflict from docs * Correct linting in docs Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>
2022-06-10 16:33:15 +00:00
import { useSelect } from '@wordpress/data';
import { CHECKOUT_STORE_KEY } from '@woocommerce/blocks-data';
const MyComponent = ( props ) => {
Convert checkout context to data store - part 1 (https://github.com/woocommerce/woocommerce-blocks/pull/6232) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Delete empty types.ts file * remove merge conflict from docs * Correct linting in docs Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>
2022-06-10 16:33:15 +00:00
const isComplete = useSelect( ( select ) =>
select( CHECKOUT_STORE_KEY ).isComplete()
);
// do something with isComplete
};
```
The following boolean flags available related to status are:
**isIdle**: When the checkout status is `IDLE` this flag is true. Checkout will be this status after any change to checkout state after the block is loaded. It will also be this status when retrying a purchase is possible after processing happens with an error.
**isBeforeProcessing**: When the checkout status is `BEFORE_PROCESSING` this flag is true. Checkout will be this status when the user submits checkout for processing.
**isProcessing**: When the checkout status is `PROCESSING` this flag is true. Checkout will be this status when all the observers on the event emitted with the `BEFORE_PROCESSING` status are completed without error. It is during this status that the block will be sending a request to the server on the checkout endpoint for processing the order. **Note:** there are some checkout payment status changes that happen during this state as well (outlined in the `PaymentProvider` exposed statuses section).
**isAfterProcessing**: When the checkout status is `AFTER_PROCESSING` this flag is true. Checkout will have this status after the the block receives the response from the server side processing request.
**isComplete**: When the checkout status is `COMPLETE` this flag is true. Checkout will have this status after all observers on the events emitted during the `AFTER_PROCESSING` status are completed successfully. When checkout is at this status, the shopper's browser will be redirected to the value of `redirectUrl` at that point (usually the `order-received` route).
#### Special States
The following are booleans exposed via the checkout provider that are independent from each other and checkout statuses but can be used in combination to react to various state in the checkout.
**isCalculating:** This is true when the total is being re-calculated for the order. There are numerous things that might trigger a recalculation of the total: coupons being added or removed, shipping rates updated, shipping rate selected etc. This flag consolidates all activity that might be occurring (including requests to the server that potentially affect calculation of totals). So instead of having to check each of those individual states you can reliably just check if this boolean is true (calculating) or false (not calculating).
**hasError:** This is true when anything in the checkout has created an error condition state. This might be validation errors, request errors, coupon application errors, payment processing errors etc.
### `ShippingProvider` Exposed Statuses
The shipping context provider exposes everything related to shipping in the checkout. Included in this are a set of error statuses that inform what error state the shipping context is in and the error state is affected by requests to the server on address changes, rate retrieval and selection.
Currently the error status may be one of `NONE`, `INVALID_ADDRESS` or `UNKNOWN` (note, this may change in the future).
The status is exposed on the `currentErrorStatus` object provided by the `useShippingDataContext` hook. This object has the following properties on it:
- `isPristine` and `isValid`: Both of these booleans are connected to the same error status. When the status is `NONE` the values for these booleans will be `true`. It basically means there is no shipping error.
- `hasInvalidAddress`: When the address provided for shipping is invalid, this will be true.
- `hasError`: This is `true` when the error status for shipping is either `UNKNOWN` or `hasInvalidAddress`.
### Payment Method Data Store Status
The status of the payment lives in the payment data store. It can be retrieved with the `getCurrentStatus` selector, liek so:
```jsx
import { useSelect } from '@wordpress/data';
import { PAYMENT_STORE_KEY } from '@woocommerce/blocks-data';
const MyComponent = ( props ) => {
const currentStatus = useSelect( ( select ) =>
select( PAYMENT_STORE_KEY ).getCurrentStatus()
);
// do something with status
};
```
The status here will help inform the current state of _client side_ processing for the payment and are updated via the store actions at different points throughout the checkout processing cycle. _Client side_ means the state of processing any payments by registered and active payment methods when the checkout form is submitted via those payment methods registered client side components. It's still possible that payment methods might have additional server side processing when the order is being processed but that is not reflected by these statuses (more in the [payment method integration doc](../../../third-party-developers/extensibility/checkout-payment-methods/payment-method-integration.md)).
The possible _internal_ statuses that may be set are:
- `PRISTINE`: This is the status when checkout is initialized and there are payment methods that are not doing anything. This status is also set whenever the checkout status is changed to `IDLE`.
- `STARTED`: **Express Payment Methods Only** - This status is used when an express payment method has been triggered by the user clicking it's button. This flow happens before processing, usually in a modal window.
- `PROCESSING`: This status is set when the checkout status is `PROCESSING`, checkout `hasError` is false, checkout is not calculating, and the current payment status is not `FINISHED`. When this status is set, it will trigger the payment processing event emitter.
- `SUCCESS`: This status is set after all the observers hooked into the payment processing event have completed successfully. The `CheckoutProcessor` component uses this along with the checkout `PROCESSING` status to signal things are ready to send the order to the server with data for processing.
- `FAILED`: This status is set after an observer hooked into the payment processing event returns a fail response. This in turn will end up causing the checkout `hasError` flag to be set to true.
- `ERROR`: This status is set after an observer hooked into the payment processing event returns an error response. This in turn will end up causing the checkout `hasError` flag to be set to true.
The `currentStatus` object has the following properties:
- `isPristine`: This is true when the current payment status is `PRISTINE`.
- `isStarted`: This is true when the current payment status is `STARTED`.
- `isProcessing`: This is true when the current payment status is `PROCESSING`.
- `isFinished`: This is true when the current payment status is one of `ERROR`, `FAILED`, or`SUCCESS`.
- `hasError`: This is true when the current payment status is `ERROR`.
- `hasFailed`: This is true when the current payment status is `FAILED`.
- `isSuccessful`: This is true when the current payment status is `SUCCESS`
### Emitting Events
Another tricky thing for extensibility, is providing opinionated, yet flexible interfaces for extensions to act and react to specific events in the flow. For stability, it's important that the core checkout flow _controls_ all communication to and from the server specific to checkout/order processing and leave extension specific requirements for the extension to handle. This allows for extensions to predictably interact with the checkout data and flow as needed without impacting other extensions hooking into it.
One of the most reliable ways to implement this type of extensibility is via the usage of an events system. Thus the various context providers:
- expose subscriber APIs for extensions to subscribe _observers_ to the events they want to react to.
- emit events at specific points of the checkout flow that in turn will feed data to the registered observers and, in some cases, react accordingly to the responses from observers.
One _**very important rule**_ when it comes to observers registered to any event emitter in this system is that they _cannot_ update context state. Updating state local to a specific component is okay but not any context or global state. The reason for this is that the observer callbacks are run sequentially at a specific point and thus subsequent observers registered to the same event will not react to any change in global/context state in earlier executed observers.
```jsx
const unsubscribe = emitter( myCallback );
```
You could substitute in whatever emitter you are registering for the `emitter` function. So for example if you are registering for the `onCheckoutValidationBeforeProcessing` event emitter, you'd have something like:
```jsx
const unsubscribe = onCheckoutValidationBeforeProcessing( myCallback );
```
You can also indicate what priority you want your observer to execute at. Lower priority is run before higher priority, so you can affect when your observer will run in the stack of observers registered to an emitter. You indicate priority via an number on the second argument:
```jsx
const unsubscribe = onCheckoutValidationBeforeProcessing( myCallback, 10 );
```
In the examples, `myCallback`, is your subscriber function. The subscriber function could receive data from the event emitter (described in the emitter details below) and may be expected to return a response in a specific shape (also described in the specific emitter details). The subscriber function can be a `Promise` and when the event emitter cycles through the registered observers it will await for any registered Promise to resolve.
Finally, the return value of the call to the emitter function is an unsubscribe function that can be used to unregister your observer. This is especially useful in a React component context where you need to make sure you unsubscribe the observer on component unmount. An example is usage in a `useEffect` hook:
```jsx
const MyComponent = ( { onCheckoutValidationBeforeProcessing } ) => {
useEffect( () => {
const unsubscribe = onCheckoutValidationBeforeProcessing( () => true );
return unsubscribe;
}, [ onCheckoutValidationBeforeProcessing ] );
return null;
};
```
Feature: Data Store Migration - Payments (https://github.com/woocommerce/woocommerce-blocks/pull/6619) * Move paymentMethodDataProvider into a data store (https://github.com/woocommerce/woocommerce-blocks/pull/6208) * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Use correct key in payment method data context * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Fix linting issues Co-authored-by: Saad Tarhi <saad.trh@gmail.com> Co-authored-by: Alex Florisca <alex.florisca@automattic.com> * Rebase on the update/checkout-data-store branch & Fix failed payments (https://github.com/woocommerce/woocommerce-blocks/pull/6587) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Fix merge conflict error * Set & get the provider's state from our data store instead of React's useReducer (https://github.com/woocommerce/woocommerce-blocks/pull/6588) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Get payment method data directly from the data store instead of the usePaymentMethodDataContext hook (https://github.com/woocommerce/woocommerce-blocks/pull/6589) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file * Get payment method state from data store in the checkout submit hook * Copy types.ts file into the payment data store folder * Fix isExpressPaymentMethodActive selector * Move the entire currentStatus into the data store * Replace the payment context state with the data store * Fix getActiveSavedToken & clean up the context file * Use the accutrate name of the "createErrorNotice" * Update the payment method data store key import * Diable unused state from the context Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Refactor the payment method data store & context (https://github.com/woocommerce/woocommerce-blocks/pull/6607) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file * Get payment method state from data store in the checkout submit hook * Copy types.ts file into the payment data store folder * Fix isExpressPaymentMethodActive selector * Move the entire currentStatus into the data store * Replace the payment context state with the data store * Fix getActiveSavedToken & clean up the context file * Use the accutrate name of the "createErrorNotice" * Update the payment method data store key import * Diable unused state from the context * Get enabled customer payment methods using data store selector * Remove remaining useReducer action from the dispatchers file * Update types and remove unused vars * Remove the payment method dispatchers hook * Refactor & clean up (remove unused files) * Remove commented line from payment methods types * Move event emitter into thunks Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Remove checkout-state after merge conflicts * Fix linting errors * Move types to types.ts * Move default states into respective store folders * Fix types and add comment * Move setExpressPaymentError to payment-methods store * fix express payment methods not showing up * Check if payment method is active from the state * Add comments * Remove commented out code in payment method data context * Display an error in the check-payment-methods directly from data store * Remove use-emit-response hook and move utils in event-emit/utils.ts * Use correct action property to remove payment methods * Fix formatting * Only try to initialize payment methods when cart is done loading * Add function to order payment methods from server * Add payment methods in the correct order * Prevent adding registered payment methods before cart is ready * Ensure payment methods get removed from state when deregistered * Reorder setting default payment methods to add customer methods first * Get customer methods from store not context * Remove error from payment-method state and associated selectors * Remove use-payment-method-registration and update the payment method state to remove the duplicated registeredPaymentMethods * Remove errorMessage from payment-methods store * Rename customerPaymentMethods -> savedPaymentMethods * Order payment methods when validating * Refactor payment-methods.js * Fix "Payment methods not set in editor" woocommerce/woocommerce-blocks#6655 bug We never get to load the payment methods object in the editor mode because there are no cart totals to load. * Initialize payment methods when available payments are loaded * Remove duplicate code * Fix data store state mutation anti-pattern A Redux rule is to never mutate the state in a reducer to avoid any unexpected results * Set availablePaymentMethods to the paymentMethods object Instead of its keys. We can get the keys using "Object.keys". * Use the available ordered payment methods The `getPaymentMethods` & `getExpressPaymentMethods` may include unordored & unavailable payment methods. * Get the correct value from the emit event response Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Saad Tarhi <saad.trh@gmail.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2022-07-08 05:53:24 +00:00
**`Event Emitter Utilities`**
Feature: Data Store Migration - Payments (https://github.com/woocommerce/woocommerce-blocks/pull/6619) * Move paymentMethodDataProvider into a data store (https://github.com/woocommerce/woocommerce-blocks/pull/6208) * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Use correct key in payment method data context * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Fix linting issues Co-authored-by: Saad Tarhi <saad.trh@gmail.com> Co-authored-by: Alex Florisca <alex.florisca@automattic.com> * Rebase on the update/checkout-data-store branch & Fix failed payments (https://github.com/woocommerce/woocommerce-blocks/pull/6587) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Fix merge conflict error * Set & get the provider's state from our data store instead of React's useReducer (https://github.com/woocommerce/woocommerce-blocks/pull/6588) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Get payment method data directly from the data store instead of the usePaymentMethodDataContext hook (https://github.com/woocommerce/woocommerce-blocks/pull/6589) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file * Get payment method state from data store in the checkout submit hook * Copy types.ts file into the payment data store folder * Fix isExpressPaymentMethodActive selector * Move the entire currentStatus into the data store * Replace the payment context state with the data store * Fix getActiveSavedToken & clean up the context file * Use the accutrate name of the "createErrorNotice" * Update the payment method data store key import * Diable unused state from the context Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Refactor the payment method data store & context (https://github.com/woocommerce/woocommerce-blocks/pull/6607) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file * Get payment method state from data store in the checkout submit hook * Copy types.ts file into the payment data store folder * Fix isExpressPaymentMethodActive selector * Move the entire currentStatus into the data store * Replace the payment context state with the data store * Fix getActiveSavedToken & clean up the context file * Use the accutrate name of the "createErrorNotice" * Update the payment method data store key import * Diable unused state from the context * Get enabled customer payment methods using data store selector * Remove remaining useReducer action from the dispatchers file * Update types and remove unused vars * Remove the payment method dispatchers hook * Refactor & clean up (remove unused files) * Remove commented line from payment methods types * Move event emitter into thunks Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Remove checkout-state after merge conflicts * Fix linting errors * Move types to types.ts * Move default states into respective store folders * Fix types and add comment * Move setExpressPaymentError to payment-methods store * fix express payment methods not showing up * Check if payment method is active from the state * Add comments * Remove commented out code in payment method data context * Display an error in the check-payment-methods directly from data store * Remove use-emit-response hook and move utils in event-emit/utils.ts * Use correct action property to remove payment methods * Fix formatting * Only try to initialize payment methods when cart is done loading * Add function to order payment methods from server * Add payment methods in the correct order * Prevent adding registered payment methods before cart is ready * Ensure payment methods get removed from state when deregistered * Reorder setting default payment methods to add customer methods first * Get customer methods from store not context * Remove error from payment-method state and associated selectors * Remove use-payment-method-registration and update the payment method state to remove the duplicated registeredPaymentMethods * Remove errorMessage from payment-methods store * Rename customerPaymentMethods -> savedPaymentMethods * Order payment methods when validating * Refactor payment-methods.js * Fix "Payment methods not set in editor" woocommerce/woocommerce-blocks#6655 bug We never get to load the payment methods object in the editor mode because there are no cart totals to load. * Initialize payment methods when available payments are loaded * Remove duplicate code * Fix data store state mutation anti-pattern A Redux rule is to never mutate the state in a reducer to avoid any unexpected results * Set availablePaymentMethods to the paymentMethods object Instead of its keys. We can get the keys using "Object.keys". * Use the available ordered payment methods The `getPaymentMethods` & `getExpressPaymentMethods` may include unordored & unavailable payment methods. * Get the correct value from the emit event response Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Saad Tarhi <saad.trh@gmail.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2022-07-08 05:53:24 +00:00
There are a bunch of utility methods that can be used related to events. These are available in `assets/js/base/context/event-emit/utils.ts` and can be imported as follows:
```jsx
Feature: Data Store Migration - Payments (https://github.com/woocommerce/woocommerce-blocks/pull/6619) * Move paymentMethodDataProvider into a data store (https://github.com/woocommerce/woocommerce-blocks/pull/6208) * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Use correct key in payment method data context * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Fix linting issues Co-authored-by: Saad Tarhi <saad.trh@gmail.com> Co-authored-by: Alex Florisca <alex.florisca@automattic.com> * Rebase on the update/checkout-data-store branch & Fix failed payments (https://github.com/woocommerce/woocommerce-blocks/pull/6587) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Fix merge conflict error * Set & get the provider's state from our data store instead of React's useReducer (https://github.com/woocommerce/woocommerce-blocks/pull/6588) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Get payment method data directly from the data store instead of the usePaymentMethodDataContext hook (https://github.com/woocommerce/woocommerce-blocks/pull/6589) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file * Get payment method state from data store in the checkout submit hook * Copy types.ts file into the payment data store folder * Fix isExpressPaymentMethodActive selector * Move the entire currentStatus into the data store * Replace the payment context state with the data store * Fix getActiveSavedToken & clean up the context file * Use the accutrate name of the "createErrorNotice" * Update the payment method data store key import * Diable unused state from the context Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Refactor the payment method data store & context (https://github.com/woocommerce/woocommerce-blocks/pull/6607) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file * Get payment method state from data store in the checkout submit hook * Copy types.ts file into the payment data store folder * Fix isExpressPaymentMethodActive selector * Move the entire currentStatus into the data store * Replace the payment context state with the data store * Fix getActiveSavedToken & clean up the context file * Use the accutrate name of the "createErrorNotice" * Update the payment method data store key import * Diable unused state from the context * Get enabled customer payment methods using data store selector * Remove remaining useReducer action from the dispatchers file * Update types and remove unused vars * Remove the payment method dispatchers hook * Refactor & clean up (remove unused files) * Remove commented line from payment methods types * Move event emitter into thunks Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Remove checkout-state after merge conflicts * Fix linting errors * Move types to types.ts * Move default states into respective store folders * Fix types and add comment * Move setExpressPaymentError to payment-methods store * fix express payment methods not showing up * Check if payment method is active from the state * Add comments * Remove commented out code in payment method data context * Display an error in the check-payment-methods directly from data store * Remove use-emit-response hook and move utils in event-emit/utils.ts * Use correct action property to remove payment methods * Fix formatting * Only try to initialize payment methods when cart is done loading * Add function to order payment methods from server * Add payment methods in the correct order * Prevent adding registered payment methods before cart is ready * Ensure payment methods get removed from state when deregistered * Reorder setting default payment methods to add customer methods first * Get customer methods from store not context * Remove error from payment-method state and associated selectors * Remove use-payment-method-registration and update the payment method state to remove the duplicated registeredPaymentMethods * Remove errorMessage from payment-methods store * Rename customerPaymentMethods -> savedPaymentMethods * Order payment methods when validating * Refactor payment-methods.js * Fix "Payment methods not set in editor" woocommerce/woocommerce-blocks#6655 bug We never get to load the payment methods object in the editor mode because there are no cart totals to load. * Initialize payment methods when available payments are loaded * Remove duplicate code * Fix data store state mutation anti-pattern A Redux rule is to never mutate the state in a reducer to avoid any unexpected results * Set availablePaymentMethods to the paymentMethods object Instead of its keys. We can get the keys using "Object.keys". * Use the available ordered payment methods The `getPaymentMethods` & `getExpressPaymentMethods` may include unordored & unavailable payment methods. * Get the correct value from the emit event response Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Saad Tarhi <saad.trh@gmail.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2022-07-08 05:53:24 +00:00
import {
isSuccessResponse,
isErrorResponse,
isFailResponse,
noticeContexts,
responseTypes,
shouldRetry,
} from '@woocommerce/base-context';
};
```
Feature: Data Store Migration - Payments (https://github.com/woocommerce/woocommerce-blocks/pull/6619) * Move paymentMethodDataProvider into a data store (https://github.com/woocommerce/woocommerce-blocks/pull/6208) * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Use correct key in payment method data context * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Fix linting issues Co-authored-by: Saad Tarhi <saad.trh@gmail.com> Co-authored-by: Alex Florisca <alex.florisca@automattic.com> * Rebase on the update/checkout-data-store branch & Fix failed payments (https://github.com/woocommerce/woocommerce-blocks/pull/6587) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Fix merge conflict error * Set & get the provider's state from our data store instead of React's useReducer (https://github.com/woocommerce/woocommerce-blocks/pull/6588) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Get payment method data directly from the data store instead of the usePaymentMethodDataContext hook (https://github.com/woocommerce/woocommerce-blocks/pull/6589) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file * Get payment method state from data store in the checkout submit hook * Copy types.ts file into the payment data store folder * Fix isExpressPaymentMethodActive selector * Move the entire currentStatus into the data store * Replace the payment context state with the data store * Fix getActiveSavedToken & clean up the context file * Use the accutrate name of the "createErrorNotice" * Update the payment method data store key import * Diable unused state from the context Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Refactor the payment method data store & context (https://github.com/woocommerce/woocommerce-blocks/pull/6607) * Add checkout data store * wip on checkout data store * CheckoutContext now uses the checkout store * Investigated and removed setting the redirectUrl on the default state * update extension and address hooks to use checkout data store * use checkout data store in checkout-processor and use-checkout-button * trim useCheckoutContext from use-payment-method-interface && use-store-cart-item-quantity * Remove useCheckoutContext from shipping provider * Remove isCalculating from state * Removed useCheckoutContext from lots of places * Remove useCheckoutContext from checkout-payment-block * Remove useCheckoutContext in checkout-shipping-methods-block and checkout-shipping-address-block * add isCart selector and action and update the checkoutstate context * Fixed redirectUrl bug by using thunks * Remove dispatchActions from checkout-state * Change SET_HAS_ERROR action to be neater * Thomas' feedback * Tidy up * Oops, deleted things I shouldn't have * Typescript * Fix types * Fix tests * Remove isCart * Update docs and remove unecessary getRedirectUrl() selector * set correct type for preloadedCheckoutData * Remove duplicate Address type * Fix missing addresses from type-defs index * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update docs/block-client-apis/checkout/checkout-api.md Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Revert feedback changes * REvert feedback formatting * Update docs formatting * Fix typographical error on LegacyRegisterExpressPaymentMethodFunction type * Add default state for PaymentMethod data store * Add preliminary action types * Add preliminary action dispatchers * Create payment method data store * Add preliminary reducers for payment method data store * Add preliminary selectors for payment method data store * Add reducers/actions for registering payment methods * Export payment method data store key * Add test for payment method data reducers * Add shouldSavePaymentMethod selector * Add store key as constant * Add more action types for registering and initializing payment methods * Get active payment method from data store instead of from context * Add registered methods to default state of payment method data store * Dispatch name of registered payment method to payment method data store * Remove setShouldSavePayment from payment method dispatcher and types * Get payment methods from registry instead of payment context * Add available payment methods to store * Add function to check whether payment methods are allowed to be used * Add selector to check if payments are initialised * Remove resolvers and add controls to payment method data store * Change type of payment requirements to string[] * Turn addRegistered and addRegisteredExpress into generators This is so we can check each payment method's validity before adding it to the list of available payment methods * Add action type for setting express payments as initialized * Only select from available methods in payment method options * Remove argument from addRegisteredPaymentMethod in payment method registry * Rename folder and store name to not contain the word data * Add selectors for express payment methods and their initialisation * Delete controls again in favour of thunks * Rename payment-method-data to payment-methdods * Create new setDefaultPaymentMethod function This will set the payment method when the cart loads. * Add CustomerPaymentMethodConfiguration type * Make getAvailableExpressPaymentMethods return correct data * Check express methods and normal methods when cart changes * Add action for setting active express payment methods * Handle express methods in checkPaymentMethodCanPay * Hide express payments area if none are available * Add selector for paymentMethodData * Add customer data to default state and add selector for it * Add setPaymentStatus action and reducer case * Set the default payment method when one isn't selected * Correct types on getCustomerPaymentMethods * Set status in data store alongside context status * Comment out active gateway selection - remove later * Set status in express payment methods in data store * Directly check payment methods from the list in blocks-registry * Add semicolon to import statement * Fix payment method data state call * Get paymentMethodData from store not context * Add addPaymentMethodData action/reducer case * Update payment method on payment success * Add 'getCurrentStatus' selector * Remove the temporary solution For getting payment method data into the data store * Prevent the 'success' context action from being dispatched * Update the "setPaymentStatus" data store action Accept status as an object instead of string * Fix the "currentStatus" reducer state update value * Get payment data into data store * Set the correct payment status to data store * Get the success status of payment from data store * Use store data in the payment dispatchers Replace the React useReducers action in the payment dispatchers file with the payment method data store * Get payment status from data store * Use data store for the payment error status * Use payment data store failed status * Use payment data store for the isFinished status * Update the setPaymentStatus argument * Set up setRegisteredPaymentMethods in data store * Use the data store version of the registeredPaymentMethods * Fix the default state type of the registeredPaymentMethods * Set up setRegisteredExpressPaymentMethod in data store * Use the data version of the registred express payment methods * Set the correct action type for removing payment methods * Fix default state express payment methods type * Use the store data version of activePaymentMethod * Use setActivePaymentMethod in the dispatchers file And refactor code * Update payment status arguments for express payment methods * Use paymentMethodData from the data store * Use payment method's errorMessage from data store * Update paymentMethods list in data store reducer * Replace remaining payment context data with data store * Clean up payment method context file * Get payment method state from data store in the checkout submit hook * Copy types.ts file into the payment data store folder * Fix isExpressPaymentMethodActive selector * Move the entire currentStatus into the data store * Replace the payment context state with the data store * Fix getActiveSavedToken & clean up the context file * Use the accutrate name of the "createErrorNotice" * Update the payment method data store key import * Diable unused state from the context * Get enabled customer payment methods using data store selector * Remove remaining useReducer action from the dispatchers file * Update types and remove unused vars * Remove the payment method dispatchers hook * Refactor & clean up (remove unused files) * Remove commented line from payment methods types * Move event emitter into thunks Co-authored-by: Alex Florisca <alex.florisca@automattic.com> Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com> * Remove checkout-state after merge conflicts * Fix linting errors * Move types to types.ts * Move default states into respective store folders * Fix types and add comment * Move setExpressPaymentError to payment-methods store * fix express payment methods not showing up * Check if payment method is active from the state * Add comments * Remove commented out code in payment method data context * Display an error in the check-payment-methods directly from data store * Remove use-emit-response hook and move utils in event-emit/utils.ts * Use correct action property to remove payment methods * Fix formatting * Only try to initialize payment methods when cart is done loading * Add function to order payment methods from server * Add payment methods in the correct order * Prevent adding registered payment methods before cart is ready * Ensure payment methods get removed from state when deregistered * Reorder setting default payment methods to add customer methods first * Get customer methods from store not context * Remove error from payment-method state and associated selectors * Remove use-payment-method-registration and update the payment method state to remove the duplicated registeredPaymentMethods * Remove errorMessage from payment-methods store * Rename customerPaymentMethods -> savedPaymentMethods * Order payment methods when validating * Refactor payment-methods.js * Fix "Payment methods not set in editor" woocommerce/woocommerce-blocks#6655 bug We never get to load the payment methods object in the editor mode because there are no cart totals to load. * Initialize payment methods when available payments are loaded * Remove duplicate code * Fix data store state mutation anti-pattern A Redux rule is to never mutate the state in a reducer to avoid any unexpected results * Set availablePaymentMethods to the paymentMethods object Instead of its keys. We can get the keys using "Object.keys". * Use the available ordered payment methods The `getPaymentMethods` & `getExpressPaymentMethods` may include unordored & unavailable payment methods. * Get the correct value from the emit event response Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> Co-authored-by: Saad Tarhi <saad.trh@gmail.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2022-07-08 05:53:24 +00:00
The helper functions are described below:
- `isSuccessResponse`, `isErrorResponse` and `isFailResponse`: These are helper functions that receive a value and report via boolean whether the object is a type of response expected. For event emitters that receive responses from registered observers, a `type` property on the returned object from the observer indicates what type of response it is and event emitters will react according to that type. So for instance if an observer returned `{ type: 'success' }` the emitter could feed that to `isSuccessResponse` and it would return `true`. You can see an example of this being implemented for the payment processing emitted event [here](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/assets/js/base/context/cart-checkout/payment-methods/payment-method-data-context.js#L281-L307).
- `noticeContexts`: This is an object containing properties referencing areas where notices can be targeted in the checkout. The object has the following properties:
- `PAYMENTS`: This is a reference to the notice area in the payment methods step.
- `EXPRESS_PAYMENTS`: This is a reference to the notice area in the express payment methods step.
- `responseTypes`: This is an object containing properties referencing the various response types that can be returned by observers for some event emitters. It makes it easier for autocompleting the types and avoiding typos due to human error. The types are `SUCCESS`, `FAIL`, `ERROR`. The values for these types also correspond to the [payment status types](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/src/Payments/PaymentResult.php#L21) from the [checkout endpoint response from the server](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/src/RestApi/StoreApi/Schemas/CheckoutSchema.php#L103-L113).
- `shouldRetry`: This is a function containing the logic whether the checkout flow should allow the user to retry the payment after a previous payment failed. It receives the `response` object and by default checks whether the `retry` property is true/undefined or false. Refer to the [`onCheckoutAfterProcessingWithSuccess`](#oncheckoutafterprocessingwithsuccess) documentation for more details.
Note: `noticeContexts` and `responseTypes` are exposed to payment methods via the `emitResponse` prop given to their component:
```jsx
const MyPaymentMethodComponent = ( { emitResponse } ) => {
const { noticeContexts, responseTypes } = emitResponse;
// other logic for payment method...
};
```
The following event emitters are available to extensions to register observers to:
### `onCheckoutValidationBeforeProcessing`
Observers registered to this event emitter will receive nothing as an argument. Also, all observers will be executed before the checkout handles the responses from the emitters. Observers registered to this emitter can return `true` if they have nothing to communicate back to checkout, `false` if they want checkout to go back to `IDLE` status state, or an object with any of the following properties:
- `errorMessage`: This will be added as an error notice on the checkout context.
- `validationErrors`: This will be set as inline validation errors on checkout fields. If your observer wants to trigger validation errors it can use the following shape for the errors:
- This is an object where keys are the property names the validation error is for (that correspond to a checkout field, eg `country` or `coupon`) and values are the error message describing the validation problem.
This event is emitted when the checkout status is `BEFORE_PROCESSING` (which happens at validation time, after the checkout form submission is triggered by the user - or Express Payment methods).
If all observers return `true` for this event, then the checkout status will be changed to `PROCESSING`.
This event emitter subscriber can be obtained via the checkout context using the `useCheckoutContext` hook or to payment method extensions as a prop on their registered component:
_For internal development:_
```jsx
import { useCheckoutContext } from '@woocommerce/base-contexts';
import { useEffect } from '@wordpress/element';
const Component = () => {
const { onCheckoutValidationBeforeProcessing } = useCheckoutContext();
useEffect( () => {
const unsubscribe = onCheckoutValidationBeforeProcessing( () => true );
return unsubscribe;
}, [ onCheckoutValidationBeforeProcessing ] );
return null;
};
```
_For registered payment method components:_
```jsx
import { useEffect } from '@wordpress/element';
const PaymentMethodComponent = ( { eventRegistration } ) => {
const { onCheckoutValidationBeforeProcessing } = eventRegistration;
useEffect( () => {
const unsubscribe = onCheckoutValidationBeforeProcessing( () => true );
return unsubscribe;
}, [ onCheckoutValidationBeforeProcessing ] );
};
```
### `onPaymentProcessing`
This event emitter is fired when the payment method context status is `PROCESSING` and that status is set when the checkout status is `PROCESSING`, checkout `hasError` is false, checkout is not calculating, and the current payment status is not `FINISHED`.
This event emitter will execute through each registered observer (passing in nothing as an argument) _until_ an observer returns a non-truthy value at which point it will _abort_ further execution of registered observers.
When a payment method returns a non-truthy value, if it returns a valid response type the event emitter will update various internal statuses according to the response. Here's the possible response types that will get handled by the emitter:
#### Success
A response is considered a success response when it at a minimum is an object with this shape:
```js
const successResponse = { type: 'success' };
```
When a success response is returned, the payment method context status will be changed to `SUCCESS`. In addition, including any of the additional properties will result in extra actions:
- `paymentMethodData`: The contents of this object will be included as the value for `payment_data` when checkout sends a request to the checkout endpoint for processing the order. This is useful if a payment method does additional server side processing.
- `billingData`: This allows payment methods to update any billing data information in the checkout (typically used by Express payment methods) so it's included in the checkout processing request to the server. This data should be in the [shape outlined here](../../../../assets/js/types/type-defs/billing.js).
- `shippingData`: This allows payment methods to update any shipping data information for the order (typically used by Express payment methods) so it's included in the checkout processing request to the server. This data should be in the [shape outlined here](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/assets/js/type-defs/cart.js#L20-L32).
If `billingData` or `shippingData` properties aren't in the response object, then the state for the data is left alone.
#### Fail
A response is considered a fail response when it at a minimum is an object with this shape:
```js
const failResponse = { type: 'failure' };
```
When a fail response is returned by an observer, the payment method context status will be changed to `FAIL`. In addition, including any of the following properties will result in extra actions:
- `message`: The string provided here will be set as an error notice in the checkout.
- `messageContext`: If provided, this will target the given area for the error notice (this is where `noticeContexts` mentioned earlier come in to play). Otherwise the notice will be added to the `noticeContexts.PAYMENTS` area.
- `paymentMethodData`: (same as for success responses).
- `billingData`: (same as for success responses).
#### Error
A response is considered an error response when it at a minimum is an object with this shape:
```js
const errorResponse = { type: 'error' };
```
When an error response is returned by an observer, the payment method context status will be changed to `ERROR`. In addition, including any of the following properties will result in extra actions:
- `message`: The string provided here will be set as an error notice.
- `messageContext`: If provided, this will target the given area for the error notice (this is where `noticeContexts` mentioned earlier come in to play). Otherwise, the notice will be added to the `noticeContexts.PAYMENTS` area.
- `validationErrors`: This will be set as inline validation errors on checkout fields. If your observer wants to trigger validation errors it can use the following shape for the errors:
- This is an object where keys are the property names the validation error is for (that correspond to a checkout field, eg `country` or `coupon`) and values are the error message describing the validation problem.
If the response object doesn't match any of the above conditions, then the fallback is to set the payment status as `SUCCESS`.
When the payment status is set to `SUCCESS` and the checkout status is `PROCESSING`, the `CheckoutProcessor` component will trigger the request to the server for processing the order.
This event emitter subscriber can be obtained via the checkout context using the `usePaymentEventsContext` hook or to payment method extensions as a prop on their registered component:
_For internal development:_
```jsx
import { usePaymentEventsContext } from '@woocommerce/base-contexts';
import { useEffect } from '@wordpress/element';
const Component = () => {
const { onPaymentProcessing } = usePaymentEventsContext();
useEffect( () => {
const unsubscribe = onPaymentProcessing( () => true );
return unsubscribe;
}, [ onPaymentProcessing ] );
return null;
};
```
_For registered payment method components:_
```jsx
import { useEffect } from '@wordpress/element';
const PaymentMethodComponent = ( { eventRegistration } ) => {
const { onPaymentMethodProcessing } = eventRegistration;
useEffect( () => {
const unsubscribe = onPaymentMethodProcessing( () => true );
return unsubscribe;
}, [ onPaymentMethodProcessing ] );
};
```
### `onCheckoutAfterProcessingWithSuccess`
This event emitter is fired when the checkout context status is `AFTER_PROCESSING` and the checkout `hasError` state is false. The `AFTER_PROCESSING` status is set by the `CheckoutProcessor` component after receiving a response from the server for the checkout processing request.
Observers registered to this event emitter will receive the following object as an argument:
```js
const onCheckoutProcessingData = {
redirectUrl,
orderId,
customerId,
orderNotes,
paymentResult,
};
```
The properties are:
- `redirectUrl`: This is a string that is the url the checkout will redirect to as returned by the processing on the server.
- `orderId`: Is the id of the current order being processed.
- `customerId`: Is the id for the customer making the purchase (that is attached to the order).
- `orderNotes`: This will be any custom note the customer left on the order.
- `paymentResult`: This is the value of [`payment_result` from the /checkout StoreApi response](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/src/RestApi/StoreApi/Schemas/CheckoutSchema.php#L103-L138). The data exposed on this object is (via the object properties):
- `paymentStatus`: Whatever the status is for the payment after it was processed server side. Will be one of `success`, `failure`, `pending`, `error`.
- `paymentDetails`: This will be an arbitrary object that contains any data the payment method processing server side sends back to the client in the checkout processing response. Payment methods are able to hook in on the processing server side and set this data for returning.
This event emitter will invoke each registered observer until a response from any of the registered observers does not equal `true`. At that point any remaining non-invoked observers will be skipped and the response from the observer triggering the abort will be processed.
This emitter will handle a `success` response type (`{ type: success }`) by setting the checkout status to `COMPLETE`. Along with that, if the response includes `redirectUrl` then the checkout will redirect to the given address.
This emitter will also handle a `failure` response type or an `error` response type and if no valid type is detected it will treat it as an `error` response type.
In all cases, if there are the following properties in the response, additional actions will happen:
- `message`: This string will be added as an error notice.
- `messageContext`: If present, the notice will be configured to show in the designated notice area (otherwise it will just be a general notice for the checkout block).
- `retry`: If this is `true` or not defined, then the checkout status will be set to `IDLE`. This basically means that the error is recoverable (for example try a different payment method) and so checkout will be reset to `IDLE` for another attempt by the shopper. If this is `false`, then the checkout status is set to `COMPLETE` and the checkout will redirect to whatever is currently set as the `redirectUrl`.
- `redirectUrl`: If this is present, then the checkout will redirect to this url when the status is `COMPLETE`.
If all observers return `true`, then the checkout status will just be set to `COMPLETE`.
This event emitter subscriber can be obtained via the checkout context using the `useCheckoutContext` hook or to payment method extensions as a prop on their registered component:
_For internal development:_
```jsx
import { useCheckoutContext } from '@woocommerce/base-contexts';
import { useEffect } from '@wordpress/element';
const Component = () => {
const { onCheckoutAfterProcessingWithSuccess } = useCheckoutContext();
useEffect( () => {
const unsubscribe = onCheckoutAfterProcessingWithSuccess( () => true );
return unsubscribe;
}, [ onCheckoutAfterProcessingWithSuccess ] );
return null;
};
```
_For registered payment method components:_
```jsx
import { useEffect } from '@wordpress/element';
const PaymentMethodComponent = ( { eventRegistration } ) => {
const { onCheckoutAfterProcessingWithSuccess } = eventRegistration;
useEffect( () => {
const unsubscribe = onCheckoutAfterProcessingWithSuccess( () => true );
return unsubscribe;
}, [ onCheckoutAfterProcessingWithSuccess ] );
};
```
### `onCheckoutAfterProcessingWithError`
This event emitter is fired when the checkout context status is `AFTER_PROCESSING` and the checkout `hasError` state is `true`. The `AFTER_PROCESSING` status is set by the `CheckoutProcessor` component after receiving a response from the server for the checkout processing request.
Observers registered to this emitter will receive the same data package as those registered to `onCheckoutAfterProcessingWithSuccess`.
The response from the first observer returning a value that does not `===` true will be handled similarly as the `onCheckoutAfterProcessingWithSuccess` except it only handles when the type is `error` or `failure`.
If all observers return `true`, then the checkout status will just be set to `IDLE` and a default error notice will be shown in the checkout context.
This event emitter subscriber can be obtained via the checkout context using the `useCheckoutContext` hook or to payment method extensions as a prop on their registered component:
_For internal development:_
```jsx
import { useCheckoutContext } from '@woocommerce/base-contexts';
import { useEffect } from '@wordpress/element';
const Component = () => {
const { onCheckoutAfterProcessingWithError } = useCheckoutContext();
useEffect( () => {
const unsubscribe = onCheckoutAfterProcessingWithError( () => true );
return unsubscribe;
}, [ onCheckoutAfterProcessingWithError ] );
return null;
};
```
_For registered payment method components:_
```jsx
import { useEffect } from '@wordpress/element';
const PaymentMethodComponent = ( { eventRegistration } ) => {
const { onCheckoutAfterProcessingWithError } = eventRegistration;
useEffect( () => {
const unsubscribe = onCheckoutAfterProcessingWithError( () => true );
return unsubscribe;
}, [ onCheckoutAfterProcessingWithError ] );
};
```
### `onShippingRateSuccess`
This event emitter is fired when shipping rates are not loading and the shipping data context error state is `NONE` and there are shipping rates available.
This event emitter doesn't care about any registered observer response and will simply execute all registered observers passing them the current shipping rates retrieved from the server.
### `onShippingRateFail`
This event emitter is fired when shipping rates are not loading and the shipping data context error state is `UNKNOWN` or `INVALID_ADDRESS`.
This event emitter doesn't care about any registered observer response and will simply execute all registered observers passing them the current error status in the context.
### `onShippingRateSelectSuccess`
This event emitter is fired when a shipping rate selection is not being persisted to the server and there are selected rates available and the current error status in the context is `NONE`.
This event emitter doesn't care about any registered observer response and will simply execute all registered observers passing them the current selected rates.
### `onShippingRateSelectFail`
This event emitter is fired when a shipping rate selection is not being persisted to the server and the shipping data context error state is `UNKNOWN` or `INVALID_ADDRESS`.
This event emitter doesn't care about any registered observer response and will simply execute all registered observers passing them the current error status in the context.
<!-- FEEDBACK -->
---
[We're hiring!](https://woocommerce.com/careers/) Come work with us!
🐞 Found a mistake, or have a suggestion? [Leave feedback about this document here.](https://github.com/woocommerce/woocommerce-blocks/issues/new?assignees=&labels=type%3A+documentation&template=--doc-feedback.md&title=Feedback%20on%20./docs/internal-developers/block-client-apis/checkout/checkout-flow-and-events.md)
<!-- /FEEDBACK -->