File size: 1,465 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
import { useMemo } from '@wordpress/element';
import usePlans from '../queries/use-plans';
import useSitePlans from '../queries/use-site-plans';
import type { PlanIntroductoryOffer } from '../types';

interface IntroOffersIndex {
	[ planSlug: string ]: PlanIntroductoryOffer | null;
}

interface Props {
	siteId: string | number | null | undefined;
	coupon: string | undefined;
}

/**
 * Get introductory offers for plans that have these defined
 * - Returns a union of the introductory offers from `/plans` and `/sites/[id]/plans` endpoints
 * - `/sites/[id]/plans` takes precedence over `/plans` (if both are defined for a plan)
 * @returns {IntroOffersIndex | undefined} - an object `{ [ planSlug: string ]: PlanIntroductoryOffer | null }`,
 * or `undefined` if we haven't observed any metadata yet
 */
const useIntroOffers = ( { siteId, coupon }: Props ): IntroOffersIndex | undefined => {
	const sitePlans = useSitePlans( { coupon: undefined, siteId } );
	const plans = usePlans( { coupon } );

	return useMemo( () => {
		if ( ! sitePlans.data && ! plans.data ) {
			return undefined;
		}

		return Object.keys( { ...sitePlans.data, ...plans.data } ).reduce< IntroOffersIndex >(
			( acc, planSlug ) => {
				const plan = sitePlans?.data?.[ planSlug ] ?? plans?.data?.[ planSlug ];

				return {
					...acc,
					[ planSlug ]: plan?.pricing?.introOffer ?? null,
				};
			},
			{}
		);
	}, [ sitePlans.data, plans.data ] );
};

export default useIntroOffers;