Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
Add key to each CartTotalItem (#4240)
Browse files Browse the repository at this point in the history
* Move type defs

* Move type guards

* Fix imports

* Extract prepareTotalItems to TS file

* usePaymentMethodInterface as TS file

* Fix TS props

* Fix currency type defs

* Add return type to usePaymentMethodInterface

* Add key prop to CartTotalItem

* Fixed up js tests

* Move SymbolPosition into type-defs package

Co-authored-by: Thomas Roberts <[email protected]>
  • Loading branch information
2 people authored and grogou committed Aug 20, 2021
1 parent c15e512 commit 193267b
Show file tree
Hide file tree
Showing 40 changed files with 209 additions and 169 deletions.
2 changes: 1 addition & 1 deletion assets/js/base/components/price-slider/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
import PropTypes from 'prop-types';
import classnames from 'classnames';
import FormattedMonetaryAmount from '@woocommerce/base-components/formatted-monetary-amount';
import { isObject } from '@woocommerce/base-utils';
import { isObject } from '@woocommerce/types';

/**
* Internal dependencies
Expand Down
2 changes: 1 addition & 1 deletion assets/js/base/components/quantity-selector/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import { speak } from '@wordpress/a11y';
import classNames from 'classnames';
import { useCallback } from '@wordpress/element';
import { DOWN, UP } from '@wordpress/keycodes';
import { isNumber } from '@woocommerce/types';

/**
* Internal dependencies
*/
import './style.scss';
import { isNumber } from '../../utils/type-guards';

interface QuantitySelectorProps {
className?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,20 @@ import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
import { useDebounce } from 'use-debounce';
import { usePrevious } from '@woocommerce/base-hooks';
import { triggerFragmentRefresh } from '@woocommerce/base-utils';
import type { CartItem, StoreCartItemQuantity } from '@woocommerce/types';
import {
CartItem,
StoreCartItemQuantity,
isNumber,
isObject,
isString,
objectHasProp,
} from '@woocommerce/types';

/**
* Internal dependencies
*/
import { useStoreCart } from './use-store-cart';
import { useCheckoutContext } from '../../providers/cart-checkout';
import {
isNumber,
isObject,
isString,
objectHasProp,
} from '../../../utils/type-guards';

/**
* Ensures the object passed has props key: string and quantity: number
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* Internal dependencies
*/
import { prepareTotalItems } from '../use-payment-method-interface';
import { prepareTotalItems } from '../utils';

describe( 'prepareTotalItems', () => {
const fixture = {
Expand All @@ -17,21 +17,25 @@ describe( 'prepareTotalItems', () => {
};
const expected = [
{
key: 'total_items',
label: 'Subtotal:',
value: 200,
valueWithTax: 220,
},
{
key: 'total_fees',
label: 'Fees:',
value: 100,
valueWithTax: 110,
},
{
key: 'total_discount',
label: 'Discount:',
value: 350,
valueWithTax: 400,
},
{
key: 'total_tax',
label: 'Taxes:',
value: 30,
valueWithTax: 30,
Expand All @@ -40,6 +44,7 @@ describe( 'prepareTotalItems', () => {
const expectedWithShipping = [
...expected,
{
key: 'total_shipping',
label: 'Shipping:',
value: 50,
valueWithTax: 55,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,67 +19,12 @@ import { useCheckoutContext } from '../../providers/cart-checkout/checkout-state
import { usePaymentMethodDataContext } from '../../providers/cart-checkout/payment-methods';
import { useShippingDataContext } from '../../providers/cart-checkout/shipping';
import { useCustomerDataContext } from '../../providers/cart-checkout/customer';
import { prepareTotalItems } from './utils';

/**
* @typedef {import('@woocommerce/type-defs/registered-payment-method-props').RegisteredPaymentMethodProps} RegisteredPaymentMethodProps
* @typedef {import('@woocommerce/type-defs/cart').CartTotalItem} CartTotalItem
* Returns am interface to use as payment method props.
*/

/**
* Prepares the total items into a shape usable for display as passed on to
* registered payment methods.
*
* @param {Object} totals Current cart total items
* @param {boolean} needsShipping Whether or not shipping is needed.
*
* @return {CartTotalItem[]} Array for cart total items prepared for use.
*/
export const prepareTotalItems = ( totals, needsShipping ) => {
const newTotals = [];
const factory = ( label, property ) => {
const value = parseInt( totals[ property ], 10 );
const tax = parseInt( totals[ property + '_tax' ], 10 );
return {
label,
value,
valueWithTax: value + tax,
};
};
newTotals.push(
factory(
__( 'Subtotal:', 'woo-gutenberg-products-block' ),
'total_items'
)
);
newTotals.push(
factory( __( 'Fees:', 'woo-gutenberg-products-block' ), 'total_fees' )
);
newTotals.push(
factory(
__( 'Discount:', 'woo-gutenberg-products-block' ),
'total_discount'
)
);
newTotals.push( {
label: __( 'Taxes:', 'woo-gutenberg-products-block' ),
value: parseInt( totals.total_tax, 10 ),
valueWithTax: parseInt( totals.total_tax, 10 ),
} );
if ( needsShipping ) {
newTotals.push(
factory(
__( 'Shipping:', 'woo-gutenberg-products-block' ),
'total_shipping'
)
);
}
return newTotals;
};

/**
* @return {RegisteredPaymentMethodProps} Interface to use as payment method props.
*/
export const usePaymentMethodInterface = () => {
export const usePaymentMethodInterface = (): Record< string, unknown > => {
const {
isCalculating,
isComplete,
Expand Down Expand Up @@ -107,7 +52,6 @@ export const usePaymentMethodInterface = () => {
selectedRates,
setSelectedRates,
isSelectingRate,

onShippingRateSuccess,
onShippingRateFail,
onShippingRateSelectSuccess,
Expand Down Expand Up @@ -142,27 +86,7 @@ export const usePaymentMethodInterface = () => {
}, [ cartTotals, needsShipping ] );

return {
checkoutStatus: {
isCalculating,
isComplete,
isIdle,
isProcessing,
},
paymentStatus: currentStatus,
shippingStatus: {
shippingErrorStatus,
shippingErrorTypes,
},
shippingData: {
shippingRates,
shippingRatesLoading,
selectedRates,
setSelectedRates,
isSelectingRate,
shippingAddress,
setShippingAddress,
needsShipping,
},
activePaymentMethod,
billing: {
billingData,
cartTotal: currentCartTotal.current,
Expand All @@ -171,10 +95,25 @@ export const usePaymentMethodInterface = () => {
displayPricesIncludingTax: getSetting(
'displayCartPricesIncludingTax',
false
),
) as boolean,
appliedCoupons,
customerId,
},
checkoutStatus: {
isCalculating,
isComplete,
isIdle,
isProcessing,
},
components: {
ValidationInputError,
PaymentMethodIcons,
PaymentMethodLabel,
},
emitResponse: {
noticeContexts,
responseTypes,
},
eventRegistration: {
onCheckoutBeforeProcessing,
onCheckoutValidationBeforeProcessing,
Expand All @@ -186,18 +125,23 @@ export const usePaymentMethodInterface = () => {
onShippingRateSelectFail,
onPaymentProcessing,
},
components: {
ValidationInputError,
PaymentMethodIcons,
PaymentMethodLabel,
},
emitResponse: {
noticeContexts,
responseTypes,
},
onSubmit,
activePaymentMethod,
paymentStatus: currentStatus,
setExpressPaymentError,
shippingData: {
shippingRates,
shippingRatesLoading,
selectedRates,
setSelectedRates,
isSelectingRate,
shippingAddress,
setShippingAddress,
needsShipping,
},
shippingStatus: {
shippingErrorStatus,
shippingErrorTypes,
},
shouldSavePayment,
};
};
85 changes: 85 additions & 0 deletions assets/js/base/context/hooks/payment-methods/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* External dependencies
*/
import { __ } from '@wordpress/i18n';
import {
CartResponseTotals,
objectHasProp,
isString,
} from '@woocommerce/types';

export interface CartTotalItem {
key: string;
label: string;
value: number;
valueWithTax: number;
}

/**
* Prepares the total items into a shape usable for display as passed on to
* registered payment methods.
*
* @param {Object} totals Current cart total items
* @param {boolean} needsShipping Whether or not shipping is needed.
*/
export const prepareTotalItems = (
totals: CartResponseTotals,
needsShipping: boolean
): CartTotalItem[] => {
const newTotals = [];

const factory = ( label: string, property: string ): CartTotalItem => {
const taxProperty = property + '_tax';
const value =
objectHasProp( totals, property ) && isString( totals[ property ] )
? parseInt( totals[ property ] as string, 10 )
: 0;
const tax =
objectHasProp( totals, taxProperty ) &&
isString( totals[ taxProperty ] )
? parseInt( totals[ taxProperty ] as string, 10 )
: 0;
return {
key: property,
label,
value,
valueWithTax: value + tax,
};
};

newTotals.push(
factory(
__( 'Subtotal:', 'woo-gutenberg-products-block' ),
'total_items'
)
);

newTotals.push(
factory( __( 'Fees:', 'woo-gutenberg-products-block' ), 'total_fees' )
);

newTotals.push(
factory(
__( 'Discount:', 'woo-gutenberg-products-block' ),
'total_discount'
)
);

newTotals.push( {
key: 'total_tax',
label: __( 'Taxes:', 'woo-gutenberg-products-block' ),
value: parseInt( totals.total_tax, 10 ),
valueWithTax: parseInt( totals.total_tax, 10 ),
} );

if ( needsShipping ) {
newTotals.push(
factory(
__( 'Shipping:', 'woo-gutenberg-products-block' ),
'total_shipping'
)
);
}

return newTotals;
};
2 changes: 1 addition & 1 deletion assets/js/base/context/hooks/use-customer-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export const useCustomerData = (): {
billingData: CartResponseBillingAddress;
shippingAddress: CartResponseShippingAddress;
setBillingData: ( data: CartResponseBillingAddress ) => void;
setShippingAddress: ( data: CartResponseBillingAddress ) => void;
setShippingAddress: ( data: CartResponseShippingAddress ) => void;
} => {
const { updateCustomerData } = useDispatch( storeKey );
const { addErrorNotice, removeNotice } = useStoreNotices();
Expand Down
4 changes: 2 additions & 2 deletions assets/js/base/context/hooks/use-emit-response.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* Internal dependencies
* External dependencies
*/
import { isObject } from '../../utils/type-guards';
import { isObject } from '@woocommerce/types';

export enum responseTypes {
SUCCESS = 'success',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
import { __ } from '@wordpress/i18n';
import { usePrevious } from '@woocommerce/base-hooks';
import deprecated from '@wordpress/deprecated';
import { isObject } from '@woocommerce/types';

/**
* Internal dependencies
Expand Down Expand Up @@ -41,7 +42,6 @@ import { useStoreNotices } from '../../../hooks/use-store-notices';
import { useStoreEvents } from '../../../hooks/use-store-events';
import { useCheckoutNotices } from '../../../hooks/use-checkout-notices';
import { useEmitResponse } from '../../../hooks/use-emit-response';
import { isObject } from '../../../../utils/type-guards';

/**
* @typedef {import('@woocommerce/type-defs/contexts').CheckoutDataContext} CheckoutDataContext
Expand Down
3 changes: 1 addition & 2 deletions assets/js/base/context/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@
"../../settings/shared/index.ts",
"../../settings/blocks/index.ts",
"../../base/hooks/index.js",
"../utils/type-guards.ts",
"../../base/utils/",
"../../data/",
"../../type-defs",
"../../types/",
"../components"
],
"exclude": [ "**/test/**" ]
Expand Down
Loading

0 comments on commit 193267b

Please sign in to comment.