Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SubscriptionCycleSelector.tsx « subscription « payments « containers « components « packages - github.com/ProtonMail/WebClients.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 520c498f8e4eb738fd90237b07305252e0f340cd (plain)
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import React from 'react';

import { c, msgid } from 'ttag';

import { CYCLE, DEFAULT_CURRENCY, PLAN_TYPES } from '@proton/shared/lib/constants';
import { getCheckout } from '@proton/shared/lib/helpers/checkout';
import { getSupportedAddons } from '@proton/shared/lib/helpers/planIDs';
import { allCycles, getNormalCycleFromCustomCycle } from '@proton/shared/lib/helpers/subscription';
import { Currency, PlanIDs, PlansMap, SubscriptionCheckResponse } from '@proton/shared/lib/interfaces';

import { Option, Price, Radio, SelectTwo } from '../../../components';
import InputField from '../../../components/v2/field/InputField';
import { classnames } from '../../../helpers';
import { getMonthFreeText, getMonthsFree } from '../../offers/helpers/offerCopies';

interface Props {
    cycle: CYCLE;
    minimumCycle?: CYCLE;
    mode: 'select' | 'buttons';
    currency: Currency;
    onChangeCycle: (cycle: CYCLE) => void;
    plansMap: PlansMap;
    planIDs: PlanIDs;
    disabled?: boolean;
}

interface TotalPricing {
    discount: number;
    total: number;
    totalPerMonth: number;
}

type TotalPricings = {
    [key in CYCLE]: TotalPricing;
};

const getText = (n: number) => {
    return c('Label').ngettext(msgid`${n} month`, `${n} months`, n);
};

const getDiscountPrice = (discount: number, currency: Currency) => {
    return discount ? (
        <>
            {c('Subscription saving').t`Save`}
            <Price className="ml0-25" currency={currency}>
                {discount}
            </Price>
        </>
    ) : null;
};

const CycleItemView = ({
    currency,
    text,
    total,
    monthlySuffix,
    totalPerMonth,
    discount,
    freeMonths,
}: {
    currency: Currency;
    text: string;
    total: number;
    monthlySuffix: string;
    totalPerMonth: number;
    discount: number;
    freeMonths: number;
}) => {
    return (
        <>
            <div className="flex-item-fluid pl0-5">
                <div className="flex flex-align-items-center">
                    <div className="flex-item-fluid-auto mr1">
                        <strong className="text-lg">{text}</strong>
                        {freeMonths > 0 && (
                            <span className="color-success">
                                {` + `}
                                {getMonthFreeText(freeMonths)}
                            </span>
                        )}
                    </div>
                    <strong className="text-lg flex-item-noshrink color-primary">
                        {c('Subscription price').t`For`}
                        <Price className="ml0-25" currency={currency}>
                            {total}
                        </Price>
                    </strong>
                </div>
                <div className="flex flex-align-items-center">
                    <span className="color-weak flex flex-item-fluid-auto">
                        <Price currency={currency} suffix={monthlySuffix}>
                            {totalPerMonth}
                        </Price>
                    </span>
                    <span className="color-success flex flex-item-noshrink">
                        {getDiscountPrice(discount, currency)}
                    </span>
                </div>
            </div>
        </>
    );
};

const CycleItem = ({
    totals,
    currency,
    cycle,
    monthlySuffix,
}: {
    totals: TotalPricings;
    monthlySuffix: string;
    cycle: CYCLE;
    currency: Currency;
}) => {
    const replacementCycle = getNormalCycleFromCustomCycle(cycle) || cycle;
    const freeMonths = getMonthsFree(cycle);
    const { total, totalPerMonth, discount } = totals[replacementCycle];

    return (
        <CycleItemView
            text={getText(replacementCycle)}
            currency={currency}
            discount={discount}
            monthlySuffix={monthlySuffix}
            freeMonths={freeMonths}
            total={total}
            totalPerMonth={totalPerMonth}
        />
    );
};

const singleClassName =
    'p1 mb1 border rounded bg-norm flex flex-nowrap flex-align-items-stretch border-primary border-2';

const getMonthlySuffix = (planIDs: PlanIDs) => {
    const supportedAddons = getSupportedAddons(planIDs);
    return Object.keys(supportedAddons).some((addon) => addon.startsWith('1member'))
        ? c('Suffix').t`/user per month`
        : c('Suffix').t`/month`;
};

export const SubscriptionCheckoutCycleItem = ({
    checkResult,
    plansMap,
    planIDs,
}: {
    checkResult: SubscriptionCheckResponse | undefined;
    plansMap: PlansMap;
    planIDs: PlanIDs;
}) => {
    const cycle = checkResult?.Cycle || CYCLE.MONTHLY;
    const currency = checkResult?.Currency || DEFAULT_CURRENCY;
    const replacementCycle = getNormalCycleFromCustomCycle(cycle) || cycle;
    const freeMonths = getMonthsFree(cycle);

    const result = getCheckout({ planIDs, plansMap, checkResult });

    return (
        <div className={singleClassName}>
            <CycleItemView
                text={getText(replacementCycle)}
                currency={currency}
                discount={result.discountPerCycle}
                monthlySuffix={getMonthlySuffix(planIDs)}
                freeMonths={freeMonths}
                total={result.withDiscountPerCycle}
                totalPerMonth={result.withDiscountPerMonth}
            />
        </div>
    );
};

