2021-05-25 11:49:13 +00:00
|
|
|
/**
|
|
|
|
* 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.
|
|
|
|
*
|
2022-04-08 13:47:19 +00:00
|
|
|
* @param {Object} totals Current cart total items
|
2021-05-25 11:49:13 +00:00
|
|
|
* @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(
|
2023-12-12 22:12:36 +00:00
|
|
|
__( 'Subtotal:', 'woocommerce' ),
|
2021-05-25 11:49:13 +00:00
|
|
|
'total_items'
|
|
|
|
)
|
|
|
|
);
|
|
|
|
|
|
|
|
newTotals.push(
|
2023-12-12 22:12:36 +00:00
|
|
|
factory( __( 'Fees:', 'woocommerce' ), 'total_fees' )
|
2021-05-25 11:49:13 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
newTotals.push(
|
|
|
|
factory(
|
2023-12-12 22:12:36 +00:00
|
|
|
__( 'Discount:', 'woocommerce' ),
|
2021-05-25 11:49:13 +00:00
|
|
|
'total_discount'
|
|
|
|
)
|
|
|
|
);
|
|
|
|
|
|
|
|
newTotals.push( {
|
|
|
|
key: 'total_tax',
|
2023-12-12 22:12:36 +00:00
|
|
|
label: __( 'Taxes:', 'woocommerce' ),
|
2021-05-25 11:49:13 +00:00
|
|
|
value: parseInt( totals.total_tax, 10 ),
|
|
|
|
valueWithTax: parseInt( totals.total_tax, 10 ),
|
|
|
|
} );
|
|
|
|
|
|
|
|
if ( needsShipping ) {
|
|
|
|
newTotals.push(
|
|
|
|
factory(
|
2023-12-12 22:12:36 +00:00
|
|
|
__( 'Shipping:', 'woocommerce' ),
|
2021-05-25 11:49:13 +00:00
|
|
|
'total_shipping'
|
|
|
|
)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return newTotals;
|
|
|
|
};
|