File size: 6,414 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import { formatCurrency } from '@automattic/number-formatters';
import { stringify } from 'qs';
import { fetchAndParse, wpcomRequest } from '../wpcom-request-controls';
import { setFeatures, setFeaturesByType, setPlanProducts, setPlans } from './actions';
import {
	TIMELESS_PLAN_FREE,
	TIMELESS_PLAN_PREMIUM,
	plansProductSlugs,
	monthlySlugs,
	annualSlugs,
	FEATURE_IDS_THAT_REQUIRE_ANNUALLY_BILLED_PLAN,
} from './constants';
import type {
	PricedAPIPlan,
	APIPlanDetail,
	PlanSimplifiedFeature,
	Plan,
	DetailsAPIResponse,
	PlanFeature,
	PlanProduct,
	PlanSlug,
	DetailsAPIFeature,
} from './types';

const MONTHLY_PLAN_BILLING_PERIOD = 31;

/**
 * Calculates the monthly price of a plan
 * Annual plans are only priced yearly
 * @param plan the plan object
 */
function getMonthlyPrice( plan: PricedAPIPlan ) {
	return formatCurrency( plan.raw_price / 12, plan.currency_code, { stripZeros: true } ) as string;
}

/**
 * Calculates the yearly price of a monthly plan
 * @param plan the plan object
 */
function getAnnualPrice( plan: PricedAPIPlan ) {
	return formatCurrency( plan.raw_price * 12, plan.currency_code, { stripZeros: true } ) as string;
}

/**
 * Formats the plan price according to 'format-currency' package rules
 * We use this for consistency in prices formats across monthly and annual plans
 * @param plan the plan object
 */
function getFormattedPrice( plan: PricedAPIPlan ) {
	return formatCurrency( plan.raw_price, plan.currency_code, { stripZeros: true } ) as string;
}

function calculateDiscounts( planProducts: PlanProduct[] ) {
	// calculate discounts
	for ( let i = 0; i < annualSlugs.length; i++ ) {
		const annualPlan = planProducts.find( ( plan ) => plan.storeSlug === annualSlugs[ i ] );
		const monthlyPlan = planProducts.find( ( plan ) => plan.storeSlug === monthlySlugs[ i ] );

		if ( annualPlan && monthlyPlan ) {
			const annualCostIfPaidMonthly = monthlyPlan.rawPrice * 12;
			const annualCostIfPaidAnnually = annualPlan.rawPrice;
			const discount = Math.floor(
				100 * ( 1 - annualCostIfPaidAnnually / annualCostIfPaidMonthly )
			);
			annualPlan.annualDiscount = discount;
			monthlyPlan.annualDiscount = discount;
		}
	}
}

function processFeatures( features: DetailsAPIFeature[] ) {
	return features.reduce(
		( features, feature ) => {
			features[ feature.id ] = {
				id: feature.id,
				name: feature.name,
				description: feature.description,
				type: 'checkbox',
				requiresAnnuallyBilledPlan:
					FEATURE_IDS_THAT_REQUIRE_ANNUALLY_BILLED_PLAN.indexOf( feature.id ) > -1,
			};
			return features;
		},
		{} as Record< string, PlanFeature >
	);
}

function featureRequiresAnnual(
	featureName: string,
	allFeaturesData: Record< string, PlanFeature >
): boolean {
	const matchedFeatureId = Object.keys( allFeaturesData ).find(
		( featureId ) => allFeaturesData[ featureId ].name === featureName
	);

	if ( matchedFeatureId ) {
		return allFeaturesData[ matchedFeatureId ].requiresAnnuallyBilledPlan;
	}

	return false;
}

function processPlanFeatures(
	planData: APIPlanDetail,
	allFeaturesData: Record< string, PlanFeature >
): PlanSimplifiedFeature[] {
	const features: PlanSimplifiedFeature[] = planData.highlighted_features.map(
		( featureName ) => ( {
			name: featureName,
			requiresAnnuallyBilledPlan: featureRequiresAnnual( featureName, allFeaturesData ),
		} )
	);

	// Features requiring an annually billed plan should be first in the array.
	features.sort(
		( a, b ) => Number( b.requiresAnnuallyBilledPlan ) - Number( a.requiresAnnuallyBilledPlan )
	);

	return features;
}

function normalizePlanProducts(
	pricedPlans: PricedAPIPlan[],
	periodAgnosticPlans: Plan[]
): PlanProduct[] {
	const plansProducts: PlanProduct[] = plansProductSlugs.reduce( ( plans, slug ) => {
		const planProduct = pricedPlans.find( ( pricedPlan ) => pricedPlan.product_slug === slug );

		if ( ! planProduct ) {
			return plans;
		}

		const periodAgnosticPlan = periodAgnosticPlans.find(
			( plan ) => plan.productIds.indexOf( planProduct.product_id ) > -1
		) as Plan;

		plans.push( {
			productId: planProduct.product_id,
			// This means that free plan is considered "annually billed"
			billingPeriod:
				planProduct.bill_period === MONTHLY_PLAN_BILLING_PERIOD ? 'MONTHLY' : 'ANNUALLY',
			periodAgnosticSlug: periodAgnosticPlan.periodAgnosticSlug,
			storeSlug: planProduct.product_slug,
			rawPrice: planProduct.raw_price,
			// Not all plans returned from /plans have a `path_slug` (e.g. monthly plans don't have)
			pathSlug: planProduct.path_slug,
			price:
				planProduct?.bill_period === MONTHLY_PLAN_BILLING_PERIOD || planProduct.raw_price === 0
					? getFormattedPrice( planProduct )
					: getMonthlyPrice( planProduct ),
			annualPrice:
				planProduct?.bill_period === MONTHLY_PLAN_BILLING_PERIOD
					? getAnnualPrice( planProduct )
					: getFormattedPrice( planProduct ),
		} );
		return plans;
	}, [] as PlanProduct[] );
	calculateDiscounts( plansProducts );
	return plansProducts;
}

export function* getSupportedPlans( locale = 'en' ) {
	const pricedPlans: PricedAPIPlan[] = yield wpcomRequest( {
		path: '/plans',
		query: stringify( { locale } ),
		apiVersion: '1.5',
	} );

	const { body: plansFeatures } = ( yield fetchAndParse(
		`https://public-api.wordpress.com/wpcom/v2/plans/details?locale=${ encodeURIComponent(
			locale
		) }`,
		{
			mode: 'cors',
			credentials: 'omit',
		}
	) ) as { body: DetailsAPIResponse };

	const features = processFeatures( plansFeatures.features );

	const periodAgnosticPlans: Plan[] = plansFeatures.plans.map( ( plan ) => {
		const planSlug = plan.nonlocalized_short_name?.toLowerCase() as PlanSlug;

		return {
			description: plan.tagline,
			features: processPlanFeatures( plan, features ),
			storage: plan.storage,
			title: plan.short_name,
			featuresSlugs: plan.features.reduce(
				( slugs, slug ) => {
					slugs[ slug ] = true;
					return slugs;
				},
				{} as Record< string, boolean >
			),
			isFree: planSlug === TIMELESS_PLAN_FREE,
			isPopular: planSlug === TIMELESS_PLAN_PREMIUM,
			periodAgnosticSlug: planSlug,
			productIds: plan.products.map( ( { plan_id } ) => plan_id ),
		};
	} );

	const planProducts = normalizePlanProducts( pricedPlans, periodAgnosticPlans );

	yield setPlans( periodAgnosticPlans, locale );
	yield setPlanProducts( planProducts );
	yield setFeatures( features, locale );
	yield setFeaturesByType( plansFeatures.features_by_type, locale );
}