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

215 lines
5.6 KiB
TypeScript
Raw Normal View History

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
/**
* External dependencies
*/
Try move shipping related dat to a `@wordpress/data` store (https://github.com/woocommerce/woocommerce-blocks/pull/5896) * Add address-related items to wc/store/cart data store * Add useUpdateCustomerData hook This allows us to have a single hook responsible for updating the customer information on the server. * Add useUpdateCustomerData hook in Checkout block * Remove shippingAsBilling from previousCustomerData ref type * Add useShippingAsBillingCheckbox hook * Remove checkbox handling from useCheckoutAddress * Merge with woocommerce/woocommerce-blocks#5810 changes * Move shipping as billing to checkout state context provider * Subscribe to changes * Cache customerDataToUpdate * Combine customerDataType and customerDataContextType * Fix notice context * Clean up inline docs for push changes * Add useShippingData hook * Add shipping related selectors to cart store * Update useShippingDataContext to useCustomerData hook * Update uses of useShippingDataContext to get data from hook instead * Remove rogue linebreak * Re-add linebreak * Re-add linebreak, remove shippingAsBilling * Re-add linebreak * Use useShippingData and useCustomerData instead of context * Fix fromEntriesPolyfill to use number or undefined as an index option * Convert derive-selected-shipping-rates to TS * Add SelectShippingRateType * Get needsShipping from new hook and not context * Get address data from useCustomerData instead of useShippingDataContext * Move selectedRates, selectShippingRate and isSelectingRate * Remove items from ShippingDatacontext that are available in data stores * Get shipping data from stores, not context in payment method interface * Consider shipping rates to be loading if customer data is updating * Get rates from useShippingData hook instead of context * Fix incorrect TypeScript types and incorrectly named destructure * Move useShippingData into shipping folder * Update tests to mock useShippingData instead of context * Remove empty string fallback from shipping phone * Get types from Cart declaration instead of Picking them Co-authored-by: Mike Jolley <mike.jolley@me.com>
2022-03-04 17:43:45 +00:00
import type {
Cart,
CartTotals,
CartMeta,
CartItem,
CartShippingRate,
} from '@woocommerce/types';
import { BillingAddress, ShippingAddress } from '@woocommerce/settings';
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
/**
* Internal dependencies
*/
import { CartState, defaultCartState } from '../default-states';
import type { ResponseError } from '../types';
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
/**
* Retrieves cart data from state.
*
* @param {CartState} state The current state.
* @return {Cart} The data to return.
*/
export const getCartData = ( state: CartState ): Cart => {
return state.cartData;
};
export const getCustomerData = (
state: CartState
): {
shippingAddress: ShippingAddress;
billingData: BillingAddress;
} => {
return {
shippingAddress: state.cartData.shippingAddress,
billingData: state.cartData.billingAddress,
};
};
Try move shipping related dat to a `@wordpress/data` store (https://github.com/woocommerce/woocommerce-blocks/pull/5896) * Add address-related items to wc/store/cart data store * Add useUpdateCustomerData hook This allows us to have a single hook responsible for updating the customer information on the server. * Add useUpdateCustomerData hook in Checkout block * Remove shippingAsBilling from previousCustomerData ref type * Add useShippingAsBillingCheckbox hook * Remove checkbox handling from useCheckoutAddress * Merge with woocommerce/woocommerce-blocks#5810 changes * Move shipping as billing to checkout state context provider * Subscribe to changes * Cache customerDataToUpdate * Combine customerDataType and customerDataContextType * Fix notice context * Clean up inline docs for push changes * Add useShippingData hook * Add shipping related selectors to cart store * Update useShippingDataContext to useCustomerData hook * Update uses of useShippingDataContext to get data from hook instead * Remove rogue linebreak * Re-add linebreak * Re-add linebreak, remove shippingAsBilling * Re-add linebreak * Use useShippingData and useCustomerData instead of context * Fix fromEntriesPolyfill to use number or undefined as an index option * Convert derive-selected-shipping-rates to TS * Add SelectShippingRateType * Get needsShipping from new hook and not context * Get address data from useCustomerData instead of useShippingDataContext * Move selectedRates, selectShippingRate and isSelectingRate * Remove items from ShippingDatacontext that are available in data stores * Get shipping data from stores, not context in payment method interface * Consider shipping rates to be loading if customer data is updating * Get rates from useShippingData hook instead of context * Fix incorrect TypeScript types and incorrectly named destructure * Move useShippingData into shipping folder * Update tests to mock useShippingData instead of context * Remove empty string fallback from shipping phone * Get types from Cart declaration instead of Picking them Co-authored-by: Mike Jolley <mike.jolley@me.com>
2022-03-04 17:43:45 +00:00
/**
* Retrieves shipping rates from state.
*
* @param { CartState } state The current state.
* @return { CartShippingRate[] } The shipping rates on the cart.
*/
export const getShippingRates = ( state: CartState ): CartShippingRate[] => {
return state.cartData.shippingRates;
};
/**
* Retrieves whether the cart needs shipping.
*
* @param { CartState } state The current state.
* @return { boolean } True if the cart needs shipping.
*/
export const getNeedsShipping = ( state: CartState ): boolean => {
return state.cartData.needsShipping;
};
/**
* Retrieves whether the cart shipping has been calculated.
*
* @param { CartState } state The current state.
* @return { boolean } True if the shipping has been calculated.
*/
export const getHasCalculatedShipping = ( state: CartState ): boolean => {
return state.cartData.hasCalculatedShipping;
};
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
/**
* Retrieves cart totals from state.
*
* @param {CartState} state The current state.
* @return {CartTotals} The data to return.
*/
export const getCartTotals = ( state: CartState ): CartTotals => {
return state.cartData.totals || defaultCartState.cartData.totals;
};
/**
* Retrieves cart meta from state.
*
* @param {CartState} state The current state.
* @return {CartMeta} The data to return.
*/
export const getCartMeta = ( state: CartState ): CartMeta => {
return state.metaData || defaultCartState.metaData;
};
/**
* Retrieves cart errors from state.
*
* @param {CartState} state The current state.
* @return {Array<ResponseError>} Array of errors.
*/
export const getCartErrors = ( state: CartState ): Array< ResponseError > => {
return state.errors;
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
};
/**
* Returns true if any coupon is being applied.
*
* @param {CartState} state The current state.
* @return {boolean} True if a coupon is being applied.
*/
export const isApplyingCoupon = ( state: CartState ): boolean => {
return !! state.metaData.applyingCoupon;
};
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
/**
* Returns true if cart is stale, false if it is not.
*
* @param {CartState} state The current state.
* @return {boolean} True if the cart data is stale.
*/
export const isCartDataStale = ( state: CartState ): boolean => {
return state.metaData.isCartDataStale;
};
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
/**
* Retrieves the coupon code currently being applied.
*
* @param {CartState} state The current state.
* @return {string} The data to return.
*/
export const getCouponBeingApplied = ( state: CartState ): string => {
return state.metaData.applyingCoupon || '';
};
/**
* Returns true if any coupon is being removed.
*
* @param {CartState} state The current state.
* @return {boolean} True if a coupon is being removed.
*/
export const isRemovingCoupon = ( state: CartState ): boolean => {
return !! state.metaData.removingCoupon;
};
/**
* Retrieves the coupon code currently being removed.
*
* @param {CartState} state The current state.
* @return {string} The data to return.
*/
export const getCouponBeingRemoved = ( state: CartState ): string => {
return state.metaData.removingCoupon || '';
};
/**
* Returns cart item matching specified key.
*
* @param {CartState} state The current state.
* @param {string} cartItemKey Key for a cart item.
* @return {CartItem | void} Cart item object, or undefined if not found.
*/
export const getCartItem = (
state: CartState,
cartItemKey: string
): CartItem | void => {
return state.cartData.items.find(
( cartItem ) => cartItem.key === cartItemKey
);
};
/**
* Returns true if the specified cart item quantity is being updated.
*
* @param {CartState} state The current state.
* @param {string} cartItemKey Key for a cart item.
* @return {boolean} True if a item has a pending request to be updated.
*/
export const isItemPendingQuantity = (
state: CartState,
cartItemKey: string
): boolean => {
return state.cartItemsPendingQuantity.includes( cartItemKey );
};
/**
* Returns true if the specified cart item quantity is being updated.
*
* @param {CartState} state The current state.
* @param {string} cartItemKey Key for a cart item.
* @return {boolean} True if a item has a pending request to be updated.
*/
export const isItemPendingDelete = (
state: CartState,
cartItemKey: string
): boolean => {
return state.cartItemsPendingDelete.includes( cartItemKey );
};
/**
* Retrieves if the address is being applied for shipping.
*
* @param {CartState} state The current state.
* @return {boolean} are shipping rates loading.
*/
export const isCustomerDataUpdating = ( state: CartState ): boolean => {
return !! state.metaData.updatingCustomerData;
};
/**
* Retrieves if the shipping rate selection is being persisted.
*
* @param {CartState} state The current state.
*
* @return {boolean} True if the shipping rate selection is being persisted to
* the server.
*/
export const isShippingRateBeingSelected = ( state: CartState ): boolean => {
return !! state.metaData.updatingSelectedRate;
};