File size: 2,154 Bytes
1e92f2d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | import { formatCurrency } from '@automattic/number-formatters';
import { useMemo } from '@wordpress/element';
import * as ProductsList from '../../products-list';
import type { AddOnMeta } from '../types';
type AddOnPrices = {
[ key in string ]?: {
monthlyPrice: number;
yearlyPrice: number;
formattedMonthlyPrice: string;
formattedYearlyPrice: string;
currencyCode: string;
} | null;
};
export const createAddOnPriceKey = ( { productSlug, quantity }: AddOnMeta ) => {
return `${ productSlug }_${ quantity ?? 0 }`;
};
export const useAddOnPrices = ( addOnMetas: AddOnMeta[] ) => {
const productSlugs = useMemo(
() => addOnMetas.map( ( { productSlug } ) => productSlug ),
[ addOnMetas ]
);
const productsList = ProductsList.useProducts( productSlugs );
return useMemo( () => {
return addOnMetas.reduce< AddOnPrices >( ( accum, addOnMeta ) => {
const { productSlug, quantity } = addOnMeta;
const product = productsList.data?.[ productSlug ];
let cost = product?.costSmallestUnit;
if ( ! cost || ! product?.currencyCode ) {
return {
[ productSlug ]: null,
...accum,
};
}
// Finds the applicable tiered price for the quantity.
const priceTier =
quantity &&
product?.priceTierList.find( ( tier ) => {
if ( quantity >= tier.minimumUnits && quantity <= ( tier.maximumUnits ?? 0 ) ) {
return tier;
}
} );
if ( priceTier ) {
cost = priceTier?.maximumPrice;
}
let monthlyPrice = cost / 12;
let yearlyPrice = cost;
if ( product?.term === 'month' ) {
monthlyPrice = cost;
yearlyPrice = cost * 12;
}
return {
[ createAddOnPriceKey( addOnMeta ) ]: {
monthlyPrice,
yearlyPrice,
formattedMonthlyPrice: formatCurrency( monthlyPrice, product?.currencyCode, {
stripZeros: true,
isSmallestUnit: true,
} ),
formattedYearlyPrice: formatCurrency( yearlyPrice, product?.currencyCode, {
stripZeros: true,
isSmallestUnit: true,
} ),
currencyCode: product?.currencyCode,
},
...accum,
};
}, {} );
}, [ addOnMetas, productsList.data ] );
};
export default useAddOnPrices;
|