const SubscriptionCycleSelector = ({
    cycle: cycleSelected,
    minimumCycle = CYCLE.MONTHLY,
    mode,
    onChangeCycle,
    currency,
    disabled,
    planIDs,
    plansMap,
}: Props) => {
    const filteredCycles = [CYCLE.YEARLY, CYCLE.MONTHLY].filter((cycle) => cycle >= minimumCycle);

    const cycles = [CYCLE.TWO_YEARS, ...filteredCycles];

    const pricing = Object.entries(planIDs).reduce(
        (acc, [planName, quantity]) => {
            const plan = plansMap[planName as keyof PlansMap];
            if (!plan) {
                return acc;
            }

            const add = (target: any, cycle: CYCLE) => {
                const price = plan.Pricing[cycle];
                if (price) {
                    target[cycle] += quantity * price;
                }
            };

            allCycles.forEach((cycle) => {
                add(acc.all, cycle);
            });

            if (plan.Type === PLAN_TYPES.PLAN) {
                allCycles.forEach((cycle) => {
                    add(acc.plans, cycle);
                });
            }

            return acc;
        },
        {
            all: { [CYCLE.MONTHLY]: 0, [CYCLE.YEARLY]: 0, [CYCLE.TWO_YEARS]: 0, [CYCLE.THIRTY]: 0, [CYCLE.FIFTEEN]: 0 },
            plans: {
                [CYCLE.MONTHLY]: 0,
                [CYCLE.YEARLY]: 0,
                [CYCLE.TWO_YEARS]: 0,
                [CYCLE.THIRTY]: 0,
                [CYCLE.FIFTEEN]: 0,
            },
        }
    );

    const getTotal = (cycle: CYCLE): TotalPricing => {
        const total = pricing.all[cycle];
        const totalPerMonth = pricing.plans[cycle] / cycle;
        const discount = cycle === CYCLE.MONTHLY ? 0 : pricing.all[CYCLE.MONTHLY] * cycle - total;
        return {
            discount,
            total,
            totalPerMonth,
        };
    };

    const monthlySuffix = getMonthlySuffix(planIDs);

    const totals = allCycles.reduce<{ [key in CYCLE]: { discount: number; total: number; totalPerMonth: number } }>(
        (acc, cycle) => {
            acc[cycle] = getTotal(cycle);
            return acc;
        },
        {} as any
    );

    if (cycles.length === 1) {
        const cycle = cycles[0];

        return (
            <div className={singleClassName}>
                <CycleItem monthlySuffix={monthlySuffix} totals={totals} cycle={cycle} currency={currency} />
            </div>
        );
    }

    if (mode === 'select') {
        return (
            <InputField
                label={c('Label').t`Billing cycle`}
                as={SelectTwo}
                bigger
                value={cycleSelected}
                onValue={(value: any) => onChangeCycle(value)}
                assistiveText={
                    <Price currency={currency} suffix={monthlySuffix}>
                        {totals[cycleSelected].totalPerMonth}
                    </Price>
                }
            >
                {cycles.map((cycle) => {
                    return (
                        <Option value={cycle} title={getText(cycle)} key={cycle}>
                            <div className="flex flex-justify-space-between">
                                <span className="flex-item-noshrink">{getText(cycle)}</span>
                                <span
                                    className={classnames([
                                        'flex-item-noshrink',
                                        cycle !== cycleSelected && 'color-success',
                                    ])}
                                >
                                    {getDiscountPrice(totals[cycle].discount, currency)}
                                </span>
                            </div>
                        </Option>
                    );
                })}
            </InputField>
        );
    }

    return (
        <ul className="unstyled m0 plan-cycle-selector">
            {cycles.map((cycle) => {
                const isSelected = cycle === cycleSelected;
                return (
                    <li key={`${cycle}`} className="flex flex-align-items-stretch mb1">
                        <button
                            className={classnames([
                                'w100 p1 plan-cycle-button flex flex-nowrap border rounded text-left',
                                isSelected && 'border-primary',
                                isSelected && 'border-2',
                            ])}
                            disabled={disabled}
                            onClick={() => onChangeCycle(cycle)}
                            type="button"
                            aria-pressed={isSelected}
                        >
                            <div className="flex-item-noshrink" aria-hidden="true">
                                <Radio
                                    id={`${cycle}`}
                                    name="cycleFakeField"
                                    tabIndex={-1}
                                    checked={isSelected}
                                    readOnly
                                />
                            </div>
                            <CycleItem
                                totals={totals}
                                monthlySuffix={monthlySuffix}
                                currency={currency}
                                cycle={cycle}
                            />
                        </button>
                    </li>
                );
            })}
        </ul>
    );
};

export default SubscriptionCycleSelector;