woocommerce/plugins/woocommerce-blocks/assets/js/data/cart/reducers.ts

190 lines
4.2 KiB
TypeScript
Raw Normal View History

Update and select shipping rates dynamically (https://github.com/woocommerce/woocommerce-blocks/pull/1794) * add select shipping endpoint to router * add select shipping method * add selected rates to cart * better select rates * move schema function to seperate function * move validation to Cart Controller * fix wrong session key * Update shipping/cart endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/1833) * Items should not have keys in API response * Include package ID in response (this is just a basic index) * /cart/select-shipping-rate/package_id * Add package_id to package array * Update responses and add shipping-rates to main cart endpoint * update-shipping endpoint * Add querying selected shipping rate to the store (https://github.com/woocommerce/woocommerce-blocks/pull/1829) * add selecting shipping to store * directly call useSelectShippingRate * refactor cart keys transformation to reducer * remove selecting first result and accept selecting * move update shipping to new endpoint * pass selected rates down * select shipping right directly and fix editor issues * fix some broken prop types * key -> package id * Update and fix cart/shipping-rate tests * fix case for when rates are set * Update useShippingRates test * add args to rest endpoint * move selecting shipping rate logic to hook * fix some naming issues * update propTypes * update action call * fully watch cart state * address review issues * fix prop type issues * fix issue with rates not loading in checkout * remove extra package for shipping * move ShippingCalculatorOptions to outside Co-authored-by: Mike Jolley <mike.jolley@me.com> Co-authored-by: Albert Juhé Lluveras <aljullu@gmail.com>
2020-03-05 19:54:05 +00:00
/**
* External dependencies
*/
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
import type { CartItem } from '@woocommerce/types';
import type { Reducer } from 'redux';
Update and select shipping rates dynamically (https://github.com/woocommerce/woocommerce-blocks/pull/1794) * add select shipping endpoint to router * add select shipping method * add selected rates to cart * better select rates * move schema function to seperate function * move validation to Cart Controller * fix wrong session key * Update shipping/cart endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/1833) * Items should not have keys in API response * Include package ID in response (this is just a basic index) * /cart/select-shipping-rate/package_id * Add package_id to package array * Update responses and add shipping-rates to main cart endpoint * update-shipping endpoint * Add querying selected shipping rate to the store (https://github.com/woocommerce/woocommerce-blocks/pull/1829) * add selecting shipping to store * directly call useSelectShippingRate * refactor cart keys transformation to reducer * remove selecting first result and accept selecting * move update shipping to new endpoint * pass selected rates down * select shipping right directly and fix editor issues * fix some broken prop types * key -> package id * Update and fix cart/shipping-rate tests * fix case for when rates are set * Update useShippingRates test * add args to rest endpoint * move selecting shipping rate logic to hook * fix some naming issues * update propTypes * update action call * fully watch cart state * address review issues * fix prop type issues * fix issue with rates not loading in checkout * remove extra package for shipping * move ShippingCalculatorOptions to outside Co-authored-by: Mike Jolley <mike.jolley@me.com> Co-authored-by: Albert Juhé Lluveras <aljullu@gmail.com>
2020-03-05 19:54:05 +00:00
/**
* Internal dependencies
*/
import { ACTION_TYPES as types } from './action-types';
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 { defaultCartState, CartState } from './default-state';
import { EMPTY_CART_ERRORS } from '../constants';
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
import type { CartAction } from './actions';
/**
* Sub-reducer for cart items array.
*
* @param {Array<CartItem>} state cartData.items state slice.
* @param {CartAction} action Action object.
*/
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
const cartItemsReducer = (
state: Array< CartItem > = [],
action: Partial< CartAction >
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
) => {
switch ( action.type ) {
Support updating quantity of cart items & sold_individually product option (https://github.com/woocommerce/woocommerce-blocks/pull/1824) * first cut - removing an item from cart: - add actions to cart store for removing an item and keeping track of pending removal API call - add reducer logic for storing pending state on an item, and removing an item - expose removeCartItem on new useStoreCartItems hook - hook it up to remove link / trashcan icon in row item * disable cart quantity picker/remove link while API request in progress: - expose cart item pending status from store using selector - use selector to disable quantity related components in line item row * add typedef for cart items store object provided by hook * allow user to change quantity of cart items (first cut): - add action for replacing a cart item in the store - add generator action for changing quantity - expose change quantity action on useStoreCartItems hook - hook up to quantity UI in cart block (work in progress) * post-rebase fixes & fix broken typedef: - rework cart item change quantity callback - now supplies item key like remove callback - fix hook StoreCartItem return value typedef - single item with specified key, was array of all items - add quantity JSDoc for changeCartItemQuantity action - remove changeQuantity callback from UI (currently infinite looping) * fix bug in recieveCartItem reducer - check keys for equality: - was key === object * fix invalid url in POST cart/items/quantity request * hook up cart line item quantity to API: - remove internal state/ref for QuantitySelector, is now a controlled component - call changeQuantity action from QuantitySelector change callback * QuantitySelector no longer needs a ref to wrangle number input value * hoist quantity state out of QuantitySelector into story (fix storybook) * add product sold_individually option to cart item API response * limit sold_individually items to 1 per cart/order: - support optional max value in QuantitySelector - set maximum dependent on sold_individually API field * prevent user from requesting zero x cart item (API 500 errors): - add minimum limit to QuantitySelector - default limit to 1 + fix bug with limiting to maximum value in number input change handler * remove useStoreCartItems, zombie hook coming back from rebase 🧟‍♂️ * address various review feedback: - inline undefined check, don't use lodash - quantityInputOnKeyDown callback hook depends on canIncrease/canDecrease - also removed undefined check for minimum, as minimum has default 0 * use safer typeof check for presence of maximum prop
2020-03-03 01:08:19 +00:00
case types.RECEIVE_CART_ITEM:
// Replace specified cart element with the new data from server.
return state.map( ( cartItem ) => {
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
if ( cartItem.key === action.cartItem?.key ) {
Support updating quantity of cart items & sold_individually product option (https://github.com/woocommerce/woocommerce-blocks/pull/1824) * first cut - removing an item from cart: - add actions to cart store for removing an item and keeping track of pending removal API call - add reducer logic for storing pending state on an item, and removing an item - expose removeCartItem on new useStoreCartItems hook - hook it up to remove link / trashcan icon in row item * disable cart quantity picker/remove link while API request in progress: - expose cart item pending status from store using selector - use selector to disable quantity related components in line item row * add typedef for cart items store object provided by hook * allow user to change quantity of cart items (first cut): - add action for replacing a cart item in the store - add generator action for changing quantity - expose change quantity action on useStoreCartItems hook - hook up to quantity UI in cart block (work in progress) * post-rebase fixes & fix broken typedef: - rework cart item change quantity callback - now supplies item key like remove callback - fix hook StoreCartItem return value typedef - single item with specified key, was array of all items - add quantity JSDoc for changeCartItemQuantity action - remove changeQuantity callback from UI (currently infinite looping) * fix bug in recieveCartItem reducer - check keys for equality: - was key === object * fix invalid url in POST cart/items/quantity request * hook up cart line item quantity to API: - remove internal state/ref for QuantitySelector, is now a controlled component - call changeQuantity action from QuantitySelector change callback * QuantitySelector no longer needs a ref to wrangle number input value * hoist quantity state out of QuantitySelector into story (fix storybook) * add product sold_individually option to cart item API response * limit sold_individually items to 1 per cart/order: - support optional max value in QuantitySelector - set maximum dependent on sold_individually API field * prevent user from requesting zero x cart item (API 500 errors): - add minimum limit to QuantitySelector - default limit to 1 + fix bug with limiting to maximum value in number input change handler * remove useStoreCartItems, zombie hook coming back from rebase 🧟‍♂️ * address various review feedback: - inline undefined check, don't use lodash - quantityInputOnKeyDown callback hook depends on canIncrease/canDecrease - also removed undefined check for minimum, as minimum has default 0 * use safer typeof check for presence of maximum prop
2020-03-03 01:08:19 +00:00
return action.cartItem;
}
return cartItem;
} );
}
return state;
};
/**
* Reducer for receiving items related to the cart.
*
* @param {CartState} state The current state in the store.
* @param {CartAction} action Action object.
*
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
* @return {CartState} New or existing state.
*/
const reducer: Reducer< CartState > = (
state = defaultCartState,
action: Partial< CartAction >
) => {
switch ( action.type ) {
case types.SET_ERROR_DATA:
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
if ( action.error ) {
state = {
...state,
errors: [ action.error ],
};
}
break;
Add notice on quantity change and update `wc/store/cart` to use thunks (https://github.com/woocommerce/woocommerce-blocks/pull/7938) * Add receiveCart thunk * Add mapCartResponseToCart helper * Add getItemsPendingQuantityUpdate selector * Update cart resolvers to be thunks * Remove RECEIVE_CART action and replace with SET_CART_DATA receiveCart will turn into a thunk. * Add notifyQuantityChanges functions * Remove receiveCart from action type definition, replace with setCartData * Move apiFetchWithHeaders out of controls This will just be a normal function since we'll be updating actions to thunks which will use this instead of a control. * Include thunks in actions file * Update receiveCart action to setCartData * Update applyCoupon action to a thunk * Update useStoreCartCoupons to get action from correct place * Update StoreCartCoupon types * Add types for Thunk and ThunkReturnType in mapped-types * Change applyCoupon to a thunk * Get applyCoupon, removeCoupon, receiveApplyingCoupon from useDispatch This is to separate the concerns of actions vs. selectors. Previously the actions were fetched during useSelect which is not a pattern we use anywhere else in the codebase. Since we updated the MapToDispatch type, we can now get correctly typed thunks from the data store. * Improve apiFetchWithHeaders typings * Convert removeCoupon from generator to thunk * Add applyCoupon and removeCoupon to CartAction type * Remove unused old-style type-def * Add receiveApplyingCoupon & receiveRemovingCoupon to StoreCartCoupon * Correct issues with StoreCartCoupon type These were not intended to reflect the actions in data store, rather the functions offered by the useStoreCartCoupons hook. * Update applyExtensionCartUpdate to a thunk * Update addItemToCart to thunk * Add ResolveSelectFromMap type that works with thunks * Add CartDispatchFromMap and CartResolveSelectFromMap types We can add this to all data stores to get them working with thunks properly. * Add docs and update generic name in ResolveSelectFromMap * Add correct types for thunk resolvers in cart data store * Update removeItemFromCart to thunk * Update apiFetchWithHeaders to use generic * Update selectShippingRate to thunk * Update resolver tests to test correct thunk functionality * Update updateCustomerData to thunk * Update reducer test to reflect new action name * Update comments on CartDispatchFromMap and CartResolveSelectFromMap * Add quantity_limits to preview cart * Make notices speak when shown * Remove copilot comment * Add isWithinQuantityLimits function This is because we shouldn't show a notice if the quantity limits change, but the item's quantity is still OK. * Add tests for notifyQuantityChanges * Show notice when multiple_of is updated * Update test to test for multiple_of changes * Remove empty export * Remove controls from cart data store Not needed anymore since the exported value from the shared-controls file was empty. * Export a control and async function for apiFetchWithHeaders This is required because async functions cannot be called from sync generators. * Use control version of apiFetchWithHeaders in the collections store * Improve comments and remove incorrect TypeScript * Update assets/js/data/cart/actions.ts Co-authored-by: Mike Jolley <mike.jolley@me.com> * Update ResolveSelectFromMap to include selectors too * Update TS in actions * Use finally to remove duplicate code * remove item pending delete/qty update after action runs in all cases This will also reset the state when the request to remove it/change quantity errors * Remove unnecessary type from param. Not needed because we have TS now. The description can stay though, it is useful. * Update snackbar wording to use active voice * Remove old WP version check * Set max quantity to high number instead of null This would only happen in a niche case, and would require several TS changes to fix, so it's better to set it as a number here. 9999 should be high enough, and is the default quantity limit set below in get_product_quantity_limit * Set code on woocommerce_rest_cart_invalid_key to 409 This is so the cart is returned in the response, so the client can update. * Fix typo in comment and add CartSelectFromMap * Remove unnecessary docblock * Add getItemsPendingDelete selector This is needed so we can show a notice for items that are unexpectedly removed from the cart. We need to know which ones are pending delete so we can skip showing the notice for them. * Add type for notifyQuantityChanges args and change args to object * Add notifyIfRemoved function This will check items that have been removed and show a notice for them. * Fix TS in receiveCart & pass itemsPendingDelete to notifyQuantiyChanges * Update wording on removal notice * Update types for notifyQuantityChanges args * Update tests to reflect new wording and args being an object * Check item is truth before running comparison of keys * Update tests for unexpectedly and expectedly removed items * Ignore print_r to satisfy phpcs * Update PHP tests to reflect correct response code when deleting items * Remove unnecessary controls and dispatch events directly from thunk Co-authored-by: Mike Jolley <mike.jolley@me.com>
2022-12-16 16:06:37 +00:00
case types.SET_CART_DATA:
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
if ( action.response ) {
state = {
...state,
errors: EMPTY_CART_ERRORS,
cartData: {
...state.cartData,
...action.response,
},
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
};
}
break;
case types.APPLYING_COUPON:
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
if ( action.couponCode || action.couponCode === '' ) {
state = {
...state,
metaData: {
...state.metaData,
applyingCoupon: action.couponCode,
},
};
}
break;
case types.SET_BILLING_ADDRESS:
state = {
...state,
cartData: {
...state.cartData,
billingAddress: {
...state.cartData.billingAddress,
...action.billingAddress,
},
},
};
break;
case types.SET_SHIPPING_ADDRESS:
state = {
...state,
cartData: {
...state.cartData,
shippingAddress: {
...state.cartData.shippingAddress,
...action.shippingAddress,
},
},
};
break;
case types.REMOVING_COUPON:
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
if ( action.couponCode || action.couponCode === '' ) {
state = {
...state,
metaData: {
...state.metaData,
removingCoupon: action.couponCode,
},
};
}
break;
case types.ITEM_PENDING_QUANTITY:
// Remove key by default - handles isQuantityPending==false
// and prevents duplicates when isQuantityPending===true.
const keysPendingQuantity = state.cartItemsPendingQuantity.filter(
( key ) => key !== action.cartItemKey
);
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
if ( action.isPendingQuantity && action.cartItemKey ) {
keysPendingQuantity.push( action.cartItemKey );
}
state = {
...state,
cartItemsPendingQuantity: keysPendingQuantity,
};
break;
case types.RECEIVE_REMOVED_ITEM:
const keysPendingDelete = state.cartItemsPendingDelete.filter(
( key ) => key !== action.cartItemKey
);
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
if ( action.isPendingDelete && action.cartItemKey ) {
keysPendingDelete.push( action.cartItemKey );
}
state = {
...state,
cartItemsPendingDelete: keysPendingDelete,
};
break;
// Delegate to cartItemsReducer.
Support updating quantity of cart items & sold_individually product option (https://github.com/woocommerce/woocommerce-blocks/pull/1824) * first cut - removing an item from cart: - add actions to cart store for removing an item and keeping track of pending removal API call - add reducer logic for storing pending state on an item, and removing an item - expose removeCartItem on new useStoreCartItems hook - hook it up to remove link / trashcan icon in row item * disable cart quantity picker/remove link while API request in progress: - expose cart item pending status from store using selector - use selector to disable quantity related components in line item row * add typedef for cart items store object provided by hook * allow user to change quantity of cart items (first cut): - add action for replacing a cart item in the store - add generator action for changing quantity - expose change quantity action on useStoreCartItems hook - hook up to quantity UI in cart block (work in progress) * post-rebase fixes & fix broken typedef: - rework cart item change quantity callback - now supplies item key like remove callback - fix hook StoreCartItem return value typedef - single item with specified key, was array of all items - add quantity JSDoc for changeCartItemQuantity action - remove changeQuantity callback from UI (currently infinite looping) * fix bug in recieveCartItem reducer - check keys for equality: - was key === object * fix invalid url in POST cart/items/quantity request * hook up cart line item quantity to API: - remove internal state/ref for QuantitySelector, is now a controlled component - call changeQuantity action from QuantitySelector change callback * QuantitySelector no longer needs a ref to wrangle number input value * hoist quantity state out of QuantitySelector into story (fix storybook) * add product sold_individually option to cart item API response * limit sold_individually items to 1 per cart/order: - support optional max value in QuantitySelector - set maximum dependent on sold_individually API field * prevent user from requesting zero x cart item (API 500 errors): - add minimum limit to QuantitySelector - default limit to 1 + fix bug with limiting to maximum value in number input change handler * remove useStoreCartItems, zombie hook coming back from rebase 🧟‍♂️ * address various review feedback: - inline undefined check, don't use lodash - quantityInputOnKeyDown callback hook depends on canIncrease/canDecrease - also removed undefined check for minimum, as minimum has default 0 * use safer typeof check for presence of maximum prop
2020-03-03 01:08:19 +00:00
case types.RECEIVE_CART_ITEM:
state = {
...state,
errors: EMPTY_CART_ERRORS,
cartData: {
...state.cartData,
items: cartItemsReducer( state.cartData.items, action ),
},
};
break;
Sync shipping address with billing address when shipping address fields are disabled (https://github.com/woocommerce/woocommerce-blocks/pull/3358) * Correct docblock description * Sync shipping address changes with billing data * Update inline documentation * Revert address sync because it fails when shipping is disabled explicitely * Avoid loading shipping address from customer is shipping is disabled * Rather than update order from the wc/store/checkout request, update the customer object This is turn is synced to order, but also allows the cart calcultions to use the posted data. This means that taxes will be updated based on address data even if not displayed on the checkout. * Add action that combines billing and shipping updates * Add route for updating billing and shipping address * Sync billing data to server on change * Shared constants for billing data * Skip address update if missing country * Allow null values to skip formatting * Add billing to cart schema * Removed unwanted hooks from previous commit * Decoding is handled in useStoreCart * Remove hook * Make shipping context hold state * Make billing context hold state * Add address processors * Cart does not have billing * Update tests, remove some unrelated changes affecting the diff * Revert "Update inline documentation" This reverts commit 0393f49316de3152c6dcf6fda1192c06a74f1b55. * Make shippingRatesAreResolving conditonal based on API request * Shared address processor in cart and checkout * Rename REST endpoint * CustomerDataProvider and hook * Update shipping address type defs * Rename customer address endpoint, and remove update-shipping * Update tests * Fix tests by restoring country validation * typo * Update assets/js/base/hooks/cart/use-store-cart.js Co-authored-by: Darren Ethier <darren@roughsmootheng.in> * Simplify debounce and request handling * Remove state from address sync This will mean billing is "forgotten" if using the checbox, but this greatly simplifies logic. * Rename shipping rates loading to customer data loading * Sync based on useStoreCart data * Made cart API less strict on addresses * Fix useCheckoutAddress sync * Add note on currentShippingAsBilling * Use incoming isCart * Add more detailed inline comment for shippingAsBilling toggle event * Combine customer billing and shipping ref * Update address docblock * Error handling in pluckAddress * Fix cart response after rebase * Update customer tests * Update src/StoreApi/Routes/CartUpdateCustomer.php Co-authored-by: Darren Ethier <darren@roughsmootheng.in> Co-authored-by: Darren Ethier <darren@roughsmootheng.in>
2020-11-20 15:13:35 +00:00
case types.UPDATING_CUSTOMER_DATA:
Update and select shipping rates dynamically (https://github.com/woocommerce/woocommerce-blocks/pull/1794) * add select shipping endpoint to router * add select shipping method * add selected rates to cart * better select rates * move schema function to seperate function * move validation to Cart Controller * fix wrong session key * Update shipping/cart endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/1833) * Items should not have keys in API response * Include package ID in response (this is just a basic index) * /cart/select-shipping-rate/package_id * Add package_id to package array * Update responses and add shipping-rates to main cart endpoint * update-shipping endpoint * Add querying selected shipping rate to the store (https://github.com/woocommerce/woocommerce-blocks/pull/1829) * add selecting shipping to store * directly call useSelectShippingRate * refactor cart keys transformation to reducer * remove selecting first result and accept selecting * move update shipping to new endpoint * pass selected rates down * select shipping right directly and fix editor issues * fix some broken prop types * key -> package id * Update and fix cart/shipping-rate tests * fix case for when rates are set * Update useShippingRates test * add args to rest endpoint * move selecting shipping rate logic to hook * fix some naming issues * update propTypes * update action call * fully watch cart state * address review issues * fix prop type issues * fix issue with rates not loading in checkout * remove extra package for shipping * move ShippingCalculatorOptions to outside Co-authored-by: Mike Jolley <mike.jolley@me.com> Co-authored-by: Albert Juhé Lluveras <aljullu@gmail.com>
2020-03-05 19:54:05 +00:00
state = {
...state,
metaData: {
...state.metaData,
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
updatingCustomerData: !! action.isResolving,
Update and select shipping rates dynamically (https://github.com/woocommerce/woocommerce-blocks/pull/1794) * add select shipping endpoint to router * add select shipping method * add selected rates to cart * better select rates * move schema function to seperate function * move validation to Cart Controller * fix wrong session key * Update shipping/cart endpoints (https://github.com/woocommerce/woocommerce-blocks/pull/1833) * Items should not have keys in API response * Include package ID in response (this is just a basic index) * /cart/select-shipping-rate/package_id * Add package_id to package array * Update responses and add shipping-rates to main cart endpoint * update-shipping endpoint * Add querying selected shipping rate to the store (https://github.com/woocommerce/woocommerce-blocks/pull/1829) * add selecting shipping to store * directly call useSelectShippingRate * refactor cart keys transformation to reducer * remove selecting first result and accept selecting * move update shipping to new endpoint * pass selected rates down * select shipping right directly and fix editor issues * fix some broken prop types * key -> package id * Update and fix cart/shipping-rate tests * fix case for when rates are set * Update useShippingRates test * add args to rest endpoint * move selecting shipping rate logic to hook * fix some naming issues * update propTypes * update action call * fully watch cart state * address review issues * fix prop type issues * fix issue with rates not loading in checkout * remove extra package for shipping * move ShippingCalculatorOptions to outside Co-authored-by: Mike Jolley <mike.jolley@me.com> Co-authored-by: Albert Juhé Lluveras <aljullu@gmail.com>
2020-03-05 19:54:05 +00:00
},
};
break;
case types.UPDATING_SELECTED_SHIPPING_RATE:
state = {
...state,
metaData: {
...state.metaData,
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
updatingSelectedRate: !! action.isResolving,
},
};
Ensure cart changes remain after using back button to get back to the cart (https://github.com/woocommerce/woocommerce-blocks/pull/3960) * Add cartUpdate middleware * Include timestamp for when cart data was generated * Add getCartFromApi action * Check whether cart can be hydrated or needs to be fetched from API * Add cartDataIsStale action and remove getCartFromApi action * Add isCartDataStale selector * Don't load cart until staleness check is complete * Add comment to ease worry about locaStorage execution * Correct doc block and fix typographical error * Cater for lastCartUpdate or the timestamp being undefined * Include @woocommerce/api and @woocommerce/e2e-utils * Add getNormalPagePermalink test utility This will allow us to get the permalink of a "normal" page, i.e. one that is not using the block editor. * Add getBlockPagePermalink test utility This will get the permalink for a page using the Block editor. * Emit action to update cart staleness in all execution paths * Add visitPostOfType function This will allow us to visit the editor page for a post based on its name and post type. * Add functions to get permalinks from editor pages * Add front-end tests for cart * Update package-lock.json * Create local function to ensure the page permalink is visible * Change functions for getting permalinks They were often failing for unknown reasons, these _somehow_ make them more stable. * Add logging for GitHub actions * Add more logging for tests * Add more logging for tests * Add more logging for tests * Wait for networkidle on back * Remove logging except timestamp * Wait for timestamp to be added to localStorage * Split tests to make runs slightly shorter * Wait for add to cart request before continuing test * Fix formatting in cart.test.js * Rename cartDataStale to setIsCartDataStale * Create constant for localStorage timestamp name * Rename cartDataIsStale to isCartDataStale This is for consistency, the action to change this is called setIsCartDataStale - I think this reads better. * Use cleaner logic when determining if the cart should render or fetch * Change docblock for isCartDataStale selector * Remove boolean cast from SET_IS_CART_DATA_STALE reducer * Set longer timeouts for frontend cart tests * Enclose cart staleness checks in condition/prevent unnecessary execution * Remove unnecessary boolean cast from selector * Use constant for local storage key in tests * Use new localstorage key in tests. cant access constants in page context
2021-03-24 13:28:11 +00:00
break;
case types.SET_IS_CART_DATA_STALE:
state = {
...state,
metaData: {
...state.metaData,
isCartDataStale: action.isCartDataStale,
},
};
break;
}
return state;
};
export type State = ReturnType< typeof reducer >;
export default reducer;