Back

100% Statements 18/18
91.66% Branches 11/12
100% Functions 4/4
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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      34x     34x 166x 76x   90x 90x     34x 83x 83x             34x       74x   74x 74x   74x 74x 74x 9x       74x    
import mapObjectKeysToCamel from './to-camel';
import type { ProductCamelCase, ProductSnakeCase } from '../types';
 
const monthsByTerm: Record< string, number > = { year: 12, 'two years': 24 };
 
// A missing or unusable catalog price stays undefined instead of NaN, so ProductPrice shows no amount for it.
const perMonth = ( price: number | null | undefined, months: number ) => {
	if ( price == null ) {
		return undefined;
	}
	const monthly = Math.round( ( price / months ) * 100 ) / 100;
	return Number.isFinite( monthly ) ? monthly : undefined;
};
 
const preparePricing = ( pricing: ProductCamelCase[ 'pricingForUi' ] ) => {
	const months = monthsByTerm[ pricing.productTerm ] || 1;
	return {
		...pricing,
		fullPricePerMonth: perMonth( pricing.fullPrice, months ),
		discountPricePerMonth: perMonth( pricing.discountPrice, months ),
	};
};
 
export const prepareProductData = ( product: ProductSnakeCase ) => {
	// The mapObjectKeysToCamel is typed correctly, however we are adding new fields
	// to the product object that don't exist on the global state object
	// Therefore we still need to cast the object to the correct type
	const camelProduct = mapObjectKeysToCamel( product ) as ProductCamelCase;
 
	camelProduct.features = camelProduct.features || [];
	camelProduct.supportedProducts = camelProduct.supportedProducts || [];
 
	Eif ( camelProduct.pricingForUi ) {
		camelProduct.pricingForUi = preparePricing( camelProduct.pricingForUi );
		camelProduct.pricingForUi.terms = camelProduct.pricingForUi.terms?.map( term =>
			preparePricing( term as ProductCamelCase[ 'pricingForUi' ] )
		);
	}
 
	return camelProduct;
};