File size: 1,768 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 |
import { formatCurrency } from '@automattic/number-formatters';
import { useSelector } from 'react-redux';
import { getProductSlugByPeriodVariation } from 'calypso/lib/plugins/utils';
import {
getProductBySlug,
isProductsListFetching,
getProductsList,
} from 'calypso/state/products-list/selectors';
import type { ReactNode } from 'react';
export const PluginAnnualSaving = ( {
plugin,
renderContent,
}: {
plugin?: {
variations?: {
yearly?: { product_slug?: string | undefined; product_id?: number | undefined };
monthly?: { product_slug?: string | undefined; product_id?: number | undefined };
};
};
renderContent: ( {
isFetching,
saving,
}: {
isFetching: boolean;
saving: string | false | 0 | null;
} ) => ReactNode;
} ) => {
const productList = useSelector( getProductsList );
const variationYearly = plugin?.variations?.yearly;
const priceSlugYearly = getProductSlugByPeriodVariation( variationYearly, productList );
const productYearly = useSelector( ( state ) => getProductBySlug( state, priceSlugYearly ) );
const variationMonthly = plugin?.variations?.monthly;
const priceSlugMonthly = getProductSlugByPeriodVariation( variationMonthly, productList );
const productMonthly = useSelector( ( state ) => getProductBySlug( state, priceSlugMonthly ) );
const isFetching = useSelector( isProductsListFetching );
const getAnnualPriceSavingText = () => {
const totalDiscount =
productMonthly && productYearly
? Math.round( productMonthly.cost * 12 - productYearly.cost )
: null;
return (
totalDiscount &&
productYearly &&
totalDiscount > 0 &&
formatCurrency( totalDiscount, productYearly.currency_code )
);
};
return renderContent( {
isFetching,
saving: getAnnualPriceSavingText(),
} );
};
|