File size: 2,368 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
import { calculateMonthlyPriceForPlan } from '@automattic/calypso-products';
import { useLocale } from '@automattic/i18n-utils';
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
import wpcomRequest from 'wpcom-proxy-request';
import unpackIntroOffer from './lib/unpack-intro-offer';
import useQueryKeysFactory from './lib/use-query-keys-factory';
import type { PricedAPIPlan, PlanNext } from '../types';

interface PlansIndex {
	[ planSlug: string ]: PlanNext;
}

/**
 * Plans from `/plans` endpoint, transformed into a map of planSlug => PlanNext
 */
function usePlans( {
	coupon,
}: {
	/**
	 * `coupon` required on purpose to mitigate risk with not passing something through when we should
	 */
	coupon: string | undefined;
} ): UseQueryResult< PlansIndex > {
	const queryKeys = useQueryKeysFactory();
	const locale = useLocale();
	const params = new URLSearchParams();
	coupon && params.append( 'coupon_code', coupon );
	params.append( 'locale', locale );

	return useQuery( {
		queryKey: queryKeys.plans( coupon ),
		queryFn: async (): Promise< PlansIndex > => {
			const data: PricedAPIPlan[] = await wpcomRequest( {
				path: '/plans',
				apiVersion: '1.5',
				query: params.toString(),
			} );

			return Object.fromEntries(
				data.map( ( plan ) => {
					const discountedPriceFull =
						plan.orig_cost_integer !== plan.raw_price_integer ? plan.raw_price_integer : null;

					return [
						plan.product_slug,
						{
							planSlug: plan.product_slug,
							productSlug: plan.product_slug,
							productId: plan.product_id,
							pathSlug: plan.path_slug,
							productNameShort: plan.product_name_short,
							pricing: {
								billPeriod: plan.bill_period,
								currencyCode: plan.currency_code,
								introOffer: unpackIntroOffer( plan ),
								originalPrice: {
									monthly:
										typeof plan.orig_cost_integer === 'number'
											? calculateMonthlyPriceForPlan( plan.product_slug, plan.orig_cost_integer )
											: null,
									full: plan.orig_cost_integer,
								},
								discountedPrice: {
									monthly:
										typeof discountedPriceFull === 'number'
											? calculateMonthlyPriceForPlan( plan.product_slug, discountedPriceFull )
											: null,
									full: discountedPriceFull,
								},
							},
						},
					];
				} )
			);
		},
	} );
}

export default usePlans;