File size: 1,445 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
import { useTranslate } from 'i18n-calypso';
import { useSelector } from 'react-redux';
import { getProductSlugByPeriodVariation } from 'calypso/lib/plugins/utils';
import { IntervalLength } from 'calypso/my-sites/marketplace/components/billing-interval-switcher/constants';
import {
	getProductDisplayCost,
	isProductsListFetching,
	getProductsList,
} from 'calypso/state/products-list/selectors';

export const PluginPrice = ( { plugin, billingPeriod, children } ) => {
	const translate = useTranslate();
	const variationPeriod = getPeriodVariationValue( billingPeriod );
	const productList = useSelector( getProductsList );
	const variation = plugin?.variations?.[ variationPeriod ];
	const priceSlug = getProductSlugByPeriodVariation( variation, productList );
	const price = useSelector( ( state ) => getProductDisplayCost( state, priceSlug ) );
	const isFetching = useSelector( isProductsListFetching );

	const getPeriodText = ( periodValue ) => {
		switch ( periodValue ) {
			case 'monthly':
				return translate( 'monthly' );
			case 'yearly':
				return translate( 'per year' );
			default:
				return '';
		}
	};

	return children( {
		isFetching,
		price,
		period: getPeriodText( variationPeriod ),
	} );
};

export function getPeriodVariationValue( billingPeriod ) {
	switch ( billingPeriod ) {
		case IntervalLength.MONTHLY:
			return 'monthly';
		case IntervalLength.ANNUALLY:
			return 'yearly';

		default:
			return '';
	}
}