index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CreditsSection.test.tsx
import { render } from '@testing-library/react'; import { mockSubscriptionCache, mockUserCache, userDefaultResponse } from '@proton/components/hooks/helpers/test'; import { PLANS } from '@proton/shared/lib/constants'; import { External, Subscription, SubscriptionModel } from '@proton/shared/lib/interfaces'; import { formatUser } from '@proton/shared/lib/models/userModel'; import { applyHOCs, withApi, withCache } from '@proton/testing/index'; import CreditsSection from './CreditsSection'; let subscription: SubscriptionModel; let upcoming: Subscription | null = null; let user: any; jest.mock('@proton/components/components/portal/Portal'); const ContextCreditsSection = applyHOCs(withApi(), withCache())(CreditsSection); beforeEach(() => { subscription = { ID: '123', InvoiceID: '1234', Cycle: 1, PeriodStart: 1696561158, PeriodEnd: 1699239558, CreateTime: 1696561161, CouponCode: null, Currency: 'CHF', Amount: 1299, Discount: 0, RenewAmount: 1299, Plans: [ { ID: '1', Type: 1, Name: PLANS.BUNDLE, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Cycle: 1, Currency: 'CHF', Amount: 1299, Offers: [], Quantity: 1, Pricing: { 1: 1299, 12: 11988, 24: 19176, }, }, ], Renew: 1, External: 0, UpcomingSubscription: null, isManagedByMozilla: false, }; upcoming = { ID: '124', InvoiceID: null as any, Cycle: 12, PeriodStart: 1699239558, PeriodEnd: 1730861958, CreateTime: 1696561195, CouponCode: null, Currency: 'CHF', Amount: 11988, Discount: 0, RenewAmount: 11988, Plans: [ { ID: '1', Type: 1, Name: PLANS.BUNDLE, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Cycle: 12, Currency: 'CHF', Amount: 11988, Quantity: 1, Offers: [], Pricing: { 1: 1299, 12: 11988, 24: 19176, }, }, ], Renew: 1, External: 0, }; jest.clearAllMocks(); user = { ...userDefaultResponse, }; user.User.Credit = 11988; // credit to buy the upcoming subscription mockUserCache(formatUser(user.User)); mockSubscriptionCache(subscription); }); it('should render', () => { const { container } = render(<ContextCreditsSection />); expect(container).not.toBeEmptyDOMElement(); }); it('should display the number of available credits', () => { const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('119.88'); }); it('should render 0 credits if the amount of credits is the same as upcoming subscription price', () => { subscription.UpcomingSubscription = upcoming; const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('0'); }); it('should render positive amount of credits if there are more credits than upcoming subscription price', () => { user.User.Credit = 12988; mockUserCache(formatUser(user.User)); subscription.UpcomingSubscription = upcoming; const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('10'); }); it('should render 0 if the number of available credits is less than price of upcoming subscription', () => { user.User.Credit = 10000; mockUserCache(formatUser(user.User)); subscription.UpcomingSubscription = upcoming; const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('0'); }); it('should render credits as-is if subscription is managed by Chargebee', () => { subscription.External = External.Chargebee; subscription.UpcomingSubscription = upcoming; subscription.UpcomingSubscription!.External = External.Chargebee; user.User.Credit = 12988; mockUserCache(formatUser(user.User)); const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('129.88'); }); it('should display loader if subscription is not available', () => { mockSubscriptionCache(null as any); const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('circle-loader')).toBeInTheDocument(); }); it('should take into account discount', () => { subscription.UpcomingSubscription = upcoming; subscription.UpcomingSubscription!.Discount = 1988; const { getByTestId } = render(<ContextCreditsSection />); expect(getByTestId('avalaible-credits')).toHaveTextContent('19.88'); });
6,700
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CreditsSection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { isFreeSubscription } from '@proton/shared/lib/constants'; import { getHasVpnB2BPlan, isManagedExternally } from '@proton/shared/lib/helpers/subscription'; import { External } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import { Loader } from '../../components'; import { useModalState, useModalTwo } from '../../components/modalTwo'; import { useTypedSubscription, useUser } from '../../hooks'; import { SettingsParagraph, SettingsSection } from '../account'; import CreditsModal from './CreditsModal'; import InAppPurchaseModal from './subscription/InAppPurchaseModal'; const CreditsSection = () => { const [subscription] = useTypedSubscription(); const [creditModalProps, setCreditModalOpen, renderCreditModal] = useModalState(); const [externalSubscriptionModal, showExternalSubscriptionModal] = useModalTwo(InAppPurchaseModal); const [{ Credit }] = useUser(); if (!subscription) { return <Loader />; } let upcomingSubscriptionPrice: number = 0; // In case of Chargebee, they don't display the balance for the upcoming subscription. // Instead, they count it as already paid, and they return credits balance already taking into account // the upcoming subscription. if ( !isFreeSubscription(subscription) && subscription.External !== External.Chargebee && subscription?.UpcomingSubscription ) { upcomingSubscriptionPrice = subscription.UpcomingSubscription.Amount - subscription.UpcomingSubscription.Discount; } let availableCredits = (Credit - upcomingSubscriptionPrice) / 100; if (availableCredits < 0) { availableCredits = 0; } const hasVpnB2B = getHasVpnB2BPlan(subscription); return ( <SettingsSection> <SettingsParagraph> {c('Info') .t`When your subscription renews, we will apply any available credits before we charge the payment method above.`} </SettingsParagraph> {hasVpnB2B ? null : ( <div className="mb-7"> <Button shape="outline" onClick={() => { if (isManagedExternally(subscription)) { showExternalSubscriptionModal({ subscription, key: 'external-subscription-modal', }).catch(noop); return; } setCreditModalOpen(true); }} >{c('Action').t`Add credits`}</Button> </div> )} <div className="px-4 mb-4 flex flex-justify-space-between"> <span className="text-bold" data-testid="unused-credits">{c('Credits').t`Available credits`}</span> <span className="text-bold" data-testid="avalaible-credits"> {availableCredits} </span> </div> <hr /> {renderCreditModal && <CreditsModal {...creditModalProps} />} {externalSubscriptionModal} </SettingsSection> ); }; export default CreditsSection;
6,701
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CurrencySelector.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Props as SelectProps } from '@proton/components/components/selectTwo/SelectTwo'; import { CURRENCIES, DEFAULT_CURRENCY } from '@proton/shared/lib/constants'; import { Currency } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { ButtonGroup, Option, SelectTwo } from '../../components'; interface SelectTwoProps extends Omit<SelectProps<Currency>, 'onSelect' | 'children'> { mode: 'select-two'; currency?: Currency; onSelect: (newCurrency: Currency) => void; } interface ButtonGroupProps { mode: 'buttons'; onSelect: (newCurrency: Currency) => void; currency?: Currency; loading?: boolean; className?: string; id?: string; disabled?: boolean; } type Props = ButtonGroupProps | SelectTwoProps; const CurrencySelector = (props: Props) => { const options = CURRENCIES.map((c) => ({ text: c, value: c })); if (props.mode === 'buttons') { const { currency = DEFAULT_CURRENCY, onSelect, loading, ...rest } = props; return ( <ButtonGroup {...rest}> {options.map(({ text, value }) => { return ( <Button className={clsx([currency === value && 'is-selected'])} key={value} onClick={() => onSelect(value as Currency)} disabled={loading} > {text} </Button> ); })} </ButtonGroup> ); } if (props.mode === 'select-two') { const { currency = DEFAULT_CURRENCY, onSelect, loading, ...rest } = props; const handleChange = ({ value }: { value: Currency }) => onSelect(value); return ( <SelectTwo value={currency} onChange={handleChange} loading={loading} aria-describedby={c('Title').t`Currency`} {...rest} > {options.map(({ text, value }) => { return ( <Option value={value} title={text} key={value}> {text} </Option> ); })} </SelectTwo> ); } return null; }; export default CurrencySelector;
6,702
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CycleSelector.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { CYCLE, DEFAULT_CYCLE } from '@proton/shared/lib/constants'; import { omit } from '@proton/shared/lib/helpers/object'; import { Cycle } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import ButtonGroup, { Props as ForwardedButtonGroupProps } from '../../components/button/ButtonGroup'; import Option from '../../components/option/Option'; import Select, { Props as ForwardedSelectProps } from '../../components/select/Select'; import SelectTwo, { Props as ForwardedSelectTwoProps } from '../../components/selectTwo/SelectTwo'; const { MONTHLY, YEARLY, TWO_YEARS } = CYCLE; interface SharedProps { cycle: Cycle; onSelect: (newCycle: Cycle) => void; options?: ForwardedSelectProps['options']; disabled?: boolean; } interface SelectProps extends Omit<ForwardedSelectProps, 'onSelect' | 'onChange' | 'options'>, SharedProps { mode: 'select'; } interface SelectTwoProps extends Omit<ForwardedSelectTwoProps<Cycle>, 'onSelect' | 'children' | 'onChange' | 'value'>, SharedProps { mode: 'select-two'; } interface ButtonGroupProps extends Omit<ForwardedButtonGroupProps, 'onSelect' | 'children'>, SharedProps { mode: 'buttons'; } type Props = ButtonGroupProps | SelectProps | SelectTwoProps; const propsToOmit = ['onSelect', 'options', 'cycle', 'disabled'] as const; const CycleSelector = (props: Props) => { const { onSelect, options = [ { text: c('Billing cycle option').t`Monthly`, value: MONTHLY }, { text: c('Billing cycle option').t`Annually`, value: YEARLY }, { text: c('Billing cycle option').t`Two-year`, value: TWO_YEARS }, ], cycle = DEFAULT_CYCLE, disabled, } = props; if (props.mode === 'buttons') { const rest = omit(props, propsToOmit); return ( <ButtonGroup {...rest}> {options.map(({ text, value }) => { // translator: this text is only for screen readers, "Billing cycle: ${text}" (${text} contains: "1 month", "12 months" or "24 months") const billingCycleVocalizedText = c('Info').t`Billing cycle: ${text}`; const isSelected = cycle === value; return ( <Button className={clsx(isSelected && 'is-selected')} key={value} onClick={() => onSelect(value as Cycle)} disabled={disabled} aria-label={billingCycleVocalizedText} aria-pressed={isSelected} > {text} </Button> ); })} </ButtonGroup> ); } if (props.mode === 'select-two') { const rest = omit(props, propsToOmit); return ( <SelectTwo {...rest} value={cycle} onChange={({ value }) => onSelect(value)} disabled={disabled}> {options.map(({ text, value }) => { return ( <Option value={value} title={`${text}`}> {text} </Option> ); })} </SelectTwo> ); } const rest = omit(props, propsToOmit); return ( <Select {...rest} title={c('Title').t`Billing cycle`} value={cycle} options={options} onChange={({ target }) => onSelect(+target.value as Cycle)} /> ); }; export default CycleSelector;
6,703
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/DowngradeModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { MAIL_APP_NAME, VPN_APP_NAME } from '@proton/shared/lib/constants'; import { Alert, ModalProps, Prompt } from '../../components'; interface Props extends ModalProps { hasMail: boolean; hasVpn: boolean; onConfirm: () => void; } const DowngradeModal = ({ hasMail, hasVpn, onConfirm, onClose, ...rest }: Props) => { const hasBundle = hasMail && hasVpn; return ( <Prompt title={c('Title').t`Confirm downgrade`} buttons={[ <Button onClick={() => { onConfirm(); onClose?.(); }} color="norm" data-testid="confirm-downgrade-btn" > {c('Action').t`Downgrade`} </Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} onClose={onClose} data-testid="confirm-downgrade-modal" {...rest} > <Alert className="mb-4" type="error"> {(() => { if (hasBundle) { return c('Info') .t`If you proceed with the downgrade, you will lose access to ${MAIL_APP_NAME} and ${VPN_APP_NAME} paid features.`; } if (hasMail) { return c('Info') .t`If you proceed with the downgrade, you will lose access to ${MAIL_APP_NAME} paid features, including additional storage and filters.`; } return c('Info') .t`If you proceed with the downgrade, you will lose access to ${VPN_APP_NAME} paid features.`; })()} </Alert> <Alert type="warning"> {[ hasMail && c('Info') .t`You must disable or remove any additional ${MAIL_APP_NAME} users, addresses, and custom domains before you can downgrade.`, hasVpn && c('Info').t`Downgrading will terminate any connections to paid ${VPN_APP_NAME} servers.`, ] .filter(Boolean) .join(' ')} </Alert> </Prompt> ); }; export default DowngradeModal;
6,704
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/EditCardModal.test.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import { Autopay, CardModel } from '@proton/components/payments/core'; import { updatePaymentMethod } from '@proton/shared/lib/api/payments'; import { apiMock, applyHOCs, withApi, withCache, withDeprecatedModals, withEventManager, withNotifications, } from '@proton/testing'; import EditCardModal from './EditCardModal'; jest.mock('@proton/components/components/portal/Portal'); jest.mock('@proton/components/components/toggle/Toggle'); const defaultCard: CardModel = { number: '', month: '', year: '', cvc: '', zip: '', country: 'US', }; beforeEach(() => { jest.clearAllMocks(); }); const ContextEditCardModal = applyHOCs( withNotifications(), withEventManager(), withApi(), withCache(), withDeprecatedModals() )(EditCardModal); it('should render', () => { const { container } = render(<ContextEditCardModal open={true} />); expect(container).not.toBeEmptyDOMElement(); }); it('should update Autopay and close modal if user edits the existing payment method', async () => { const paymentMethodId = 'paymentMethodId123'; const onClose = jest.fn(); const { getByTestId } = render( <ContextEditCardModal card={defaultCard} renewState={Autopay.DISABLE} paymentMethodId={paymentMethodId} open={true} onClose={onClose} /> ); fireEvent.click(getByTestId('toggle-subscription-renew')); await waitFor(() => { expect(apiMock).toHaveBeenCalledWith(updatePaymentMethod(paymentMethodId, { Autopay: Autopay.ENABLE })); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should update Autopay and close modal if user edits the existing payment method (toggle off)', async () => { const paymentMethodId = 'paymentMethodId123'; const onClose = jest.fn(); const { getByTestId } = render( <ContextEditCardModal card={defaultCard} renewState={Autopay.ENABLE} paymentMethodId={paymentMethodId} open={true} onClose={onClose} /> ); fireEvent.click(getByTestId('toggle-subscription-renew')); fireEvent.click(getByTestId('action-disable-autopay')); await waitFor(() => { expect(apiMock).toHaveBeenCalledWith(updatePaymentMethod(paymentMethodId, { Autopay: Autopay.DISABLE })); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should not update autopay if this is Add Credit card mode', async () => { const onClose = jest.fn(); const { getByTestId } = render(<ContextEditCardModal open={true} onClose={onClose} />); fireEvent.click(getByTestId('toggle-subscription-renew')); fireEvent.click(getByTestId('action-disable-autopay')); await waitFor(() => {}); expect(apiMock).not.toHaveBeenCalled(); expect(onClose).not.toHaveBeenCalled(); }); it('should toggle back if API returned error', async () => { apiMock.mockRejectedValue(new Error()); const paymentMethodId = 'paymentMethodId123'; const onClose = jest.fn(); const { getByTestId } = render( <ContextEditCardModal card={defaultCard} renewState={Autopay.DISABLE} paymentMethodId={paymentMethodId} open={true} onClose={onClose} /> ); fireEvent.click(getByTestId('toggle-subscription-renew')); await waitFor(() => { expect(apiMock).toHaveBeenCalledWith(updatePaymentMethod(paymentMethodId, { Autopay: Autopay.ENABLE })); }); await waitFor(() => { expect(onClose).not.toHaveBeenCalled(); }); await waitFor(() => { expect(getByTestId('toggle-subscription-renew')).not.toHaveTextContent('CHECKED'); }); }); it('should disable Save button while updating the toggle status', async () => { let resolve!: () => void; const manualPromise = new Promise<void>((innerResolve) => (resolve = innerResolve)); apiMock.mockReturnValue(manualPromise); const paymentMethodId = 'paymentMethodId123'; const onClose = jest.fn(); const { getByTestId } = render( <ContextEditCardModal card={defaultCard} renewState={Autopay.DISABLE} paymentMethodId={paymentMethodId} open={true} onClose={onClose} /> ); fireEvent.click(getByTestId('toggle-subscription-renew')); await waitFor(() => { expect(getByTestId('edit-card-action-save')).toHaveAttribute('disabled'); }); resolve(); await waitFor(() => { expect(getByTestId('edit-card-action-save')).not.toHaveAttribute('disabled'); }); });
6,705
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/EditCardModal.tsx
import { FormEvent } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getDefaultVerifyPayment } from '@proton/components/payments/client-extensions/validators/validators'; import { Autopay, isTokenPayment } from '@proton/components/payments/core'; import { useCard } from '@proton/components/payments/react-extensions'; import { useLoading } from '@proton/hooks'; import { setPaymentMethod, updatePaymentMethod } from '@proton/shared/lib/api/payments'; import { captureMessage } from '@proton/shared/lib/helpers/sentry'; import { getSentryError } from '@proton/shared/lib/keys'; import noop from '@proton/utils/noop'; import { ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../components'; import { useApi, useEventManager, useModals, useNotifications } from '../../hooks'; import { CardModel } from '../../payments/core'; import CreditCard from './CreditCard'; import RenewToggle, { useRenewToggle } from './RenewToggle'; interface Props extends Omit<ModalProps<'form'>, 'as' | 'children' | 'size'> { card?: CardModel; renewState?: Autopay; paymentMethodId?: string; } const EditCardModal = ({ card: existingCard, renewState, paymentMethodId, ...rest }: Props) => { const api = useApi(); const { createModal } = useModals(); const { call } = useEventManager(); const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const title = existingCard ? c('Title').t`Edit credit/debit card` : c('Title').t`Add credit/debit card`; const { onChange: renewOnChange, setRenewState, ...renewToggleProps } = useRenewToggle({ initialRenewState: renewState }); const cardHook = useCard( { verifyOnly: true, amountAndCurrency: { Amount: 0, Currency: 'USD', }, initialCard: existingCard, onChargeable: async (chargeablePaymentParameters) => { withLoading(async () => { const { Payment } = chargeablePaymentParameters; if (!isTokenPayment(Payment)) { return; } await api( setPaymentMethod({ ...Payment, Autopay: renewToggleProps.renewState, }) ); await call(); rest.onClose?.(); createNotification({ text: c('Success').t`Payment method updated` }); }).catch(noop); }, }, { api, verifyPayment: getDefaultVerifyPayment(createModal, api) } ); const process = async () => { try { await cardHook.processPaymentToken(); } catch (e) { const error = getSentryError(e); if (error) { const context = { hasExistingCard: !!existingCard, renewState, paymentMethodId, processorType: cardHook.meta.type, }; captureMessage('Payments: failed to add card', { level: 'error', extra: { error, context }, }); } } }; return ( <ModalTwo size="small" as="form" onSubmit={(event: FormEvent) => { event.preventDefault(); withLoading(process()).catch(noop); }} {...rest} > <ModalTwoHeader title={title} /> <ModalTwoContent> <CreditCard card={cardHook.card} errors={cardHook.errors} onChange={cardHook.setCardProperty} loading={loading} fieldsStatus={cardHook.fieldsStatus} /> <RenewToggle loading={loading} onChange={async () => { const result = await renewOnChange(); // Case when the change wasn't done. For example because user canceled the change and decided to keep the setting as-is. if (result === null) { return; } // Case when <EditCardModal /> is rendered in Add mode. In this case there is no existing paymentMethodId. if (!paymentMethodId) { return; } void withLoading(async () => { try { await api( updatePaymentMethod(paymentMethodId, { Autopay: result, }) ); await call().catch(noop); const text = result === Autopay.ENABLE ? c('Subscription renewal state').t`Auto-pay is enabled` : c('Subscription renewal state').t`Auto-pay is disabled`; createNotification({ text }); rest.onClose?.(); } catch { setRenewState(result === Autopay.ENABLE ? Autopay.DISABLE : Autopay.ENABLE); } }); }} {...renewToggleProps} /> </ModalTwoContent> <ModalTwoFooter> <Button disabled={loading} onClick={rest.onClose}>{c('Action').t`Cancel`}</Button> <Button loading={loading} color="norm" type="submit" data-testid="edit-card-action-save">{c('Action') .t`Save`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default EditCardModal;
6,706
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/GiftCodeSection.tsx
import { ChangeEvent, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { buyCredit, validateCredit } from '@proton/shared/lib/api/payments'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { InputFieldTwo, useFormErrors } from '../../components'; import { useApiWithoutResult, useEventManager, useNotifications } from '../../hooks'; import { SettingsSection } from '../account'; import SettingsParagraph from '../account/SettingsParagraph'; const GiftCodeSection = () => { const [value, setValue] = useState(''); const { validator, reset, onFormSubmit } = useFormErrors(); const [loading, withLoading] = useLoading(); const { request: requestBuyCredit } = useApiWithoutResult(buyCredit); const { request: requestValidateCredit } = useApiWithoutResult(validateCredit); const { call } = useEventManager(); const { createNotification } = useNotifications(); const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => { setValue(target.value.replace(/\s|\t/g, '').toUpperCase()); }; const submit = async () => { await requestValidateCredit({ GiftCode: value }); await requestBuyCredit({ GiftCode: value, Amount: 0 }); await call(); setValue(''); reset(); createNotification({ text: c('Success').t`Gift code applied` }); }; return ( <SettingsSection> <SettingsParagraph> {c('Info').t`If you have a gift code, enter it below to apply your discount.`} </SettingsParagraph> <label htmlFor="gift-code-input" className="sr-only"> {c('Label').t`Gift code`} </label> <form className="gift-code_container flex flex-nowrap flex-align-items-start on-mobile-flex-column-no-stretch" onSubmit={(e) => { e.preventDefault(); if (onFormSubmit()) { withLoading(submit()); } }} > <InputFieldTwo id="gift-code-input" rootClassName="mr-0 mb-2 md:mr-4 md:mb-0" value={value} error={validator([requiredValidator(value)])} placeholder={c('Placeholder').t`Add gift code`} onChange={handleChange} /> <Button className="on-mobile-flex-align-self-start flex-item-noshrink" color="norm" type="submit" data-testid="submitCodeBtn" loading={loading} > {c('Action').t`Submit`} </Button> </form> </SettingsSection> ); }; export default GiftCodeSection;
6,707
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/LossLoyaltyModal.tsx
import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { BRAND_NAME, VPN_APP_NAME } from '@proton/shared/lib/constants'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { Organization } from '@proton/shared/lib/interfaces'; import { ModalProps, Prompt } from '../../components'; interface Props extends ModalProps { organization: Organization; onConfirm: () => void; } const LossLoyaltyModal = ({ organization, onConfirm, onClose, ...rest }: Props) => { const bonusSpace = organization.BonusSpace && humanSize(organization.BonusSpace, 'GB'); return ( <Prompt title={c('Title').t`Confirm loss of ${BRAND_NAME} bonuses`} buttons={[ <Button onClick={() => { onConfirm(); onClose?.(); }} color="danger" data-testid="confirm-loss-btn" > {c('Action').t`Remove bonuses`} </Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} onClose={onClose} data-testid="confirm-loss" {...rest} > <div className="mb-4"> {c('Info').t`Since you're a loyal user, your account has additional features enabled.`} </div> <div> {c('Info') .t`By downgrading to a Free plan, you will permanently lose these benefits, even if you upgrade again in the future.`} <ul> {organization.BonusSpace ? <li>{c('Info').t`+${bonusSpace} bonus storage`}</li> : null} {organization.BonusVPN ? ( <li> {c('Info').ngettext( msgid`+${organization.BonusVPN} connection for ${VPN_APP_NAME} (allows you to connect more devices to VPN)`, `+${organization.BonusVPN} connections for ${VPN_APP_NAME} (allows you to connect more devices to VPN)`, organization.BonusVPN )} </li> ) : null} </ul> </div> </Prompt> ); }; export default LossLoyaltyModal;
6,708
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/MemberDowngradeModal.tsx
import { FormEvent, useState } from 'react'; import { c } from 'ttag'; import { Button, Card } from '@proton/atoms'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { hasFamily } from '@proton/shared/lib/helpers/subscription'; import { Organization } from '@proton/shared/lib/interfaces'; import { useSubscription } from '../..'; import { Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, useFormErrors, } from '../../components'; interface Props extends ModalProps { organization: Organization; onConfirm: () => void; } const MemberDowngradeModal = ({ organization, onConfirm, onClose, ...rest }: Props) => { const [subscription] = useSubscription(); const { validator, onFormSubmit } = useFormErrors(); const [confirmText, setConfirmText] = useState(''); const organizationName = organization.Name; const modalTitle = hasFamily(subscription) ? c('familyOffer_2023:Title').t`Delete family group?` : c('familyOffer_2023:Title').t`Delete organization?`; const warningMessage = hasFamily(subscription) ? c('familyOffer_2023:Member downgrade modal') .t`This will remove all ${BRAND_NAME} premium features for every family member.` : c('familyOffer_2023:Member downgrade modal') .t`This will permanently delete all sub-users, accounts, and data associated with your organization.`; const label = hasFamily(subscription) ? c('familyOffer_2023:Label').t`Enter family group name to confirm` : c('familyOffer_2023:Label').t`Enter organization name to confirm`; const validatorError = hasFamily(subscription) ? c('familyOffer_2023:Error').t`Family group not recognized. Try again.` : c('familyOffer_2023:Error').t`Organization not recognized. Try again.`; return ( <Modal as={Form} onSubmit={(event: FormEvent) => { event.preventDefault(); if (!onFormSubmit()) { return; } onConfirm(); onClose?.(); }} onClose={onClose} {...rest} > <ModalHeader title={modalTitle} /> <ModalContent> <div className="mb-4">{warningMessage}</div> <Card rounded className="text-break user-select mb-4"> {organizationName} </Card> <InputFieldTwo id="confirm-text" bigger label={label} error={validator([ requiredValidator(confirmText), confirmText !== organizationName ? validatorError : '', ])} autoFocus value={confirmText} onValue={setConfirmText} /> </ModalContent> <ModalFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button type="submit" color="danger"> {c('Action').t`Delete`} </Button> </ModalFooter> </Modal> ); }; export default MemberDowngradeModal;
6,709
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PayPalButton.tsx
import { c } from 'ttag'; import { Button, ButtonProps } from '@proton/atoms'; import { PaypalProcessorHook } from '@proton/components/payments/react-extensions/usePaypal'; import { Currency } from '@proton/shared/lib/interfaces'; import { PaymentMethodFlows } from '../paymentMethods/interface'; export type PayPalButtonProps = ButtonProps & { amount: number; flow?: PaymentMethodFlows; prefetchToken?: boolean; currency: Currency; paypal: PaypalProcessorHook; }; export const PayPalButton = ({ amount, flow, children, paypal, loading, disabled: disabledProp, currency, onClick, ...rest }: PayPalButtonProps) => { const disabled = disabledProp || paypal.disabled; if (paypal.verifyingToken) { return <Button loading {...rest}>{c('Action').t`Loading verification`}</Button>; } if (paypal.verificationError) { return ( <Button onClick={paypal.fetchPaymentToken} disabled={disabled} loading={paypal.processingToken} {...rest} >{c('Action').t`Retry`}</Button> ); } return ( <Button loading={paypal.processingToken || loading} disabled={disabled} onClick={onClick} {...rest}> {children} </Button> ); }; export default PayPalButton;
6,710
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PayPalInfoMessage.tsx
import { c } from 'ttag'; const PayPalInfoMessage = () => { const payPalInfoMessage = c('Info') .t`We will redirect you to PayPal in a new browser tab to complete this transaction. If you use any pop-up blockers, please disable them to continue.`; return <div className="mb-4">{payPalInfoMessage}</div>; }; export default PayPalInfoMessage;
6,711
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PayPalModal.tsx
import { useEffect, useRef } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ensureTokenChargeable } from '@proton/components/payments/client-extensions'; import { PAYMENT_METHOD_TYPES } from '@proton/components/payments/core'; import { useLoading } from '@proton/hooks'; import { createToken, setPaymentMethod } from '@proton/shared/lib/api/payments'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { ModalProps, Prompt } from '../../components'; import { useApi, useEventManager, useNotifications } from '../../hooks'; import { PaymentTokenResult } from '../../payments/core/interface'; const PAYMENT_AUTHORIZATION_AMOUNT = 100; const PAYMENT_AUTHORIZATION_CURRENCY = 'CHF'; const PayPalModal = ({ onClose, ...rest }: ModalProps) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loadingToken, withLoadingToken] = useLoading(); const [loading, withLoading] = useLoading(); const abortRef = useRef<AbortController>(); const paypalRef = useRef<PaymentTokenResult | undefined>(); const paymentMethodType = PAYMENT_METHOD_TYPES.PAYPAL; useEffect(() => { const run = async () => { const result = await api<PaymentTokenResult>( createToken({ Amount: PAYMENT_AUTHORIZATION_AMOUNT, Currency: PAYMENT_AUTHORIZATION_CURRENCY, Payment: { Type: paymentMethodType, }, }) ); paypalRef.current = result; }; void withLoadingToken(run()); return () => { abortRef.current?.abort(); }; }, []); const handleSubmit = async (data: PaymentTokenResult) => { try { abortRef.current = new AbortController(); await ensureTokenChargeable({ Token: data.Token, api, ApprovalURL: data.ApprovalURL, ReturnHost: data.ReturnHost, signal: abortRef.current.signal, }); await api( setPaymentMethod({ Type: PAYMENT_METHOD_TYPES.TOKEN, Details: { Token: data.Token, }, }) ); await call(); onClose?.(); createNotification({ text: c('Success').t`Payment method added` }); } catch (error: any) { // if not coming from API error if (error && error.message && !error.config) { createNotification({ text: error.message, type: 'error' }); } } }; return ( <Prompt data-testid="addPPalModalTitle" title={c('Title').t`Add PayPal payment method`} onClose={onClose} buttons={[ <Button color="norm" loading={loading} disabled={loadingToken} onClick={() => { if (!paypalRef.current) { return; } void withLoading(handleSubmit(paypalRef.current)); }} >{c('Action').t`Add PayPal`}</Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {loading ? ( <> <div className="mb-4">{c('Info').t`Please verify payment at the new tab which was opened.`}</div> <div>{c('Info').t`Verification can take a few minutes.`}</div> </> ) : ( <> <div className="mb-4"> {c('Info') .t`This will enable PayPal to be used to pay for your ${BRAND_NAME} subscription. We will redirect you to PayPal in a new browser tab. If you use any pop-up blockers, please disable them to continue.`} </div> <div> {c('Info') .t`You must have a credit card or bank account linked with your PayPal account in order to add it as a payment method.`} </div> </> )} </Prompt> ); }; export default PayPalModal;
6,712
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PayPalView.test.tsx
import { render } from '@testing-library/react'; import { renderHook } from '@testing-library/react-hooks'; import { usePaypal } from '@proton/components/payments/react-extensions/usePaypal'; import { Currency } from '@proton/shared/lib/interfaces'; import { apiMock, mockVerifyPayment } from '@proton/testing'; import PayPalView from './PayPalView'; const onChargeable = jest.fn(); const onClick = jest.fn(); beforeEach(() => { jest.clearAllMocks(); }); let amountAndCurrency = { Amount: 1000, Currency: 'EUR' as Currency, }; function paypalHook({ isCredit, Amount, Currency, mockVerificationResult, }: { isCredit: boolean; mockVerificationResult?: boolean; Amount: number; Currency: Currency; }) { const verifyPayment = mockVerifyPayment(); if (mockVerificationResult) { verifyPayment.mockVerification(); } return renderHook( ({ amountAndCurrency }) => usePaypal( { amountAndCurrency, onChargeable, isCredit, }, { api: apiMock, verifyPayment: mockVerifyPayment(), } ), { initialProps: { amountAndCurrency: { Amount, Currency, }, }, } ); } it('should render', () => { const { result: paypal } = paypalHook({ isCredit: false, ...amountAndCurrency }); const { result: paypalCredit } = paypalHook({ isCredit: true, ...amountAndCurrency }); const { container } = render( <PayPalView type="credit" paypal={paypal.current} paypalCredit={paypalCredit.current} onClick={onClick} amount={amountAndCurrency.Amount} currency={amountAndCurrency.Currency} /> ); expect(container).not.toBeEmptyDOMElement(); }); it('should render the message of paypal credit and "click here" button', () => { const { result: paypal } = paypalHook({ isCredit: false, ...amountAndCurrency }); const { result: paypalCredit } = paypalHook({ isCredit: true, ...amountAndCurrency }); const { getByText, getByTestId } = render( <PayPalView type="credit" paypal={paypal.current} paypalCredit={paypalCredit.current} onClick={onClick} amount={amountAndCurrency.Amount} currency={amountAndCurrency.Currency} /> ); const message = `You must have a credit card or bank account linked with your PayPal account. If your PayPal account doesn't have that, please click on the button below.`; expect(getByText(message)).toBeInTheDocument(); expect(getByTestId('paypal-credit-button')).toBeInTheDocument(); }); it('should disable the "click here" button when triggers are disabled', () => { const { result: paypal } = paypalHook({ isCredit: false, ...amountAndCurrency }); const { result: paypalCredit } = paypalHook({ isCredit: true, ...amountAndCurrency }); const { getByTestId } = render( <PayPalView type="credit" paypal={paypal.current} paypalCredit={paypalCredit.current} onClick={onClick} amount={amountAndCurrency.Amount} currency={amountAndCurrency.Currency} triggersDisabled={true} /> ); expect(getByTestId('paypal-credit-button')).toBeDisabled(); }); it('should disable the "click here" button when paypal credit is in initial state', () => { const { result: paypal } = paypalHook({ isCredit: false, ...amountAndCurrency }); const { result: paypalCredit } = paypalHook({ isCredit: true, ...amountAndCurrency }); const { getByTestId } = render( <PayPalView type="credit" paypal={paypal.current} paypalCredit={paypalCredit.current} onClick={onClick} amount={amountAndCurrency.Amount} currency={amountAndCurrency.Currency} /> ); expect(getByTestId('paypal-credit-button')).toBeDisabled(); });
6,713
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PayPalView.tsx
import { c } from 'ttag'; import { PaypalProcessorHook } from '@proton/components/payments/react-extensions/usePaypal'; import { MAX_PAYPAL_AMOUNT, MIN_PAYPAL_AMOUNT } from '@proton/shared/lib/constants'; import { Currency } from '@proton/shared/lib/interfaces'; import { Alert, Price } from '../../components'; import { PaymentMethodFlows } from '../paymentMethods/interface'; import PayPalButton from './PayPalButton'; import PayPalInfoMessage from './PayPalInfoMessage'; interface Props { paypal: PaypalProcessorHook; paypalCredit: PaypalProcessorHook; type?: PaymentMethodFlows; amount: number; currency: Currency; disabled?: boolean; prefetchToken?: boolean; onClick?: () => void; triggersDisabled?: boolean; } const PayPalView = ({ type, amount, currency, paypalCredit, disabled, prefetchToken, onClick, triggersDisabled, }: Props) => { if (amount < MIN_PAYPAL_AMOUNT) { return ( <Alert className="mb-4" type="error"> {c('Error').t`Amount below minimum.`} {`(${(<Price currency={currency}>{MIN_PAYPAL_AMOUNT}</Price>)})`} </Alert> ); } if (amount > MAX_PAYPAL_AMOUNT) { return <Alert className="mb-4" type="error">{c('Error').t`Amount above the maximum.`}</Alert>; } const clickHere = ( <PayPalButton id="paypal-credit" data-testid="paypal-credit-button" shape="outline" color="norm" flow={type} key="click-here" size="small" paypal={paypalCredit} amount={amount} disabled={disabled || paypalCredit.isInitialState || triggersDisabled} prefetchToken={prefetchToken} currency={currency} onClick={onClick} loading={paypalCredit.processingToken} > {c('Link').t`click here`} </PayPalButton> ); const allowedPaymentTypes: PaymentMethodFlows[] = ['signup', 'signup-pass', 'subscription', 'invoice', 'credit']; const isAllowedPaymentType = type && allowedPaymentTypes.includes(type); const allowedOtherTypes: PaymentMethodFlows[] = ['donation', 'human-verification']; const isAllowedOtherType = type && allowedOtherTypes.includes(type); return ( <div className="p-4 border rounded bg-weak mb-4" data-testid="paypal-view"> {isAllowedPaymentType ? ( <> <PayPalInfoMessage /> <div className="mb-4"> {c('Info') .t`You must have a credit card or bank account linked with your PayPal account. If your PayPal account doesn't have that, please click on the button below.`} <br /> {clickHere} </div> </> ) : null} {isAllowedOtherType ? <PayPalInfoMessage /> : null} </div> ); }; export default PayPalView;
6,714
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/Payment.spec.tsx
import { render, waitFor } from '@testing-library/react'; import { ViewPaymentMethod } from '@proton/components/payments/client-extensions'; import { CardModel, PAYMENT_METHOD_TYPES, SavedPaymentMethod } from '@proton/components/payments/core'; import { CardFieldStatus } from '@proton/components/payments/react-extensions/useCard'; import { PaymentsNoApi } from './Payment'; let apiMock: jest.Mock; jest.mock('../../hooks/useApi', () => { let api = jest.fn(); apiMock = api; return { __esModule: true, default: () => api, }; }); const defaultCard: CardModel = { number: '', month: '', year: '', cvc: '', zip: '', country: 'US', }; const cardFieldStatus: CardFieldStatus = { number: false, month: false, year: false, cvc: false, zip: false, country: false, }; let paymentMethods: SavedPaymentMethod[]; let options; let lastUsedMethod: ViewPaymentMethod; let allMethods: ViewPaymentMethod[]; beforeEach(() => { paymentMethods = [ { ID: 'methodid1', Type: PAYMENT_METHOD_TYPES.CARD, Autopay: 1, Order: 497, Details: { Last4: '4242', Brand: 'Visa', ExpMonth: '01', ExpYear: '2025', Name: 'Arthur Morgan', Country: 'US', ZIP: '11111', }, }, { ID: 'methodid2', Type: PAYMENT_METHOD_TYPES.PAYPAL, Order: 498, Details: { BillingAgreementID: 'Billing1', PayerID: 'Payer1', Payer: 'buyer@example.com', }, }, { ID: 'methodid3', Type: PAYMENT_METHOD_TYPES.CARD, Autopay: 0, Order: 499, Details: { Last4: '3220', Brand: 'Visa', ExpMonth: '11', ExpYear: '2030', Name: 'Arthur Morgan', Country: 'US', ZIP: '1211', }, }, ]; options = { usedMethods: [ { icon: 'brand-visa', text: 'Visa ending in 4242', // some plausible value value: 'methodid1', // disabled: false, // custom: true, }, { icon: 'brand-paypal', text: 'PayPal - someId', value: 'methodid2', // disabled: false, // custom: true, }, { icon: 'brand-visa', text: 'Visa ending in 3220', value: 'methodid3', // disabled: false, // custom: true, }, ] as ViewPaymentMethod[], methods: [ { icon: 'credit-card', value: 'card', text: 'New credit/debit card', }, { icon: 'money-bills', text: 'Cash', value: 'cash', }, ] as ViewPaymentMethod[], }; lastUsedMethod = options.usedMethods[options.usedMethods.length - 1]; allMethods = [...options.usedMethods, ...options.methods]; }); describe('Payment', () => { beforeEach(() => { apiMock.mockReset(); }); it('should render', () => { apiMock.mockReturnValue({}); const method = PAYMENT_METHOD_TYPES.CARD; const customPaymentMethod = paymentMethods.find(({ ID }) => method === ID); render( <PaymentsNoApi api={apiMock} type="subscription" onMethod={() => {}} method={method} amount={1000} card={defaultCard} cardErrors={{}} onCard={() => {}} paypal={{}} paypalCredit={{}} cardFieldStatus={cardFieldStatus} paymentMethods={paymentMethods} isAuthenticated={true} lastUsedMethod={lastUsedMethod} allMethods={allMethods} customPaymentMethod={customPaymentMethod} loading={false} currency="USD" /> ); }); it('should render <Alert3DS> if the payment method is card', async () => { apiMock.mockReturnValue({}); let { container } = render( <PaymentsNoApi api={apiMock} type="subscription" onMethod={() => {}} method={PAYMENT_METHOD_TYPES.CARD} amount={1000} card={defaultCard} cardErrors={{}} onCard={() => {}} paypal={{}} paypalCredit={{}} cardFieldStatus={cardFieldStatus} paymentMethods={paymentMethods} isAuthenticated={true} lastUsedMethod={lastUsedMethod} allMethods={allMethods} customPaymentMethod={undefined} loading={false} currency="USD" /> ); await waitFor(() => { expect(container).toHaveTextContent('We use 3-D Secure to protect your payments'); }); }); it('should not render <Alert3DS> if flow type is "signup"', async () => { apiMock.mockReturnValue({}); let { container } = render( <PaymentsNoApi api={apiMock} onMethod={() => {}} type="signup" method={PAYMENT_METHOD_TYPES.CARD} amount={1000} card={defaultCard} cardErrors={{}} onCard={() => {}} paypal={{}} paypalCredit={{}} cardFieldStatus={cardFieldStatus} paymentMethods={paymentMethods} isAuthenticated={true} lastUsedMethod={lastUsedMethod} allMethods={allMethods} customPaymentMethod={undefined} loading={false} currency="USD" /> ); await waitFor(() => { expect(container).not.toHaveTextContent('We use 3-D Secure to protect your payments'); }); }); it('should render <Alert3DS> if user selected a perviously used credit card (customPaymentMethod)', async () => { apiMock.mockImplementation((query) => { if (query.url === 'payments/v4/methods') { return { PaymentMethods: [ { ID: 'my-custom-method-123', Type: PAYMENT_METHOD_TYPES.CARD, }, ], }; } return {}; }); paymentMethods = [ { ID: 'my-custom-method-123', Type: PAYMENT_METHOD_TYPES.CARD, Autopay: 1, Order: 497, Details: { Last4: '4242', Brand: 'Visa', ExpMonth: '01', ExpYear: '2025', Name: 'Arthur Morgan', Country: 'US', ZIP: '11111', }, }, ]; let customPaymentMethod = paymentMethods[0]; let { container } = render( <PaymentsNoApi api={apiMock} onMethod={() => {}} type="signup" method="my-custom-method-123" amount={1000} card={defaultCard} cardErrors={{}} onCard={() => {}} paypal={{}} paypalCredit={{}} cardFieldStatus={cardFieldStatus} paymentMethods={paymentMethods} isAuthenticated={true} lastUsedMethod={lastUsedMethod} allMethods={allMethods} customPaymentMethod={customPaymentMethod} loading={false} currency="USD" /> ); await waitFor(() => { expect(container).toHaveTextContent('We use 3-D Secure to protect your payments'); }); }); it('should render <Alert3DS> if user selected a perviously used method which is not a credit card', async () => { apiMock.mockImplementation((query) => { if (query.url === 'payments/v4/methods') { return { PaymentMethods: [ { ID: 'my-custom-method-123', Type: PAYMENT_METHOD_TYPES.PAYPAL, }, ], }; } return {}; }); paymentMethods = [ { ID: 'my-custom-method-123', Type: PAYMENT_METHOD_TYPES.PAYPAL, Order: 497, Details: { BillingAgreementID: 'Billing1', PayerID: 'Payer1', Payer: '', }, }, ]; let customPaymentMethod = paymentMethods[0]; let { container } = render( <PaymentsNoApi api={apiMock} onMethod={() => {}} type="signup" method="my-custom-method-123" amount={1000} card={defaultCard} cardErrors={{}} onCard={() => {}} paypal={{}} paypalCredit={{}} cardFieldStatus={cardFieldStatus} paymentMethods={paymentMethods} isAuthenticated={true} lastUsedMethod={lastUsedMethod} allMethods={allMethods} customPaymentMethod={customPaymentMethod} loading={false} currency="USD" /> ); await waitFor(() => { expect(container).not.toHaveTextContent('We use 3-D Secure to protect your payments'); }); }); });
6,715
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/Payment.tsx
import { ReactNode, Ref, useEffect } from 'react'; import { c } from 'ttag'; import { ViewPaymentMethod } from '@proton/components/payments/client-extensions'; import { PAYMENT_METHOD_TYPES, PaymentMethodStatus, PaymentMethodType, SavedPaymentMethod, } from '@proton/components/payments/core'; import { CardFieldStatus } from '@proton/components/payments/react-extensions/useCard'; import { useLoading } from '@proton/hooks'; import { MIN_CREDIT_AMOUNT, MIN_DONATION_AMOUNT } from '@proton/shared/lib/constants'; import { Api, Currency } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { Alert, Loader, Price } from '../../components'; import { CardModel } from '../../payments/core'; import PaymentMethodDetails from '../paymentMethods/PaymentMethodDetails'; import PaymentMethodSelector from '../paymentMethods/PaymentMethodSelector'; import { PaymentMethodData, PaymentMethodFlows } from '../paymentMethods/interface'; import Alert3DS from './Alert3ds'; import Bitcoin from './Bitcoin'; import BitcoinInfoMessage from './BitcoinInfoMessage'; import Cash from './Cash'; import CreditCard from './CreditCard'; import PayPalInfoMessage from './PayPalInfoMessage'; import PayPalView from './PayPalView'; import useBitcoin, { OnBitcoinTokenValidated } from './useBitcoin'; export interface Props { api: Api; children?: ReactNode; type: PaymentMethodFlows; amount?: number; currency?: Currency; coupon?: string; method?: PaymentMethodType; onMethod: (value: PaymentMethodType | undefined) => void; paypal: any; paypalCredit: any; card: CardModel; onCard: (key: keyof CardModel, value: string) => void; cardErrors: Partial<CardModel>; noMaxWidth?: boolean; paymentMethodStatus?: PaymentMethodStatus; paymentMethods?: SavedPaymentMethod[]; creditCardTopRef?: Ref<HTMLDivElement>; disabled?: boolean; cardFieldStatus: CardFieldStatus; paypalPrefetchToken?: boolean; onBitcoinTokenValidated?: OnBitcoinTokenValidated; onAwaitingBitcoinPayment?: (awaiting: boolean) => void; isAuthenticated?: boolean; hideFirstLabel?: boolean; triggersDisabled?: boolean; hideSavedMethodsDetails?: boolean; defaultMethod?: PAYMENT_METHOD_TYPES; } export interface NoApiProps extends Props { lastUsedMethod?: PaymentMethodData | ViewPaymentMethod; allMethods: PaymentMethodData[]; isAuthenticated: boolean; loading: boolean; customPaymentMethod?: SavedPaymentMethod; currency: Currency; amount: number; onPaypalCreditClick?: () => void; } export const PaymentsNoApi = ({ children, type, amount, currency, paypal, paypalCredit, method, onMethod, card, onCard, cardErrors, cardFieldStatus, noMaxWidth = false, creditCardTopRef, disabled, paypalPrefetchToken, onBitcoinTokenValidated, lastUsedMethod, allMethods, isAuthenticated, loading, customPaymentMethod, api, onPaypalCreditClick, onAwaitingBitcoinPayment, hideFirstLabel, triggersDisabled, hideSavedMethodsDetails, defaultMethod, }: NoApiProps) => { const [handlingBitcoinPayment, withHandlingBitcoinPayment] = useLoading(); const showBitcoinMethod = method === PAYMENT_METHOD_TYPES.BITCOIN; const bitcoinHook = useBitcoin({ api, Amount: amount, Currency: currency, onTokenValidated: (data) => withHandlingBitcoinPayment(async () => onBitcoinTokenValidated?.(data)), onAwaitingPayment: onAwaitingBitcoinPayment, enablePolling: showBitcoinMethod, }); useEffect(() => { if (loading) { return onMethod(undefined); } if (defaultMethod) { onMethod(defaultMethod); return; } const selectedMethod = allMethods.find((otherMethod) => otherMethod.value === method); const result = allMethods.find(({ disabled }) => !disabled); if ((!selectedMethod || selectedMethod.disabled) && result) { onMethod(result.value); } }, [loading, allMethods.length]); if (['donation', 'human-verification'].includes(type) && amount < MIN_DONATION_AMOUNT) { const price = ( <Price key="price" currency={currency}> {MIN_DONATION_AMOUNT} </Price> ); return ( <Alert className="mb-4" type="error">{c('Error') .jt`The minimum amount that can be donated is ${price}`}</Alert> ); } if (type === 'credit' && amount < MIN_CREDIT_AMOUNT) { const price = ( <Price key="price" currency={currency}> {MIN_CREDIT_AMOUNT} </Price> ); return ( <Alert className="mb-4" type="error">{c('Error') .jt`The minimum amount of credit that can be added is ${price}`}</Alert> ); } if (amount <= 0) { const price = ( <Price key="price" currency={currency}> {0} </Price> ); return <Alert className="mb-4" type="error">{c('Error').jt`The minimum payment we accept is ${price}`}</Alert>; } if (loading) { return <Loader />; } const isSignupPass = type === 'signup-pass'; const isSignupVpn = type === 'signup-vpn'; const isSingleSignup = isSignupPass || isSignupVpn; const isSignup = type === 'signup' || isSignupPass || isSignupVpn; return ( <> <div className={clsx('payment-container center', noMaxWidth === false && 'max-w-full md:max-w-custom')} style={noMaxWidth === false ? { '--md-max-w-custom': '37em' } : undefined} > <div> {!isSingleSignup && !hideFirstLabel && ( <h2 className="text-rg text-bold mb-1" data-testid="payment-label"> {c('Label').t`Payment method`} </h2> )} <PaymentMethodSelector options={allMethods} method={method} onChange={(value) => onMethod(value)} lastUsedMethod={lastUsedMethod} forceDropdown={isSingleSignup} narrow={isSingleSignup} /> </div> <div className="mt-4"> {method === PAYMENT_METHOD_TYPES.CARD && ( <> <div ref={creditCardTopRef} /> <CreditCard card={card} errors={cardErrors} onChange={onCard} fieldsStatus={cardFieldStatus} /> {!isSignup && <Alert3DS />} </> )} {method === PAYMENT_METHOD_TYPES.CASH && <Cash />} {showBitcoinMethod && ( <> {!isAuthenticated && ( <p> {c('Info') .t`In the next step, you’ll be able to submit a deposit using a Bitcoin address.`} </p> )} {isAuthenticated && ( <> <BitcoinInfoMessage /> <Bitcoin processingToken={handlingBitcoinPayment} {...bitcoinHook} /> </> )} </> )} {method === PAYMENT_METHOD_TYPES.PAYPAL && !isSingleSignup && ( <PayPalView paypal={paypal} paypalCredit={paypalCredit} amount={amount} currency={currency} type={type} disabled={disabled} prefetchToken={paypalPrefetchToken} onClick={onPaypalCreditClick} triggersDisabled={triggersDisabled} /> )} {method === PAYMENT_METHOD_TYPES.PAYPAL && isSingleSignup && <PayPalInfoMessage />} {customPaymentMethod && ( <> {!hideSavedMethodsDetails && ( <PaymentMethodDetails type={customPaymentMethod.Type} details={customPaymentMethod.Details} /> )} {customPaymentMethod.Type === PAYMENT_METHOD_TYPES.CARD && <Alert3DS />} </> )} {children} </div> </div> {type === 'subscription' && method && method === PAYMENT_METHOD_TYPES.CASH ? ( <Alert className="mb-4" type="warning">{c('Warning') .t`Please note that by choosing this payment method, your account cannot be upgraded immediately. We will update your account once the payment is cleared.`}</Alert> ) : null} </> ); };
6,716
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PaymentGiftCode.tsx
import { RefObject, useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button, Input } from '@proton/atoms'; import { Icon, Info, UnderlineButton } from '../../components'; import { useToggle } from '../../hooks'; interface Props { loading?: boolean; giftCode?: string; onApply: (value: string) => void; giftCodeRef: RefObject<HTMLInputElement>; } const getFormattedGiftCode = (giftCode: string) => { const splittedGiftCode = giftCode.replace(/-/g, '').match(/.{1,4}/g) || ['']; return splittedGiftCode.join('-').toUpperCase(); }; const PaymentGiftCode = ({ giftCodeRef, giftCode = '', onApply, loading }: Props) => { const { state, toggle, set } = useToggle(); const [code, setCode] = useState(''); const handleCancel = () => { set(false); setCode(''); }; useEffect(() => { // When we remove the gift code if (!giftCode) { handleCancel(); } }, [giftCode]); if (giftCode) { return ( <div className="flex flex-align-items-center"> <span className="flex-item-fluid flex-nowrap flex-align-items-center"> <Icon name="gift" className="mr-2 mb-1 flex-item-noshrink" /> <code>{getFormattedGiftCode(giftCode)}</code> </span> <Button icon shape="ghost" className="flex flex-align-items-center ml-1" onClick={() => onApply('')} title={c('Action').t`Remove gift code`} > <Icon name="trash" alt={c('Action').t`Remove gift code`} /> </Button> </div> ); } if (state) { const handleSubmit = () => { if (!code) { return; } onApply(code); }; return ( <div className="flex flex-nowrap flex-align-items-center flex-align-items-start mb-2"> <div className="pr-2 flex-item-fluid"> <Input value={code} ref={giftCodeRef} placeholder={c('Placeholder').t`Gift code`} autoFocus onValue={setCode} data-testid="gift-code-input" onKeyDown={(event) => { if (event.key === 'Enter') { event.preventDefault(); handleSubmit(); } }} /> </div> <Button color="norm" title={c('Title').t`Apply gift code`} loading={loading} disabled={!code} onClick={handleSubmit} data-testid="apply-gift-code" >{c('Action').t`Apply`}</Button> </div> ); } return ( <> <UnderlineButton className="mr-2" onClick={toggle} data-testid="add-gift-code">{c('Link') .t`Add a gift code`}</UnderlineButton> <Info title={c('Tooltip') .t`If you purchased a gift code or received one from our support team, you can enter it here.`} /> </> ); }; export default PaymentGiftCode;
6,717
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PaymentInfo.tsx
import { c } from 'ttag'; import { PAYMENT_METHOD_TYPES, PlainPaymentMethodType, methodMatches } from '@proton/components/payments/core'; interface Props { paymentMethodType?: PlainPaymentMethodType; } const PaymentInfo = ({ paymentMethodType }: Props) => { if (methodMatches(paymentMethodType, [PAYMENT_METHOD_TYPES.BITCOIN, PAYMENT_METHOD_TYPES.CASH])) { return null; } return ( <div className="mb-4">{c('Info') .t`Your payment details are protected with TLS encryption and Swiss privacy laws.`}</div> ); }; export default PaymentInfo;
6,718
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PaymentSelector.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { isNumber } from '@proton/shared/lib/helpers/validators'; import { Currency } from '@proton/shared/lib/interfaces'; import { Input, Label } from '../../components'; import AmountButton from './AmountButton'; import CurrencySelector from './CurrencySelector'; interface Props { currency?: Currency; amount: number; onChangeCurrency: (currency: Currency) => void; onChangeAmount: (amount: number) => void; maxAmount?: number; minAmount?: number; } const PaymentSelector = ({ currency, amount, onChangeCurrency, onChangeAmount, minAmount, maxAmount }: Props) => { const [inputValue, setInputValue] = useState(''); const handleButton = (value: number) => { setInputValue(''); onChangeAmount(value); }; return ( <> <div className="flex gap-4 flex-justify-space-between mb-4 on-mobile-flex-column"> <div className="flex-item-fluid mb-2 md:mb-0"> <AmountButton aria-describedby="id_desc_amount id_desc_currency" className="w-full" onSelect={handleButton} value={500} amount={amount} /> </div> <div className="flex-item-fluid mb-2 md:mb-0"> <AmountButton aria-describedby="id_desc_amount id_desc_currency" className="w-full" onSelect={handleButton} value={1000} amount={amount} /> </div> <div className="flex-item-fluid mb-2 md:mb-0"> <AmountButton aria-describedby="id_desc_amount id_desc_currency" className="w-full" onSelect={handleButton} value={5000} amount={amount} /> </div> <div className="flex-item-fluid mb-2 md:mb-0"> <AmountButton aria-describedby="id_desc_amount id_desc_currency" className="w-full" onSelect={handleButton} value={10000} amount={amount} /> </div> </div> <div className="flex gap-4 flex-justify-space-between on-mobile-flex-column"> <div className="flex-item-fluid mb-2 md:mb-0"> <Label htmlFor="otherAmount" className="sr-only">{c('Label').t`Other amount`}</Label> <Input className="w-full" onChange={({ target }) => { if (target.value === '') { setInputValue(''); onChangeAmount(0); return; } if (!isNumber(target.value)) { return; } const value = Number(target.value); if (minAmount && value < minAmount / 100) { return; } if (maxAmount && value > maxAmount / 100) { return; } setInputValue(`${value}`); onChangeAmount(Math.floor(value * 100)); }} onBlur={() => { setInputValue(`${amount / 100}`); }} value={inputValue} id="otherAmount" placeholder={c('Placeholder').t`Other`} aria-describedby="id_desc_amount id_desc_currency" data-testid="other-amount" /> </div> <div className="flex-item-fluid mb-2 md:mb-0"> <CurrencySelector mode="select-two" className="w-full" id="id_desc_currency" currency={currency} onSelect={onChangeCurrency} /> </div> </div> </> ); }; export default PaymentSelector;
6,719
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PaymentVerificationImage.spec.tsx
import { render } from '@testing-library/react'; import { PAYMENT_METHOD_TYPES } from '@proton/components/payments/core'; import { CardPayment, PaypalPayment } from '../../payments/core/interface'; import PaymentVerificationImage from './PaymentVerificationImage'; describe('PaymentVerificationImage', () => { it.each([PAYMENT_METHOD_TYPES.PAYPAL, PAYMENT_METHOD_TYPES.PAYPAL_CREDIT])( 'should render paypal image. Payment method: %s', (Type) => { const payment: PaypalPayment = { Type: Type as any, }; const { getByAltText } = render(<PaymentVerificationImage payment={payment} type={Type as any} />); expect(getByAltText('PayPal')).toBeDefined(); } ); it('should render Paypal if payment object is empty but the type is defined', () => { const { getByAltText } = render(<PaymentVerificationImage payment={{}} type={PAYMENT_METHOD_TYPES.PAYPAL} />); expect(getByAltText('PayPal')).toBeDefined(); }); it('should render image for the respective credit card', () => { const payment: CardPayment = { Type: PAYMENT_METHOD_TYPES.CARD, Details: { Number: '4242424242424242', } as any, }; const { getByAltText } = render( <PaymentVerificationImage payment={payment} type={PAYMENT_METHOD_TYPES.CARD} /> ); expect(getByAltText('Visa')).toBeDefined(); }); it('should render nothing if payment is empty and type is card', () => { const { container } = render(<PaymentVerificationImage payment={{}} type={PAYMENT_METHOD_TYPES.CARD} />); expect(container).toBeEmptyDOMElement(); }); });
6,720
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PaymentVerificationImage.tsx
import creditCardType from 'credit-card-type'; import { PAYMENT_METHOD_TYPES } from '@proton/components/payments/core'; import treeDSecureSvg from '@proton/styles/assets/img/bank-icons/3d-secure.svg'; import americanExpressSafekeySvg from '@proton/styles/assets/img/bank-icons/amex-safekey.svg'; import discoverProtectBuySvg from '@proton/styles/assets/img/bank-icons/discover-protectbuy.svg'; import mastercardSecurecodeSvg from '@proton/styles/assets/img/bank-icons/mastercard-securecode.svg'; import paypalSvg from '@proton/styles/assets/img/bank-icons/paypal.svg'; import verifiedByVisaSvg from '@proton/styles/assets/img/bank-icons/visa-secure.svg'; import { CardPayment, PaypalPayment, isCardPayment, isPaypalPayment } from '../../payments/core/interface'; const getImage = (type: string): string => { const images: Record<string, string> = { 'american-express': americanExpressSafekeySvg, discover: discoverProtectBuySvg, mastercard: mastercardSecurecodeSvg, visa: verifiedByVisaSvg, }; return images[type] ?? treeDSecureSvg; }; export interface Props { payment: PaypalPayment | CardPayment | {}; type: PAYMENT_METHOD_TYPES.PAYPAL | PAYMENT_METHOD_TYPES.PAYPAL_CREDIT | PAYMENT_METHOD_TYPES.CARD; } const PaymentVerificationImage = ({ payment, type }: Props) => { const isPaypalType = [PAYMENT_METHOD_TYPES.PAYPAL, PAYMENT_METHOD_TYPES.PAYPAL_CREDIT].includes(type); if (isPaypalPayment(payment) || isPaypalType) { return <img src={paypalSvg} alt="PayPal" />; } if (!isCardPayment(payment)) { return null; } const cardTypes = creditCardType(payment.Details.Number); const { type: cardType, niceType } = cardTypes[0] ?? { type: '', niceType: '' }; return <img src={getImage(cardType)} alt={niceType} />; }; export default PaymentVerificationImage;
6,721
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PaymentWrapper.tsx
import { usePaymentFacade } from '@proton/components/payments/client-extensions'; import { PAYMENT_METHOD_TYPES } from '@proton/components/payments/core'; import { useAuthentication } from '../..'; import { Props as PaymentProps, PaymentsNoApi } from './Payment'; export type Props = ReturnType<typeof usePaymentFacade> & { onPaypalCreditClick?: () => void; noMaxWidth?: boolean; onBitcoinTokenValidated?: PaymentProps['onBitcoinTokenValidated']; onAwaitingBitcoinPayment?: PaymentProps['onAwaitingBitcoinPayment']; triggersDisabled?: boolean; hideFirstLabel?: boolean; hideSavedMethodsDetails?: boolean; disabled?: boolean; isAuthenticated?: boolean; defaultMethod?: PAYMENT_METHOD_TYPES; }; const PaymentWrapper = ({ card, api, flow, methods, amount, currency, paypal, paypalCredit, noMaxWidth, onPaypalCreditClick, onBitcoinTokenValidated, onAwaitingBitcoinPayment, triggersDisabled, hideFirstLabel, hideSavedMethodsDetails, disabled, isAuthenticated: isAuthenticatedProp, defaultMethod, }: Props) => { const { UID } = useAuthentication(); const isAuthenticated = !!UID || !!isAuthenticatedProp; return ( <PaymentsNoApi api={api} type={flow} method={methods.selectedMethod?.value} amount={amount} currency={currency} card={card.card} onMethod={methods.selectMethod} onCard={card.setCardProperty} cardErrors={card.errors} paypal={paypal} paypalCredit={paypalCredit} lastUsedMethod={methods.lastUsedMethod} loading={methods.loading} customPaymentMethod={methods.savedSelectedMethod} allMethods={methods.allMethods} isAuthenticated={isAuthenticated} noMaxWidth={noMaxWidth} onPaypalCreditClick={onPaypalCreditClick} onBitcoinTokenValidated={onBitcoinTokenValidated} onAwaitingBitcoinPayment={onAwaitingBitcoinPayment} triggersDisabled={triggersDisabled} hideFirstLabel={hideFirstLabel} cardFieldStatus={card.fieldsStatus} hideSavedMethodsDetails={hideSavedMethodsDetails} disabled={disabled} defaultMethod={defaultMethod} /> ); }; export default PaymentWrapper;
6,722
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/PlansSection.tsx
import { useEffect, useState } from 'react'; import { useLocation } from 'react-router-dom'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { checkSubscription } from '@proton/shared/lib/api/payments'; import { APPS, APP_NAMES, DEFAULT_CYCLE, PLANS } from '@proton/shared/lib/constants'; import { toMap } from '@proton/shared/lib/helpers/object'; import { hasPlanIDs } from '@proton/shared/lib/helpers/planIDs'; import { getIsB2BPlan, getPlanIDs } from '@proton/shared/lib/helpers/subscription'; import { Audience, Currency, PlanIDs, PlansMap, Subscription, SubscriptionCheckResponse, } from '@proton/shared/lib/interfaces'; import { Icon, Loader } from '../../components'; import { useApi, useFeature, useLoad, useOrganization, usePlans, useSubscription, useUser, useVPNServersCount, } from '../../hooks'; import MozillaInfoPanel from '../account/MozillaInfoPanel'; import { FeatureCode, useFlag } from '../index'; import PlanSelection from './subscription/PlanSelection'; import { useSubscriptionModal } from './subscription/SubscriptionModalProvider'; import { SUBSCRIPTION_STEPS } from './subscription/constants'; import { getCurrency, getDefaultSelectedProductPlans } from './subscription/helpers'; const FREE_SUBSCRIPTION = {} as Subscription; const getSearchParams = (search: string) => { const params = new URLSearchParams(search); return { audience: params.has('business') ? Audience.B2B : undefined, }; }; const PlansSection = ({ app }: { app: APP_NAMES }) => { const [loading, withLoading] = useLoading(); const [subscription = FREE_SUBSCRIPTION, loadingSubscription] = useSubscription(); const [organization, loadingOrganization] = useOrganization(); const [plans = [], loadingPlans] = usePlans(); const plansMap = toMap(plans, 'Name') as PlansMap; const [vpnServers] = useVPNServersCount(); const [user] = useUser(); const api = useApi(); const location = useLocation(); const currentPlanIDs = getPlanIDs(subscription); const searchParams = getSearchParams(location.search); const [audience, setAudience] = useState(searchParams.audience || Audience.B2C); const [selectedProductPlans, setSelectedProductPlans] = useState(() => { return getDefaultSelectedProductPlans(app, getPlanIDs(subscription)); }); const calendarSharingEnabled = !!useFeature(FeatureCode.CalendarSharingEnabled).feature?.Value; const sentinelPassplusEnabled = !!useFlag('SentinelPassPlus'); const [open] = useSubscriptionModal(); const isLoading = Boolean(loadingPlans || loadingSubscription || loadingOrganization); const [selectedCurrency, setCurrency] = useState<Currency>(); const currency = selectedCurrency || getCurrency(user, subscription, plans); const [cycle, setCycle] = useState(DEFAULT_CYCLE); const { CouponCode } = subscription; useLoad(); const handleModal = async (newPlanIDs: PlanIDs) => { if (!hasPlanIDs(newPlanIDs)) { throw new Error('Downgrade not supported'); } const couponCode = CouponCode || undefined; // From current subscription; CouponCode can be null const { Coupon } = await api<SubscriptionCheckResponse>( checkSubscription({ Plans: newPlanIDs, Currency: currency, Cycle: cycle, CouponCode: couponCode, }) ); const step = newPlanIDs[PLANS.VPN_BUSINESS] || newPlanIDs[PLANS.VPN_PRO] ? SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION : SUBSCRIPTION_STEPS.CUSTOMIZATION; open({ defaultSelectedProductPlans: selectedProductPlans, planIDs: newPlanIDs, coupon: Coupon?.Code, step, cycle, currency, defaultAudience: Object.keys(newPlanIDs).some((planID) => getIsB2BPlan(planID as any)) ? Audience.B2B : Audience.B2C, metrics: { source: 'plans', }, }); }; useEffect(() => { if (isLoading) { return; } setCycle(subscription.Cycle || DEFAULT_CYCLE); setSelectedProductPlans(getDefaultSelectedProductPlans(app, getPlanIDs(subscription))); }, [isLoading, subscription, app]); // @ts-ignore if (subscription.isManagedByMozilla) { return <MozillaInfoPanel />; } if (isLoading) { return <Loader />; } return ( <> <PlanSelection app={app} filter={app === APPS.PROTONPASS ? [Audience.B2C] : undefined} mode="settings" audience={audience} onChangeAudience={setAudience} loading={loading} plans={plans} plansMap={plansMap} vpnServers={vpnServers} currency={currency} cycle={cycle} onChangeCycle={setCycle} planIDs={currentPlanIDs} hasFreePlan={false} hasPlanSelectionComparison={false} subscription={subscription} onChangePlanIDs={(planIDs) => { void withLoading(handleModal(planIDs)); }} onChangeCurrency={setCurrency} selectedProductPlans={selectedProductPlans} onChangeSelectedProductPlans={setSelectedProductPlans} organization={organization} calendarSharingEnabled={calendarSharingEnabled} sentinelPassplusEnabled={sentinelPassplusEnabled} /> <Button color="norm" shape="ghost" className="flex mx-auto flex-align-items-center mb-4" onClick={() => { open({ step: SUBSCRIPTION_STEPS.PLAN_SELECTION, defaultAudience: audience, defaultSelectedProductPlans: selectedProductPlans, metrics: { source: 'plans', }, }); }} > {c('Action').t`View plans details`} <Icon name="arrow-right" className="ml-2 on-rtl-mirror" /> </Button> </> ); }; export default PlansSection;
6,723
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/ProtonPlanCustomizer.tsx
import { ComponentPropsWithoutRef, ReactElement, ReactNode, useState } from 'react'; import { c, msgid } from 'ttag'; import { ADDON_NAMES, BRAND_NAME, GIGA, MAX_ADDRESS_ADDON, MAX_DOMAIN_PRO_ADDON, MAX_IPS_ADDON, MAX_MEMBER_ADDON, MAX_MEMBER_VPN_B2B_ADDON, MAX_SPACE_ADDON, MAX_VPN_ADDON, } from '@proton/shared/lib/constants'; import { getSupportedAddons, setQuantity } from '@proton/shared/lib/helpers/planIDs'; import { getVPNDedicatedIPs, hasVpnBusiness } from '@proton/shared/lib/helpers/subscription'; import { Currency, Cycle, MaxKeys, Organization, Plan, PlanIDs, Subscription, getPlanMaxIPs, } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { Icon, Info, Price } from '../../components'; const AddonKey: Readonly<{ [K in ADDON_NAMES]: MaxKeys; }> = { [ADDON_NAMES.ADDRESS]: 'MaxAddresses', [ADDON_NAMES.MEMBER]: 'MaxMembers', [ADDON_NAMES.DOMAIN]: 'MaxDomains', [ADDON_NAMES.DOMAIN_BUNDLE_PRO]: 'MaxDomains', [ADDON_NAMES.DOMAIN_ENTERPRISE]: 'MaxDomains', [ADDON_NAMES.VPN]: 'MaxVPN', [ADDON_NAMES.SPACE]: 'MaxSpace', [ADDON_NAMES.MEMBER_MAIL_PRO]: 'MaxMembers', [ADDON_NAMES.MEMBER_DRIVE_PRO]: 'MaxMembers', [ADDON_NAMES.MEMBER_BUNDLE_PRO]: 'MaxMembers', [ADDON_NAMES.MEMBER_ENTERPRISE]: 'MaxMembers', [ADDON_NAMES.MEMBER_VPN_PRO]: 'MaxMembers', [ADDON_NAMES.MEMBER_VPN_BUSINESS]: 'MaxMembers', [ADDON_NAMES.IP_VPN_BUSINESS]: 'MaxIPs', } as const; export type CustomiserMode = 'signup' | undefined; interface Props extends ComponentPropsWithoutRef<'div'> { cycle: Cycle; currency: Currency; currentPlan: Plan; planIDs: PlanIDs; onChangePlanIDs: (planIDs: PlanIDs) => void; plansMap: { [key: string]: Plan }; organization?: Organization; loading?: boolean; mode?: CustomiserMode; forceHideDescriptions?: boolean; showUsersTooltip?: boolean; currentSubscription?: Subscription; } const ButtonNumberInput = ({ value, onChange, id, min = 0, max = 999, step = 1, disabled = false, }: { step?: number; id: string; min?: number; max?: number; value: number; disabled?: boolean; onChange?: (newValue: number) => void; }) => { const [tmpValue, setTmpValue] = useState<number | undefined>(value); const getIsValidValue = (newValue?: number) => { return newValue !== undefined && newValue >= min && newValue <= max && newValue % step === 0; }; const isDecDisabled = disabled || !getIsValidValue((tmpValue || 0) - step); const isIncDisabled = disabled || !getIsValidValue((tmpValue || 0) + step); const isValidTmpValue = getIsValidValue(tmpValue); return ( <div className="border rounded flex-item-noshrink flex flex-nowrap"> <button type="button" title={c('Action').t`Decrease`} className={clsx(['p-2 flex', isDecDisabled && 'color-disabled'])} disabled={isDecDisabled} onClick={() => { if (!isValidTmpValue || tmpValue === undefined) { return; } const newValue = tmpValue - step; setTmpValue?.(newValue); onChange?.(newValue); }} > <Icon name="minus" alt={c('Action').t`Decrease`} className="m-auto" /> </button> <label htmlFor={id} className="my-2 flex"> <input autoComplete="off" min={min} max={max} value={tmpValue} id={id} className="w-custom border-left border-right text-center" style={{ '--w-custom': '6em' }} onBlur={() => { if (!isValidTmpValue) { // Revert to the latest valid value upon blur setTmpValue(value); } }} onChange={({ target: { value: newValue } }) => { if (newValue === '') { setTmpValue?.(undefined); return; } const newIntValue = parseInt(newValue, 10); setTmpValue?.(newIntValue); if (getIsValidValue(newIntValue)) { onChange?.(newIntValue); } }} /> </label> <button type="button" title={c('Action').t`Increase`} className={clsx(['p-2 flex', isIncDisabled && 'color-disabled'])} disabled={isIncDisabled} onClick={() => { if (!isValidTmpValue || tmpValue === undefined) { return; } const newValue = tmpValue + step; setTmpValue?.(newValue); onChange?.(newValue); }} > <Icon name="plus" alt={c('Action').t`Increase`} className="m-auto" /> </button> </div> ); }; const addonLimit = { [ADDON_NAMES.SPACE]: MAX_SPACE_ADDON, [ADDON_NAMES.MEMBER]: MAX_MEMBER_ADDON, [ADDON_NAMES.DOMAIN]: MAX_DOMAIN_PRO_ADDON, [ADDON_NAMES.DOMAIN_BUNDLE_PRO]: MAX_DOMAIN_PRO_ADDON, [ADDON_NAMES.DOMAIN_ENTERPRISE]: MAX_DOMAIN_PRO_ADDON, [ADDON_NAMES.ADDRESS]: MAX_ADDRESS_ADDON, [ADDON_NAMES.VPN]: MAX_VPN_ADDON, [ADDON_NAMES.MEMBER_MAIL_PRO]: MAX_MEMBER_ADDON, [ADDON_NAMES.MEMBER_DRIVE_PRO]: MAX_MEMBER_ADDON, [ADDON_NAMES.MEMBER_BUNDLE_PRO]: MAX_MEMBER_ADDON, [ADDON_NAMES.MEMBER_ENTERPRISE]: MAX_MEMBER_ADDON, [ADDON_NAMES.MEMBER_VPN_PRO]: MAX_MEMBER_VPN_B2B_ADDON, [ADDON_NAMES.MEMBER_VPN_BUSINESS]: MAX_MEMBER_VPN_B2B_ADDON, [ADDON_NAMES.IP_VPN_BUSINESS]: MAX_IPS_ADDON, } as const; // translator: This string is a part of a larger string asking the user to "contact" our sales team => full sentence: Should you need more than ${maxUsers} user accounts, please <contact> our Sales team const contactString = c('plan customizer, users').t`contact`; const contactHref = ( <a key={1} href="mailto:enterprise@proton.me"> {contactString} </a> ); // Since ttag doesn't support ngettext with jt, we manually replace the string with a react node... const getAccountSizeString = (maxUsers: number, price: ReactNode) => { // translator: This string is followed up by the string "Should you need more than ${maxUsers} user accounts, please <contact> our Sales team" const first = c('plan customizer, users') .jt`Select the number of users to include in your plan. Each additional user costs ${price}.`; const contact = '_TMPL_'; const second = c('plan customizer, users').ngettext( msgid`Should you need more than ${maxUsers} user account, please ${contact} our Sales team.`, `Should you need more than ${maxUsers} user accounts, please ${contact} our Sales team.`, maxUsers ); return [ first, ' ', ...second .split(contact) .map((value, index, arr) => (index !== arr.length - 1 ? [value, contactHref] : [value])), ]; }; const AccountSizeCustomiser = ({ addon, maxUsers, price, input, showDescription = true, showTooltip = true, }: { addon: Plan; maxUsers: number; price: ReactElement; input: ReactElement; showDescription?: boolean; showTooltip?: boolean; }) => { return ( <div className={clsx(showDescription ? 'mb-8' : 'mb-4')}> {showDescription && ( <> <h2 className="text-2xl text-bold mb-4">{c('Info').t`Account size`}</h2> <div className="mb-4">{getAccountSizeString(maxUsers, price)}</div> </> )} <div className="flex-no-min-children flex-nowrap flex-align-items-center mb-4 on-mobile-flex-wrap"> <label htmlFor={addon.Name} className="w-full md:w-auto min-w-custom md:min-w-custom flex-item-fluid plan-customiser-addon-label text-bold pr-2" style={{ '--min-w-custom': '8em', '--md-min-w-custom': '14em' }} > {c('Info').t`Users`} {showTooltip && ( <Info buttonClass="ml-2" title={c('Info') .t`A user is an account associated with a single username, mailbox, and person`} /> )} </label> {input} </div> </div> ); }; const AdditionalOptionsCustomiser = ({ addon, price, input, showDescription = true, }: { addon: Plan; price: ReactElement; input: ReactElement; showDescription?: boolean; }) => { return ( <> {showDescription && ( <> <h2 className="text-2xl text-bold mb-4">{c('Info').t`Additional options`}</h2> <div className="mb-4"> {c('Info') .jt`Email hosting for 10 custom email domain names is included for free. Additional domains can be added for ${price}.`} </div> </> )} <div className="flex-no-min-children flex-nowrap flex-align-items-center mb-4 on-mobile-flex-wrap"> <label htmlFor={addon.Name} className="w-full md:w-auto min-w-custom md:min-w-custom flex-item-fluid plan-customiser-addon-label text-bold pr-2" style={{ '--min-w-custom': '8em', '--md-min-w-custom': '14em' }} > {c('Info').t`Custom email domains`} <Info className="ml-2" title={c('Info') .t`Email hosting is only available for domains you already own. Domain registration is not currently available through ${BRAND_NAME}. You can host email for domains registered on any domain registrar.`} /> </label> {input} </div> </> ); }; const IPsNumberCustomiser = ({ addon, maxIPs, price, input, showDescription = true, }: { addon: Plan; maxIPs: number; price: ReactElement; input: ReactElement; showDescription?: boolean; }) => { const title = c('Info').t`Dedicated servers`; const select = c('plan customizer, ips') .jt`Select the number of IPs to include in your plan. Each additional IP costs ${price}.`; // translator: the plural is based on maxIPs variable (number written in digits). This string is part of another one, full sentence is: Should you need more than <maxIPs> IPs, (please <contact> our Sales team). const description = c('plan customizer, ips').ngettext( msgid`Should you need more than ${maxIPs} IP, `, `Should you need more than ${maxIPs} IPs, `, maxIPs ); // translator: this string is part of another one, full sentence is: (Should you need more than <maxIPs> IPs, )please <contact> our Sales team. const pleaseContact = c('plan customizer, ips').jt`please ${contactHref} our Sales team.`; return ( <div className={clsx(showDescription ? 'mb-8' : 'mb-4')}> {showDescription && ( <> <h2 className="text-2xl text-bold mb-4">{title}</h2> <div className="mb-4"> {select} {description} {pleaseContact} </div> </> )} <div className="flex-no-min-children flex-nowrap flex-align-items-center mb-4 on-mobile-flex-wrap"> <label htmlFor={addon.Name} className="w-full md:w-auto min-w-custom md:min-w-custom flex-item-fluid plan-customiser-addon-label text-bold pr-2" style={{ '--min-w-custom': '8em', '--md-min-w-custom': '14em' }} > {title} <Info buttonClass="ml-2" title={c('Info').t`Number of dedicated servers in the organization`} /> </label> {input} </div> </div> ); }; const ProtonPlanCustomizer = ({ cycle, mode, currency, onChangePlanIDs, planIDs, plansMap, currentPlan, organization, loading, className, forceHideDescriptions, showUsersTooltip, currentSubscription, ...rest }: Props) => { const supportedAddons = getSupportedAddons(planIDs); const showAddonDescriptions = mode !== 'signup' && !forceHideDescriptions; return ( <div className={clsx(['plan-customiser', className])} {...rest}> {Object.entries(supportedAddons).map(([addonName]) => { const addon = plansMap[addonName]; if (!addon) { return null; } const addonNameKey = addon.Name as ADDON_NAMES; const quantity = planIDs[addon.Name] ?? 0; const isSupported = !!supportedAddons[addonNameKey]; const addonMaxKey = AddonKey[addonNameKey]; /** * Workaround specifically for MaxIPs property. There is an upcoming mirgation in payments API v5 * That will sctructure all these Max* properties in a different way. * For now, we need to handle MaxIPs separately. * See {@link MaxKeys} and {@link Plan}. Note that all properties from MaxKeys must be present in Plan * with the exception of MaxIPs. */ let addonMultiplier: number; if (addonMaxKey === 'MaxIPs') { addonMultiplier = getPlanMaxIPs(addon); if (addonMultiplier === 0) { addonMultiplier = 1; } } else { addonMultiplier = addon[addonMaxKey] ?? 1; } // The same workaround as above let min: number; if (addonMaxKey === 'MaxIPs') { min = getPlanMaxIPs(currentPlan); } else { min = currentPlan[addonMaxKey] ?? 0; } const max = addonLimit[addonNameKey] * addonMultiplier; // Member addon comes with MaxSpace + MaxAddresses const value = isSupported ? min + quantity * addonMultiplier : Object.entries(planIDs).reduce((acc, [planName, quantity]) => { // and the same workaround as above let multiplier: number; if (addonMaxKey === 'MaxIPs') { multiplier = getPlanMaxIPs(plansMap[planName]); } else { multiplier = plansMap[planName][addonMaxKey]; } return acc + quantity * multiplier; }, 0); const divider = addonNameKey === ADDON_NAMES.SPACE ? GIGA : 1; const maxTotal = max / divider; const addonPricePerCycle = addon.Pricing[cycle] || 0; const addonPriceInline = ( <Price key={`${addon.Name}-1`} currency={currency} suffix={c('Suffix for price').t`per month`}> {addonPricePerCycle / cycle} </Price> ); const canDowngrade = addonMaxKey !== 'MaxIPs' || !hasVpnBusiness(currentSubscription); const displayMin = canDowngrade ? min / divider : getVPNDedicatedIPs(currentSubscription); const input = ( <ButtonNumberInput key={`${addon.Name}-input`} id={addon.Name} value={value / divider} min={displayMin} max={maxTotal} disabled={loading || !isSupported} onChange={(newQuantity) => { onChangePlanIDs( setQuantity(planIDs, addon.Name, (newQuantity * divider - min) / addonMultiplier) ); }} step={addonMultiplier} /> ); if ( [ ADDON_NAMES.MEMBER, ADDON_NAMES.MEMBER_BUNDLE_PRO, ADDON_NAMES.MEMBER_DRIVE_PRO, ADDON_NAMES.MEMBER_MAIL_PRO, ADDON_NAMES.MEMBER_ENTERPRISE, ADDON_NAMES.MEMBER_VPN_PRO, ADDON_NAMES.MEMBER_VPN_BUSINESS, ].includes(addonNameKey) ) { return ( <AccountSizeCustomiser key={`${addon.Name}-size`} addon={addon} price={addonPriceInline} input={input} maxUsers={maxTotal} showDescription={showAddonDescriptions} showTooltip={showUsersTooltip} /> ); } if ( mode !== 'signup' && [ADDON_NAMES.DOMAIN, ADDON_NAMES.DOMAIN_BUNDLE_PRO, ADDON_NAMES.DOMAIN_ENTERPRISE].includes( addonNameKey ) ) { return ( <AdditionalOptionsCustomiser key={`${addon.Name}-options`} addon={addon} price={addonPriceInline} input={input} showDescription={showAddonDescriptions} /> ); } if (addonNameKey === ADDON_NAMES.IP_VPN_BUSINESS) { return ( <IPsNumberCustomiser key={`${addon.Name}-ips`} addon={addon} price={addonPriceInline} input={input} showDescription={showAddonDescriptions} maxIPs={maxTotal} /> ); } return null; })} </div> ); }; export default ProtonPlanCustomizer;
6,724
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/RenewToggle.test.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import { renderHook } from '@testing-library/react-hooks'; import { mockSubscriptionCache } from '@proton/components/hooks/helpers/test'; import { Autopay } from '@proton/components/payments/core'; import { applyHOCs, hookWrapper, withCache } from '@proton/testing'; import RenewToggle, { useRenewToggle } from './RenewToggle'; jest.mock('@proton/components/components/portal/Portal'); jest.mock('@proton/components/components/toggle/Toggle'); beforeEach(() => { jest.clearAllMocks(); mockSubscriptionCache(); }); const providers = [withCache()]; const ContextRenewToggle = applyHOCs(...providers)(RenewToggle); const wrapper = hookWrapper(...providers); it('should render', () => { const { result } = renderHook(() => useRenewToggle({}), { wrapper }); const { container } = render(<ContextRenewToggle {...result.current} />); expect(container).not.toBeEmptyDOMElement(); }); it('should be checked when RenewState is Active', () => { const { result } = renderHook(() => useRenewToggle({}), { wrapper }); const { getByTestId } = render(<ContextRenewToggle {...result.current} />); expect(getByTestId('toggle-subscription-renew')).toHaveTextContent('CHECKED'); }); it('should be unchecked when RenewState is Disabled', () => { const { result } = renderHook(() => useRenewToggle({ initialRenewState: Autopay.DISABLE }), { wrapper }); const { getByTestId } = render(<ContextRenewToggle {...result.current} />); expect(getByTestId('toggle-subscription-renew')).not.toHaveTextContent('CHECKED'); }); it('should show modal when user disables auto renew', () => { const { result } = renderHook(() => useRenewToggle({}), { wrapper }); const { container, getByTestId, rerender } = render(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('toggle-subscription-renew')); rerender(<ContextRenewToggle {...result.current} />); expect(container).toHaveTextContent('Our system will no longer auto-charge you using this payment method'); }); it('should not toggle off if user clicked Keep auto-pay/Cancel', async () => { const { result, rerender: rerenderHook } = renderHook(() => useRenewToggle({}), { wrapper }); const { getByTestId, rerender, container } = render(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('toggle-subscription-renew')); rerenderHook(); rerender(<ContextRenewToggle {...result.current} />); expect(container).toHaveTextContent('Are you sure?'); fireEvent.click(getByTestId('action-keep-autopay')); await waitFor(() => {}); rerenderHook(); rerender(<ContextRenewToggle {...result.current} />); expect(getByTestId('toggle-subscription-renew')).toHaveTextContent('CHECKED'); }); it('should toggle off if user clicked Disable', async () => { const { result, rerender: rerenderHook } = renderHook(() => useRenewToggle({}), { wrapper }); const { getByTestId, rerender, container } = render(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('toggle-subscription-renew')); rerenderHook(); rerender(<ContextRenewToggle {...result.current} />); expect(container).toHaveTextContent('Are you sure?'); fireEvent.click(getByTestId('action-disable-autopay')); await waitFor(() => {}); rerenderHook(); rerender(<ContextRenewToggle {...result.current} />); await waitFor(() => { expect(getByTestId('toggle-subscription-renew')).not.toHaveTextContent('CHECKED'); }); }); it('should toggle on without modal', async () => { const { result, rerender: rerenderHook } = renderHook( () => useRenewToggle({ initialRenewState: Autopay.DISABLE }), { wrapper } ); const { getByTestId, container, rerender } = render(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('toggle-subscription-renew')); await waitFor(() => {}); rerenderHook(); rerender(<ContextRenewToggle {...result.current} />); expect(container).not.toHaveTextContent('Our system will no longer auto-charge you using this payment method'); expect(getByTestId('toggle-subscription-renew')).toHaveTextContent('CHECKED'); }); describe('useRenewToggle', () => { it('onChange should return ENABLE if toggled on', async () => { const { result } = renderHook(() => useRenewToggle({ initialRenewState: Autopay.DISABLE }), { wrapper }); expect(await result.current.onChange()).toEqual(Autopay.ENABLE); }); it('onChange should return DISABLE if toggled off', async () => { const { result } = renderHook(() => useRenewToggle({ initialRenewState: Autopay.ENABLE }), { wrapper }); const { getByTestId, rerender } = render(<ContextRenewToggle {...result.current} />); const onChangePromise = result.current.onChange(); rerender(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('action-disable-autopay')); expect(await onChangePromise).toEqual(Autopay.DISABLE); }); it('onChange should return null if the checkbox was not toggled off', async () => { const { result } = renderHook(() => useRenewToggle({ initialRenewState: Autopay.ENABLE }), { wrapper }); const { getByTestId, rerender } = render(<ContextRenewToggle {...result.current} />); const onChangePromise = result.current.onChange(); rerender(<ContextRenewToggle {...result.current} />); fireEvent.click(getByTestId('action-keep-autopay')); expect(await onChangePromise).toEqual(null); }); });
6,725
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/RenewToggle.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Autopay } from '@proton/components/payments/core'; import { ADDON_NAMES, PLANS } from '@proton/shared/lib/constants'; import { PrimaryButton } from '../../components/button'; import { ModalProps } from '../../components/modalTwo'; import { useModalTwo } from '../../components/modalTwo/useModalTwo'; import { Prompt } from '../../components/prompt'; import { Toggle } from '../../components/toggle'; import { useSubscription } from '../../hooks'; type DisableRenewModalOwnProps = { isVPNPlan: boolean }; type DisableRenewModalPromiseProps = { onResolve: (result: boolean) => void }; type DisableRenewModalProps = ModalProps & DisableRenewModalPromiseProps & DisableRenewModalOwnProps; export const DisableRenewModal = ({ isVPNPlan, onResolve, ...rest }: DisableRenewModalProps) => { return ( <Prompt data-testid="disable-renew-modal" title={c('Subscription renewal state').t`Are you sure?`} buttons={[ <Button data-testid="action-disable-autopay" onClick={() => onResolve(true)}>{c( 'Subscription renewal state' ).t`Disable`}</Button>, <PrimaryButton data-testid="action-keep-autopay" onClick={() => onResolve(false)}>{c( 'Subscription renewal state' ).t`Keep auto-pay`}</PrimaryButton>, ]} {...rest} > <p> {isVPNPlan ? c('Subscription renewal state') .t`Our system will no longer auto-charge you using this payment method, but your subscription will still renew at the end of the billing cycle. If you want to downgrade or change your subscription, you still need to do that yourself before the end of the billing period. Furthermore, if you forget to make a manual payment and auto-pay is disabled for all payment methods, we may auto-downgrade your account which will lead to the loss of many features.` : c('Subscription renewal state') .t`Our system will no longer auto-charge you using this payment method, but your subscription will still renew at the end of the billing cycle. If you want to downgrade or change your subscription, you still need to do that yourself before the end of the billing period. We cannot auto-downgrade you because if you are over free plan storage quota or using other paid features, we cannot auto delete files, emails, or other data for you. If you disable automatic payment, remember to pay your next subscription invoice before the due date to prevent account suspension.`} </p> </Prompt> ); }; export interface UseRenewToggleOptions { initialRenewState?: Autopay; } export interface UseRenewToggleResult { onChange: () => Promise<Autopay | null>; disableRenewModal: JSX.Element | null; renewState: Autopay; setRenewState: (newState: Autopay) => void; } export const useRenewToggle = ({ initialRenewState = Autopay.ENABLE }: UseRenewToggleOptions): UseRenewToggleResult => { const [subscription] = useSubscription(); const vpnPlans: (PLANS | ADDON_NAMES)[] = [PLANS.VPN, PLANS.VPNBASIC, PLANS.VPNPLUS]; const isVPNPlan = subscription?.Plans?.some(({ Name }) => vpnPlans.includes(Name)); const [disableRenewModal, showDisableRenewModal] = useModalTwo<DisableRenewModalOwnProps, boolean>( DisableRenewModal ); const [renewState, setRenewState] = useState(initialRenewState); const onChange = async (): Promise<Autopay | null> => { let newState: Autopay; if (renewState === Autopay.ENABLE) { const userDecidedDisable = await showDisableRenewModal({ isVPNPlan }); if (!userDecidedDisable) { return null; } newState = Autopay.DISABLE; } else { newState = Autopay.ENABLE; } setRenewState(newState); return newState; }; return { onChange, disableRenewModal, renewState, setRenewState }; }; export type Props = { loading?: boolean; onChange: () => any; } & Pick<UseRenewToggleResult, 'renewState' | 'disableRenewModal'>; const RenewToggle = ({ renewState, onChange, disableRenewModal, loading }: Props) => { const toggleId = 'toggle-subscription-renew'; const checked = renewState === Autopay.ENABLE; return ( <> {disableRenewModal} <div className="flex flex-justify-space-between mx-2"> <label htmlFor={toggleId}> <span>{c('Subscription renewal state').t`Enable auto-pay support`}</span> </label> <Toggle id={toggleId} checked={checked} onChange={onChange} loading={loading} data-testid="toggle-subscription-renew" /> </div> </> ); }; export default RenewToggle;
6,726
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/RenewalNotice.test.tsx
import { render } from '@testing-library/react'; import { getRenewalNoticeText } from './RenewalNotice'; const RenewalNotice = (...props: Parameters<typeof getRenewalNoticeText>) => { return <div>{getRenewalNoticeText(...props)}</div>; }; describe('<RenewalNotice />', () => { beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers(); }); afterEach(() => { jest.useRealTimers(); }); it('should render', () => { const { container } = render( <RenewalNotice renewCycle={12} isCustomBilling={false} isScheduledSubscription={false} subscription={undefined} /> ); expect(container).not.toBeEmptyDOMElement(); }); it('should display the correct renewal date', () => { const mockedDate = new Date(2023, 10, 1); jest.setSystemTime(mockedDate); const renewCycle = 12; const expectedDateString = '11/01/2024'; // because months are 0-indexed ¯\_(ツ)_/¯ const { container } = render( <RenewalNotice renewCycle={renewCycle} isCustomBilling={false} isScheduledSubscription={false} subscription={undefined} /> ); expect(container).toHaveTextContent( `Subscription auto-renews every 12 months. Your next billing date is ${expectedDateString}.` ); }); it('should use period end date if custom billing is enabled', () => { const mockedDate = new Date(2023, 10, 1); jest.setSystemTime(mockedDate); const renewCycle = 12; const expectedDateString = '08/11/2025'; // because months are 0-indexed ¯\_(ツ)_/¯ const { container } = render( <RenewalNotice renewCycle={renewCycle} isCustomBilling={true} isScheduledSubscription={false} subscription={ { // the backend returns seconds, not milliseconds PeriodEnd: +new Date(2025, 7, 11) / 1000, } as any } /> ); expect(container).toHaveTextContent( `Subscription auto-renews every 12 months. Your next billing date is ${expectedDateString}.` ); }); it('should use the end of upcoming subscription period if scheduled subscription is enabled', () => { const mockedDate = new Date(2023, 10, 1); jest.setSystemTime(mockedDate); const renewCycle = 24; // the upcoming subscription takes another 24 months const { container } = render( <RenewalNotice renewCycle={renewCycle} isCustomBilling={false} isScheduledSubscription={true} subscription={ { // the backend returns seconds, not milliseconds PeriodEnd: +new Date(2024, 1, 3) / 1000, // the current subscription period ends on 02/03/2024 (3rd of February 2024) } as any } /> ); const expectedDateString = '02/03/2026'; // and finally the renewal date is 02/03/2026 (3rd of February 2026) expect(container).toHaveTextContent( `Subscription auto-renews every 24 months. Your next billing date is ${expectedDateString}.` ); }); });
6,727
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/RenewalNotice.tsx
import { addMonths } from 'date-fns'; import { c, msgid } from 'ttag'; import { CYCLE } from '@proton/shared/lib/constants'; import { getPlanFromPlanIDs } from '@proton/shared/lib/helpers/planIDs'; import { getNormalCycleFromCustomCycle } from '@proton/shared/lib/helpers/subscription'; import { Currency, PlanIDs, PlansMap, Subscription } from '@proton/shared/lib/interfaces'; import Price from '../../components/price/Price'; import Time from '../../components/time/Time'; import { getMonths } from './SubscriptionsSection'; export type RenewalNoticeProps = { renewCycle: number; isCustomBilling?: boolean; isScheduledSubscription?: boolean; subscription?: Subscription; }; export const getBlackFridayRenewalNoticeText = ({ price, cycle, plansMap, planIDs, currency, }: { price: number; cycle: CYCLE; plansMap: PlansMap; planIDs: PlanIDs; currency: Currency; }) => { const nextCycle = getNormalCycleFromCustomCycle(cycle); const plan = getPlanFromPlanIDs(plansMap, planIDs); const discountedPrice = ( <Price key="a" currency={currency}> {price} </Price> ); const nextPrice = plan ? ( <Price key="b" currency={currency}> {plan?.Pricing[nextCycle] || 0} </Price> ) : null; if (nextCycle === CYCLE.MONTHLY) { // translator: The specially discounted price of $8.99 is valid for the first month. Then it will automatically be renewed at $9.99 every month. You can cancel at any time. return c('bf2023: renew') .jt`The specially discounted price of ${discountedPrice} is valid for the first month. Then it will automatically be renewed at ${nextPrice} every month. You can cancel at any time.`; } const discountedMonths = ((n: number) => { if (n === CYCLE.MONTHLY) { // translator: This string is a special case for 1 month billing cycle, together with the string "The specially discounted price of ... is valid for the first 'month' ..." return c('bf2023: renew').t`the first month`; } // translator: The singular is not handled in this string. The month part of the string "The specially discounted price of EUR XX is valid for the first 30 months. Then it will automatically be renewed at the discounted price of EUR XX for 24 months. You can cancel at any time." return c('bf2023: renew').ngettext(msgid`${n} month`, `the first ${n} months`, n); })(cycle); const nextMonths = getMonths(nextCycle); // translator: The specially discounted price of EUR XX is valid for the first 30 months. Then it will automatically be renewed at the discounted price of EUR XX for 24 months. You can cancel at any time. return c('bf2023: renew') .jt`The specially discounted price of ${discountedPrice} is valid for ${discountedMonths}. Then it will automatically be renewed at the discounted price of ${nextPrice} for ${nextMonths}. You can cancel at any time.`; }; export const getRenewalNoticeText = ({ renewCycle, isCustomBilling, isScheduledSubscription, subscription, }: RenewalNoticeProps) => { let unixRenewalTime: number = +addMonths(new Date(), renewCycle) / 1000; if (isCustomBilling && subscription) { unixRenewalTime = subscription.PeriodEnd; } if (isScheduledSubscription && subscription) { const periodEndMilliseconds = subscription.PeriodEnd * 1000; unixRenewalTime = +addMonths(periodEndMilliseconds, renewCycle) / 1000; } const renewalTime = ( <Time format="P" key="auto-renewal-time"> {unixRenewalTime} </Time> ); const nextCycle = getNormalCycleFromCustomCycle(renewCycle); let start; if (nextCycle === CYCLE.MONTHLY) { start = c('Info').t`Subscription auto-renews every month.`; } if (nextCycle === CYCLE.YEARLY) { start = c('Info').t`Subscription auto-renews every 12 months.`; } if (nextCycle === CYCLE.TWO_YEARS) { start = c('Info').t`Subscription auto-renews every 24 months.`; } return [start, ' ', c('Info').jt`Your next billing date is ${renewalTime}.`]; };
6,728
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/StartDateCheckoutRow.tsx
import { c } from 'ttag'; import { Info, Time } from '../../components'; export interface Props { nextSubscriptionStart: number; } const StartDateCheckoutRow = ({ nextSubscriptionStart }: Props) => { const formattedTime = <Time key="time-text">{nextSubscriptionStart}</Time>; return ( <div className="flex flex-nowrap flex-justify-space-between mb-4" data-testid="start-date-row"> <div className="pr-2"> {c('Label').t`Start date`}{' '} <Info title={c('Tooltip').jt`The new subscription cycle starts on ${formattedTime}`} /> </div> {formattedTime} </div> ); }; export default StartDateCheckoutRow;
6,729
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/StyledPayPalButton.scss
.button.paypal-button { // The Design team wants the button to be branded as PayPal yellow for every theme --button-default-background-color: #ffc439; --button-hover-background-color: #f3ba37; --button-active-background-color: #e5b034; --button-default-text-color: black; --button-hover-text-color: black; --button-active-text-color: black; }
6,730
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/StyledPayPalButton.tsx
import paypalSvg from '@proton/styles/assets/img/bank-icons/paypal-color.svg'; import clsx from '@proton/utils/clsx'; import PayPalButton, { PayPalButtonProps } from './PayPalButton'; import './StyledPayPalButton.scss'; type Omitted = 'children' | 'shape' | 'color' | 'icon'; type Props = Omit<PayPalButtonProps, Omitted>; const StyledPayPalButton = ({ className, ...rest }: Props) => { const payPalButtonClassName = clsx(['paypal-button', className]); return ( <PayPalButton {...rest} className={payPalButtonClassName} color="norm"> <img src={paypalSvg} alt="PayPal" width="50" /> </PayPalButton> ); }; export default StyledPayPalButton;
6,731
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/SubscriptionsSection.test.tsx
import { render } from '@testing-library/react'; import { mockPlansCache, mockSubscriptionCache, mockUserCache } from '@proton/components/hooks/helpers/test'; import { changeRenewState } from '@proton/shared/lib/api/payments'; import { PLANS } from '@proton/shared/lib/constants'; import { Renew, Subscription, SubscriptionModel } from '@proton/shared/lib/interfaces'; import { apiMock, applyHOCs, withApi, withCache, withEventManager } from '@proton/testing/index'; import SubscriptionsSection from './SubscriptionsSection'; const ContextSubscriptionSection = applyHOCs(withEventManager(), withApi(), withCache())(SubscriptionsSection); describe('SubscriptionsSection', () => { let subscription: SubscriptionModel; let upcoming: Subscription | null = null; beforeEach(() => { subscription = { ID: '123', InvoiceID: '1234', Cycle: 1, PeriodStart: 1696561158, PeriodEnd: 1699239558, CreateTime: 1696561161, CouponCode: null, Currency: 'CHF', Amount: 1299, Discount: 0, RenewAmount: 1299, Plans: [ { ID: '1', Type: 1, Name: PLANS.BUNDLE, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Cycle: 1, Currency: 'CHF', Amount: 1299, Offers: [], Quantity: 1, Pricing: { 1: 1299, 12: 11988, 24: 19176, }, }, ], Renew: 1, External: 0, UpcomingSubscription: null, isManagedByMozilla: false, }; upcoming = { ID: '124', InvoiceID: null as any, Cycle: 12, PeriodStart: 1699239558, PeriodEnd: 1730861958, CreateTime: 1696561195, CouponCode: null, Currency: 'CHF', Amount: 11988, Discount: 0, RenewAmount: 11988, Plans: [ { ID: '1', Type: 1, Name: PLANS.BUNDLE, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Cycle: 12, Currency: 'CHF', Amount: 11988, Quantity: 1, Offers: [], Pricing: { 1: 1299, 12: 11988, 24: 19176, }, }, ], Renew: 1, External: 0, }; jest.clearAllMocks(); mockUserCache(); mockPlansCache(); mockSubscriptionCache(subscription); }); it('should return MozillaInfoPanel if isManagedByMozilla is true', () => { subscription.isManagedByMozilla = true; const { container } = render(<ContextSubscriptionSection />); expect(container).toHaveTextContent('Your subscription is managed by Mozilla'); }); it('should render current subscription', () => { const { getByTestId } = render(<ContextSubscriptionSection />); expect(getByTestId('planNameId')).toHaveTextContent('Proton Unlimited'); expect(getByTestId('subscriptionStatusId')).toHaveTextContent('Active'); expect(getByTestId('planEndTimeId')).toHaveTextContent('Nov 6, 2023'); }); it('should display Expiring badge if renew is disabled', () => { subscription.Renew = Renew.Disabled; const { getByTestId } = render(<ContextSubscriptionSection />); expect(getByTestId('planNameId')).toHaveTextContent('Proton Unlimited'); expect(getByTestId('subscriptionStatusId')).toHaveTextContent('Expiring'); expect(getByTestId('planEndTimeId')).toHaveTextContent('Nov 6, 2023'); }); it('should render end date of upcoming subscription', () => { subscription.UpcomingSubscription = upcoming; const { getByTestId } = render(<ContextSubscriptionSection />); expect(getByTestId('planNameId')).toHaveTextContent('Proton Unlimited'); expect(getByTestId('subscriptionStatusId')).toHaveTextContent('Active'); expect(getByTestId('planEndTimeId')).toHaveTextContent('Nov 6, 2024'); }); it('should show renewal notice if there is no upcoming subscription', () => { const { getByTestId } = render(<ContextSubscriptionSection />); expect(getByTestId('renewalNotice')).toHaveTextContent('Renews automatically at CHF 12.99, for 1 month'); }); it('should show renewal notice if there is upcoming subscription', () => { subscription.UpcomingSubscription = upcoming; const { getByTestId } = render(<ContextSubscriptionSection />); expect(getByTestId('renewalNotice')).toHaveTextContent('Renews automatically at CHF 119.88, for 12 months'); }); it('should now show renewal notice if subscription is expiring', () => { subscription.Renew = Renew.Disabled; const { container } = render(<ContextSubscriptionSection />); expect(container).not.toHaveTextContent('Renews automatically'); }); it('should display Reactivate button when Renew is disabled', () => { subscription.Renew = Renew.Disabled; const { getByText } = render(<ContextSubscriptionSection />); expect(getByText('Reactivate')).toBeInTheDocument(); }); it('should display warning icon when renewal is disabled', () => { subscription.Renew = Renew.Disabled; const { queryByTestId } = render(<ContextSubscriptionSection />); expect(queryByTestId('periodEndWarning')).toBeInTheDocument(); }); it('should not display date of upcoming subscription if renew is disabled', () => { subscription.Renew = Renew.Disabled; subscription.UpcomingSubscription = upcoming; const { container } = render(<ContextSubscriptionSection />); expect(container).not.toHaveTextContent('Upcoming'); }); it('should call API when user presses reactivate button', () => { subscription.Renew = Renew.Disabled; const { getByText } = render(<ContextSubscriptionSection />); getByText('Reactivate').click(); expect(apiMock).toHaveBeenCalledWith( changeRenewState({ RenewalState: Renew.Enabled, }) ); }); });
6,732
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/SubscriptionsSection.tsx
import { c, msgid } from 'ttag'; import { DropdownActionProps } from '@proton/components/components/dropdown/DropdownActions'; import { useLoading } from '@proton/hooks'; import { changeRenewState } from '@proton/shared/lib/api/payments'; import { COUPON_CODES, PLANS } from '@proton/shared/lib/constants'; import { getCheckResultFromSubscription, getCheckout, getOptimisticCheckResult, } from '@proton/shared/lib/helpers/checkout'; import { toMap } from '@proton/shared/lib/helpers/object'; import { getNormalCycleFromCustomCycle, getPlanIDs } from '@proton/shared/lib/helpers/subscription'; import { Renew } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import { DropdownActions, Icon, Loader, Price, Table, TableBody, TableCell, TableHeader, TableRow, Time, Tooltip, } from '../../components'; import { default as Badge, BadgeType } from '../../components/badge/Badge'; import { useApi, useEventManager, usePlans, useSubscription } from '../../hooks'; import { SettingsSectionWide } from '../account'; import MozillaInfoPanel from '../account/MozillaInfoPanel'; import { subscriptionExpires } from './subscription/helpers'; export const getMonths = (n: number) => c('Billing cycle').ngettext(msgid`${n} month`, `${n} months`, n); const SubscriptionsSection = () => { const [plans, loadingPlans] = usePlans(); const [current, loadingSubscription] = useSubscription(); const upcoming = current?.UpcomingSubscription ?? undefined; const api = useApi(); const eventManager = useEventManager(); const [reactivating, withReactivating] = useLoading(); if (loadingSubscription || loadingPlans) { return <Loader />; } if (current.isManagedByMozilla) { return <MozillaInfoPanel />; } const plansMap = toMap(plans, 'Name'); const currentPlanIDs = getPlanIDs(current); const currentCheckout = getCheckout({ plansMap, planIDs: currentPlanIDs, checkResult: getCheckResultFromSubscription(current), }); const { renewEnabled, subscriptionExpiresSoon } = subscriptionExpires(current); const reactivateAction: DropdownActionProps[] = [ !renewEnabled && { text: c('Action subscription').t`Reactivate`, loading: reactivating, onClick: () => { withReactivating(async () => { await api( changeRenewState({ RenewalState: Renew.Enabled, }) ); await eventManager.call(); }).catch(noop); }, }, ].filter(isTruthy); const latestSubscription = upcoming ?? current; const { renewPrice, renewalLength } = (() => { const latestPlanIDs = getPlanIDs(latestSubscription); if ( latestSubscription.CouponCode === COUPON_CODES.BLACK_FRIDAY_2023 && (latestPlanIDs[PLANS.VPN] || latestPlanIDs[PLANS.VPN_PASS_BUNDLE]) ) { const nextCycle = getNormalCycleFromCustomCycle(latestSubscription.Cycle); const latestCheckout = getCheckout({ plansMap, planIDs: latestPlanIDs, checkResult: getOptimisticCheckResult({ planIDs: latestPlanIDs, plansMap, cycle: nextCycle, }), }); return { // The API doesn't return the correct next cycle or RenewAmount for the VPN or VPN+Pass bundle plan since we don't have chargebee // So we calculate it with the cycle discount here renewPrice: ( <Price key="renewal-price" currency={latestSubscription.Currency}> {latestCheckout.withDiscountPerCycle} </Price> ), renewalLength: getMonths(nextCycle), }; } return { renewPrice: ( <Price key="renewal-price" currency={latestSubscription.Currency}> {latestSubscription.RenewAmount} </Price> ), renewalLength: getMonths(latestSubscription.Cycle), }; })(); const renewalText = ( <span data-testid="renewalNotice">{c('Billing cycle') .jt`Renews automatically at ${renewPrice}, for ${renewalLength}`}</span> ); const status = subscriptionExpiresSoon ? { type: 'error' as BadgeType, label: c('Subscription status').t`Expiring`, } : { type: 'success' as BadgeType, label: c('Subscription status').t`Active` }; return ( <SettingsSectionWide> <div style={{ overflow: 'auto' }}> <Table className="table-auto" responsive="cards"> <TableHeader> <TableRow> <TableCell type="header">{c('Title subscription').t`Plan`}</TableCell> <TableCell type="header">{c('Title subscription').t`Status`}</TableCell> <TableCell type="header">{c('Title subscription').t`End date`}</TableCell> <TableCell type="header"> </TableCell> </TableRow> </TableHeader> <TableBody colSpan={4}> <TableRow> <TableCell label={c('Title subscription').t`Plan`}> <span data-testid="planNameId">{currentCheckout.planTitle}</span> </TableCell> <TableCell data-testid="subscriptionStatusId"> <Badge type={status.type}>{status.label}</Badge> </TableCell> <TableCell label={c('Title subscription').t`End date`}> <Time format="PP" sameDayFormat={false} data-testid="planEndTimeId"> {latestSubscription.PeriodEnd} </Time> {subscriptionExpiresSoon && ( <Tooltip title={c('Info subscription') .t`You can prevent expiry by reactivating the subscription`} data-testid="periodEndWarning" > <Icon name="exclamation-circle-filled" className="color-danger ml-1" size={18} /> </Tooltip> )} </TableCell> <TableCell data-testid="subscriptionActionsId"> {subscriptionExpiresSoon ? ( <DropdownActions size="small" list={reactivateAction} /> ) : ( renewalText )} </TableCell> </TableRow> </TableBody> </Table> </div> </SettingsSectionWide> ); }; export default SubscriptionsSection;
6,733
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/helper.ts
import { c, msgid } from 'ttag'; import { Cycle } from '@proton/shared/lib/interfaces'; export const getTotalBillingText = (cycle: Cycle) => { const n = cycle; return c('Checkout row').ngettext(msgid`Total for ${n} month`, `Total for ${n} months`, n); }; export const getShortBillingText = (n: number) => { return c('Label').ngettext(msgid`${n} month`, `${n} months`, n); };
6,734
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/index.ts
export { default as Alert3ds } from './Alert3ds'; export { default as AmountButton } from './AmountButton'; export { default as AmountRow } from './AmountRow'; export { default as Bitcoin } from './Bitcoin'; export { default as BitcoinDetails } from './BitcoinDetails'; export { default as BitcoinQRCode } from './BitcoinQRCode'; export { default as Cash } from './Cash'; export { default as CreditsSection } from './CreditsSection'; export { default as CurrencySelector } from './CurrencySelector'; export { default as CycleSelector } from './CycleSelector'; export { default as DowngradeModal } from './DowngradeModal'; export { default as EditCardModal } from './EditCardModal'; export { default as GiftCodeSection } from './GiftCodeSection'; export { default as LossLoyaltyModal } from './LossLoyaltyModal'; export { default as PayPalButton } from './PayPalButton'; export { default as PaymentInfo } from './PaymentInfo'; export { default as PaymentSelector } from './PaymentSelector'; export { default as PlansSection } from './PlansSection'; export * from './RenewalNotice'; export { default as StyledPayPalButton } from './StyledPayPalButton'; export { default as SubscriptionsSection } from './SubscriptionsSection'; export * from './subscription';
6,735
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/useBitcoin.test.tsx
import { renderHook } from '@testing-library/react-hooks'; import { AmountAndCurrency, PAYMENT_TOKEN_STATUS } from '@proton/components/payments/core'; import { createToken, getTokenStatus } from '@proton/shared/lib/api/payments'; import { MAX_BITCOIN_AMOUNT } from '@proton/shared/lib/constants'; import { addApiMock, addApiResolver, apiMock, flushPromises } from '@proton/testing/index'; import useBitcoin, { BITCOIN_POLLING_INTERVAL } from './useBitcoin'; const onTokenValidated = jest.fn(); const onAwaitingPayment = jest.fn(); beforeEach(() => { jest.clearAllMocks(); }); it('should render', () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; const { result } = renderHook(() => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }) ); expect(result.current).toBeDefined(); }); it('should request the token', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; const { result } = renderHook(() => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }) ); await result.current.request(); jest.runAllTicks(); expect(apiMock).toHaveBeenCalledTimes(1); }); it('should not request the token automatically', () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; const { rerender } = renderHook( ({ amountAndCurrency }) => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }), { initialProps: { amountAndCurrency, }, } ); expect(apiMock).toHaveBeenCalledTimes(0); rerender({ amountAndCurrency: { Amount: 2000, Currency: 'USD', }, }); expect(apiMock).toHaveBeenCalledTimes(0); }); it('should not request the token if the amount is too low', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: 100, Currency: 'EUR', }; const { result } = renderHook(() => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }) ); await result.current.request(); expect(apiMock).toHaveBeenCalledTimes(0); }); it('should not request the token if the amount is too high', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: MAX_BITCOIN_AMOUNT + 1000, Currency: 'EUR', }; const { result } = renderHook(() => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }) ); await result.current.request(); expect(apiMock).toHaveBeenCalledTimes(0); }); describe('', () => { beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers(); }); afterEach(() => { jest.useRealTimers(); }); it('should not request if the token exists and amount and currency are the same', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; addApiMock(createToken({} as any).url, () => ({ Code: 1000, Token: 'Token-12345', Status: 0, Data: { CoinAddress: 'some-btc-address', CoinAmount: 0.000789, CoinType: 6, CoinAddressReused: false, }, })); const { result } = renderHook(() => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling: true, ...amountAndCurrency, }) ); await result.current.request(); jest.runAllTicks(); expect(apiMock).toHaveBeenCalledTimes(1); await result.current.request(); jest.runAllTicks(); expect(apiMock).toHaveBeenCalledTimes(1); }); it('should stop polling when enablePolling is set to false', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; addApiMock(createToken({} as any).url, () => ({ Code: 1000, Token: 'Token-12345', Status: 0, Data: { CoinAddress: 'some-btc-address', CoinAmount: 0.000789, CoinType: 6, CoinAddressReused: false, }, })); addApiMock(getTokenStatus('Token-12345').url, () => ({ Code: 1000, Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, })); const { result, rerender } = renderHook( ({ enablePolling }) => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling, ...amountAndCurrency, }), { initialProps: { enablePolling: true, }, } ); await result.current.request(); expect(apiMock).toHaveBeenCalledTimes(1); // getting the token jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(apiMock).toHaveBeenCalledTimes(2); // checking the token for the first time rerender({ enablePolling: false, }); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(apiMock).toHaveBeenCalledTimes(2); // checking the token for the second time must not happen after polling was disabled jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(apiMock).toHaveBeenCalledTimes(2); // checking the token for the second time must not happen after polling was disabled }); it('should stop polling when the token is invalid', async () => { const amountAndCurrency: AmountAndCurrency = { Amount: 1000, Currency: 'EUR', }; addApiMock(createToken({} as any).url, () => ({ Code: 1000, Token: 'Token-12345', Status: 0, Data: { CoinAddress: 'some-btc-address', CoinAmount: 0.000789, CoinType: 6, CoinAddressReused: false, }, })); let resolvers: ReturnType<typeof addApiResolver>; const updateResolvers = () => { resolvers = addApiResolver(getTokenStatus('Token-12345').url); }; updateResolvers(); const resolveToken = () => resolvers.resolve({ Code: 1000, Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING, }); const rejectToken = () => resolvers.reject({ status: 400, }); const { result } = renderHook( ({ enablePolling }) => useBitcoin({ api: apiMock, onTokenValidated, onAwaitingPayment, enablePolling, ...amountAndCurrency, }), { initialProps: { enablePolling: true, }, } ); await result.current.request(); expect(apiMock).toHaveBeenCalledTimes(1); // getting the token updateResolvers(); await jest.advanceTimersByTimeAsync(BITCOIN_POLLING_INTERVAL); resolveToken(); expect(apiMock).toHaveBeenCalledTimes(2); // checking the token for the first time updateResolvers(); await jest.advanceTimersByTimeAsync(BITCOIN_POLLING_INTERVAL); rejectToken(); expect(apiMock).toHaveBeenCalledTimes(3); // checking the token for the second time updateResolvers(); await jest.advanceTimersByTimeAsync(BITCOIN_POLLING_INTERVAL); resolveToken(); // because of the rejection last time, the next call should never happen, the script must exit from the loop expect(apiMock).toHaveBeenCalledTimes(3); }); });
6,736
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/useBitcoin.ts
import { useEffect, useState } from 'react'; import { useLoading } from '@proton/hooks'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { CreateBitcoinTokenData, createToken, getTokenStatus } from '@proton/shared/lib/api/payments'; import { MAX_BITCOIN_AMOUNT, MIN_BITCOIN_AMOUNT } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Api } from '@proton/shared/lib/interfaces'; import { AmountAndCurrency, PAYMENT_METHOD_TYPES, PAYMENT_TOKEN_STATUS, TokenPaymentMethod, isTokenPaymentMethod, } from '../../payments/core'; export const BITCOIN_POLLING_INTERVAL = 60000; function pause() { return wait(BITCOIN_POLLING_INTERVAL); } type TokenValidationStatus = 'chargeable' | 'pending' | 'error-token-invalid'; const useCheckStatus = ({ api, token, onTokenValidated, onTokenInvalid, enablePolling, }: { api: Api; token: string | null; onTokenValidated: (token: string) => void; onTokenInvalid: () => void; enablePolling: boolean; }) => { const [paymentValidated, setPaymentValidated] = useState(false); const awaitingPayment = token !== null && !paymentValidated; useEffect(() => { let active = true; const validate = async (token: string): Promise<TokenValidationStatus> => { try { const { Status } = await api<any>(getTokenStatus(token)); if (Status === PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE) { return 'chargeable'; } } catch (err: any) { // it happens when token expires and no longer valid if (err?.status === 400) { return 'error-token-invalid'; } } return 'pending'; }; async function run() { if (!token) { return; } await pause(); while (active && enablePolling) { const status = await validate(token); if (status === 'chargeable' && active) { setPaymentValidated(true); onTokenValidated?.(token); active = false; break; } // stop the polling loop if the token is no longer valid if (status === 'error-token-invalid') { active = false; onTokenInvalid(); break; } await pause(); } } void run(); return () => { active = false; }; }, [token, enablePolling]); return { paymentValidated, awaitingPayment, }; }; export interface BitcoinTokenModel { amountBitcoin: number; address: string; token: string | null; amount: number; currency: string | null; } export interface ValidatedBitcoinToken extends TokenPaymentMethod { cryptoAmount: number; cryptoAddress: string; } export function isValidatedBitcoinToken(paymentMethod: any): paymentMethod is ValidatedBitcoinToken { return ( isTokenPaymentMethod(paymentMethod) && typeof (paymentMethod as any).cryptoAmount === 'number' && typeof (paymentMethod as any).cryptoAddress === 'string' ); } export type OnBitcoinTokenValidated = (data: ValidatedBitcoinToken) => void; export type OnBitcoinAwaitingPayment = (awaitingBitcoinPayment: boolean) => void; export type UseBitcoinParams = { api: Api; onTokenValidated: OnBitcoinTokenValidated; onAwaitingPayment?: OnBitcoinAwaitingPayment; enablePolling: boolean; } & AmountAndCurrency; const useBitcoin = ({ api, onTokenValidated, onAwaitingPayment, enablePolling, Amount: amount, Currency: currency, }: UseBitcoinParams) => { const silentApi = getSilentApi(api); const [error, setError] = useState(false); const INITIAL_STATE: BitcoinTokenModel = { amountBitcoin: 0, address: '', token: null, amount: 0, currency: null }; const [model, setModel] = useState(INITIAL_STATE); const [loading, withLoading] = useLoading(); const checkStatus = useCheckStatus({ api: silentApi, token: model.token, onTokenValidated: (token) => onTokenValidated({ Payment: { Type: PAYMENT_METHOD_TYPES.TOKEN, Details: { Token: token, }, }, cryptoAmount: model.amountBitcoin, cryptoAddress: model.address, }), onTokenInvalid: () => { setError(true); setModel(INITIAL_STATE); onAwaitingPayment?.(false); }, enablePolling, }); useEffect(() => { onAwaitingPayment?.(checkStatus.awaitingPayment && !loading); }, [checkStatus.awaitingPayment, loading]); const fetchAsToken = async () => { try { const data: CreateBitcoinTokenData = { Amount: amount, Currency: currency, Payment: { Type: 'cryptocurrency', Details: { Coin: 'bitcoin', }, }, }; const { Token, Data } = await silentApi<any>(createToken(data)); setModel({ amountBitcoin: Data.CoinAmount, address: Data.CoinAddress, token: Token, amount: amount, currency: currency, }); } catch (error) { setModel(INITIAL_STATE); throw error; } }; const request = async () => { const isCorrectAmount = amount >= MIN_BITCOIN_AMOUNT && amount <= MAX_BITCOIN_AMOUNT; const alreadyHasToken = model.amount === amount && model.currency === currency && !!model.token; if (!isCorrectAmount || alreadyHasToken) { return; } setError(false); try { await withLoading(fetchAsToken()); } catch { setError(true); } }; return { model, loading, request, error, amount, currency, ...checkStatus, }; }; export default useBitcoin;
6,737
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/__mocks__/RenewToggle.tsx
export default () => <>RenewToggle</>;
6,738
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/features/b2b.ts
import { c } from 'ttag'; import { BRAND_NAME, PLANS } from '@proton/shared/lib/constants'; import { Audience } from '@proton/shared/lib/interfaces'; import { PlanCardFeature, PlanCardFeatureDefinition } from './interface'; export const getTwoFA = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Two-factor authentication`, tooltip: c('new_plans: tooltip') .t`Requires a code sent to a mobile phone to sign in. This ensures even if a password is compromised, the account stays secure.`, included: true, }; }; export const getConsole = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Admin console`, tooltip: c('new_plans: tooltip') .t`Organization management tool that lets admins add and remove users, allocate storage, configure domains, and perform other tasks`, included: true, }; }; export const getBilling = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Centralized billing`, tooltip: c('new_plans: tooltip') .t`Manage your subscription, including customization of your plan. Payment methods accepted are credit card, PayPal, cryptocurrency, and wire transfer.`, included: true, }; }; export const getAdmins = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Multiple admin roles`, tooltip: c('new_plans: tooltip') .t`You can have more than one admin. All admins can add and manage users but only the primary admin has control over billing.`, included: true, }; }; export const getSignIn = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Sign in as user`, tooltip: c('new_plans: tooltip') .t`Option to view non-private user inboxes as the user would, including full message and contact details`, included: true, }; }; export const getCredentials = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`User credential management`, tooltip: c('new_plans: tooltip').t`Reset user passwords and reset two-factor authentication on users`, included: true, }; }; export const getSessions = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`User session management`, tooltip: c('new_plans: tooltip') .t`Force sign-out of user sessions when user credentials are believed to be compromised`, included: true, }; }; export const getTeamManagementFeatures = (): PlanCardFeature[] => { return [ { name: 'two-fa', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getTwoFA(), [PLANS.BUNDLE_PRO]: getTwoFA(), [PLANS.VPN_PRO]: getTwoFA(), [PLANS.VPN_BUSINESS]: getTwoFA(), }, }, { name: 'console', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getConsole(), [PLANS.BUNDLE_PRO]: getConsole(), [PLANS.VPN_PRO]: getConsole(), [PLANS.VPN_BUSINESS]: getConsole(), }, }, { name: 'billing', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getBilling(), [PLANS.BUNDLE_PRO]: getBilling(), [PLANS.VPN_PRO]: getBilling(), [PLANS.VPN_BUSINESS]: getBilling(), }, }, { name: 'admins', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getAdmins(), [PLANS.BUNDLE_PRO]: getAdmins(), [PLANS.VPN_PRO]: getAdmins(), [PLANS.VPN_BUSINESS]: getAdmins(), }, }, { name: 'sign-in', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getSignIn(), [PLANS.BUNDLE_PRO]: getSignIn(), [PLANS.VPN_PRO]: getSignIn(), [PLANS.VPN_BUSINESS]: getSignIn(), }, }, { name: 'credentials', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getCredentials(), [PLANS.BUNDLE_PRO]: getCredentials(), [PLANS.VPN_PRO]: getCredentials(), [PLANS.VPN_BUSINESS]: getCredentials(), }, }, { name: 'sessions', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getSessions(), [PLANS.BUNDLE_PRO]: getSessions(), [PLANS.VPN_PRO]: getSessions(), [PLANS.VPN_BUSINESS]: getSessions(), }, }, ]; }; export const getGDPR = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`GDPR data processing agreement`, included: true, }; }; export const getHIPAA = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Enables HIPAA compliance`, tooltip: c('new_plans: tooltip') .t`We’re committed to helping customers subject to HIPAA/HITECH regulations safeguard protected health information (PHI). Signed BAAs are available for all ${BRAND_NAME} for Business customers.`, included: true, }; }; export const getSupport = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Priority email support`, tooltip: c('new_plans: tooltip') .t`On business days, receive support from the ${BRAND_NAME} Customer Support team within 24 hours of requests`, included: true, }; }; export const getPhoneSupport = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Phone support (6+ users)`, tooltip: c('new_plans: tooltip') .t`Phone support is available from the ${BRAND_NAME} Customer Success team during European business hours, for customers with 6 or more users`, included: true, }; }; export const getSLA = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`99.95% SLA`, tooltip: c('new_plans: tooltip') .t`Our robust infrastructure ensures you will be able to access your account when you need it`, included: true, }; }; export const getSupportFeatures = (): PlanCardFeature[] => { return [ { name: 'gdpr', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getGDPR(), [PLANS.BUNDLE_PRO]: getGDPR(), [PLANS.VPN_PRO]: getGDPR(), [PLANS.VPN_BUSINESS]: getGDPR(), }, }, { name: 'hipaa', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getHIPAA(), [PLANS.BUNDLE_PRO]: getHIPAA(), [PLANS.VPN_PRO]: getHIPAA(), [PLANS.VPN_BUSINESS]: getHIPAA(), }, }, { name: 'b2b-support', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getSupport(), [PLANS.BUNDLE_PRO]: getSupport(), [PLANS.VPN_PRO]: getSupport(), [PLANS.VPN_BUSINESS]: getSupport(), }, }, { name: 'phone-support', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getPhoneSupport(), [PLANS.BUNDLE_PRO]: getPhoneSupport(), [PLANS.VPN_PRO]: getPhoneSupport(), [PLANS.VPN_BUSINESS]: getPhoneSupport(), }, }, { name: 'sla', target: Audience.B2B, plans: { [PLANS.FREE]: null, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.DRIVE]: null, [PLANS.PASS_PLUS]: null, [PLANS.FAMILY]: null, [PLANS.MAIL_PRO]: getSLA(), [PLANS.BUNDLE_PRO]: getSLA(), [PLANS.VPN_PRO]: getSLA(), [PLANS.VPN_BUSINESS]: getSLA(), }, }, ]; };
6,739
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/features/calendar.ts
import { c, msgid } from 'ttag'; import { MAX_CALENDARS_FAMILY, MAX_CALENDARS_FREE, MAX_CALENDARS_PAID } from '@proton/shared/lib/calendar/constants'; import { CALENDAR_APP_NAME, FAMILY_MAX_USERS, PLANS, PLAN_SERVICES } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { Audience, PlansMap } from '@proton/shared/lib/interfaces'; import { PlanCardFeature, PlanCardFeatureDefinition } from './interface'; const getNCalendarsTooltipText = (n: number) => { return c('new_plans: tooltip').ngettext( msgid`Create up to ${n} calendar or add calendars from friends, family, colleagues, and organizations`, `Create up to ${n} calendars or add calendars from friends, family, colleagues, and organizations`, n ); }; export const getNCalendarToCreateFeature = (n: number): PlanCardFeatureDefinition => ({ icon: 'brand-proton-calendar', included: true, text: c('new_plans: Upsell attribute').ngettext( msgid`Create up to ${n} calendar`, `Create up to ${n} calendars`, n ), }); export const getNCalendarsFeature = (n: number): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').ngettext(msgid`${n} calendar`, `${n} calendars`, n), tooltip: n > 1 ? getNCalendarsTooltipText(n) : '', included: true, icon: 'brand-proton-calendar', }; }; export const getNCalendarsPerUserFeature = (n: number): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').ngettext(msgid`${n} calendar per user`, `${n} calendars per user`, n), tooltip: n > 1 ? getNCalendarsTooltipText(n) : '', included: true, icon: 'brand-proton-calendar', }; }; const getEndToEndEncryption = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`End-to-end encryption`, included: true, }; }; const getShareFeature = ( plansMap: PlansMap, plan: PLANS, calendarSharingEnabled: boolean, audience?: Audience ): PlanCardFeatureDefinition => { const included = hasBit(plansMap[plan]?.Services, PLAN_SERVICES.MAIL); const tooltipText = calendarSharingEnabled ? c('new_plans: tooltip').t`Easily share your calendars with your family, friends, or colleagues` : c('new_plans: tooltip').t`Easily share your calendars with your colleagues, family, and friends via a link`; return { text: calendarSharingEnabled ? c('new_plans: feature').t`Calendar sharing` : c('new_plans: feature').t`Share calendar via link`, tooltip: audience === Audience.B2B ? tooltipText : tooltipText, included, }; }; const getInvitation = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Send & receive invitations`, included: true, }; }; export const getCalendarAppFeature = (options?: { family?: boolean }): PlanCardFeatureDefinition => { return { text: CALENDAR_APP_NAME, tooltip: options?.family ? c('new_plans: tooltip').t`Keep your plans private to you and your family with an encrypted calendar` : c('new_plans: tooltip') .t`${CALENDAR_APP_NAME}: Secure your schedule with end-to-end encryption. Includes support for custom calendars, calendar sharing, and more.`, included: true, icon: 'brand-proton-calendar', }; }; export const getCalendarFeatures = (plansMap: PlansMap, calendarSharingEnabled: boolean): PlanCardFeature[] => { return [ { name: 'calendars', plans: { [PLANS.FREE]: getNCalendarsFeature(MAX_CALENDARS_FREE), // TODO: Order should be inverted in ORs of the inputs of getNCalendarsFeature below (B || A instead of A || B). The limits need to be changed API-side for that though. Only after that this TODO can be tackled [PLANS.BUNDLE]: getNCalendarsFeature(MAX_CALENDARS_PAID || plansMap[PLANS.BUNDLE]?.MaxCalendars), [PLANS.MAIL]: getNCalendarsFeature(MAX_CALENDARS_PAID || plansMap[PLANS.MAIL]?.MaxCalendars), [PLANS.VPN]: getNCalendarsFeature(MAX_CALENDARS_FREE || plansMap[PLANS.VPN]?.MaxCalendars), [PLANS.DRIVE]: getNCalendarsFeature(MAX_CALENDARS_FREE || plansMap[PLANS.DRIVE]?.MaxCalendars), [PLANS.PASS_PLUS]: getNCalendarsFeature(MAX_CALENDARS_FREE || plansMap[PLANS.PASS_PLUS]?.MaxCalendars), [PLANS.FAMILY]: getNCalendarsPerUserFeature( Math.floor((MAX_CALENDARS_FAMILY ?? plansMap[PLANS.FAMILY]?.MaxCalendars) / FAMILY_MAX_USERS) ), [PLANS.BUNDLE_PRO]: getNCalendarsFeature( MAX_CALENDARS_PAID || plansMap[PLANS.BUNDLE_PRO]?.MaxCalendars ), [PLANS.MAIL_PRO]: getNCalendarsFeature(MAX_CALENDARS_PAID || plansMap[PLANS.MAIL_PRO]?.MaxCalendars), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'encryption', plans: { [PLANS.FREE]: getEndToEndEncryption(), [PLANS.BUNDLE]: getEndToEndEncryption(), [PLANS.MAIL]: getEndToEndEncryption(), [PLANS.VPN]: getEndToEndEncryption(), [PLANS.DRIVE]: getEndToEndEncryption(), [PLANS.PASS_PLUS]: getEndToEndEncryption(), [PLANS.FAMILY]: getEndToEndEncryption(), [PLANS.BUNDLE_PRO]: getEndToEndEncryption(), [PLANS.MAIL_PRO]: getEndToEndEncryption(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'share', plans: { [PLANS.FREE]: getShareFeature(plansMap, PLANS.FREE, calendarSharingEnabled), [PLANS.BUNDLE]: getShareFeature(plansMap, PLANS.BUNDLE, calendarSharingEnabled), [PLANS.MAIL]: getShareFeature(plansMap, PLANS.MAIL, calendarSharingEnabled), [PLANS.VPN]: getShareFeature(plansMap, PLANS.VPN, calendarSharingEnabled), [PLANS.DRIVE]: getShareFeature(plansMap, PLANS.DRIVE, calendarSharingEnabled), [PLANS.PASS_PLUS]: getShareFeature(plansMap, PLANS.PASS_PLUS, calendarSharingEnabled), [PLANS.FAMILY]: getShareFeature(plansMap, PLANS.FAMILY, calendarSharingEnabled), [PLANS.BUNDLE_PRO]: getShareFeature(plansMap, PLANS.BUNDLE_PRO, calendarSharingEnabled, Audience.B2B), [PLANS.MAIL_PRO]: getShareFeature(plansMap, PLANS.MAIL_PRO, calendarSharingEnabled, Audience.B2B), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'invitation', plans: { [PLANS.FREE]: getInvitation(), [PLANS.BUNDLE]: getInvitation(), [PLANS.MAIL]: getInvitation(), [PLANS.VPN]: getInvitation(), [PLANS.DRIVE]: getInvitation(), [PLANS.PASS_PLUS]: getInvitation(), [PLANS.FAMILY]: getInvitation(), [PLANS.BUNDLE_PRO]: getInvitation(), [PLANS.MAIL_PRO]: getInvitation(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, ]; };
6,740
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/features/drive.tsx
import { c } from 'ttag'; import { CALENDAR_APP_NAME, DRIVE_APP_NAME, MAIL_APP_NAME, PLANS } from '@proton/shared/lib/constants'; import humanSize, { getSizeFormat } from '@proton/shared/lib/helpers/humanSize'; import { Audience, PlansMap } from '@proton/shared/lib/interfaces'; import { PlanCardFeature, PlanCardFeatureDefinition } from './interface'; const getTb = (n: number) => { return `${n} ${getSizeFormat('TB', n)}`; }; export const getStorageFeature = ( bytes: number, options: { highlight?: boolean; boldStorageSize?: boolean; family?: boolean; visionary?: boolean } = {} ): PlanCardFeatureDefinition => { const { highlight = false, boldStorageSize = false } = options; if (bytes === -1) { const freeStorageSize = humanSize(500 * 1024 ** 2, undefined, undefined, 0); const totalStorageSize = humanSize(1 * 1024 ** 3, undefined, undefined, 0); return { text: c('new_plans: feature').t`Up to ${totalStorageSize} storage`, tooltip: c('new_plans: tooltip') .t`Start with ${freeStorageSize} and unlock more storage along the way. Storage space is shared across ${MAIL_APP_NAME}, ${CALENDAR_APP_NAME}, and ${DRIVE_APP_NAME}.`, included: true, icon: 'storage', }; } // humanSize doesn't support TB and we don't want to add it yet because of "nice numbers" rounding issues. const humanReadableSize = options.visionary ? getTb(6) : options.family ? getTb(3) : humanSize(bytes, undefined, undefined, 0); const size = boldStorageSize ? <b key="bold-storage-size">{humanReadableSize}</b> : humanReadableSize; const tooltip = options.family ? c('new_plans: tooltip') .t`Storage space is shared between users across ${MAIL_APP_NAME}, ${CALENDAR_APP_NAME}, and ${DRIVE_APP_NAME}` : c('new_plans: tooltip') .t`Storage space is shared across ${MAIL_APP_NAME}, ${CALENDAR_APP_NAME}, and ${DRIVE_APP_NAME}`; return { text: c('new_plans: feature').jt`${size} storage`, tooltip, included: true, highlight, icon: 'storage', }; }; export const getStorageBoostFeature = (bundleStorage: string): PlanCardFeatureDefinition => { return { icon: 'storage', text: c('new_plans: Upsell attribute').t`Boost your storage space to ${bundleStorage} total`, included: true, }; }; export const getStorageBoostFeatureB2B = (bundleStorage: string): PlanCardFeatureDefinition => { return { icon: 'storage', text: c('new_plans: Upsell attribute').t`Boost your storage space to ${bundleStorage} per user`, included: true, }; }; export const getStorageFeatureB2B = (bytes: number, highlight?: boolean): PlanCardFeatureDefinition => { const size = humanSize(bytes, undefined, undefined, 0); return { text: c('new_plans: feature').t`${size} storage per user`, tooltip: c('new_plans: tooltip') .t`Storage space is shared across ${MAIL_APP_NAME}, ${CALENDAR_APP_NAME}, and ${DRIVE_APP_NAME}. Administrators can allocate different storage amounts to users in their organization`, included: true, highlight, icon: 'storage', }; }; const getEndToEndEncryption = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`End-to-end encryption`, included: true, }; }; export const getDriveAppFeature = (options?: { family?: boolean }): PlanCardFeatureDefinition => { return { text: DRIVE_APP_NAME, tooltip: options?.family ? c('new_plans: tooltip') .t`Secure your files with encrypted cloud storage. Includes automatic sync, encrypted file sharing, and more.` : c('new_plans: tooltip') .t`${DRIVE_APP_NAME}: Secure your files with encrypted cloud storage. Includes version history, encrypted file sharing, and more.`, included: true, icon: 'brand-proton-drive', }; }; const getShareFeature = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Share files and folders via link`, tooltip: c('new_plans: tooltip').t`Share your files or folders with anyone by using secure, shareable links`, included: true, }; }; const getAdvancedShareFeature = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Advanced sharing security`, tooltip: c('new_plans: tooltip') .t`Control access to your shared files by adding password protection and link expiration dates`, included: true, }; }; const getTeamManagement = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Team management`, included: false, }; }; const getDocumentEditor = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Document editors (docs, sheets, slides)`, included: false, }; }; export const getStorage = (plansMap: PlansMap): PlanCardFeature => { return { name: 'storage', plans: { [PLANS.FREE]: getStorageFeature(-1), [PLANS.BUNDLE]: getStorageFeature(plansMap[PLANS.BUNDLE]?.MaxSpace ?? 536870912000), [PLANS.MAIL]: getStorageFeature(plansMap[PLANS.MAIL]?.MaxSpace ?? 16106127360), [PLANS.VPN]: getStorageFeature(-1), [PLANS.DRIVE]: getStorageFeature(plansMap[PLANS.DRIVE]?.MaxSpace ?? 214748364800), [PLANS.PASS_PLUS]: getStorageFeature(-1), [PLANS.FAMILY]: getStorageFeature(plansMap[PLANS.FAMILY]?.MaxSpace ?? 2748779069440, { family: true, }), [PLANS.MAIL_PRO]: getStorageFeatureB2B(plansMap[PLANS.MAIL_PRO]?.MaxSpace ?? 16106127360), [PLANS.BUNDLE_PRO]: getStorageFeatureB2B(plansMap[PLANS.BUNDLE_PRO]?.MaxSpace ?? 536870912000), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }; }; export const getDriveFeatures = (plansMap: PlansMap): PlanCardFeature[] => { return [ getStorage(plansMap), { name: 'encryption', plans: { [PLANS.FREE]: getEndToEndEncryption(), [PLANS.BUNDLE]: getEndToEndEncryption(), [PLANS.MAIL]: getEndToEndEncryption(), [PLANS.VPN]: getEndToEndEncryption(), [PLANS.DRIVE]: getEndToEndEncryption(), [PLANS.PASS_PLUS]: getEndToEndEncryption(), [PLANS.FAMILY]: getEndToEndEncryption(), [PLANS.MAIL_PRO]: getEndToEndEncryption(), [PLANS.BUNDLE_PRO]: getEndToEndEncryption(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'share', plans: { [PLANS.FREE]: getShareFeature(), [PLANS.BUNDLE]: getShareFeature(), [PLANS.MAIL]: getShareFeature(), [PLANS.VPN]: getShareFeature(), [PLANS.DRIVE]: getShareFeature(), [PLANS.PASS_PLUS]: getShareFeature(), [PLANS.FAMILY]: getShareFeature(), [PLANS.MAIL_PRO]: getShareFeature(), [PLANS.BUNDLE_PRO]: getShareFeature(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'advanced-share', plans: { [PLANS.FREE]: getAdvancedShareFeature(), [PLANS.BUNDLE]: getAdvancedShareFeature(), [PLANS.MAIL]: getAdvancedShareFeature(), [PLANS.VPN]: getAdvancedShareFeature(), [PLANS.DRIVE]: getAdvancedShareFeature(), [PLANS.PASS_PLUS]: getAdvancedShareFeature(), [PLANS.FAMILY]: getAdvancedShareFeature(), [PLANS.MAIL_PRO]: getAdvancedShareFeature(), [PLANS.BUNDLE_PRO]: getAdvancedShareFeature(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'team-management', target: Audience.B2B, plans: { [PLANS.FREE]: getTeamManagement(), [PLANS.BUNDLE]: getTeamManagement(), [PLANS.MAIL]: getTeamManagement(), [PLANS.VPN]: getTeamManagement(), [PLANS.DRIVE]: getTeamManagement(), [PLANS.PASS_PLUS]: getTeamManagement(), [PLANS.FAMILY]: getTeamManagement(), [PLANS.MAIL_PRO]: getTeamManagement(), [PLANS.BUNDLE_PRO]: getTeamManagement(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'document-editor', target: Audience.B2B, plans: { [PLANS.FREE]: getDocumentEditor(), [PLANS.BUNDLE]: getDocumentEditor(), [PLANS.MAIL]: getDocumentEditor(), [PLANS.VPN]: getDocumentEditor(), [PLANS.DRIVE]: getDocumentEditor(), [PLANS.PASS_PLUS]: getDocumentEditor(), [PLANS.FAMILY]: getDocumentEditor(), [PLANS.MAIL_PRO]: getDocumentEditor(), [PLANS.BUNDLE_PRO]: getDocumentEditor(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, ]; };
6,741
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/features/highlights.ts
import { c } from 'ttag'; import { FAMILY_MAX_USERS, PLANS, PROTON_SENTINEL_NAME } from '@proton/shared/lib/constants'; import { Audience, PlansMap } from '@proton/shared/lib/interfaces'; import { getStorage } from './drive'; import { PlanCardFeature, PlanCardFeatureDefinition } from './interface'; const getUsers = (): PlanCardFeature => { return { name: 'user-number', target: Audience.FAMILY, plans: { [PLANS.FREE]: { text: c('new_plans: feature').t`1 user`, included: true, }, [PLANS.BUNDLE]: null, [PLANS.MAIL]: null, [PLANS.VPN]: null, [PLANS.PASS_PLUS]: null, [PLANS.DRIVE]: null, [PLANS.FAMILY]: { text: c('new_plans: feature').t`Up to ${FAMILY_MAX_USERS} users`, included: true, highlight: true, }, [PLANS.MAIL_PRO]: null, [PLANS.BUNDLE_PRO]: null, [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }; }; export const getUsersFeature = (n: number): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Up to ${n} users`, icon: 'users', included: true, }; }; export const getSupport = (type: 'limited' | 'priority'): PlanCardFeatureDefinition => { return { text: type === 'limited' ? c('new_plans: feature').t`Limited support` : c('new_plans: feature').t`Priority support`, included: true, icon: 'life-ring', }; }; const getEasySwitch = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Easy Switch import assistant`, tooltip: c('new_plans: tooltip').t`Quickly transfer your emails, calendars or contacts from any provider`, included: true, }; }; export const getSentinel = (included: boolean = true): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`${PROTON_SENTINEL_NAME} program`, tooltip: c('new_plans: tooltip') .t`Provides the highest level of account security protection and specialist support`, included: included, icon: 'shield', }; }; export const getHighlightFeatures = (plansMap: PlansMap, sentinelPassplusEnabled: boolean): PlanCardFeature[] => { return [ getUsers(), getStorage(plansMap), { name: 'support', plans: { [PLANS.FREE]: getSupport('limited'), [PLANS.BUNDLE]: getSupport('priority'), [PLANS.MAIL]: getSupport('priority'), [PLANS.VPN]: getSupport('priority'), [PLANS.DRIVE]: getSupport('priority'), [PLANS.PASS_PLUS]: getSupport('priority'), [PLANS.FAMILY]: getSupport('priority'), [PLANS.MAIL_PRO]: getSupport('priority'), [PLANS.BUNDLE_PRO]: getSupport('priority'), [PLANS.VPN_PRO]: getSupport('priority'), [PLANS.VPN_BUSINESS]: getSupport('priority'), }, }, { name: 'sentinel', plans: { [PLANS.FREE]: getSentinel(false), [PLANS.BUNDLE]: getSentinel(), [PLANS.MAIL]: getSentinel(false), [PLANS.VPN]: getSentinel(false), [PLANS.DRIVE]: getSentinel(false), [PLANS.PASS_PLUS]: getSentinel(sentinelPassplusEnabled), [PLANS.FAMILY]: getSentinel(), [PLANS.MAIL_PRO]: getSentinel(false), [PLANS.BUNDLE_PRO]: getSentinel(), [PLANS.VPN_PRO]: getSentinel(false), [PLANS.VPN_BUSINESS]: getSentinel(), }, }, { name: 'easy-switch', plans: { [PLANS.FREE]: getEasySwitch(), [PLANS.BUNDLE]: getEasySwitch(), [PLANS.MAIL]: getEasySwitch(), [PLANS.VPN]: getEasySwitch(), [PLANS.DRIVE]: getEasySwitch(), [PLANS.PASS_PLUS]: getEasySwitch(), [PLANS.FAMILY]: getEasySwitch(), [PLANS.MAIL_PRO]: getEasySwitch(), [PLANS.BUNDLE_PRO]: getEasySwitch(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, ]; };
6,742
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/features/index.ts
import { PLANS } from '@proton/shared/lib/constants'; import { Audience, PlansMap, VPNServersCountData } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { getSupportFeatures, getTeamManagementFeatures } from './b2b'; import { getCalendarFeatures } from './calendar'; import { getDriveFeatures } from './drive'; import { getHighlightFeatures } from './highlights'; import { PlanCardFeature } from './interface'; import { getMailFeatures } from './mail'; import { getPassFeatures } from './pass'; import { getVPNFeatures } from './vpn'; export const getAllFeatures = ({ plansMap, serversCount, calendarSharingEnabled, sentinelPassplusEnabled, }: { plansMap: PlansMap; serversCount: VPNServersCountData; calendarSharingEnabled: boolean; sentinelPassplusEnabled: boolean; }) => { return { highlight: getHighlightFeatures(plansMap, sentinelPassplusEnabled), mail: getMailFeatures(plansMap), calendar: getCalendarFeatures(plansMap, calendarSharingEnabled), drive: getDriveFeatures(plansMap), pass: getPassFeatures(), vpn: getVPNFeatures(serversCount), team: getTeamManagementFeatures(), support: getSupportFeatures(), } as const; }; export const getFeatureDefinitions = (plan: PLANS, features: PlanCardFeature[], audience: Audience) => { const filterAudience = (feature: PlanCardFeature) => { return feature.target === undefined || feature.target === audience; }; return features .filter(filterAudience) .map((feature) => { return feature.plans[plan as keyof typeof feature.plans]; }) .filter(isTruthy); }; export type AllFeatures = ReturnType<typeof getAllFeatures>;
6,743
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/features/interface.ts
import { PLANS } from '@proton/shared/lib/constants'; import { Audience } from '@proton/shared/lib/interfaces'; import { IconName } from '../../../components'; export interface PlanCardFeatureDefinition { text: string | string[]; included: boolean; hideInDowngrade?: boolean; status?: 'available' | 'coming-soon'; tooltip?: string; highlight?: boolean; icon?: IconName; iconUrl?: string; } export interface PlanCardFeature { name: string; /* If targeting a specific audience */ target?: Audience; plans: { [PLANS.FREE]: PlanCardFeatureDefinition | null; [PLANS.BUNDLE]: PlanCardFeatureDefinition | null; [PLANS.MAIL]: PlanCardFeatureDefinition | null; [PLANS.VPN]: PlanCardFeatureDefinition | null; [PLANS.DRIVE]: PlanCardFeatureDefinition | null; [PLANS.PASS_PLUS]: PlanCardFeatureDefinition | null; [PLANS.FAMILY]: PlanCardFeatureDefinition | null; [PLANS.MAIL_PRO]: PlanCardFeatureDefinition | null; [PLANS.BUNDLE_PRO]: PlanCardFeatureDefinition | null; [PLANS.VPN_PRO]: PlanCardFeatureDefinition | null; [PLANS.VPN_BUSINESS]: PlanCardFeatureDefinition | null; }; } export enum PlanCardFeatureType { highlight, mail, calendar, drive, vpn, team, support, } export interface ShortPlan { label: string; description: string; title: string; plan: | PLANS.FREE | PLANS.BUNDLE | PLANS.MAIL | PLANS.DRIVE | PLANS.PASS_PLUS | PLANS.BUNDLE_PRO | PLANS.MAIL_PRO | PLANS.VPN | PLANS.NEW_VISIONARY | PLANS.FAMILY | PLANS.VPN_PRO | PLANS.VPN_BUSINESS; cta: string; features: PlanCardFeatureDefinition[]; } /** * Can be used for UI-only plans. For example, the enterprise-talk-to-us plan doesn't exist on the backend, * but we still want to display it in the UI. */ export type ShortPlanLike = { plan: string; cta?: string; isPlanLike: true; } & Pick<ShortPlan, 'label' | 'description' | 'title' | 'features'>; export function isShortPlanLike(plan: any): plan is ShortPlanLike { return !!plan && plan.isPlanLike; }
6,744
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/features/mail.ts
import { c, msgid } from 'ttag'; import { BRAND_NAME, MAIL_APP_NAME, PLANS } from '@proton/shared/lib/constants'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Audience, PlansMap } from '@proton/shared/lib/interfaces'; import { PlanCardFeature, PlanCardFeatureDefinition } from './interface'; export const getMailAppFeature = (): PlanCardFeatureDefinition => { return { text: MAIL_APP_NAME, included: true, icon: 'brand-proton-mail', tooltip: c('new_plans: tooltip') .t`${MAIL_APP_NAME}: Secure your emails with end-to-end encryption. Includes support for custom email domains, 15 email addresses, unlimited hide-my-email aliases, and more.`, }; }; export const getNAddressesFeature = ({ n, highlight, family, }: { n: number; highlight?: boolean; family?: boolean; }): PlanCardFeatureDefinition => { const domain = 'proton.me'; let tooltip = ''; if (n > 1) { tooltip = c('new_plans: tooltip') .t`Create multiple email addresses for your online identities, e.g., JohnShopper@${domain} for shopping accounts, JohnNews@${domain} for news subscription`; } if (family) { tooltip = c('new_plans: tooltip') .t`Create up to ${n} email addresses/aliases that you can assign to family members. Use them for online identities, e.g., JohnShopper@${domain} for shopping accounts.`; } return { text: c('new_plans: feature').ngettext(msgid`${n} email address`, `${n} email addresses/aliases`, n), tooltip, included: true, highlight, icon: 'envelope', }; }; export const getNAddressesFeatureB2B = ({ n, highlight, }: { n: number; highlight?: boolean; }): PlanCardFeatureDefinition => { const tooltip = c('new_plans: tooltip') .t`Addresses have full sending and receiving capability. A user can have multiple addresses assigned to them; however, a single address cannot be assigned to multiple users.`; return { text: c('new_plans: feature').ngettext(msgid`${n} email address per user`, `${n} email addresses per user`, n), tooltip, included: true, highlight, icon: 'envelope', }; }; export const getExtraPersonalizationFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark-circle', text: c('new_plans: Upsell attribute') .t`Add more personalization with 15 email addresses and support for 3 custom email domains`, included: true, }); export const getNMessagesFeature = (n: number | 'unlimited'): PlanCardFeatureDefinition => { if (n === Number.POSITIVE_INFINITY || n === 'unlimited') { return { text: c('new_plans: feature').t`Unlimited messages per day`, tooltip: c('new_plans: tooltip') .t`Bulk promotional or programmatic email sending is currently not supported. We recommend using a dedicated email service provider for this use case.`, included: true, icon: 'speech-bubble', }; } return { text: c('new_plans: feature').ngettext(msgid`${n} message per day`, `${n} messages per day`, n), included: true, icon: 'speech-bubble', }; }; export const getB2BNDomainsFeature = (): PlanCardFeatureDefinition => ({ icon: 'globe', text: c('new_plans: Upsell attribute').t`Cover more ground with support for 10 custom email domains`, included: true, }); export const getNDomainsFeature = ({ n, highlight }: { n: number; highlight?: boolean }): PlanCardFeatureDefinition => { if (n === 0) { return { text: c('new_plans: feature').t`Custom email domains`, included: false, highlight, icon: 'globe', }; } return { text: c('new_plans: feature').ngettext(msgid`${n} custom email domain`, `${n} custom email domains`, n), tooltip: c('new_plans: tooltip').t`Use your own custom email domain addresses, e.g., you@yourname.com`, included: true, highlight, icon: 'globe', }; }; export const getFoldersAndLabelsFeature = (n: number | 'unlimited'): PlanCardFeatureDefinition => { if (n === Number.POSITIVE_INFINITY || n === 'unlimited') { return { text: c('new_plans: feature').t`Unlimited folders, labels, and filters`, included: true, icon: 'tag', }; } return { text: c('new_plans: feature').ngettext(msgid`${n} folder and label`, `${n} folders and labels`, n), included: true, icon: 'tag', }; }; const getFolders = (n: number | 'unlimited'): PlanCardFeatureDefinition => { const tooltip = c('new_plans').t`Keep your inbox organized with folders`; if (n === Number.POSITIVE_INFINITY || n === 'unlimited') { return { text: c('new_plans: feature').t`Unlimited folders`, tooltip, included: true, }; } return { text: c('new_plans: feature').ngettext(msgid`${n} folder`, `${n} folders`, n), tooltip, included: true, }; }; const getLabels = (n: number | 'unlimited'): PlanCardFeatureDefinition => { const tooltip = c('new_plans: tooltip') .t`Labels are simple tags you can add to messages to make them easier to find or to apply filters to`; if (n === Number.POSITIVE_INFINITY || n === 'unlimited') { return { text: c('new_plans: feature').t`Unlimited labels`, tooltip, included: true, }; } return { text: c('new_plans: feature').ngettext(msgid`${n} label`, `${n} labels`, n), tooltip, included: true, }; }; const getFilters = (n: number | 'unlimited'): PlanCardFeatureDefinition => { const tooltip = c('new_plans: tooltip').t`Set up filters to automatically reply to, sort, and/or label your emails`; if (n === Number.POSITIVE_INFINITY || n === 'unlimited') { return { text: c('new_plans: feature').t`Unlimited filters`, tooltip, included: true, }; } return { text: c('new_plans: feature').ngettext(msgid`${n} filter`, `${n} filters`, n), tooltip, included: true, }; }; const getAttachments = (): PlanCardFeatureDefinition => { const size = humanSize(26214400, undefined, undefined, 0); return { text: c('new_plans: feature').t`${size} attachment size`, included: true, }; }; const getSignature = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`HTML signatures`, tooltip: c('new_plans: tooltip') .t`Personalize your email signature with logos, images, social media icons, links to your contact details, and more`, included: true, }; }; export const getEndToEndEncryption = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`End-to-end encryption`, tooltip: c('new_plans: tooltip') .t`Prevents messages from being accessed by ${BRAND_NAME} or third parties. The only people who can read the messages are the sender and the intended recipient.`, included: true, }; }; export const getEncryptionOutside = (): PlanCardFeatureDefinition => { /** * Workaround for bug where ttag cannot handle strings where the same variable appears twice * https://confluence.protontech.ch/pages/viewpage.action?pageId=64690626#LocalisationonFrontendrulesandbestpractices-Twicesamevariables */ const MAIL_APP_NAME_TWO = MAIL_APP_NAME; return { text: c('new_plans: feature').t`Password-protected Emails`, tooltip: c('new_plans: tooltip') .t`When sending to other ${MAIL_APP_NAME} users, encryption is automatic. Sending to non-${MAIL_APP_NAME_TWO} users requires setting a password prior to sending.`, included: true, }; }; const getEncryptedContacts = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Encrypted contact details`, tooltip: c('new_plans: tooltip') .t`Securely store your contacts’ details, such as phone number, address, birthday, and personal notes. Zero-access encryption ensures even ${BRAND_NAME} can't access them.`, included: true, }; }; const getContactGroups = (included: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Contact groups`, tooltip: c('new_plans: tooltip') .t`Send emails to large groups quickly and easily by creating as many contact groups as you need (up to 100 contacts per group)`, included, }; }; export const getContactGroupsManagement = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Contact groups management`, included: true, icon: 'users', }; }; const getSMTP = (included: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Email client support (via IMAP/SMTP)`, tooltip: c('new_plans: tooltip') .t`IMAP support is limited to the use of desktop apps (e.g., Outlook, Apple Mail, Thunderbird) via ${MAIL_APP_NAME} Bridge. Cloud-based IMAP integrations are currently not supported.`, included, }; }; export const getSMTPToken = (included: boolean): PlanCardFeatureDefinition => { return { text: included ? c('new_plans: feature').t`SMTP submission for select organizations` : c('new_plans: feature').t`SMTP submission`, tooltip: c('new_plans: tooltip') .t`SMTP allows 3rd-party services or devices to send email through ${MAIL_APP_NAME}.`, included, iconUrl: getKnowledgeBaseUrl('/smtp-submission'), icon: 'envelopes', }; }; const getAutoReply = (included: boolean, audience?: Audience): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Auto-reply`, tooltip: audience === Audience.B2B ? c('new_plans: tooltip').t`Quickly set up out-of-office messages` : c('new_plans: tooltip') .t`Allows you to set up automatic responses (auto-reply) for your incoming messages`, included, }; }; const getCatchAll = (included: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Catch-all`, tooltip: c('new_plans: tooltip') .t`Ensures you receive all emails sent to your domain, even if the email address doesn't exist, no longer exists, or has a typo`, included, }; }; export const getMailFeatures = (plansMap: PlansMap): PlanCardFeature[] => { return [ { name: 'addresses', plans: { [PLANS.FREE]: getNAddressesFeature({ n: 1 }), [PLANS.BUNDLE]: getNAddressesFeature({ n: plansMap[PLANS.BUNDLE]?.MaxAddresses || 15 }), [PLANS.MAIL]: getNAddressesFeature({ n: plansMap[PLANS.MAIL]?.MaxAddresses || 10 }), [PLANS.VPN]: getNAddressesFeature({ n: plansMap[PLANS.VPN]?.MaxAddresses || 1 }), [PLANS.DRIVE]: getNAddressesFeature({ n: plansMap[PLANS.DRIVE]?.MaxAddresses || 1 }), [PLANS.PASS_PLUS]: getNAddressesFeature({ n: plansMap[PLANS.PASS_PLUS]?.MaxAddresses || 1 }), [PLANS.FAMILY]: getNAddressesFeature({ n: plansMap[PLANS.FAMILY]?.MaxAddresses || 75, family: true, }), [PLANS.MAIL_PRO]: getNAddressesFeatureB2B({ n: plansMap[PLANS.MAIL_PRO]?.MaxAddresses || 10 }), [PLANS.BUNDLE_PRO]: getNAddressesFeatureB2B({ n: plansMap[PLANS.BUNDLE_PRO]?.MaxAddresses || 15, }), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'domains', plans: { [PLANS.FREE]: getNDomainsFeature({ n: 0 }), [PLANS.BUNDLE]: getNDomainsFeature({ n: plansMap[PLANS.BUNDLE]?.MaxDomains ?? 3 }), [PLANS.MAIL]: getNDomainsFeature({ n: plansMap[PLANS.MAIL]?.MaxDomains ?? 1 }), [PLANS.VPN]: getNDomainsFeature({ n: plansMap[PLANS.VPN]?.MaxDomains ?? 0 }), [PLANS.DRIVE]: getNDomainsFeature({ n: plansMap[PLANS.DRIVE]?.MaxDomains ?? 0 }), [PLANS.PASS_PLUS]: getNDomainsFeature({ n: plansMap[PLANS.PASS_PLUS]?.MaxDomains ?? 0 }), [PLANS.FAMILY]: getNDomainsFeature({ n: plansMap[PLANS.FAMILY]?.MaxDomains ?? 5 }), [PLANS.MAIL_PRO]: getNDomainsFeature({ n: plansMap[PLANS.MAIL_PRO]?.MaxDomains ?? 3 }), [PLANS.BUNDLE_PRO]: getNDomainsFeature({ n: plansMap[PLANS.BUNDLE_PRO]?.MaxDomains ?? 10 }), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'messages', plans: { [PLANS.FREE]: getNMessagesFeature(150), [PLANS.BUNDLE]: getNMessagesFeature('unlimited'), [PLANS.MAIL]: getNMessagesFeature('unlimited'), [PLANS.VPN]: getNMessagesFeature('unlimited'), [PLANS.DRIVE]: getNMessagesFeature(150), [PLANS.PASS_PLUS]: getNMessagesFeature(150), [PLANS.FAMILY]: getNMessagesFeature('unlimited'), [PLANS.MAIL_PRO]: getNMessagesFeature('unlimited'), [PLANS.BUNDLE_PRO]: getNMessagesFeature('unlimited'), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'folders', plans: { [PLANS.FREE]: getFolders(3), [PLANS.BUNDLE]: getFolders('unlimited'), [PLANS.MAIL]: getFolders('unlimited'), [PLANS.VPN]: getFolders(3), [PLANS.DRIVE]: getFolders(3), [PLANS.PASS_PLUS]: getFolders(3), [PLANS.FAMILY]: getFolders('unlimited'), [PLANS.MAIL_PRO]: getFolders('unlimited'), [PLANS.BUNDLE_PRO]: getFolders('unlimited'), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'labels', plans: { [PLANS.FREE]: getLabels(3), [PLANS.BUNDLE]: getLabels('unlimited'), [PLANS.MAIL]: getLabels('unlimited'), [PLANS.VPN]: getLabels(3), [PLANS.DRIVE]: getLabels(3), [PLANS.PASS_PLUS]: getLabels(3), [PLANS.FAMILY]: getLabels('unlimited'), [PLANS.MAIL_PRO]: getLabels('unlimited'), [PLANS.BUNDLE_PRO]: getLabels('unlimited'), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'filters', plans: { [PLANS.FREE]: getFilters(1), [PLANS.BUNDLE]: getFilters('unlimited'), [PLANS.MAIL]: getFilters('unlimited'), [PLANS.VPN]: getFilters(1), [PLANS.DRIVE]: getFilters(1), [PLANS.PASS_PLUS]: getFilters(1), [PLANS.FAMILY]: getFilters('unlimited'), [PLANS.MAIL_PRO]: getFilters('unlimited'), [PLANS.BUNDLE_PRO]: getFilters('unlimited'), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'attachments', plans: { [PLANS.FREE]: getAttachments(), [PLANS.BUNDLE]: getAttachments(), [PLANS.MAIL]: getAttachments(), [PLANS.VPN]: getAttachments(), [PLANS.DRIVE]: getAttachments(), [PLANS.PASS_PLUS]: getAttachments(), [PLANS.FAMILY]: getAttachments(), [PLANS.MAIL_PRO]: getAttachments(), [PLANS.BUNDLE_PRO]: getAttachments(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'signature', plans: { [PLANS.FREE]: getSignature(), [PLANS.BUNDLE]: getSignature(), [PLANS.MAIL]: getSignature(), [PLANS.VPN]: getSignature(), [PLANS.DRIVE]: getSignature(), [PLANS.PASS_PLUS]: getSignature(), [PLANS.FAMILY]: getSignature(), [PLANS.MAIL_PRO]: getSignature(), [PLANS.BUNDLE_PRO]: getSignature(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'encryption', plans: { [PLANS.FREE]: getEndToEndEncryption(), [PLANS.BUNDLE]: getEndToEndEncryption(), [PLANS.MAIL]: getEndToEndEncryption(), [PLANS.VPN]: getEndToEndEncryption(), [PLANS.DRIVE]: getEndToEndEncryption(), [PLANS.PASS_PLUS]: getEndToEndEncryption(), [PLANS.FAMILY]: getEndToEndEncryption(), [PLANS.MAIL_PRO]: getEndToEndEncryption(), [PLANS.BUNDLE_PRO]: getEndToEndEncryption(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'eo', plans: { [PLANS.FREE]: getEncryptionOutside(), [PLANS.BUNDLE]: getEncryptionOutside(), [PLANS.MAIL]: getEncryptionOutside(), [PLANS.VPN]: getEncryptionOutside(), [PLANS.DRIVE]: getEncryptionOutside(), [PLANS.PASS_PLUS]: getEncryptionOutside(), [PLANS.FAMILY]: getEncryptionOutside(), [PLANS.MAIL_PRO]: getEncryptionOutside(), [PLANS.BUNDLE_PRO]: getEncryptionOutside(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'contacts', plans: { [PLANS.FREE]: getEncryptedContacts(), [PLANS.BUNDLE]: getEncryptedContacts(), [PLANS.MAIL]: getEncryptedContacts(), [PLANS.VPN]: getEncryptedContacts(), [PLANS.DRIVE]: getEncryptedContacts(), [PLANS.PASS_PLUS]: getEncryptedContacts(), [PLANS.FAMILY]: getEncryptedContacts(), [PLANS.MAIL_PRO]: getEncryptedContacts(), [PLANS.BUNDLE_PRO]: getEncryptedContacts(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'contact-groups', plans: { [PLANS.FREE]: getContactGroups(false), [PLANS.BUNDLE]: getContactGroups(true), [PLANS.MAIL]: getContactGroups(true), [PLANS.VPN]: getContactGroups(false), [PLANS.DRIVE]: getContactGroups(false), [PLANS.PASS_PLUS]: getContactGroups(false), [PLANS.FAMILY]: getContactGroups(true), [PLANS.MAIL_PRO]: getContactGroups(true), [PLANS.BUNDLE_PRO]: getContactGroups(true), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'smtp', plans: { [PLANS.FREE]: getSMTP(false), [PLANS.BUNDLE]: getSMTP(true), [PLANS.MAIL]: getSMTP(true), [PLANS.VPN]: getSMTP(false), [PLANS.DRIVE]: getSMTP(false), [PLANS.PASS_PLUS]: getSMTP(false), [PLANS.FAMILY]: getSMTP(true), [PLANS.MAIL_PRO]: getSMTP(true), [PLANS.BUNDLE_PRO]: getSMTP(true), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'smtp-token', plans: { [PLANS.FREE]: getSMTPToken(false), [PLANS.BUNDLE]: getSMTPToken(false), [PLANS.MAIL]: getSMTPToken(false), [PLANS.VPN]: getSMTPToken(false), [PLANS.DRIVE]: getSMTPToken(false), [PLANS.PASS_PLUS]: getSMTPToken(false), [PLANS.FAMILY]: getSMTPToken(true), [PLANS.MAIL_PRO]: getSMTPToken(true), [PLANS.BUNDLE_PRO]: getSMTPToken(true), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'auto-reply', plans: { [PLANS.FREE]: getAutoReply(false), [PLANS.BUNDLE]: getAutoReply(true), [PLANS.MAIL]: getAutoReply(true), [PLANS.VPN]: getAutoReply(false), [PLANS.DRIVE]: getAutoReply(false), [PLANS.PASS_PLUS]: getAutoReply(false), [PLANS.FAMILY]: getAutoReply(true), [PLANS.MAIL_PRO]: getAutoReply(true, Audience.B2B), [PLANS.BUNDLE_PRO]: getAutoReply(true, Audience.B2B), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'catch-all', plans: { [PLANS.FREE]: getCatchAll(false), [PLANS.BUNDLE]: getCatchAll(true), [PLANS.MAIL]: getCatchAll(true), [PLANS.VPN]: getCatchAll(false), [PLANS.DRIVE]: getCatchAll(false), [PLANS.PASS_PLUS]: getCatchAll(false), [PLANS.FAMILY]: getCatchAll(true), [PLANS.MAIL_PRO]: getCatchAll(true), [PLANS.BUNDLE_PRO]: getCatchAll(true), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, ]; };
6,745
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/features/pass.tsx
import { c, msgid } from 'ttag'; import { BRAND_NAME, PASS_APP_NAME, PLANS } from '@proton/shared/lib/constants'; import { PlanCardFeature, PlanCardFeatureDefinition } from './interface'; export const getPassAppFeature = (): PlanCardFeatureDefinition => { return { text: PASS_APP_NAME, included: true, icon: 'brand-proton', tooltip: c('tooltip') .t`${PASS_APP_NAME}: Secure logins on all your devices. Includes unlimited aliases, sharing, integrated 2FA, and more.`, }; }; export const getCustomDomains = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Custom domains for email aliases`, included: true, }; }; export const getProtonPassFeature = (n: 'unlimited' | number = 'unlimited'): PlanCardFeatureDefinition => { return { text: n === 'unlimited' ? c('new_plans: feature').t`${PASS_APP_NAME} with unlimited hide-my-email aliases` : c('new_plans: feature').ngettext( msgid`${PASS_APP_NAME} with ${n} hide-my-email alias`, `${PASS_APP_NAME} with ${n} hide-my-email aliases`, n ), icon: 'pass-all-vaults', included: true, hideInDowngrade: true, }; }; export const getLoginsAndNotesText = () => { return c('new_plans: feature').t`Unlimited logins and notes`; }; export const getLoginsAndNotes = (): PlanCardFeatureDefinition => { return { text: getLoginsAndNotesText(), icon: 'note', included: true, hideInDowngrade: true, }; }; export const getItems = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Organize items with multiple vaults`, included: true, }; }; export const getCreditCards = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Autofill credit cards (coming soon)`, included: true, }; }; export const getDevicesText = () => { return c('new_plans: feature').t`Unlimited devices`; }; export const getDevices = (): PlanCardFeatureDefinition => { return { text: getDevicesText(), icon: 'mobile', included: true, hideInDowngrade: true, }; }; export const getNHideMyEmailAliasesText = (n: number) => { return c('new_plans: feature').ngettext(msgid`${n} hide-my-email alias`, `${n} hide-my-email aliases`, n); }; export const getUnlimitedHideMyEmailAliasesText = () => { return c('new_plans: feature').t`Unlimited hide-my-email aliases`; }; export const getHideMyEmailAliases = (n: number | 'unlimited'): PlanCardFeatureDefinition => { return { text: n === 'unlimited' ? getUnlimitedHideMyEmailAliasesText() : getNHideMyEmailAliasesText(10), tooltip: c('new_plans: tooltip') .t`Unique, on-the-fly email addresses that protect your online identity and let you control what lands in your inbox. From SimpleLogin by ${BRAND_NAME}.`, included: true, icon: 'eye-slash', }; }; export const get2FAAuthenticatorText = () => { return c('new_plans: feature').t`Integrated 2FA authenticator`; }; export const get2FAAuthenticator = (included: boolean = false): PlanCardFeatureDefinition => { return { text: get2FAAuthenticatorText(), included, icon: 'key', }; }; export const getVaults = (n: number): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').ngettext(msgid`${n} vault`, `${n} vaults`, n), tooltip: c('new_plans: tooltip') .t`Like a folder, a vault is a convenient way to organize your items. Sharing vaults with friends and family is in the works.`, included: true, icon: 'vault', }; }; export const getCustomFields = (included: boolean = false): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Custom fields`, included, icon: 'pen-square', }; }; export const getVaultSharingText = (n: number) => { return c('new_plans: feature').ngettext( msgid`Vault sharing (up to ${n} person)`, `Vault sharing (up to ${n} people)`, n ); }; export const getVaultSharing = (n: number): PlanCardFeatureDefinition => { return { text: getVaultSharingText(n), icon: 'arrow-up-from-square', included: true, hideInDowngrade: true, }; }; export const getDataBreachMonitoring = (included: boolean = false): PlanCardFeatureDefinition => { return { text: included ? c('new_plans: feature').t`Data breach monitoring (coming soon)` : c('new_plans: feature').t`Data breach monitoring`, included, icon: 'shield', status: 'coming-soon', }; }; export const FREE_PASS_ALIASES = 10; export const FREE_VAULTS = 2; export const PASS_PLUS_VAULTS = 20; export const getPassFeatures = (): PlanCardFeature[] => { return [ { name: 'passwords-and-notes', plans: { [PLANS.FREE]: getLoginsAndNotes(), [PLANS.BUNDLE]: getLoginsAndNotes(), [PLANS.MAIL]: getLoginsAndNotes(), [PLANS.VPN]: getLoginsAndNotes(), [PLANS.DRIVE]: getLoginsAndNotes(), [PLANS.PASS_PLUS]: getLoginsAndNotes(), [PLANS.FAMILY]: getLoginsAndNotes(), [PLANS.MAIL_PRO]: getLoginsAndNotes(), [PLANS.BUNDLE_PRO]: getLoginsAndNotes(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'devices', plans: { [PLANS.FREE]: getDevices(), [PLANS.BUNDLE]: getDevices(), [PLANS.MAIL]: getDevices(), [PLANS.VPN]: getDevices(), [PLANS.DRIVE]: getDevices(), [PLANS.PASS_PLUS]: getDevices(), [PLANS.FAMILY]: getDevices(), [PLANS.MAIL_PRO]: getDevices(), [PLANS.BUNDLE_PRO]: getDevices(), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'vaults', plans: { [PLANS.FREE]: getVaults(FREE_VAULTS), [PLANS.BUNDLE]: getVaults(PASS_PLUS_VAULTS), [PLANS.MAIL]: getVaults(FREE_VAULTS), [PLANS.VPN]: getVaults(FREE_VAULTS), [PLANS.DRIVE]: getVaults(FREE_VAULTS), [PLANS.PASS_PLUS]: getVaults(PASS_PLUS_VAULTS), [PLANS.FAMILY]: getVaults(PASS_PLUS_VAULTS), [PLANS.MAIL_PRO]: getVaults(FREE_VAULTS), [PLANS.BUNDLE_PRO]: getVaults(PASS_PLUS_VAULTS), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'hide-my-email-aliases', plans: { [PLANS.FREE]: getHideMyEmailAliases(FREE_PASS_ALIASES), [PLANS.BUNDLE]: getHideMyEmailAliases('unlimited'), [PLANS.MAIL]: getHideMyEmailAliases(FREE_PASS_ALIASES), [PLANS.VPN]: getHideMyEmailAliases(FREE_PASS_ALIASES), [PLANS.DRIVE]: getHideMyEmailAliases(FREE_PASS_ALIASES), [PLANS.PASS_PLUS]: getHideMyEmailAliases('unlimited'), [PLANS.FAMILY]: getHideMyEmailAliases('unlimited'), [PLANS.MAIL_PRO]: getHideMyEmailAliases(FREE_PASS_ALIASES), [PLANS.BUNDLE_PRO]: getHideMyEmailAliases('unlimited'), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'vault-and-item-sharing', plans: { [PLANS.FREE]: getVaultSharing(3), [PLANS.BUNDLE]: getVaultSharing(10), [PLANS.MAIL]: getVaultSharing(3), [PLANS.VPN]: getVaultSharing(3), [PLANS.DRIVE]: getVaultSharing(3), [PLANS.PASS_PLUS]: getVaultSharing(10), [PLANS.FAMILY]: getVaultSharing(10), [PLANS.MAIL_PRO]: getVaultSharing(3), [PLANS.BUNDLE_PRO]: getVaultSharing(10), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: '2fa-authenticator', plans: { [PLANS.FREE]: get2FAAuthenticator(), [PLANS.BUNDLE]: get2FAAuthenticator(true), [PLANS.MAIL]: get2FAAuthenticator(), [PLANS.VPN]: get2FAAuthenticator(), [PLANS.DRIVE]: get2FAAuthenticator(), [PLANS.PASS_PLUS]: get2FAAuthenticator(true), [PLANS.FAMILY]: get2FAAuthenticator(true), [PLANS.MAIL_PRO]: get2FAAuthenticator(), [PLANS.BUNDLE_PRO]: get2FAAuthenticator(true), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'forwarding-mailboxes', plans: { [PLANS.FREE]: getCustomFields(), [PLANS.BUNDLE]: getCustomFields(true), [PLANS.MAIL]: getCustomFields(), [PLANS.VPN]: getCustomFields(), [PLANS.DRIVE]: getCustomFields(), [PLANS.PASS_PLUS]: getCustomFields(true), [PLANS.FAMILY]: getCustomFields(true), [PLANS.MAIL_PRO]: getCustomFields(), [PLANS.BUNDLE_PRO]: getCustomFields(true), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, { name: 'data-breach-monitoring', plans: { [PLANS.FREE]: getDataBreachMonitoring(), [PLANS.BUNDLE]: getDataBreachMonitoring(true), [PLANS.MAIL]: getDataBreachMonitoring(), [PLANS.VPN]: getDataBreachMonitoring(), [PLANS.DRIVE]: getDataBreachMonitoring(), [PLANS.PASS_PLUS]: getDataBreachMonitoring(true), [PLANS.FAMILY]: getDataBreachMonitoring(true), [PLANS.MAIL_PRO]: getDataBreachMonitoring(), [PLANS.BUNDLE_PRO]: getDataBreachMonitoring(true), [PLANS.VPN_PRO]: null, [PLANS.VPN_BUSINESS]: null, }, }, ]; }; export const getPassIdentityFeature = (): PlanCardFeatureDefinition => { return { text: PASS_APP_NAME, tooltip: c('new_plans: tooltip').t`Password management and identity protection`, included: true, icon: 'pass-all-vaults', }; };
6,746
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/features/plan.ts
import { c } from 'ttag'; import { MAX_CALENDARS_FREE } from '@proton/shared/lib/calendar/constants'; import { BRAND_NAME, FAMILY_MAX_USERS, PLANS, PLAN_NAMES, VPN_CONNECTIONS } from '@proton/shared/lib/constants'; import { Plan, PlansMap, VPNServersCountData } from '@proton/shared/lib/interfaces'; import { getFreeServers, getPlusServers } from '@proton/shared/lib/vpn/features'; import { getCalendarAppFeature, getNCalendarsFeature } from './calendar'; import { getDriveAppFeature, getStorageFeature, getStorageFeatureB2B } from './drive'; import { getSentinel, getSupport, getUsersFeature } from './highlights'; import { ShortPlan, ShortPlanLike } from './interface'; import { getContactGroupsManagement, getFoldersAndLabelsFeature, getNAddressesFeature, getNAddressesFeatureB2B, getNDomainsFeature, getNMessagesFeature, getSMTPToken, } from './mail'; import { FREE_PASS_ALIASES, FREE_VAULTS, PASS_PLUS_VAULTS, get2FAAuthenticator, getCustomFields, getDevices, getHideMyEmailAliases, getLoginsAndNotes, getPassAppFeature, getProtonPassFeature, getVaults, } from './pass'; import { get24x7SupportVPNFeature, getAESEncryptionVPNFeature, getAutoConnectVPNFeature, getB2BHighSpeedVPNConnections, getBandwidth, getBrowserExtensionVPNFeature, getCensorshipCircumventionVPNFeature, getCentralControlPanelVPNFeature, getCountries, getDedicatedServersVPNFeature, getDoubleHop, getKillSwitch, getMultiPlatformSupportVPNFeature, getNetShield, getNoLogs, getP2P, getPrioritySupport, getPrivateGatewaysVPNFeature, getProtectDevices, getRequire2FAVPNFeature, getSecureCore, getStreaming, getTor, getVPNAppFeature, getVPNConnections, getVPNSpeed, } from './vpn'; const getCTA = (planName: string) => { return c('new_plans: action').t`Get ${planName}`; }; export const getFreePlan = (): ShortPlan => { return { plan: PLANS.FREE, title: PLAN_NAMES[PLANS.FREE], label: '', description: c('new_plans: info') .t`The no-cost starter account designed to empower everyone with privacy by default.`, cta: c('new_plans: action').t`Get ${BRAND_NAME} for free`, features: [ getStorageFeature(-1), getNAddressesFeature({ n: 1 }), getFoldersAndLabelsFeature(3), getNMessagesFeature(150), ], }; }; export const getBundlePlan = (plan: Plan, vpnServersCountData: VPNServersCountData): ShortPlan => { return { plan: PLANS.BUNDLE, title: plan.Title, label: c('new_plans: info').t`Popular`, description: c('new_plans: info') .t`Comprehensive privacy and security with all ${BRAND_NAME} services combined.`, cta: getCTA(plan.Title), features: [ getStorageFeature(plan.MaxSpace), getNAddressesFeature({ n: plan.MaxAddresses }), getFoldersAndLabelsFeature('unlimited'), getNMessagesFeature('unlimited'), getNDomainsFeature({ n: plan.MaxDomains }), getSentinel(), getSupport('priority'), getCalendarAppFeature(), getDriveAppFeature(), getVPNAppFeature({ serversCount: vpnServersCountData }), getPassAppFeature(), ], }; }; export const getDrivePlan = (plan: Plan, boldStorageSize?: boolean): ShortPlan => { return { plan: PLANS.DRIVE, title: plan.Title, label: '', description: c('new_plans: info') .t`Secure cloud storage that lets you store, sync, and share files easily and securely.`, cta: getCTA(plan.Title), features: [ getStorageFeature(plan.MaxSpace, { boldStorageSize }), getNAddressesFeature({ n: plan.MaxAddresses || 1 }), getNCalendarsFeature(plan.MaxCalendars || MAX_CALENDARS_FREE), getVPNConnections(1), getSupport('priority'), ], }; }; export const getPassPlan = (plan: Plan, sentinelPassplusEnabled?: boolean): ShortPlan => { return { plan: PLANS.PASS_PLUS, title: plan.Title, label: '', description: c('new_plans: info').t`For next-level password management and identity protection.`, cta: getCTA(plan.Title), features: [ getLoginsAndNotes(), getDevices(), getHideMyEmailAliases('unlimited'), getVaults(PASS_PLUS_VAULTS), get2FAAuthenticator(true), getCustomFields(true), ...(sentinelPassplusEnabled ? [getSentinel()] : []), getSupport('priority'), ], }; }; export const getFreePassPlan = (): ShortPlan => { return { plan: PLANS.FREE, title: PLAN_NAMES[PLANS.FREE], label: '', description: c('new_plans: info') .t`The no-cost starter account designed to empower everyone with privacy by default.`, cta: c('new_plans: action').t`Get ${BRAND_NAME} for free`, features: [getLoginsAndNotes(), getDevices(), getVaults(FREE_VAULTS), getHideMyEmailAliases(FREE_PASS_ALIASES)], }; }; export const getMailPlan = (plan: Plan): ShortPlan => { return { plan: PLANS.MAIL, title: plan.Title, label: '', description: c('new_plans: info').t`Secure email with advanced features for your everyday communications.`, cta: getCTA(plan.Title), features: [ getStorageFeature(plan.MaxSpace), getNAddressesFeature({ n: plan.MaxAddresses }), getFoldersAndLabelsFeature('unlimited'), getNMessagesFeature('unlimited'), getNDomainsFeature({ n: plan.MaxDomains }), getSupport('priority'), getCalendarAppFeature(), ], }; }; export const getFreeVPNPlan = (serversCount: VPNServersCountData): ShortPlan => { const freeServers = getFreeServers(serversCount.free.servers, serversCount.free.countries); return { plan: PLANS.FREE, title: PLAN_NAMES[PLANS.FREE], label: '', description: c('new_plans: info') .t`The no-cost starter account designed to empower everyone with privacy by default.`, cta: c('new_plans: action').t`Get ${BRAND_NAME} for free`, features: [getVPNConnections(1), getCountries(freeServers), getVPNSpeed('medium'), getNoLogs()], }; }; export const getFreeDrivePlan = (): ShortPlan => { return { plan: PLANS.FREE, title: PLAN_NAMES[PLANS.FREE], label: '', description: c('new_plans: info') .t`The no-cost starter account designed to empower everyone with privacy by default.`, cta: c('new_plans: action').t`Get ${BRAND_NAME} for free`, features: [getStorageFeature(-1), getNAddressesFeature({ n: 1 })], }; }; export const getVPNPlan = (plan: Plan, serversCount: VPNServersCountData): ShortPlan => { const plusServers = getPlusServers(serversCount.paid.servers, serversCount.paid.countries); return { plan: PLANS.VPN, title: plan.Title, label: '', description: c('new_plans: info') .t`The dedicated VPN solution that provides secure, unrestricted, high-speed access to the internet.`, cta: getCTA(plan.Title), features: [ getCountries(plusServers), getVPNSpeed('highest'), getProtectDevices(VPN_CONNECTIONS), getStreaming(true), getP2P(true), getDoubleHop(true), getNetShield(true), getTor(true), getPrioritySupport(), ], }; }; export const getVPNPassPlan = (plan: Plan, serversCount: VPNServersCountData): ShortPlan => { const plusServers = getPlusServers(serversCount.paid.servers, serversCount.paid.countries); return { plan: PLANS.VPN, title: plan.Title, label: '', description: c('new_plans: info') .t`The dedicated VPN solution that provides secure, unrestricted, high-speed access to the internet.`, cta: getCTA(plan.Title), features: [ getCountries(plusServers), getVPNSpeed('highest'), getProtonPassFeature(), getStreaming(true), getP2P(true), getDoubleHop(true), getNetShield(true), getTor(true), getPrioritySupport(), ], }; }; export const getMailProPlan = (plan: Plan): ShortPlan => { return { plan: PLANS.MAIL_PRO, title: plan.Title, label: '', description: c('new_plans: info').t`Secure email and calendar for professionals and businesses.`, cta: getCTA(plan.Title), features: [ getStorageFeatureB2B(plan.MaxSpace), getNAddressesFeatureB2B({ n: plan.MaxAddresses }), getNDomainsFeature({ n: plan.MaxDomains }), getFoldersAndLabelsFeature('unlimited'), getContactGroupsManagement(), getCalendarAppFeature(), getSMTPToken(true), ], }; }; export const getBundleProPlan = (plan: Plan): ShortPlan => { return { plan: PLANS.BUNDLE_PRO, title: plan.Title, label: '', description: c('new_plans: info') .t`Privacy and security suite for businesses, including all premium ${BRAND_NAME} services.`, cta: getCTA(plan.Title), features: [ getStorageFeatureB2B(plan.MaxSpace), getNAddressesFeatureB2B({ n: plan.MaxAddresses }), getNDomainsFeature({ n: plan.MaxDomains }), getSentinel(), getFoldersAndLabelsFeature('unlimited'), getContactGroupsManagement(), getCalendarAppFeature(), getDriveAppFeature(), getPassAppFeature(), getB2BHighSpeedVPNConnections(), getNetShield(true), getSecureCore(true), getSMTPToken(true), ], }; }; export const getNewVisionaryPlan = (plan: Plan): ShortPlan => { return { plan: PLANS.NEW_VISIONARY, title: plan.Title, label: '', description: '', cta: getCTA(plan.Title), features: [ getStorageFeature(plan.MaxSpace), getNAddressesFeature({ n: plan.MaxAddresses }), getNDomainsFeature({ n: plan.MaxDomains }), getFoldersAndLabelsFeature('unlimited'), getContactGroupsManagement(), getCalendarAppFeature(), getDriveAppFeature(), getPassAppFeature(), getB2BHighSpeedVPNConnections(), getNetShield(true), getSecureCore(true), ], }; }; export const getFamilyPlan = (plan: Plan, serversCount: VPNServersCountData): ShortPlan => { return { plan: PLANS.FAMILY, title: plan.Title, label: '', description: c('new_plans: info').t`Protect your family’s privacy with all ${BRAND_NAME} services combined.`, cta: getCTA(plan.Title), features: [ getUsersFeature(FAMILY_MAX_USERS), getStorageFeature(plan.MaxSpace, { family: true }), getNAddressesFeature({ n: plan.MaxAddresses, family: true }), getFoldersAndLabelsFeature(Number.POSITIVE_INFINITY), getNMessagesFeature(Number.POSITIVE_INFINITY), getNDomainsFeature({ n: plan.MaxDomains }), getSentinel(), getCalendarAppFeature({ family: true }), getDriveAppFeature({ family: true }), getVPNAppFeature({ family: true, serversCount, }), getPassAppFeature(), getSupport('priority'), getSMTPToken(true), ], }; }; export const getVPNProPlan = (plan: Plan, serversCount: VPNServersCountData | undefined): ShortPlan => { const plusServers = getPlusServers(serversCount?.paid.servers, serversCount?.paid.countries); return { plan: PLANS.VPN_PRO, title: plan.Title, label: '', description: c('new_plans: info').t`Safely access internet from anywhere with essential network monitoring`, cta: getCTA(plan.Title), features: [ getCountries(plusServers), getAESEncryptionVPNFeature(), getBandwidth(), getCensorshipCircumventionVPNFeature(), getCentralControlPanelVPNFeature(), getKillSwitch(), getAutoConnectVPNFeature(), getMultiPlatformSupportVPNFeature(), get24x7SupportVPNFeature(), ], }; }; export const getVPNBusinessPlan = (plan: Plan, serversCount: VPNServersCountData | undefined): ShortPlan => { const plusServers = getPlusServers(serversCount?.paid.servers, serversCount?.paid.countries); return { plan: PLANS.VPN_BUSINESS, title: plan.Title, label: '', description: c('new_plans: info') .t`Advanced network security and access management with dedicated secure Gateways`, cta: getCTA(plan.Title), features: [ getCountries(plusServers), getAESEncryptionVPNFeature(), getBandwidth(), getCensorshipCircumventionVPNFeature(), getCentralControlPanelVPNFeature(), getKillSwitch(), getAutoConnectVPNFeature(), getMultiPlatformSupportVPNFeature(), get24x7SupportVPNFeature(), getPrivateGatewaysVPNFeature(), getDedicatedServersVPNFeature(), getRequire2FAVPNFeature(), getNetShield(true), getBrowserExtensionVPNFeature(), ], }; }; export const getVPNEnterprisePlan = (serversCount: VPNServersCountData | undefined): ShortPlanLike => { const plusServers = getPlusServers(serversCount?.paid.servers, serversCount?.paid.countries); return { isPlanLike: true, plan: 'PLANS.VPN_ENTERPRISE', title: c('new_plans: Title').t`VPN Enterprise`, label: '', description: c('new_plans: info') .t`Tailor-made solutions for larger organizations with specific security needs`, features: [ getCountries(plusServers), getAESEncryptionVPNFeature(), getBandwidth(), getCensorshipCircumventionVPNFeature(), getCentralControlPanelVPNFeature(), getKillSwitch(), getAutoConnectVPNFeature(), getMultiPlatformSupportVPNFeature(), get24x7SupportVPNFeature(), getPrivateGatewaysVPNFeature(), getDedicatedServersVPNFeature(), getRequire2FAVPNFeature(), getNetShield(true), getBrowserExtensionVPNFeature(), ], }; }; /** * Takes a plans map, a plan and some options and returns short visual plan details * * @param options.boldStorageSize Whether or not print the storage size in bold * @param options.vpnServers Details about vpn servers. WARNING: If this option is not provided, then VPN plan won't be returned */ export const getShortPlan = ( plan: PLANS, plansMap: PlansMap, options: { boldStorageSize?: boolean; vpnServers: VPNServersCountData; sentinelPassplusEnabled?: boolean; } ) => { if (plan === PLANS.FREE) { return getFreePlan(); } const planData = plansMap[plan]; if (!planData) { return null; } const { vpnServers, boldStorageSize, sentinelPassplusEnabled } = options; switch (plan) { case PLANS.MAIL: return getMailPlan(planData); case PLANS.VPN: return getVPNPlan(planData, vpnServers); case PLANS.VPN_PASS_BUNDLE: return getVPNPassPlan(planData, vpnServers); case PLANS.DRIVE: return getDrivePlan(planData, boldStorageSize); case PLANS.PASS_PLUS: return getPassPlan(planData, sentinelPassplusEnabled); case PLANS.MAIL_PRO: return getMailProPlan(planData); case PLANS.BUNDLE: return getBundlePlan(planData, vpnServers); case PLANS.BUNDLE_PRO: return getBundleProPlan(planData); case PLANS.NEW_VISIONARY: return getNewVisionaryPlan(planData); case PLANS.FAMILY: return getFamilyPlan(planData, vpnServers); case PLANS.VPN_PRO: return getVPNProPlan(planData, vpnServers); case PLANS.VPN_BUSINESS: return getVPNBusinessPlan(planData, vpnServers); default: return null; } };
6,747
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/features/vpn.ts
import { c, msgid } from 'ttag'; import { BRAND_NAME, CALENDAR_SHORT_APP_NAME, DRIVE_SHORT_APP_NAME, FREE_VPN_CONNECTIONS, MAIL_SHORT_APP_NAME, PLANS, VPN_APP_NAME, VPN_CONNECTIONS, } from '@proton/shared/lib/constants'; import { Audience, VPNServersCountData } from '@proton/shared/lib/interfaces'; import { getFreeServers, getPlusServers } from '@proton/shared/lib/vpn/features'; import { PlanCardFeature, PlanCardFeatureDefinition } from './interface'; export const getFreeVPNConnectionTotal = () => c('new_plans: feature').t`1 free VPN connection in total`; export const getAdvancedVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark-circle', included: true, text: c('new_plans: Upsell attribute').t`Access advanced VPN features`, }); export const getB2BHighSpeedVPNConnectionsText = (n: number) => { return c('Subscription attribute').ngettext( msgid`${n} high-speed VPN connection per user`, `${n} high-speed VPN connections per user`, n ); }; export const getB2BHighSpeedVPNConnectionsFeature = (): PlanCardFeatureDefinition => ({ icon: 'brand-proton-vpn', text: getB2BHighSpeedVPNConnectionsText(VPN_CONNECTIONS), included: true, }); export const getB2BVPNConnectionsText = (n: number) => { return c('Subscription attribute').ngettext( msgid`${n} VPN connection per user`, `${n} VPN connections per user`, n ); }; export const getHighSpeedVPNConnectionsText = (n: number) => { return c('Subscription attribute').ngettext( msgid`${n} high-speed VPN connection`, `${n} high-speed VPN connections`, n ); }; export const getHighSpeedVPNConnectionsFeature = (n: number = VPN_CONNECTIONS): PlanCardFeatureDefinition => ({ icon: 'brand-proton-vpn', text: getHighSpeedVPNConnectionsText(n), included: true, }); export const getVPNConnectionsText = (n: number) => { return c('Subscription attribute').ngettext(msgid`${n} VPN connection`, `${n} VPN connections`, n); }; export const getVPNConnectionsFeature = (n: number = VPN_CONNECTIONS): PlanCardFeatureDefinition => ({ icon: 'brand-proton-vpn', text: getVPNConnectionsText(n), included: true, }); export const getB2BHighSpeedVPNConnections = (): PlanCardFeatureDefinition => { return { text: getB2BHighSpeedVPNConnectionsText(VPN_CONNECTIONS), included: true, icon: 'brand-proton-vpn', }; }; export const getVPNAppFeature = ({ serversCount, family, }: { serversCount: VPNServersCountData; family?: boolean; }): PlanCardFeatureDefinition => { const serversAndCountries = getPlusServers(serversCount.paid.servers, serversCount.paid.countries); return { text: VPN_APP_NAME, tooltip: family ? c('new_plans: tooltip') .t`Protect your family from harmful websites and access our high-speed VPN servers to stream your favorite content` : // translator: Includes [X+ servers across Y+ countries], ... c('new_plans: tooltip') .t`${VPN_APP_NAME}: Access blocked content and browse privately. Includes ${serversAndCountries}, highest VPN speeds, access to worldwide streaming services, malware and ad-blocker, fast BitTorrent downloads, and more.`, included: true, icon: 'brand-proton-vpn', }; }; export const getCountries = (text: string, highlight?: boolean): PlanCardFeatureDefinition => { return { text, included: true, highlight, icon: 'earth', }; }; export const getVPNSpeed = (type: 'medium' | 'highest', highlight?: boolean): PlanCardFeatureDefinition => { return { text: type === 'medium' ? c('new_plans').t`Medium VPN speed` : c('new_plans').t`Highest VPN speed`, included: true, highlight, icon: 'chevrons-right', }; }; export const getStreaming = (included: boolean, highlight?: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`High-speed streaming`, tooltip: c('new_plans: tooltip') .t`Access content on streaming services, including Netflix, Disney+, and Prime Video, from anywhere`, included, highlight, icon: 'play', }; }; export const getP2P = (included: boolean, highlight?: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Fast P2P/BitTorrent downloads`, tooltip: c('new_plans: tooltip').t`Support for file-sharing protocols like BitTorrent`, included, highlight, icon: 'arrows-switch', }; }; export const getAdvancedVPNCustomizations = (included: boolean, highlight?: boolean): PlanCardFeatureDefinition => { return { text: c('vpn_2step: feature').t`Advanced VPN customizations`, tooltip: c('vpn_2step: tooltip') .t`Access to Secure core servers, fast P2P/BitTorrent downloads, Tor over VPN, and more.`, included, highlight, icon: 'arrows-switch', }; }; export const getDoubleHop = (included: boolean, highlight?: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Double hop`, tooltip: c('new_plans: tooltip') .t`Defends against the threat to VPN privacy by passing your internet traffic through multiple servers.`, included, highlight, icon: 'arrows-switch', }; }; export const getNetShield = (included: boolean, highlight?: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Ad-blocker and malware protection`, tooltip: c('new_plans: tooltip') .t`Specially designed NetShield protects your device and speeds up your browsing by blocking ads, trackers, and malware`, included, highlight, icon: 'shield', }; }; export const getSecureCore = (included: boolean, highlight?: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Secure Core servers`, tooltip: c('new_plans: tooltip') .t`Defends against the threat to VPN privacy by passing your internet traffic through multiple servers`, included, highlight, icon: 'servers', }; }; export const getTor = (included: boolean, highlight?: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Tor over VPN`, tooltip: c('new_plans: tooltip').t`Route your internet traffic through the Tor network with a single click`, included, highlight, icon: 'brand-tor', }; }; const getVPNConnectionsB2B = (n = 0, highlight?: boolean): PlanCardFeatureDefinition => { const BRAND_NAME_TWO = BRAND_NAME; return { text: n === 1 ? getFreeVPNConnectionTotal() : c('new_plans: feature').ngettext( msgid`${n} VPN connection per user`, `${n} VPN connections per user`, n ), tooltip: c('new_plans: tooltip') .t`One VPN connection allows one device to connect to ${BRAND_NAME} VPN at any given time. For instance, to connect a phone and a laptop to ${BRAND_NAME_TWO} VPN at the same time, you need two VPN connections.`, included: true, highlight, icon: 'brand-proton-vpn', }; }; export const getVPNConnections = (n = 0, highlight?: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').ngettext(msgid`${n} VPN connection`, `${n} VPN connections`, n), included: true, highlight, icon: 'brand-proton-vpn', }; }; export const getProtectDevices = (n = 0, highlight?: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').ngettext( msgid`Protect ${n} device at a time`, `Protect ${n} devices at a time`, n ), included: true, highlight, icon: 'brand-proton-vpn', }; }; export const getNoLogs = (highlight?: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Strict no-logs policy`, tooltip: c('new_plans: tooltip') .t`We keep no session usage logs of what you do online, and we do not log metadata that can compromise your privacy`, included: true, highlight, icon: 'alias', }; }; export const getBandwidth = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Unlimited volume/bandwidth`, included: true, }; }; export const getNoAds = (): PlanCardFeatureDefinition => { return { text: c('vpn_2step: feature').t`No ads`, included: true, }; }; const getDNSLeak = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`DNS leak prevention`, tooltip: c('new_plans: tooltip') .t`When connected to our VPN, your DNS queries through our encrypted VPN tunnel, adding to your online privacy and security`, included: true, }; }; export const getKillSwitch = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Kill switch/always-on VPN`, tooltip: c('new_plans: tooltip') .t`Keeps you protected by blocking all network connections when you are unexpectedly disconnected from our VPN server.`, included: true, }; }; const getEncryption = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Encrypted VPN servers`, tooltip: c('new_plans: tooltip') .t`Our servers’ hard disks are fully encrypted with multiple password layers so your data is protected even if our hardware is compromised`, included: true, }; }; const getRouterSupport = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Router support`, tooltip: c('new_plans: tooltip') .t`Protect every device connected to your WiFi network. It’s also useful if you have devices that do not support VPN settings directly.`, included: true, }; }; export const getPrioritySupport = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Priority support & live chat`, tooltip: '', included: true, icon: 'life-ring', }; }; export const getFreeFeatures = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature') .t`Free features from ${BRAND_NAME} ${MAIL_SHORT_APP_NAME}, ${CALENDAR_SHORT_APP_NAME}, and ${DRIVE_SHORT_APP_NAME}`, tooltip: '', included: true, }; }; export const getAllPlatforms = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Available on all platforms`, tooltip: '', included: true, }; }; export const getRefundable = (): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Fully refundable for 30 days`, tooltip: '', included: true, }; }; const getSplitTunnel = (included: boolean): PlanCardFeatureDefinition => { return { text: c('new_plans: feature').t`Split tunneling (Android and Windows)`, tooltip: c('new_plans: tooltip') .t`Allows you to access more than one network at the same time, e.g., stream a film from another country while still getting local search results`, included: included, }; }; export const getVPNDevices = (n: number): PlanCardFeatureDefinition => { if (n === 1) { return { text: c('new_plans: feature').t`Free VPN on a single device`, tooltip: c('new_plans: tooltip') .t`Allows you to access more than one network at the same time, e.g., stream a film from another country while still getting local search results`, included: true, }; } return { text: c('new_plans: feature').ngettext( msgid`High-speed VPN on ${n} device`, `High-speed VPN on ${n} devices`, n ), included: true, }; }; export const getDedicatedServersVPNFeature = (serversCount?: VPNServersCountData): PlanCardFeatureDefinition => { let text: string; if (serversCount === undefined) { text = c('new_plans: Upsell attribute').t`Dedicated server locations in North America and Europe`; } else { const numberOfCountries = serversCount.paid.countries; text = c('new_plans: Upsell attribute').t`Dedicated server locations in ${numberOfCountries}+ countries`; } return { icon: 'checkmark', included: true, text, tooltip: c('new_plans: tooltip') .t`Dedicated servers with dedicated IP address(es) can be added to private gateways to enable fine-tuned access control`, }; }; export const getDedicatedAccountManagerVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark', included: true, text: c('new_plans: Upsell attribute').t`Dedicated Account manager`, }); export const getAESEncryptionVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark', included: true, text: c('new_plans: Upsell attribute').t`AES 256-bit VPN encryption`, }); export const getCensorshipCircumventionVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark', included: true, text: c('new_plans: Upsell attribute').t`Censorship circumvention`, }); export const getCentralControlPanelVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark', included: true, text: c('new_plans: Upsell attribute').t`Central control panel`, }); export const getAutoConnectVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark', included: true, text: c('new_plans: Upsell attribute').t`Auto-connect`, }); export const getMultiPlatformSupportVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark', included: true, text: c('new_plans: Upsell attribute').t`Multi-platform support`, }); export const get24x7SupportVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark', included: true, text: c('new_plans: Upsell attribute').t`24/7 support`, }); export const getRequire2FAVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark', included: true, text: c('new_plans: Upsell attribute').t`Require 2FA`, }); export const getBrowserExtensionVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark', included: true, text: c('new_plans: Upsell attribute').t`Browser extension`, }); export const getPrivateGatewaysVPNFeature = (): PlanCardFeatureDefinition => ({ icon: 'checkmark', included: true, text: c('new_plans: Upsell attribute').t`Private gateways`, tooltip: c('new_plans: tooltip') .t`Lock down your company resources from the public internet and make them accessible only via your private gateways`, }); export const getVPNFeatures = (serversCount: VPNServersCountData): PlanCardFeature[] => { const freeServers = getFreeServers(serversCount.free.servers, serversCount.free.countries); const plusServers = getPlusServers(serversCount.paid.servers, serversCount.paid.countries); return [ { name: 'vpn', target: Audience.B2C, plans: { [PLANS.FREE]: getVPNConnections(FREE_VPN_CONNECTIONS), [PLANS.BUNDLE]: getVPNConnections(VPN_CONNECTIONS), [PLANS.MAIL]: getVPNConnections(FREE_VPN_CONNECTIONS), [PLANS.VPN]: getVPNConnections(VPN_CONNECTIONS), [PLANS.DRIVE]: getVPNConnections(FREE_VPN_CONNECTIONS), [PLANS.PASS_PLUS]: getVPNConnections(FREE_VPN_CONNECTIONS), [PLANS.FAMILY]: getVPNConnections(VPN_CONNECTIONS), [PLANS.MAIL_PRO]: getVPNConnections(FREE_VPN_CONNECTIONS), [PLANS.BUNDLE_PRO]: getVPNConnections(VPN_CONNECTIONS), [PLANS.VPN_PRO]: getVPNConnections(VPN_CONNECTIONS), [PLANS.VPN_BUSINESS]: getVPNConnections(VPN_CONNECTIONS), }, }, { name: 'vpn-connections-per-user', target: Audience.B2B, plans: { [PLANS.FREE]: getVPNConnectionsB2B(1), [PLANS.BUNDLE]: getVPNConnectionsB2B(VPN_CONNECTIONS), [PLANS.MAIL]: getVPNConnectionsB2B(1), [PLANS.VPN]: getVPNConnectionsB2B(VPN_CONNECTIONS), [PLANS.DRIVE]: getVPNConnectionsB2B(1), [PLANS.PASS_PLUS]: getVPNConnectionsB2B(1), [PLANS.FAMILY]: getVPNConnectionsB2B(1), [PLANS.MAIL_PRO]: getVPNConnectionsB2B(1), [PLANS.BUNDLE_PRO]: getVPNConnectionsB2B(VPN_CONNECTIONS), [PLANS.VPN_PRO]: getVPNConnectionsB2B(VPN_CONNECTIONS), [PLANS.VPN_BUSINESS]: getVPNConnectionsB2B(VPN_CONNECTIONS), }, }, { name: 'vpn-connections-per-user-family', target: Audience.FAMILY, plans: { [PLANS.FREE]: getVPNConnections(1), [PLANS.BUNDLE]: getVPNConnections(VPN_CONNECTIONS), [PLANS.MAIL]: getVPNConnections(1), [PLANS.VPN]: getVPNConnections(VPN_CONNECTIONS), [PLANS.DRIVE]: getVPNConnections(1), [PLANS.PASS_PLUS]: getVPNConnections(1), [PLANS.FAMILY]: getVPNConnectionsB2B(VPN_CONNECTIONS), [PLANS.MAIL_PRO]: getVPNConnectionsB2B(1), [PLANS.BUNDLE_PRO]: getVPNConnectionsB2B(VPN_CONNECTIONS), [PLANS.VPN_PRO]: getVPNConnectionsB2B(VPN_CONNECTIONS), [PLANS.VPN_BUSINESS]: getVPNConnectionsB2B(VPN_CONNECTIONS), }, }, { name: 'countries', plans: { [PLANS.FREE]: getCountries(freeServers), [PLANS.BUNDLE]: getCountries(plusServers), [PLANS.MAIL]: getCountries(freeServers), [PLANS.VPN]: getCountries(plusServers), [PLANS.DRIVE]: getCountries(freeServers), [PLANS.PASS_PLUS]: getCountries(freeServers), [PLANS.FAMILY]: getCountries(plusServers), [PLANS.MAIL_PRO]: getCountries(freeServers), [PLANS.BUNDLE_PRO]: getCountries(plusServers), [PLANS.VPN_PRO]: getCountries(plusServers), [PLANS.VPN_BUSINESS]: getCountries(plusServers), }, }, { name: 'vpn-speed', plans: { [PLANS.FREE]: getVPNSpeed('medium'), [PLANS.BUNDLE]: getVPNSpeed('highest'), [PLANS.MAIL]: getVPNSpeed('medium'), [PLANS.VPN]: getVPNSpeed('highest'), [PLANS.DRIVE]: getVPNSpeed('medium'), [PLANS.PASS_PLUS]: getVPNSpeed('medium'), [PLANS.FAMILY]: getVPNSpeed('highest'), [PLANS.MAIL_PRO]: getVPNSpeed('medium'), [PLANS.BUNDLE_PRO]: getVPNSpeed('highest'), [PLANS.VPN_PRO]: getVPNSpeed('highest'), [PLANS.VPN_BUSINESS]: getVPNSpeed('highest'), }, }, { name: 'netshield', plans: { [PLANS.FREE]: getNetShield(false), [PLANS.BUNDLE]: getNetShield(true), [PLANS.MAIL]: getNetShield(false), [PLANS.VPN]: getNetShield(true), [PLANS.DRIVE]: getNetShield(false), [PLANS.PASS_PLUS]: getNetShield(false), [PLANS.FAMILY]: getNetShield(true), [PLANS.MAIL_PRO]: getNetShield(false), [PLANS.BUNDLE_PRO]: getNetShield(true), [PLANS.VPN_PRO]: getNetShield(true), [PLANS.VPN_BUSINESS]: getNetShield(true), }, }, { name: 'streaming', plans: { [PLANS.FREE]: getStreaming(false), [PLANS.BUNDLE]: getStreaming(true), [PLANS.MAIL]: getStreaming(false), [PLANS.VPN]: getStreaming(true), [PLANS.DRIVE]: getStreaming(false), [PLANS.PASS_PLUS]: getStreaming(false), [PLANS.FAMILY]: getStreaming(true), [PLANS.MAIL_PRO]: getStreaming(false), [PLANS.BUNDLE_PRO]: getStreaming(true), [PLANS.VPN_PRO]: getStreaming(true), [PLANS.VPN_BUSINESS]: getStreaming(true), }, }, { name: 'p2p', plans: { [PLANS.FREE]: getP2P(false), [PLANS.BUNDLE]: getP2P(true), [PLANS.MAIL]: getP2P(false), [PLANS.VPN]: getP2P(true), [PLANS.DRIVE]: getP2P(false), [PLANS.PASS_PLUS]: getP2P(false), [PLANS.FAMILY]: getP2P(true), [PLANS.MAIL_PRO]: getP2P(false), [PLANS.BUNDLE_PRO]: getP2P(true), [PLANS.VPN_PRO]: getP2P(true), [PLANS.VPN_BUSINESS]: getP2P(true), }, }, { name: 'hop', plans: { [PLANS.FREE]: getDoubleHop(false), [PLANS.BUNDLE]: getDoubleHop(true, true), [PLANS.MAIL]: getDoubleHop(false), [PLANS.VPN]: getDoubleHop(true, true), [PLANS.DRIVE]: getDoubleHop(false), [PLANS.PASS_PLUS]: getDoubleHop(false), [PLANS.FAMILY]: getDoubleHop(true, true), [PLANS.MAIL_PRO]: getDoubleHop(false), [PLANS.BUNDLE_PRO]: getDoubleHop(true, true), [PLANS.VPN_PRO]: getDoubleHop(true, true), [PLANS.VPN_BUSINESS]: getDoubleHop(true, true), }, }, { name: 'secure', plans: { [PLANS.FREE]: getSecureCore(false), [PLANS.BUNDLE]: getSecureCore(true), [PLANS.MAIL]: getSecureCore(false), [PLANS.VPN]: getSecureCore(true), [PLANS.DRIVE]: getSecureCore(false), [PLANS.PASS_PLUS]: getSecureCore(false), [PLANS.FAMILY]: getSecureCore(true), [PLANS.MAIL_PRO]: getSecureCore(false), [PLANS.BUNDLE_PRO]: getSecureCore(true), [PLANS.VPN_PRO]: getSecureCore(true), [PLANS.VPN_BUSINESS]: getSecureCore(true), }, }, { name: 'tor', plans: { [PLANS.FREE]: getTor(false), [PLANS.BUNDLE]: getTor(true), [PLANS.MAIL]: getTor(false), [PLANS.VPN]: getTor(true), [PLANS.DRIVE]: getTor(false), [PLANS.PASS_PLUS]: getTor(false), [PLANS.FAMILY]: getTor(true), [PLANS.MAIL_PRO]: getTor(false), [PLANS.BUNDLE_PRO]: getTor(true), [PLANS.VPN_PRO]: getTor(true), [PLANS.VPN_BUSINESS]: getTor(true), }, }, { name: 'logs', plans: { [PLANS.FREE]: getNoLogs(), [PLANS.BUNDLE]: getNoLogs(), [PLANS.MAIL]: getNoLogs(), [PLANS.VPN]: getNoLogs(), [PLANS.DRIVE]: getNoLogs(), [PLANS.PASS_PLUS]: getNoLogs(), [PLANS.FAMILY]: getNoLogs(), [PLANS.MAIL_PRO]: getNoLogs(), [PLANS.BUNDLE_PRO]: getNoLogs(), [PLANS.VPN_PRO]: getNoLogs(), [PLANS.VPN_BUSINESS]: getNoLogs(), }, }, { name: 'bandwidth', plans: { [PLANS.FREE]: getBandwidth(), [PLANS.BUNDLE]: getBandwidth(), [PLANS.MAIL]: getBandwidth(), [PLANS.VPN]: getBandwidth(), [PLANS.DRIVE]: getBandwidth(), [PLANS.PASS_PLUS]: getBandwidth(), [PLANS.FAMILY]: getBandwidth(), [PLANS.MAIL_PRO]: getBandwidth(), [PLANS.BUNDLE_PRO]: getBandwidth(), [PLANS.VPN_PRO]: getBandwidth(), [PLANS.VPN_BUSINESS]: getBandwidth(), }, }, { name: 'dns-leak', plans: { [PLANS.FREE]: getDNSLeak(), [PLANS.BUNDLE]: getDNSLeak(), [PLANS.MAIL]: getDNSLeak(), [PLANS.VPN]: getDNSLeak(), [PLANS.DRIVE]: getDNSLeak(), [PLANS.PASS_PLUS]: getDNSLeak(), [PLANS.FAMILY]: getDNSLeak(), [PLANS.MAIL_PRO]: getDNSLeak(), [PLANS.BUNDLE_PRO]: getDNSLeak(), [PLANS.VPN_PRO]: getDNSLeak(), [PLANS.VPN_BUSINESS]: getDNSLeak(), }, }, { name: 'kill-switch', plans: { [PLANS.FREE]: getKillSwitch(), [PLANS.BUNDLE]: getKillSwitch(), [PLANS.MAIL]: getKillSwitch(), [PLANS.VPN]: getKillSwitch(), [PLANS.DRIVE]: getKillSwitch(), [PLANS.PASS_PLUS]: getKillSwitch(), [PLANS.FAMILY]: getKillSwitch(), [PLANS.MAIL_PRO]: getKillSwitch(), [PLANS.BUNDLE_PRO]: getKillSwitch(), [PLANS.VPN_PRO]: getKillSwitch(), [PLANS.VPN_BUSINESS]: getKillSwitch(), }, }, { name: 'encryption', plans: { [PLANS.FREE]: getEncryption(), [PLANS.BUNDLE]: getEncryption(), [PLANS.MAIL]: getEncryption(), [PLANS.VPN]: getEncryption(), [PLANS.DRIVE]: getEncryption(), [PLANS.PASS_PLUS]: getEncryption(), [PLANS.FAMILY]: getEncryption(), [PLANS.MAIL_PRO]: getEncryption(), [PLANS.BUNDLE_PRO]: getEncryption(), [PLANS.VPN_PRO]: getEncryption(), [PLANS.VPN_BUSINESS]: getEncryption(), }, }, { name: 'router', plans: { [PLANS.FREE]: getRouterSupport(), [PLANS.BUNDLE]: getRouterSupport(), [PLANS.MAIL]: getRouterSupport(), [PLANS.VPN]: getRouterSupport(), [PLANS.DRIVE]: getRouterSupport(), [PLANS.PASS_PLUS]: getRouterSupport(), [PLANS.FAMILY]: getRouterSupport(), [PLANS.MAIL_PRO]: getRouterSupport(), [PLANS.BUNDLE_PRO]: getRouterSupport(), [PLANS.VPN_PRO]: getRouterSupport(), [PLANS.VPN_BUSINESS]: getRouterSupport(), }, }, { name: 'split-tunnel', plans: { [PLANS.FREE]: getSplitTunnel(false), [PLANS.BUNDLE]: getSplitTunnel(true), [PLANS.MAIL]: getSplitTunnel(false), [PLANS.VPN]: getSplitTunnel(true), [PLANS.DRIVE]: getSplitTunnel(false), [PLANS.PASS_PLUS]: getSplitTunnel(false), [PLANS.FAMILY]: getSplitTunnel(true), [PLANS.MAIL_PRO]: getSplitTunnel(false), [PLANS.BUNDLE_PRO]: getSplitTunnel(true), [PLANS.VPN_PRO]: getSplitTunnel(true), [PLANS.VPN_BUSINESS]: getSplitTunnel(true), }, }, ]; };
6,748
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/AutomaticSubscriptionModal.tsx
import { useEffect, useRef } from 'react'; import { useHistory, useLocation } from 'react-router-dom'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { ModalProps, OpenCallbackProps, Prompt, useConfig, useLastSubscriptionEnd, useLoad, useModalState, usePlans, useSubscription, useSubscriptionModal, useUser, } from '@proton/components'; import { blackFriday2023DriveFreeConfig, blackFriday2023DriveFreeEligibility, } from '@proton/components/containers/offers/operations/blackFridayDrive2023Free'; import { blackFriday2023DrivePlusConfig, blackFriday2023DrivePlusEligibility, } from '@proton/components/containers/offers/operations/blackFridayDrive2023Plus'; import { blackFriday2023DriveUnlimitedConfig, blackFriday2023DriveUnlimitedEligibility, } from '@proton/components/containers/offers/operations/blackFridayDrive2023Unlimited'; import { blackFriday2023InboxFreeConfig, blackFriday2023InboxFreeEligibility, } from '@proton/components/containers/offers/operations/blackFridayInbox2023Free'; import { blackFriday2023InboxMailConfig, blackFriday2023InboxMailEligibility, } from '@proton/components/containers/offers/operations/blackFridayInbox2023Plus'; import { blackFriday2023InboxUnlimitedConfig, blackFriday2023InboxUnlimitedEligibility, } from '@proton/components/containers/offers/operations/blackFridayInbox2023Unlimited'; import { blackFriday2023VPNFreeConfig, blackFriday2023VPNFreeEligibility, } from '@proton/components/containers/offers/operations/blackFridayVPN2023Free'; import { blackFriday2023VPNMonthlyConfig, blackFriday2023VPNMonthlyEligibility, } from '@proton/components/containers/offers/operations/blackFridayVPN2023Monthly'; import { blackFriday2023VPNTwoYearsConfig, blackFriday2023VPNTwoYearsEligibility, } from '@proton/components/containers/offers/operations/blackFridayVPN2023TwoYears'; import { blackFriday2023VPNYearlyConfig, blackFriday2023VPNYearlyEligibility, } from '@proton/components/containers/offers/operations/blackFridayVPN2023Yearly'; import { getMonths } from '@proton/components/containers/payments/SubscriptionsSection'; import { SUBSCRIPTION_STEPS } from '@proton/components/containers/payments/subscription/constants'; import getBoldFormattedText from '@proton/components/helpers/getBoldFormattedText'; import { CURRENCIES, DEFAULT_CYCLE, PLANS } from '@proton/shared/lib/constants'; import { toMap } from '@proton/shared/lib/helpers/object'; import { getValidCycle } from '@proton/shared/lib/helpers/subscription'; import { Currency, Plan, PlansMap, Subscription, UserModel } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { getCurrency } from './helpers'; import { Eligibility, PlanCombinationWithDiscount, getEligibility } from './subscriptionEligbility'; const getParameters = ( search: string, plansMap: PlansMap, plans: Plan[], subscription: Subscription, user: UserModel ) => { const params = new URLSearchParams(search); const planName = params.get('plan') || ''; const coupon = params.get('coupon') || undefined; const cycleParam = parseInt(params.get('cycle') as any, 10); const currencyParam = params.get('currency')?.toUpperCase(); const target = params.get('target'); const edit = params.get('edit'); const type = params.get('type'); const offer = params.get('offer'); const parsedTarget = (() => { if (target === 'compare') { return SUBSCRIPTION_STEPS.PLAN_SELECTION; } if (target === 'checkout') { return SUBSCRIPTION_STEPS.CHECKOUT; } })(); const parsedCycle = cycleParam && getValidCycle(cycleParam); const parsedCurrency = currencyParam && CURRENCIES.includes(currencyParam as any) ? (currencyParam as Currency) : undefined; const plan = plansMap?.[planName as PLANS]; return { plan, coupon, cycle: parsedCycle || subscription?.Cycle || DEFAULT_CYCLE, currency: parsedCurrency || getCurrency(user, subscription, plans), step: parsedTarget || SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: type === 'offer' || edit === 'disable', disableCycleSelector: edit === 'enable' ? false : type === 'offer' || Boolean(offer), }; }; interface Props extends ModalProps { planCombination: PlanCombinationWithDiscount; onConfirm: () => void; } const PromotionAppliedPrompt = (rest: ModalProps) => { return ( <Prompt title={c('Info').t`Your account was successfully updated with this promotion`} buttons={[ <Button color="norm" onClick={rest.onClose}> {c('bf2023: Action').t`Close`} </Button>, ]} {...rest} > {c('Info') .t`Thanks for supporting our mission to build a better internet where privacy and freedom come first.`} </Prompt> ); }; const UnavailablePrompt = (rest: ModalProps) => { return ( <Prompt title={c('bf2023: Title').t`Offer unavailable`} buttons={[<Button onClick={rest.onClose}>{c('bf2023: Action').t`Close`}</Button>]} {...rest} > {getBoldFormattedText(c('bf2023: info').t`Sorry, this offer is not available with your current plan.`)} </Prompt> ); }; const UpsellPrompt = ({ planCombination: { discount, plan, cycle }, onConfirm, ...rest }: Props) => { const months = getMonths(cycle); const discountPercentage = `${discount}%`; return ( <Prompt title={c('bf2023: Title').t`Offer unavailable`} buttons={[ <Button color="norm" onClick={() => { onConfirm(); rest.onClose?.(); }} > {c('bf2023: Action').t`Get the deal`} </Button>, <Button onClick={rest.onClose}>{c('bf2023: Action').t`Cancel`}</Button>, ]} {...rest} > {getBoldFormattedText( c('bf2023: info') .t`Sorry, this offer is not available with your current plan. But you can get **${discountPercentage} off ${plan.Title}** when you subscribe for **${months}**.` )} </Prompt> ); }; const AutomaticSubscriptionModal = () => { const history = useHistory(); const location = useLocation(); const protonConfig = useConfig(); const [open, loadingModal] = useSubscriptionModal(); const [plans, loadingPlans] = usePlans(); const [subscription, loadingSubscription] = useSubscription(); const [lastSubscriptionEnd, loadingLastSubscriptionEnd] = useLastSubscriptionEnd(); const [user] = useUser(); const tmpProps = useRef<{ props: OpenCallbackProps; eligibility: Eligibility } | undefined>(undefined); const [upsellModalProps, setUpsellModal, renderUpsellModal] = useModalState(); const [unavailableModalProps, setUnavailableModal, renderUnavailableModal] = useModalState(); const [promotionAppliedProps, setPromotionAppliedModal, renderPromotionAppliedModal] = useModalState(); useLoad(); useEffect(() => { if ( !plans || !subscription || loadingPlans || loadingSubscription || loadingModal || loadingLastSubscriptionEnd ) { return; } const plansMap = toMap(plans, 'Name') as PlansMap; const { plan, currency, cycle, coupon, step, disablePlanSelection, disableCycleSelector } = getParameters( location.search, plansMap, plans, subscription, user ); if (!plan) { return; } const options = { subscription, protonConfig, user, lastSubscriptionEnd, }; const eligibleBlackFridayConfigs = [ blackFriday2023InboxFreeEligibility(options) && blackFriday2023InboxFreeConfig, blackFriday2023InboxMailEligibility(options) && blackFriday2023InboxMailConfig, blackFriday2023InboxUnlimitedEligibility(options) && blackFriday2023InboxUnlimitedConfig, blackFriday2023VPNFreeEligibility(options) && blackFriday2023VPNFreeConfig, blackFriday2023VPNMonthlyEligibility(options) && blackFriday2023VPNMonthlyConfig, blackFriday2023VPNYearlyEligibility(options) && blackFriday2023VPNYearlyConfig, blackFriday2023VPNTwoYearsEligibility(options) && blackFriday2023VPNTwoYearsConfig, blackFriday2023DriveFreeEligibility(options) && blackFriday2023DriveFreeConfig, blackFriday2023DrivePlusEligibility(options) && blackFriday2023DrivePlusConfig, blackFriday2023DriveUnlimitedEligibility(options) && blackFriday2023DriveUnlimitedConfig, ].filter(isTruthy); const eligibility = getEligibility({ plansMap, offer: { plan, cycle, coupon, }, subscription, user, eligibleBlackFridayConfigs, }); history.replace({ search: undefined }); const openProps: OpenCallbackProps = { plan: plan.Name as PLANS, currency, cycle, coupon, step, disablePlanSelection, disableCycleSelector, metrics: { source: 'automatic', }, }; if (eligibility.type === 'bf-applied') { setPromotionAppliedModal(true); return; } if (eligibility.type === 'not-eligible') { setUnavailableModal(true); return; } if (eligibility.type === 'upsell') { tmpProps.current = { props: { ...openProps, plan: eligibility.planCombination.plan.Name as PLANS, cycle: eligibility.planCombination.cycle, }, eligibility, }; setUpsellModal(true); return; } if (eligibility.type === 'pass-through') { open(openProps); } }, [loadingPlans, loadingSubscription, loadingModal, loadingLastSubscriptionEnd, location.search]); const tmp = tmpProps.current; return ( <> {renderPromotionAppliedModal && <PromotionAppliedPrompt {...promotionAppliedProps} />} {renderUnavailableModal && <UnavailablePrompt {...unavailableModalProps} />} {renderUpsellModal && tmp && tmp.eligibility.type === 'upsell' && ( <UpsellPrompt planCombination={tmp.eligibility.planCombination} {...upsellModalProps} onConfirm={() => { if (tmp.props) { open(tmp.props); } }} /> )} </> ); }; export default AutomaticSubscriptionModal;
6,749
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/CalendarDowngradeModal.tsx
import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { MAX_CALENDARS_FREE } from '@proton/shared/lib/calendar/constants'; import { getCalendarsSettingsPath } from '@proton/shared/lib/calendar/settingsRoutes'; import { APPS, BRAND_NAME, CALENDAR_APP_NAME, MAIL_SHORT_APP_NAME } from '@proton/shared/lib/constants'; import { AppLink, ModalProps, Prompt } from '../../../components'; import { useFeature } from '../../../hooks'; import { FeatureCode } from '../../index'; const getText = (isDowngrade: boolean, calendarSharingEnabled: boolean) => { if (isDowngrade) { if (calendarSharingEnabled) { return c('Info').ngettext( msgid`You can keep up to ${MAX_CALENDARS_FREE} calendar. Please remove shared calendar links and any ${BRAND_NAME} user with whom you shared your calendars before you cancel your subscription.`, `You can keep up to ${MAX_CALENDARS_FREE} calendars. Please remove shared calendar links and any ${BRAND_NAME} user with whom you shared your calendars before you cancel your subscription.`, MAX_CALENDARS_FREE ); } return c('Info').ngettext( msgid`You can keep up to ${MAX_CALENDARS_FREE} calendar. Please remove shared calendar links before you cancel your subscription.`, `You can keep up to ${MAX_CALENDARS_FREE} calendars. Please remove shared calendar links before you cancel your subscription.`, MAX_CALENDARS_FREE ); } if (calendarSharingEnabled) { return c('Info').ngettext( msgid`You can keep up to ${MAX_CALENDARS_FREE} calendar. Please remove shared calendar links and any ${BRAND_NAME} user with whom you shared your calendars before you cancel your ${MAIL_SHORT_APP_NAME} subscription.`, `You can keep up to ${MAX_CALENDARS_FREE} calendars. Please remove shared calendar links and any ${BRAND_NAME} user with whom you shared your calendars before you cancel your ${MAIL_SHORT_APP_NAME} subscription.`, MAX_CALENDARS_FREE ); } return c('Info').ngettext( msgid`You can keep up to ${MAX_CALENDARS_FREE} calendar. Please remove shared calendar links before you cancel your ${MAIL_SHORT_APP_NAME} subscription.`, `You can keep up to ${MAX_CALENDARS_FREE} calendars. Please remove shared calendar links before you cancel your ${MAIL_SHORT_APP_NAME} subscription.`, MAX_CALENDARS_FREE ); }; interface Props extends ModalProps { onConfirm: () => void; isDowngrade?: boolean; } const CalendarDowngradeModal = ({ isDowngrade, onConfirm, onClose, ...rest }: Props) => { const calendarSharingEnabled = !!useFeature(FeatureCode.CalendarSharingEnabled).feature?.Value; const linkButton = ( <AppLink toApp={APPS.PROTONACCOUNT} to={getCalendarsSettingsPath({ fullPath: true })} onClick={onClose}> {c('Action').t`Open ${CALENDAR_APP_NAME} settings`} </AppLink> ); const title = isDowngrade ? c('Title').t`Downgrade account` : c('Title').t`Cancel ${MAIL_SHORT_APP_NAME} subscription`; const text = getText(!!isDowngrade, calendarSharingEnabled); return ( <Prompt title={title} buttons={[ <Button onClick={() => { onConfirm(); onClose?.(); }} color="norm" > {c('Action').t`OK`} </Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} onClose={onClose} {...rest} > <div> {text} <br /> {linkButton} </div> </Prompt> ); }; export default CalendarDowngradeModal;
6,750
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/DowngradeSubscriptionSection.tsx
import { c } from 'ttag'; import { SettingsParagraph, SettingsSection } from '../../account'; import UnsubscribeButton from './UnsubscribeButton'; const DowngradeSubscriptionSection = () => { return ( <SettingsSection> <SettingsParagraph> {c('Info') .t`This will cancel your current paid subscription and you will lose any loyalty benefits you have accumulated. The remaining balance of your subscription will be returned as account credits.`} </SettingsParagraph> <UnsubscribeButton color="danger" shape="outline"> {c('Action').t`Downgrade account`} </UnsubscribeButton> </SettingsSection> ); }; export default DowngradeSubscriptionSection;
6,751
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/FeedbackDowngradeModal.tsx
import { Fragment, ReactNode, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ModalTwoPromiseHandlers } from '@proton/components/components/modalTwo/useModalTwo'; import { BRAND_NAME, SUBSCRIPTION_CANCELLATION_REASONS } from '@proton/shared/lib/constants'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { UserModel } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import shuffle from '@proton/utils/shuffle'; import { Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, Option, SelectTwo, TextAreaTwo, useFormErrors, } from '../../../components'; import { useConfig } from '../../../hooks'; interface ReasonOption { title: string; value: string; } interface ReasonDetail { forReason: SUBSCRIPTION_CANCELLATION_REASONS; content: ReactNode; } const { DIFFERENT_ACCOUNT, TOO_EXPENSIVE, MISSING_FEATURE, QUALITY_ISSUE, STREAMING_SERVICE_UNSUPPORTED, SWITCHING_TO_DIFFERENT_SERVICE, TEMPORARY, OTHER, } = SUBSCRIPTION_CANCELLATION_REASONS; export interface FeedbackDowngradeData { Reason?: string; Feedback?: string; ReasonDetails?: string; Context?: 'vpn' | 'mail'; } export type KeepSubscription = { status: 'kept'; }; export function isKeepSubscription(data: FeedbackDowngradeResult): data is KeepSubscription { return (data as KeepSubscription)?.status === 'kept'; } export type FeedbackDowngradeResult = FeedbackDowngradeData | KeepSubscription; export type FeedbackDowngradeModalProps = Omit<ModalProps, 'onSubmit'> & { user: UserModel; }; type PromiseHandlers = ModalTwoPromiseHandlers<FeedbackDowngradeResult>; const FeedbackDowngradeModal = ({ onResolve, onClose, user, onReject, ...rest }: FeedbackDowngradeModalProps & PromiseHandlers) => { const { APP_NAME } = useConfig(); const { isPaid } = user; const isVpnApp = APP_NAME === 'proton-vpn-settings'; const [model, setModel] = useState<FeedbackDowngradeData>({ Reason: '', Feedback: '', ReasonDetails: '', Context: isVpnApp ? 'vpn' : 'mail', }); const { validator, onFormSubmit } = useFormErrors(); const [randomisedOptions] = useState(() => { const reasons: ReasonOption[] = [ !isVpnApp ? { title: c('Downgrade account reason').t`I use a different ${BRAND_NAME} account`, value: DIFFERENT_ACCOUNT, } : undefined, isPaid ? { title: c('Downgrade account reason').t`Subscription is too expensive`, value: TOO_EXPENSIVE, } : undefined, { title: c('Downgrade account reason').t`Missing feature(s)`, value: MISSING_FEATURE, }, { title: c('Downgrade account reason').t`Bugs or quality issue`, value: QUALITY_ISSUE, }, isVpnApp ? { title: c('Downgrade account reason').t`Streaming service unsupported`, value: STREAMING_SERVICE_UNSUPPORTED, } : undefined, { title: c('Downgrade account reason').t`Switching to a different provider`, value: SWITCHING_TO_DIFFERENT_SERVICE, }, { title: c('Downgrade account reason').t`Temporary need, may come back in the future`, value: TEMPORARY, }, ].filter(isTruthy); return shuffle(reasons); }); const options = [ ...randomisedOptions.map(({ title, value }) => <Option key={value} title={title} value={value} />), <Option title={c('Downgrade account reason').t`My reason isn't listed, please comment`} value={OTHER} key={OTHER} />, ]; const sharedReasonDetailsProps = { value: model.ReasonDetails, onValue: (value: string) => setModel({ ...model, ReasonDetails: value }), }; const reasonDetails: ReasonDetail[] = [ { forReason: MISSING_FEATURE, content: ( <InputFieldTwo id={MISSING_FEATURE} as={TextAreaTwo} rows={3} label={c('Label').t`Could you please specify?`} error={validator(model.Reason === MISSING_FEATURE ? [requiredValidator(model.ReasonDetails)] : [])} {...sharedReasonDetailsProps} /> ), }, { forReason: QUALITY_ISSUE, content: ( <InputFieldTwo id={QUALITY_ISSUE} as={TextAreaTwo} rows={3} label={c('Label').t`Could you please specify?`} error={validator(model.Reason === QUALITY_ISSUE ? [requiredValidator(model.ReasonDetails)] : [])} {...sharedReasonDetailsProps} /> ), }, { forReason: STREAMING_SERVICE_UNSUPPORTED, content: ( <InputFieldTwo id={STREAMING_SERVICE_UNSUPPORTED} as={TextAreaTwo} rows={3} label={c('Label').t`Could you please specify which streaming service?`} error={validator( model.Reason === STREAMING_SERVICE_UNSUPPORTED ? [requiredValidator(model.ReasonDetails)] : [] )} {...sharedReasonDetailsProps} /> ), }, { forReason: SWITCHING_TO_DIFFERENT_SERVICE, content: ( <InputFieldTwo id={SWITCHING_TO_DIFFERENT_SERVICE} as={TextAreaTwo} rows={3} label={c('Label').t`Could you please let us know which provider?`} error={validator( model.Reason === SWITCHING_TO_DIFFERENT_SERVICE ? [requiredValidator(model.ReasonDetails)] : [] )} {...sharedReasonDetailsProps} /> ), }, ]; const handleSubmit = () => { if (!onFormSubmit()) { return; } const shouldSendReasonDetails = reasonDetails.some(({ forReason }) => model.Reason === forReason); const data: FeedbackDowngradeData = { ...model, ReasonDetails: shouldSendReasonDetails ? model.ReasonDetails : '', }; onResolve(data); onClose?.(); }; const handleKeepSubscription = () => { onResolve({ status: 'kept' }); onClose?.(); }; return ( <Modal as={Form} onClose={handleKeepSubscription} onSubmit={handleSubmit} data-testid="help-improve" {...rest}> <ModalHeader title={c('Downgrade modal exit survey title').t`Help us improve!`} /> <ModalContent> <InputFieldTwo as={SelectTwo} label={c('Label').t`What is the main reason you are canceling?`} placeholder={c('Placeholder').t`Select a reason`} id="reason" autoFocus value={model.Reason} onValue={(value: unknown) => setModel({ ...model, Reason: value as string })} error={validator([requiredValidator(model.Reason)])} > {options} </InputFieldTwo> {reasonDetails.map(({ forReason, content }) => { if (model.Reason !== forReason) { return; } return <Fragment key={forReason}>{content}</Fragment>; })} <InputFieldTwo id="feedback" as={TextAreaTwo} rootClassName="mt-2" rows={5} label={c('Label').t`Do you have any suggestions for our team?`} hint={c('Label').t`Optional`} placeholder={c('Placeholder').t`Feedback`} value={model.Feedback} onValue={(value: string) => setModel({ ...model, Feedback: value })} /> </ModalContent> <ModalFooter> <Button data-testid="cancelFeedback" onClick={handleKeepSubscription}>{c('Action').t`Cancel`}</Button> <Button data-testid="submitFeedback" type="submit" color="norm"> {c('Action').t`Submit`} </Button> </ModalFooter> </Modal> ); }; export default FeedbackDowngradeModal;
6,752
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/HighlightPlanDowngradeModal.tsx
import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { getDifferenceInDays } from '@proton/shared/lib/date/date'; import { Alert, Form, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, } from '../../../components'; import { ShortPlan } from '../features/interface'; import { getFreePlan } from '../features/plan'; import SubscriptionCancelPlan from './SubscriptionCancelPlan'; interface Props extends Omit<ModalProps, 'onSubmit'> { onConfirm: () => void; shortPlan: ShortPlan; periodEnd: number; } const HighlightPlanDowngradeModal = ({ onConfirm, onClose, shortPlan, periodEnd, ...rest }: Props) => { const downgradedShortPlan = getFreePlan(); const downgradedPlanName = `${BRAND_NAME} ${downgradedShortPlan.title}`; const currentPlanName = shortPlan.title; const daysRemaining = getDifferenceInDays(new Date(), new Date(periodEnd * 1000)); // translator: daysRemaining contains the number of days remaining for the current subscription eg 288 days remaining const planTimeRemainingString = c('new_plans: Plan time remaining').ngettext( msgid`You still have ${daysRemaining} day left on your ${currentPlanName} account.`, `You still have ${daysRemaining} days left on your ${currentPlanName} account.`, daysRemaining ); // translator: will be something like "Downgrade to Proton Free" (where "Free" is the plan name) const downgradeButtonString = c('new_plans: Action').t`Downgrade to ${downgradedPlanName}`; // translator: will be something like "Keep my Proton Plus account" const keepButtonString = c('new_plans: Action').t`Keep my ${currentPlanName} account`; const shortPlanFeatures = shortPlan?.features?.filter((feature) => !feature.hideInDowngrade) || []; return ( <Modal as={Form} onClose={onClose} size="large" {...rest}> <ModalHeader title={c('Title').t`Downgrade account`} /> <ModalContent> {daysRemaining > 0 && ( <Alert className="mb-4" type="warning"> {planTimeRemainingString} <br /> {c('Info') .t`By downgrading you will lose the following benefits. Are you sure you want to proceed?`} </Alert> )} <div className="flex flex-row flex-nowrap on-mobile-flex-column"> <SubscriptionCancelPlan name={downgradedPlanName} info={downgradedShortPlan?.description || ''} features={shortPlanFeatures} downgrade /> <SubscriptionCancelPlan name={currentPlanName} info={shortPlan?.description || ''} features={shortPlanFeatures} /> </div> </ModalContent> <ModalFooter> <Button className="w-full md:w-auto mb-4 md:mb-0" onClick={() => { onConfirm(); onClose?.(); }} data-testid="downgrade-to-free" > {downgradeButtonString} </Button> <Button className="w-full md:w-auto" color="norm" onClick={onClose}> {keepButtonString} </Button> </ModalFooter> </Modal> ); }; export default HighlightPlanDowngradeModal;
6,753
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/InAppPurchaseModal.test.tsx
import { act, fireEvent, render } from '@testing-library/react'; import { External } from '@proton/shared/lib/interfaces'; import InAppPurchaseModal from './InAppPurchaseModal'; jest.mock('@proton/components/components/portal/Portal'); it('should render', () => { const { container } = render( <InAppPurchaseModal open={true} subscription={{ External: External.Android } as any} onClose={() => {}} /> ); expect(container).not.toBeEmptyDOMElement(); }); it('should trigger onClose when user presses the button', async () => { const onClose = jest.fn(); const { getByTestId } = render( <InAppPurchaseModal onClose={onClose} open={true} subscription={{ External: External.Android } as any} /> ); await act(async () => { fireEvent.click(getByTestId('InAppPurchaseModal/onClose')); }); expect(onClose).toHaveBeenCalled(); }); it('should render iOS text if subscription is managed by Apple', async () => { const { container } = render( <InAppPurchaseModal onClose={() => {}} open={true} subscription={{ External: External.iOS } as any} /> ); expect(container).toHaveTextContent('Apple App Store'); expect(container).not.toHaveTextContent('Google'); expect(container).not.toHaveTextContent('Google Play'); }); it('should immediately close if subscription is not managed externally', () => { const onClose = jest.fn(); const { container } = render( <InAppPurchaseModal onClose={onClose} open={true} subscription={{ External: External.Default } as any} /> ); expect(onClose).toHaveBeenCalled(); expect(container).toBeEmptyDOMElement(); });
6,754
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/InAppPurchaseModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '@proton/components/components'; import { External, Subscription } from '@proton/shared/lib/interfaces'; interface Props extends ModalProps { subscription: Subscription; onClose: NonNullable<ModalProps['onClose']>; } function getSubscritionManagerName(externalCode: External.Android | External.iOS): string { if (externalCode === External.Android) { return 'Google Play'; } else if (externalCode === External.iOS) { return 'Apple App Store'; } return ''; } export const InAppText = ({ subscription }: { subscription: Subscription }) => { const subscriptions = <span className="text-bold">{c('Subscription change warning').t`Subscriptions`}</span>; let firstLine: string; let secondLine: string | string[]; if (subscription.External === External.Android) { firstLine = c('Subscription change warning') .t`Your plan was purchased using an Android app. So to make changes to your plan or update your payment details, you’ll need to go to the Google Play Store.`; secondLine = c('Subscription change warning') .jt`Just sign in to your Play Store account, then press ${subscriptions}.`; } else { firstLine = c('Subscription change warning') .t`Your plan was purchased using an iOS app. So to make changes to your plan or update your payment details, you’ll need to go to the Apple App Store.`; secondLine = c('Subscription change warning') .jt`Just sign in to your Apple App Store account, then press ${subscriptions}.`; } return ( <> <p data-testid="InAppPurchaseModal/text">{firstLine}</p> <p className="mt-4">{secondLine}</p> </> ); }; const InAppPurchaseModal = ({ subscription, ...rest }: Props) => { if (subscription.External !== External.iOS && subscription.External !== External.Android) { rest.onClose(); return null; } const subscriptionManager = getSubscritionManagerName(subscription.External); // translator: subscriptionManager currently can be "Google Play" or "Apple App Store" const title = c('Subscription change warning').t`Manage your subscription on ${subscriptionManager}`; return ( <ModalTwo size="large" {...rest}> <ModalTwoHeader title={title}></ModalTwoHeader> <ModalTwoContent> <InAppText subscription={subscription} /> </ModalTwoContent> <ModalTwoFooter> <Button className="mx-auto" color="norm" onClick={rest.onClose} data-testid="InAppPurchaseModal/onClose" > {c('Subscription change warning').t`Got it`} </Button> </ModalTwoFooter> </ModalTwo> ); }; export default InAppPurchaseModal;
6,755
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/PendingInvitationModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, useSettingsLink, } from '@proton/components/components'; import { useApi, useCache, useConfig, useEventManager, useNotifications } from '@proton/components/hooks'; import { useLoading } from '@proton/hooks'; import { acceptInvitation, rejectInvitation } from '@proton/shared/lib/api/user'; import { APPS, BRAND_NAME } from '@proton/shared/lib/constants'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { PendingInvitation } from '@proton/shared/lib/interfaces'; import { OrganizationModel } from '@proton/shared/lib/models'; import PendingInvitationModalErrors from './PendingInvitationModalErrors'; interface Props extends ModalStateProps { invite: PendingInvitation; } const PendingInvitationModal = ({ invite, ...modalProps }: Props) => { const api = useApi(); const cache = useCache(); const goToSettings = useSettingsLink(); const protonConfig = useConfig(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const [loadingAccept, withLoadingAccept] = useLoading(); const [loadingReject, withLoadingReject] = useLoading(); const hasErrors = !invite.Validation.Valid; const handleRejectInvitation = async () => { await api(rejectInvitation(invite.ID)); await call(); modalProps.onClose(); }; const handleAcceptInvitation = async () => { await api(acceptInvitation(invite.ID)); await call(); modalProps.onClose(); createNotification({ text: c('familyOffer_2023:Family plan').t`You have successfully joined the Family plan`, }); if (protonConfig.APP_NAME === APPS.PROTONACCOUNT) { cache.delete(OrganizationModel.key); // Force refresh the organization since it's not present in the event manager goToSettings('/account-password', APPS.PROTONACCOUNT); } }; const inviteEmail = <strong>{`${invite.InviterEmail}`}</strong>; const assignedStorage = <strong>{humanSize(invite.MaxSpace, undefined, false, 0)}</strong>; const BRAND_NAME_TWO = BRAND_NAME; return ( <ModalTwo {...modalProps} size="large"> <ModalTwoHeader // translator: Title of the modal to accept or reject an invitation to join a family plan, no period at the end of the sentence. Looks like: "You are invited to join Bernie's family" title={c('familyOffer_2023:Family plan').t`You are invited to join ${invite.OrganizationName}`} /> <ModalTwoContent> <div className="bg-weak p-3 rounded flex gap-2 mb-4"> <div>{c('familyOffer_2023:Family plan').jt`Invited by: ${inviteEmail}`}</div> <div>{c('familyOffer_2023:Family plan').jt`Storage assigned to you: ${assignedStorage}`}</div> </div> {hasErrors ? ( <PendingInvitationModalErrors errors={invite.Validation} invite={invite} onClose={modalProps.onClose} /> ) : ( <> <p className="my-2">{c('familyOffer_2023:Family plan') .jt`You're invited to link your ${BRAND_NAME} Account to this group plan and together enjoy all ${BRAND_NAME_TWO} premium features.`}</p> <p className="my-2">{c('familyOffer_2023:Family plan') .t`The subscription is billed to the Visionary or family plan's primary admin.`}</p> <p className="my-2">{c('familyOffer_2023:Family plan') .t`If you accept the invitation, we'll switch you from your current plan and credit your account with any remaining balance.`}</p> </> )} </ModalTwoContent> <ModalTwoFooter> <Button loading={loadingReject} disabled={loadingAccept} onClick={() => withLoadingReject(handleRejectInvitation())} >{c('familyOffer_2023:Action').t`Decline invitation`}</Button> {hasErrors ? ( <Button color="norm" onClick={() => modalProps.onClose()}>{c('familyOffer_2023:Action') .t`Got it`}</Button> ) : ( <Button disabled={loadingReject} loading={loadingAccept} color="norm" onClick={() => withLoadingAccept(handleAcceptInvitation())} >{c('familyOffer_2023:Action').t`Switch plans`}</Button> )} </ModalTwoFooter> </ModalTwo> ); }; export default PendingInvitationModal;
6,756
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/PendingInvitationModalErrors.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { SettingsLink, useModalState } from '@proton/components/components'; import { BugModal, useUser } from '@proton/components/index'; import { APPS, BRAND_NAME } from '@proton/shared/lib/constants'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { AcceptInvitationValidation, PendingInvitation } from '@proton/shared/lib/interfaces'; interface Props { invite: PendingInvitation; errors: AcceptInvitationValidation; onClose: () => void; } const PendingInvitationModalErrors = ({ errors, invite, onClose }: Props) => { const [user] = useUser(); const [bugReportModal, setBugReportOpen, render] = useModalState(); const inviteSpace = humanSize(invite.MaxSpace, undefined, false, 0); const usedSpace = humanSize(user.UsedSpace, undefined, false, 0); let errorDescription: string | string[] = ''; // translator: full sentence is: You can only accept 3 invitations in a 6-month period. Please contact <customer support> if you require an exception. const supportLink = ( <Button className="p-0 align-baseline" shape="underline" color="norm" onClick={() => setBugReportOpen(true)}>{c( 'familyOffer_2023:Family plan' ).t`customer support`}</Button> ); const addressSettingsLink = ( <SettingsLink app={APPS.PROTONMAIL} path="/identity-addresses" onClick={onClose} target="_self"> {c('familyOffer_2023:Family plan').t`Manage addresses.`} </SettingsLink> ); if (errors.IsLifetimeAccount) { errorDescription = c('familyOffer_2023:Family plan') .t`Visionary and family plans do not currently support lifetime accounts.`; } else if (errors.HasOrgWithMembers) { errorDescription = c('familyOffer_2023:Family plan') .t`Owners of a plan with members cannot join another group plan.`; } else if (errors.HasCustomDomains) { errorDescription = c('familyOffer_2023:Family plan') .t`Accounts with custom domains cannot join a Visionary or family plan.`; } else if (errors.ExceedsMaxSpace) { errorDescription = c('familyOffer_2023:Family plan') .t`Your account is using ${usedSpace} of storage, which exceeds the ${inviteSpace} you were allocated. Delete some data or ask the plan admin to increase your storage.`; } else if (errors.ExceedsAddresses) { errorDescription = c('familyOffer_2023:Family plan') .jt`Your account has more email addresses than what's available to you in this plan. ${addressSettingsLink}`; } else if (errors.ExceedsMaxAcceptedInvitations) { // translator: full sentence is: You can only accept 3 invitations in a 6-month period. Please contact <customer support> if you require an exception. errorDescription = c('familyOffer_2023:Family plan') .jt`You can only accept 3 invitations in a 6-month period. Please contact ${supportLink} if you require an exception.`; } else if (errors.IsOnForbiddenPlan) { errorDescription = c('familyOffer_2023:Family plan') .t`Your current plan cannot join a Visionary or family plan.`; } else if (errors.IsExternalUser) { errorDescription = c('familyOffer_2023:Family plan') .jt`Visionary and family plans do not currently support external accounts. Create a ${BRAND_NAME} address before joining. ${addressSettingsLink}`; } return ( <> {render && <BugModal email={user.Email} username={user.Name} {...bugReportModal} />} <div> <p className="color-danger text-bold m-0">{c('familyOffer_2023:Family plan') .t`Sorry, you can't switch plans at this time.`}</p> <p className="m-0">{errorDescription}</p> </div> </> ); }; export default PendingInvitationModalErrors;
6,757
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/PlanCard.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { PLANS } from '@proton/shared/lib/constants'; import { Currency, Cycle } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { Icon, Price, PrimaryButton } from '../../../components'; interface Base { planName: PLANS; planTitle: ReactNode; price: number | string; info: string; features: ReactNode; currency: Currency; cycle: Cycle; isCurrentPlan?: boolean; recommended?: boolean; canSelect?: boolean; actionLabel?: ReactNode; enableActionLabelSpacing?: boolean; } interface ActionElement { actionElement: ReactNode; } interface Action { action: string; onSelect: (planName: PLANS) => void; disabled?: boolean; } type Props = Base & Partial<ActionElement> & Partial<Action>; const getCycleUnit = (planName: PLANS) => { switch (planName) { case PLANS.FREE: return ''; case PLANS.MAIL_PRO: case PLANS.DRIVE_PRO: case PLANS.BUNDLE_PRO: case PLANS.ENTERPRISE: case PLANS.VPN_PRO: case PLANS.VPN_BUSINESS: return c('Cycle').t`/user per month`; default: return c('Cycle').t`/month`; } }; const PlanCard = ({ planName, planTitle, price, info, action, actionLabel, enableActionLabelSpacing, onSelect, features, currency, cycle, disabled, isCurrentPlan, recommended, actionElement, }: Props) => { const actionButton = (() => { if (actionElement) { return actionElement; } if (onSelect && action) { return ( <PrimaryButton onClick={() => onSelect(planName)} disabled={disabled} className="w-full" aria-describedby={`desc_${planName}`} data-testid={`select-${planName}`} > {action} </PrimaryButton> ); } return null; })(); return ( <> <div className={clsx([ 'border relative h-full plan-selection-plan p-6 pb-0 flex flex-column flex-nowrap', isCurrentPlan && 'plan-selection-plan-current-card', recommended && 'plan-selection-plan-recommended border-primary', ])} data-testid={planName} > {recommended ? ( <div className="plan-selection-plan-recommended-pill-container text-aligncenter flex"> <div className="plan-selection-plan-recommended-pill inline-flex mx-auto flex-items-align-center bg-primary py-1 px-3"> <Icon name="star-filled" className="my-auto" /> <span className="ml-1">{c('Title').t`Recommended`}</span> </div> </div> ) : null} <div className="flex flex-row flex-align-items-center"> <h2 className="h3 plan-selection-title flex text-bold text-capitalize mb-2" id={`desc_${planName}`}> {planTitle} </h2> </div> <p className="text-lg plan-selection-info text-left color-weak mb-4">{info}</p> <div className="mb-4 flex flex-wrap flex-align-items-baseline plan-selection-price"> {typeof price === 'number' ? ( <> <span className="mr-2"> <Price large currency={currency}> {price / cycle} </Price> </span> <span className="color-weak plan-selection-suffix">{getCycleUnit(planName)}</span> </> ) : ( <span className="mb-5"> <Price large className="mb-0.5"> {price} </Price> </span> )} </div> {actionButton} {actionLabel || enableActionLabelSpacing ? ( <div className="mb-1 plan-selection-spacing">{actionLabel}</div> ) : null} <div className="flex flex-column flex-nowrap flex-item-fluid-auto mt-2">{features}</div> </div> </> ); }; export default PlanCard;
6,758
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/PlanCardFeatures.tsx
import React from 'react'; import { c } from 'ttag'; import { PLANS } from '@proton/shared/lib/constants'; import { Audience } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { CalendarLogo, DriveLogo, Icon, IconSize, Info, MailLogo, PassLogo, VpnLogo } from '../../../components'; import { AllFeatures, getFeatureDefinitions } from '../features'; import { PlanCardFeatureDefinition, ShortPlan } from '../features/interface'; interface FeatureListProps { features: PlanCardFeatureDefinition[]; icon?: boolean; highlight?: boolean; margin?: boolean; odd?: boolean; tooltip?: boolean; iconSize?: IconSize; className?: string; itemClassName?: string; gapClassName?: string; } export const PlanCardFeatureList = ({ odd = true, features, icon, highlight = false, margin = true, tooltip = true, iconSize = 20, className, itemClassName, }: FeatureListProps) => { if (!features.length) { return null; } return ( <ul className={clsx( 'unstyled flex flex-column', className, odd && 'bg-weak-odd', margin ? 'mt-4 mb-0 md:mb-6' : 'm-0' )} > {features.map((feature) => { const iconToDisplay = (() => { if (feature.highlight && highlight) { return <Icon size={iconSize} name="fire" className="color-warning" />; } if (feature.included) { return ( <span className="color-success"> {icon && feature.icon ? ( <Icon size={iconSize} name={feature.icon} /> ) : ( <Icon size={iconSize} name="checkmark" /> )} </span> ); } return <Icon size={iconSize} name="cross" className="mt-0.5" />; })(); const key = typeof feature.text === 'string' ? feature.text : `${feature.tooltip}-${feature.highlight}-${feature.icon}`; return ( <li key={key} className={clsx(odd && 'px-3 py-2 rounded', itemClassName, 'flex')}> <div className={clsx( 'flex-no-min-children flex-nowrap', !feature.included && 'color-hint', feature.included && feature.status === 'coming-soon' && 'color-weak' )} > <span className={clsx('flex flex-item-noshrink', iconSize < 20 ? 'mr-1' : 'mr-3')}> {iconToDisplay} </span> <span className="flex-item-fluid text-left"> <span className="mr-2 align-middle">{feature.text}</span> {tooltip && feature.tooltip ? ( <Info url={feature.iconUrl} className="align-middle" title={feature.tooltip} colorPrimary={feature.included} /> ) : null} </span> </div> </li> ); })} </ul> ); }; interface Props { planName: PLANS; features: AllFeatures; audience: Audience; } const PlanCardFeatures = ({ planName, features, audience }: Props) => { const highlightFeatures = ( <div data-testid={planName}> <PlanCardFeatureList features={getFeatureDefinitions(planName, features.highlight, audience)} /> </div> ); const mailFeatures = ( <div data-testid={`${planName}-mail`}> <h3> <MailLogo /> </h3> <PlanCardFeatureList features={getFeatureDefinitions(planName, features.mail, audience)} /> </div> ); const calendarFeatures = ( <div data-testid={`${planName}-calendar`}> <h3> <CalendarLogo /> </h3> <PlanCardFeatureList features={getFeatureDefinitions(planName, features.calendar, audience)} /> </div> ); const driveFeatures = ( <div data-testid={`${planName}-drive`}> <h3> <DriveLogo /> </h3> <PlanCardFeatureList features={getFeatureDefinitions(planName, features.drive, audience)} /> </div> ); const passFeatures = ( <div data-testid={`${planName}-pass`}> <h3> <PassLogo /> </h3> <PlanCardFeatureList features={getFeatureDefinitions(planName, features.pass, audience)} /> </div> ); const vpnFeatures = ( <div data-testid={`${planName}-vpn`}> <h3> <VpnLogo /> </h3> <PlanCardFeatureList features={getFeatureDefinitions(planName, features.vpn, audience)} /> </div> ); const teamFeatures = audience === Audience.B2B && planName !== PLANS.FREE && ( <div> <h3 className="h4 text-bold">{c('new_plans: heading').t`Team management`}</h3> <PlanCardFeatureList features={getFeatureDefinitions(planName, features.team, audience)} /> </div> ); const supportFeatures = audience === Audience.B2B && planName !== PLANS.FREE && ( <div> <h3 className="h4 text-bold">{c('new_plans: heading').t`Support`}</h3> <PlanCardFeatureList features={getFeatureDefinitions(planName, features.support, audience)} /> </div> ); return ( <> {highlightFeatures} {mailFeatures} {calendarFeatures} {driveFeatures} {vpnFeatures} {passFeatures} {teamFeatures} {supportFeatures} </> ); }; interface PlanCardFeaturesShortProps { plan: ShortPlan; icon?: boolean; } export const PlanCardFeaturesShort = ({ plan, icon }: PlanCardFeaturesShortProps) => { const highlightFeatures = ( <div> <PlanCardFeatureList features={plan.features} icon={icon} /> </div> ); return <>{highlightFeatures}</>; }; export default PlanCardFeatures;
6,759
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/PlanCustomization.tsx
import { PLANS, PLAN_TYPES } from '@proton/shared/lib/constants'; import { Currency, Cycle, Organization, PlanIDs, PlansMap, Subscription } from '@proton/shared/lib/interfaces'; import ProtonPlanCustomizer, { CustomiserMode } from '../ProtonPlanCustomizer'; interface Props { loading: boolean; cycle: Cycle; currency: Currency; onChangePlanIDs: (planIDs: PlanIDs) => void; planIDs: PlanIDs; plansMap: PlansMap; mode?: CustomiserMode; organization?: Organization; forceHideDescriptions?: boolean; showUsersTooltip?: boolean; className?: string; currentSubscription?: Subscription; } const PlanCustomization = ({ mode, plansMap, planIDs, cycle, currency, onChangePlanIDs, loading, organization, forceHideDescriptions, ...rest }: Props) => { const [currentPlanName] = Object.entries(planIDs).find(([planName, planQuantity]) => { if (planQuantity) { const plan = plansMap[planName as keyof PlansMap]; return plan?.Type === PLAN_TYPES.PLAN; } return false; }) || []; const currentPlan = plansMap?.[currentPlanName as keyof PlansMap]; const hasPlanCustomiser = currentPlan && [ PLANS.MAIL_PRO, PLANS.DRIVE_PRO, PLANS.BUNDLE_PRO, PLANS.ENTERPRISE, PLANS.VPN_PRO, PLANS.VPN_BUSINESS, ].includes(currentPlan.Name as PLANS); return ( <> {currentPlan && hasPlanCustomiser && ( <ProtonPlanCustomizer mode={mode} loading={loading} cycle={cycle} currency={currency} planIDs={planIDs} plansMap={plansMap} currentPlan={currentPlan} organization={organization} onChangePlanIDs={onChangePlanIDs} forceHideDescriptions={forceHideDescriptions} {...rest} /> )} </> ); }; export default PlanCustomization;
6,760
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/PlanLossWarningModal.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Prompt, PromptProps } from '../../../components'; interface Props extends Omit<PromptProps, 'children' | 'title' | 'buttons'> { onConfirm: () => void; } export const NewVisionaryWarningModal = ({ onConfirm, type, ...rest }: Props & { type: 'downgrade' | 'switch' | 'delete' }) => { const visionary = 'Visionary'; const plan = 'visionary'; return ( <Prompt data-testid="confirm-loss-visionary" title={(() => { if (type === 'switch') { return c('new_plans: title').t`Switch plans?`; } if (type === 'delete') { return c('new_plans: title').t`Delete account?`; } if (type === 'downgrade') { return c('new_plans: title').t`Downgrade account?`; } return ''; })()} buttons={[ <Button color="norm" onClick={rest.onClose}> {(() => { if (type === 'switch') { return c('new_plans: action').t`Keep ${plan}`; } if (type === 'downgrade') { return c('new_plans: action').t`Keep account`; } if (type === 'delete') { return c('new_plans: action').t`Keep account`; } return ''; })()} </Button>, <Button data-testid="confirm-loss-btn" onClick={() => { onConfirm(); rest.onClose?.(); }} > {(() => { if (type === 'switch') { return c('new_plans: action').t`Switch plan`; } if (type === 'downgrade') { return c('new_plans: action').t`Downgrade account`; } if (type === 'delete') { return c('new_plans: action').t`Delete account`; } return ''; })()} </Button>, ]} {...rest} > {c('new_plans: info') .t`Our ${visionary} plan is no longer available to new subscribers as it is a special plan for original ${BRAND_NAME} users with special features and benefits.`}{' '} {(() => { if (type === 'switch') { return c('new_plans: info') .t`If you switch to a different plan, you lose all ${visionary} plan benefits and won’t be able to switch back to ${visionary}.`; } if (type === 'downgrade') { return c('new_plans: info') .t`If you downgrade your account, you lose all ${visionary} plan benefits and it won’t be available if you try to subscribe again.`; } if (type === 'delete') { return c('new_plans: info') .t`If you delete your account, you lose all ${visionary} plan benefits and it won’t be available if you create a new account.`; } })()}{' '} <Href href={getKnowledgeBaseUrl('/upgrading-to-new-proton-plan/#switch-from-visionary')}>{c('Info') .t`Learn more`}</Href> </Prompt> ); }; export const DiscountWarningModal = ({ onConfirm, type, ...rest }: Props & { type: 'downgrade' | 'delete' }) => { return ( <Prompt title={(() => { if (type === 'delete') { return c('new_plans: title').t`Delete account?`; } return c('new_plans: title').t`Downgrade account?`; })()} buttons={[ <Button color="norm" onClick={rest.onClose}> {(() => { if (type === 'delete') { return c('new_plans: action').t`Keep account`; } return c('new_plans: action').t`Keep account`; })()} </Button>, <Button onClick={() => { onConfirm(); rest.onClose?.(); }} > {(() => { if (type === 'delete') { return c('new_plans: action').t`Delete account`; } return c('new_plans: action').t`Downgrade account`; })()} </Button>, ]} {...rest} > {(() => { if (type === 'delete') { return c('new_plans: info') .t`You’re enjoying a promotional price on your current plan. If you delete your account, you will lose your promotional price and it won’t be available if you create a new account.`; } return c('new_plans: info') .t`You’re enjoying a promotional price on your current plan. If you downgrade your account, you will lose your promotional price and it won’t be available if you try to subscribe again.`; })()} </Prompt> ); };
6,761
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/PlanSelection.scss
@import '~@proton/styles/scss/lib'; /* * cycle selector */ @include media('<=#{em(1100, 16)}') { .cycle-currency-selectors { &.flex-nowrap { flex-wrap: wrap; > .flex-item-fluid { min-inline-size: 100%; margin-inline-start: 0; margin-block-end: 0.25em; } } } } .plan-selection { display: grid; grid-gap: 1.5em; grid-template-columns: repeat(var(--plan-selection-number, 4), 1fr); & &-plan { border-radius: var(--border-radius-lg); } // dirty, but to avoid inserting content in tabs &-currency-selector { margin-block-end: -2.5em; } &-suffix { min-block-size: rem(22); // just to keep elements aligned &:empty { @include media('<=small') { min-block-size: 0; } } @include media('<=#{em(1250, 16)}') { // to check with l10n issues min-inline-size: 100%; } } .plan-selection { &-plan-recommended { border-width: 2px; &-pill { &-container { position: absolute; inset-block-end: calc(100% - 1em); inset-inline: 0; } border-radius: 5em; } } &-title { .select { border: 0; padding: 0; display: inline-block; text-align: start; block-size: auto; background: transparent; svg { inline-size: rem(16); block-size: rem(16); } } } &-info { min-block-size: 6em; @include media('<=#{em(1100, 16)}') { min-block-size: 7em; } @include media('<=#{em(970, 16)}') { min-block-size: 8.5em; } @include media('<=medium') { min-block-size: 7em; } @include media('<=small') { min-block-size: 0; } } &-spacing { min-block-size: 5em; @include media('<=#{em(1100, 16)}') { min-block-size: 6em; } @include media('<=#{em(970, 16)}') { min-block-size: 7.5em; } @include media('<=medium') { min-block-size: 6em; } @include media('<=small') { min-block-size: 0; } } } @include media('<=medium') { grid-template-columns: repeat(2, 1fr); grid-gap: 2.2em 1em; } @include media('<=small') { grid-template-columns: repeat(1, 1fr); } // special case for b2b/family, put suffix on the line, not enough space &--b2b, &--family { .plan-selection-suffix { min-inline-size: 100%; } } &--family { // centering the 2 plans (free + family) on the large screens. Apply the usual rules on smaller screens. @include media('>=large') { // The variable here for the case if the free plan isn't displayed. In this case the only Family plan will be simply centered grid-template-columns: 0.25fr repeat(var(--plan-selection-number), 1fr) 0.25fr; .plan-selection-plan:first-child { grid-column-start: 2; } } } } .subscriptionCheckout { &-column { inline-size: rem(360); // as design request @include media('<=medium') { inline-size: rem(300); // to avoid left content shrinking too much } @include media('<=#{em(800, 16)}') { inline-size: 100%; // a bit earlier than mobile breakpoint, same reason as above } } @include media('<=#{em(800, 16)}') { &-container { position: static; } &-options { &, & .payment-container { max-inline-size: 100%; } } } @include media('>#{em(800, 16)}') { &-top-container { display: flex; flex-wrap: nowrap; } } } .lg-text-nowrap { @include media('>=small') { white-space: nowrap; } }
6,762
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/PlanSelection.test.tsx
import { ADDON_NAMES, CYCLE, PLANS } from '@proton/shared/lib/constants'; import { Plan } from '@proton/shared/lib/interfaces'; import { PLANS_MAP } from '@proton/testing/data'; import { getPrice } from './PlanSelection'; describe('getPrice', () => { it('should return null if the current plan does not have pricing for the celected cycle', () => { const plan = PLANS_MAP[PLANS.VPN_PRO] as Plan; expect(getPrice(plan, CYCLE.THIRTY, PLANS_MAP)).toBeNull(); }); it('should return cycle price for the current plan', () => { const plan = PLANS_MAP[PLANS.FAMILY] as Plan; expect(getPrice(plan, CYCLE.TWO_YEARS, PLANS_MAP)).toBe(plan.Pricing[CYCLE.TWO_YEARS]); }); it.each([ [PLANS.VPN_PRO, ADDON_NAMES.MEMBER_VPN_PRO], [PLANS.VPN_BUSINESS, ADDON_NAMES.MEMBER_VPN_BUSINESS], ])('should return member addon cycle price for the selected plans: %s', (planName, addonName) => { const plan = PLANS_MAP[planName] as Plan; const addon = PLANS_MAP[addonName] as Plan; expect(getPrice(plan, CYCLE.TWO_YEARS, PLANS_MAP)).toBe(addon.Pricing[CYCLE.TWO_YEARS]); }); it('should return the plan pricing if the addon is not available', () => { const plan = PLANS_MAP[PLANS.VPN_PRO] as Plan; const plansMap = { ...PLANS_MAP, [ADDON_NAMES.MEMBER_VPN_PRO]: undefined, }; expect(getPrice(plan, CYCLE.TWO_YEARS, plansMap)).toBe(plan.Pricing[CYCLE.TWO_YEARS]); }); });
6,763
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/PlanSelection.tsx
import { ReactElement } from 'react'; import { c } from 'ttag'; import { ProductParam } from '@proton/shared/lib/apps/product'; import { ADDON_NAMES, APPS, CYCLE, PLANS, PLAN_TYPES } from '@proton/shared/lib/constants'; import { switchPlan } from '@proton/shared/lib/helpers/planIDs'; import { getIpPricePerMonth } from '@proton/shared/lib/helpers/subscription'; import { Audience, Currency, Cycle, Organization, Plan, PlanIDs, PlansMap, Subscription, VPNServersCountData, } from '@proton/shared/lib/interfaces'; import { FREE_PLAN } from '@proton/shared/lib/subscription/freePlans'; import isTruthy from '@proton/utils/isTruthy'; import { CalendarLogo, DriveLogo, Icon, MailLogo, Option, PassLogo, Price, SelectTwo, Tabs, VpnLogo, } from '../../../components'; import CurrencySelector from '../CurrencySelector'; import CycleSelector from '../CycleSelector'; import { getAllFeatures } from '../features'; import { ShortPlanLike, isShortPlanLike } from '../features/interface'; import { getShortPlan, getVPNEnterprisePlan } from '../features/plan'; import PlanCard from './PlanCard'; import PlanCardFeatures, { PlanCardFeatureList, PlanCardFeaturesShort } from './PlanCardFeatures'; import VpnEnterpriseAction from './helpers/VpnEnterpriseAction'; import './PlanSelection.scss'; export interface SelectedProductPlans { [Audience.B2C]: PLANS; [Audience.B2B]: PLANS; [Audience.FAMILY]: PLANS; } const getPlansList = (enabledProductPlans: PLANS[], plansMap: PlansMap) => { return enabledProductPlans .map((planName) => { const plan = plansMap[planName]; if (plan) { return { planName, label: plan.Title, }; } }) .filter(isTruthy); }; const getPlanPanel = (enabledProductPlans: PLANS[], planName: PLANS, plansMap: PlansMap) => { if (enabledProductPlans.includes(planName)) { return plansMap[planName]; } }; interface Tab { title: string; content: ReactElement; audience: Audience; } interface Props { app: ProductParam; planIDs: PlanIDs; currency: Currency; hasPlanSelectionComparison?: boolean; hasFreePlan?: boolean; cycle: Cycle; plans: Plan[]; plansMap: PlansMap; vpnServers: VPNServersCountData; loading?: boolean; mode: 'signup' | 'settings' | 'modal'; onChangePlanIDs: (newPlanIDs: PlanIDs) => void; onChangeCurrency: (newCurrency: Currency) => void; onChangeCycle: (newCyle: Cycle) => void; audience: Audience; onChangeAudience: (newAudience: Audience) => void; selectedProductPlans: SelectedProductPlans; onChangeSelectedProductPlans: (newPlans: SelectedProductPlans) => void; subscription?: Subscription; organization?: Organization; calendarSharingEnabled: boolean; sentinelPassplusEnabled: boolean; filter?: Audience[]; } export const getPrice = (plan: Plan, cycle: Cycle, plansMap: PlansMap): number | null => { const price = plan.Pricing[cycle]; if (price === undefined) { return null; } const plansThatMustUseAddonPricing = { [PLANS.VPN_PRO]: ADDON_NAMES.MEMBER_VPN_PRO, [PLANS.VPN_BUSINESS]: ADDON_NAMES.MEMBER_VPN_BUSINESS, }; type PlanWithAddon = keyof typeof plansThatMustUseAddonPricing; // If the current plan is one of those that must use addon pricing, // then we find the matching addon object and return its price for (const planWithAddon of Object.keys(plansThatMustUseAddonPricing) as PlanWithAddon[]) { if (plan.Name !== planWithAddon) { continue; } const addonName = plansThatMustUseAddonPricing[planWithAddon]; const memberAddon = plansMap[addonName]; const memberPrice = memberAddon?.Pricing[cycle]; if (memberPrice === undefined) { continue; } return memberPrice; } return price; }; const ActionLabel = ({ plan, currency, cycle }: { plan: Plan; currency: Currency; cycle: Cycle }) => { const serverPrice = <Price currency={currency}>{getIpPricePerMonth(cycle)}</Price>; // translator: example of full sentence: "VPN Business requires at least 1 dedicated server (CHF 39.99 /month)" const serverPriceStr = c('Info').jt`(${serverPrice} /month)`; const serverPricePerMonth = <span className="text-nowrap">{serverPriceStr}</span>; return ( <div className="mt-6 flex flex-nowrap color-weak"> <div className="flex-item-noshrink mr-2"> <Icon name="info-circle" /> </div> <div>{c('Info').jt`${plan.Title} requires at least 1 dedicated server ${serverPricePerMonth}`}</div> </div> ); }; const PlanSelection = ({ app, mode, hasFreePlan = true, planIDs, plans, plansMap, vpnServers, cycle, currency, loading, subscription, organization, onChangePlanIDs, onChangeCurrency, onChangeCycle, audience, onChangeAudience, selectedProductPlans, onChangeSelectedProductPlans, calendarSharingEnabled, sentinelPassplusEnabled, filter, }: Props) => { const isVpnSettingsApp = app == APPS.PROTONVPN_SETTINGS; const currentPlan = subscription ? subscription.Plans?.find(({ Type }) => Type === PLAN_TYPES.PLAN) : null; const enabledProductB2CPlans = [PLANS.MAIL, PLANS.VPN, PLANS.DRIVE, PLANS.PASS_PLUS].filter(isTruthy); const enabledProductB2BPlans = [PLANS.MAIL_PRO /*, PLANS.DRIVE_PRO*/]; const B2CPlans = [ hasFreePlan ? FREE_PLAN : null, getPlanPanel(enabledProductB2CPlans, selectedProductPlans[Audience.B2C], plansMap) || plansMap[PLANS.MAIL], plansMap[PLANS.BUNDLE], ].filter(isTruthy); const FamilyPlans = [hasFreePlan ? FREE_PLAN : null, plansMap[PLANS.FAMILY]].filter(isTruthy); const vpnB2BPlans = [ plansMap[PLANS.VPN_PRO], plansMap[PLANS.VPN_BUSINESS], getVPNEnterprisePlan(vpnServers), ].filter(isTruthy); let B2BPlans: (Plan | ShortPlanLike)[] = []; /** * The VPN B2B plans should be displayed only in the ProtonVPN Settings app (protonvpn.com). * * The check for length of plans is needed for the case if the VPN B2B plans are not available. * Then we should fallback to the usual set of plans. It can happen if backend doesn't return the VPN B2B plans. */ const isVpnB2bPlans = isVpnSettingsApp && vpnB2BPlans.length !== 0; if (isVpnB2bPlans) { B2BPlans = vpnB2BPlans; } else { B2BPlans = [ hasFreePlan ? FREE_PLAN : null, getPlanPanel(enabledProductB2BPlans, selectedProductPlans[Audience.B2B], plansMap) || plansMap[PLANS.MAIL_PRO], plansMap[PLANS.BUNDLE_PRO], ].filter(isTruthy); } const isSignupMode = mode === 'signup'; const features = getAllFeatures({ plansMap, serversCount: vpnServers, calendarSharingEnabled, sentinelPassplusEnabled, }); const plansListB2C = getPlansList(enabledProductB2CPlans, plansMap); const recommendedPlans = [PLANS.BUNDLE, PLANS.BUNDLE_PRO, PLANS.FAMILY]; const renderPlanCard = (plan: Plan, audience: Audience) => { const isFree = plan.ID === PLANS.FREE; const isCurrentPlan = isFree ? !currentPlan : currentPlan?.ID === plan.ID; const isRecommended = recommendedPlans.includes(plan.Name as PLANS); const shortPlan = getShortPlan(plan.Name as PLANS, plansMap, { vpnServers, sentinelPassplusEnabled }); if (!shortPlan) { return null; } const planTitle = shortPlan.title; const selectedPlanLabel = isFree ? c('Action').t`Current plan` : c('Action').t`Edit subscription`; const action = isCurrentPlan ? selectedPlanLabel : c('Action').t`Select ${planTitle}`; const actionLabel = plan.Name === PLANS.VPN_BUSINESS ? <ActionLabel plan={plan} currency={currency} cycle={cycle} /> : null; const plansList = audience === Audience.B2C ? plansListB2C : []; const isSelectable = plansList.some(({ planName: otherPlanName }) => otherPlanName === plan.Name); const selectedPlan = plansList.some( ({ planName: otherPlanName }) => otherPlanName === selectedProductPlans[audience] ) ? selectedProductPlans[audience] : plansList[0]?.planName; const price = getPrice(plan, cycle, plansMap); if (price === null) { return null; } const featuresElement = mode === 'settings' || (audience === Audience.B2B && isVpnSettingsApp) ? ( <PlanCardFeaturesShort plan={shortPlan} icon /> ) : ( <PlanCardFeatures audience={audience} features={features} planName={plan.Name as PLANS} /> ); return ( <PlanCard isCurrentPlan={!isSignupMode && isCurrentPlan} action={action} actionLabel={actionLabel} enableActionLabelSpacing={isVpnB2bPlans && audience === Audience.B2B} info={shortPlan.description} planName={plan.Name as PLANS} planTitle={ plansList && isSelectable ? ( <SelectTwo value={selectedPlan} onChange={({ value: newPlanName }) => { onChangeSelectedProductPlans({ ...selectedProductPlans, [audience]: newPlanName }); }} > {plansList.map(({ planName, label }) => ( <Option key={label} value={planName} title={label}> {label} </Option> ))} </SelectTwo> ) : ( planTitle ) } recommended={isRecommended} currency={currency} disabled={loading || (isFree && !isSignupMode && isCurrentPlan)} cycle={cycle} key={plan.ID} price={price} features={featuresElement} onSelect={(planName) => { onChangePlanIDs( switchPlan({ planIDs, planID: isFree ? undefined : planName, organization, plans, }) ); }} /> ); }; const renderShortPlanCard = (plan: ShortPlanLike) => { return ( // this render contains some assumptions that are valid only because we currently have the only UI plan. // If we get more later, then this code must be generalized. Examples: "Let's talk" price might be // different, so is the actionElement. <PlanCard isCurrentPlan={false} actionElement={<VpnEnterpriseAction />} enableActionLabelSpacing={isVpnB2bPlans && audience === Audience.B2B} info={plan.description} planName={plan.plan as any} planTitle={plan.title} recommended={false} currency={currency} cycle={cycle} key={plan.plan} price={ // translator: displayed instead of price for VPN Enterprise plan. User should contact Sales first. c('Action').t`Let's talk` } features={<PlanCardFeatureList features={plan.features} icon />} /> ); }; const tabs: Tab[] = [ { title: c('Tab subscription modal').t`For individuals`, content: ( <div className="plan-selection plan-selection--b2c mt-4" style={{ '--plan-selection-number': B2CPlans.length }} data-testid="b2c-plan" > {B2CPlans.map((plan) => renderPlanCard(plan, Audience.B2C))} </div> ), audience: Audience.B2C, }, { title: c('Tab subscription modal').t`For families`, content: ( <div className="plan-selection plan-selection--family mt-4" style={{ '--plan-selection-number': FamilyPlans.length }} > {FamilyPlans.map((plan) => renderPlanCard(plan, Audience.FAMILY))} </div> ), audience: Audience.FAMILY, }, { title: c('Tab subscription modal').t`For businesses`, content: ( <div className="plan-selection plan-selection--b2b mt-4" style={{ '--plan-selection-number': B2BPlans.length }} data-testid="b2b-plan" > {B2BPlans.map((plan) => { if (isShortPlanLike(plan)) { return renderShortPlanCard(plan); } else { return renderPlanCard(plan, Audience.B2B); } })} </div> ), audience: Audience.B2B, }, ].filter((tab): tab is Tab => { if (!tab) { return false; } return filter?.includes(tab.audience) ?? true; }); const currencyItem = ( <CurrencySelector mode="select-two" currency={currency} onSelect={onChangeCurrency} disabled={loading} /> ); const currencySelectorRow = ( <div className="flex flex-justify-space-between on-mobile-flex-column-nostretch"> <div className="hidden md:inline-block visibility-hidden">{currencyItem}</div> <div className="flex on-mobile-flex on-mobile-flex-justify-center w-full md:w-auto"> <CycleSelector mode="buttons" cycle={cycle} onSelect={onChangeCycle} disabled={loading} options={[ { text: c('Billing cycle option').t`1 month`, value: CYCLE.MONTHLY }, { text: c('Billing cycle option').t`12 months`, value: CYCLE.YEARLY }, { text: c('Billing cycle option').t`24 months`, value: CYCLE.TWO_YEARS }, ]} /> </div> <div className="flex mx-auto md:mx-0 mt-4 md:mt-0">{currencyItem}</div> </div> ); const logosRow = ( <div className="my-6 flex flex-justify-center flex-nowrap flex-align-items-center color-weak"> <MailLogo variant="glyph-only" /> <Icon name="plus" alt="+" className="mx-2" /> <CalendarLogo variant="glyph-only" /> <Icon name="plus" alt="+" className="mx-2" /> <DriveLogo variant="glyph-only" /> <Icon name="plus" alt="+" className="mx-2" /> <VpnLogo variant="glyph-only" /> <Icon name="plus" alt="+" className="mx-2" /> <PassLogo variant="glyph-only" /> </div> ); const tabNumberToAudience = (tabNumber: number): Audience => { return tabs[tabNumber].audience ?? Audience.B2C; }; const audienceToTabNumber = (audience: Audience): number => { const tabIndex = tabs.findIndex((tab) => tab.audience === audience); return tabIndex !== -1 ? tabIndex : 0; }; return ( <> <div className="mb-6"> <Tabs value={audienceToTabNumber(audience)} onChange={(tabNumber) => onChangeAudience(tabNumberToAudience(tabNumber))} tabs={tabs} fullWidth={true} containerClassName="inline-block" navContainerClassName="text-center lg-text-nowrap" gap={ mode === 'settings' ? ( <> {logosRow} {currencySelectorRow} </> ) : ( <div className="mt-6">{currencySelectorRow}</div> ) } /> </div> </> ); }; export default PlanSelection;
6,764
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionCancelPlan.scss
@import '~@proton/styles/scss/lib'; .subscription-cancel-plan { &-info { min-block-size: 4em; @include media('<=small') { min-block-size: unset; } } }
6,765
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionCancelPlan.tsx
import clsx from '@proton/utils/clsx'; import { Icon, Info } from '../../../components'; import { PlanCardFeatureDefinition } from '../features/interface'; import './SubscriptionCancelPlan.scss'; interface Props { name: string; info: string; features: PlanCardFeatureDefinition[]; downgrade?: boolean; } const SubscriptionCancelPlan = ({ name, info, features, downgrade = false }: Props) => { return ( <div className="pr-0 py-4 md:pr-4 flex-item-fluid"> <h3 className="text-bold text-capitalize mb-2" id={`desc_${name}`}> {name} </h3> <p className="text-lg subscription-cancel-plan-info">{info}</p> {features.length ? ( <ul className="unstyled mt-4"> {features.map((feature) => { const key = typeof feature.text === 'string' ? feature.text : `${feature.tooltip}-${feature.icon}-${feature.included}-${feature.status}`; return ( <li key={key} className="flex flex-nowrap mb-2"> <span className={clsx('flex-item-noshrink mr-4', downgrade && 'color-weak')}> {downgrade ? '-' : <Icon name="checkmark" className="color-primary" />} </span> <span className="flex-item-fluid"> <span className={clsx( 'align-middle', downgrade && 'text-strike color-weak', !downgrade && feature.status === 'coming-soon' && 'color-weak' )} > {feature.text} </span> {feature.tooltip ? ( <Info buttonClass="align-middle ml-2" title={feature.tooltip} /> ) : null} </span> </li> ); })} </ul> ) : null} </div> ); }; export default SubscriptionCancelPlan;
6,766
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionContainer.scss
@import '~@proton/styles/scss/lib'; .subscription-modal { &--large-width { --size: #{rem(1200)}; --margin: #{rem(32)}; } &--medium-width { --size: #{rem(900)}; --margin: #{rem(24)}; } } @include media('>medium') { // Set height to avoid it switching between steps .subscription-modal--fixed-height { block-size: rem(900); } }
6,767
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionContainer.test.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import { defaultSubscriptionCache, mockOrganizationApi, mockPlansCache, mockSubscriptionCache, mockUserCache, mockUserVPNServersCountApi, organizationDefaultResponse, plansDefaultResponse, } from '@proton/components/hooks/helpers/test'; import { createToken, subscribe } from '@proton/shared/lib/api/payments'; import { ADDON_NAMES, PLANS } from '@proton/shared/lib/constants'; import { Audience, Organization, Plan } from '@proton/shared/lib/interfaces'; import { apiMock, applyHOCs, withApi, withAuthentication, withCache, withConfig, withDeprecatedModals, withEventManager, withFeatures, withNotifications, } from '@proton/testing/index'; import SubscriptionContainer, { SubscriptionContainerProps } from './SubscriptionContainer'; import { SUBSCRIPTION_STEPS } from './constants'; jest.mock('@proton/components/components/portal/Portal'); const ContextSubscriptionContainer = applyHOCs( withConfig(), withNotifications(), withEventManager(), withApi(), withCache(), withDeprecatedModals(), withFeatures(), withAuthentication() )(SubscriptionContainer); describe('SubscriptionContainer', () => { let props: SubscriptionContainerProps; beforeEach(() => { jest.clearAllMocks(); mockUserCache(); mockPlansCache(); mockSubscriptionCache(); mockUserVPNServersCountApi(); mockOrganizationApi(); }); beforeEach(() => { props = { app: 'proton-mail', defaultSelectedProductPlans: { [Audience.B2C]: PLANS.MAIL, [Audience.B2B]: PLANS.MAIL_PRO, [Audience.FAMILY]: PLANS.FAMILY, }, metrics: { source: 'dashboard', }, render: ({ onSubmit, title, content, footer }) => { return ( <form onSubmit={onSubmit}> <div>{title}</div> <div>{content}</div> <div>{footer}</div> </form> ); }, subscription: defaultSubscriptionCache, organization: organizationDefaultResponse.Organization as any as Organization, plans: plansDefaultResponse.Plans as any as Plan[], }; }); it('should render', () => { const { container } = render(<ContextSubscriptionContainer {...props} />); expect(container).not.toBeEmptyDOMElement(); }); it('should redirect user without supported addons directly to checkout step', async () => { props.step = SUBSCRIPTION_STEPS.CUSTOMIZATION; const { container } = render(<ContextSubscriptionContainer {...props} />); await waitFor(() => { expect(container).toHaveTextContent('Review subscription and pay'); }); // that's text from one of the branches of <Payment> component // depending on the specific test setup, you might need to change this text in the test. // The key idea is to ensure that the Payment component was rendered, and no matter what's exactly inside. // I could mock the Payment component, but I wanted to test the whole flow. await waitFor(() => { expect(container).toHaveTextContent('The minimum payment we accept is'); }); }); it('should render customization step', async () => { props.step = SUBSCRIPTION_STEPS.CUSTOMIZATION; props.planIDs = { [PLANS.MAIL_PRO]: 1, }; const { container } = render(<ContextSubscriptionContainer {...props} />); await waitFor(() => { expect(container).toHaveTextContent('Customize your plan'); }); }); it('should not proceed to the checkout step after customization if there was a check error', async () => { props.step = SUBSCRIPTION_STEPS.CUSTOMIZATION; props.planIDs = { [PLANS.MAIL_PRO]: 1, [ADDON_NAMES.MEMBER]: 329 }; // user with 330 users in the organization const { findByTestId, container } = render(<ContextSubscriptionContainer {...props} />); const continueButton = await findByTestId('continue-to-review'); apiMock.mockClear(); apiMock.mockRejectedValueOnce(new Error()); fireEvent.click(continueButton); await waitFor(() => {}); expect(apiMock).toHaveBeenCalledTimes(1); expect(container).toHaveTextContent('Customize your plan'); }); it.skip('should not create payment token if the amount is 0', async () => { props.step = SUBSCRIPTION_STEPS.CHECKOUT; props.planIDs = { mail2022: 1 }; const { container } = render(<ContextSubscriptionContainer {...props} />); let form: HTMLFormElement | null = null; await waitFor(() => { form = container.querySelector('form'); expect(form).not.toBeEmptyDOMElement(); }); if (!form) { throw new Error('Form not found'); } fireEvent.submit(form); const createTokenUrl = createToken({} as any).url; const subscribeUrl = subscribe({} as any, '' as any).url; await waitFor(() => {}); expect(apiMock).not.toHaveBeenCalledWith(expect.objectContaining({ url: createTokenUrl })); await waitFor(() => { expect(apiMock).toHaveBeenCalledWith( expect.objectContaining({ url: subscribeUrl, data: expect.objectContaining({ Amount: 0, }), }) ); }); }); });
6,768
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionContainer.tsx
import { FormEvent, ReactNode, RefObject, useEffect, useMemo, useRef, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getSimplePriceString } from '@proton/components/components/price/helper'; import { FeatureCode, useFlag } from '@proton/components/containers'; import { getShortBillingText } from '@proton/components/containers/payments/helper'; import VPNPassPromotionButton from '@proton/components/containers/payments/subscription/VPNPassPromotionButton'; import { usePaymentFacade } from '@proton/components/payments/client-extensions'; import { PAYMENT_METHOD_TYPES } from '@proton/components/payments/core'; import { Operations, OperationsSubscriptionData } from '@proton/components/payments/react-extensions'; import { PaymentProcessorHook } from '@proton/components/payments/react-extensions/interface'; import { useLoading } from '@proton/hooks'; import metrics, { observeApiError } from '@proton/metrics'; import { WebPaymentsSubscriptionStepsTotal } from '@proton/metrics/types/web_payments_subscription_steps_total_v1.schema'; import { subscribe as apiSubscribe, checkSubscription, deleteSubscription } from '@proton/shared/lib/api/payments'; import { ProductParam } from '@proton/shared/lib/apps/product'; import { getShouldCalendarPreventSubscripitionChange, willHavePaidMail } from '@proton/shared/lib/calendar/plans'; import { APPS, COUPON_CODES, DEFAULT_CURRENCY, DEFAULT_CYCLE, PASS_APP_NAME, PLANS, PLAN_TYPES, isFreeSubscription, } from '@proton/shared/lib/constants'; import { API_CUSTOM_ERROR_CODES } from '@proton/shared/lib/errors'; import { canUpsellToVPNPassBundle } from '@proton/shared/lib/helpers/blackfriday'; import { getCheckout, getIsCustomCycle, getOptimisticCheckResult } from '@proton/shared/lib/helpers/checkout'; import { toMap } from '@proton/shared/lib/helpers/object'; import { hasBonuses } from '@proton/shared/lib/helpers/organization'; import { getPlanFromCheckout, hasPlanIDs, supportAddons, switchPlan } from '@proton/shared/lib/helpers/planIDs'; import { captureMessage } from '@proton/shared/lib/helpers/sentry'; import { getHasB2BPlan, getHasVpnB2BPlan, getIsB2BPlan, getNormalCycleFromCustomCycle, getPlanIDs, hasMigrationDiscount, hasNewVisionary, hasPassPlus, hasVPN, hasVPNPassBundle, } from '@proton/shared/lib/helpers/subscription'; import { Audience, Currency, Cycle, Organization, Plan, PlanIDs, Renew, SubscriptionCheckResponse, SubscriptionModel, } from '@proton/shared/lib/interfaces'; import { getSentryError } from '@proton/shared/lib/keys'; import { getFreeCheckResult } from '@proton/shared/lib/subscription/freePlans'; import { hasPaidMail } from '@proton/shared/lib/user/helpers'; import debounce from '@proton/utils/debounce'; import isTruthy from '@proton/utils/isTruthy'; import { Icon, Tooltip } from '../../../components'; import { useApi, useConfig, useEventManager, useFeature, useGetCalendars, useModals, useNotifications, useUser, useVPNServersCount, } from '../../../hooks'; import GenericError from '../../error/GenericError'; import LossLoyaltyModal from '../LossLoyaltyModal'; import MemberDowngradeModal from '../MemberDowngradeModal'; import PaymentGiftCode from '../PaymentGiftCode'; import PaymentWrapper from '../PaymentWrapper'; import { ValidatedBitcoinToken, isValidatedBitcoinToken } from '../useBitcoin'; import CalendarDowngradeModal from './CalendarDowngradeModal'; import PlanCustomization from './PlanCustomization'; import { DiscountWarningModal, NewVisionaryWarningModal } from './PlanLossWarningModal'; import PlanSelection from './PlanSelection'; import SubscriptionCycleSelector, { SubscriptionItemView, getDiscountPrice, getMonthlySuffix, } from './SubscriptionCycleSelector'; import SubscriptionSubmitButton from './SubscriptionSubmitButton'; import { useCancelSubscriptionFlow } from './cancelSubscription'; import { SUBSCRIPTION_STEPS } from './constants'; import { SelectedProductPlans, getCurrency, getDefaultSelectedProductPlans } from './helpers'; import SubscriptionCheckout from './modal-components/SubscriptionCheckout'; import SubscriptionThanks from './modal-components/SubscriptionThanks'; import { useCheckoutModifiers } from './useCheckoutModifiers'; import './SubscriptionContainer.scss'; type Source = WebPaymentsSubscriptionStepsTotal['Labels']['source']; type FromPlan = WebPaymentsSubscriptionStepsTotal['Labels']['fromPlan']; type MetricsStep = WebPaymentsSubscriptionStepsTotal['Labels']['step']; export interface Model { step: SUBSCRIPTION_STEPS; planIDs: PlanIDs; currency: Currency; cycle: Cycle; coupon?: string | null; gift?: string; initialCheckComplete: boolean; } const BACK: Partial<{ [key in SUBSCRIPTION_STEPS]: SUBSCRIPTION_STEPS }> = { [SUBSCRIPTION_STEPS.CUSTOMIZATION]: SUBSCRIPTION_STEPS.PLAN_SELECTION, [SUBSCRIPTION_STEPS.CHECKOUT]: SUBSCRIPTION_STEPS.CUSTOMIZATION, }; const getCodes = ({ gift, coupon }: Model): string[] => [gift, coupon].filter(isTruthy); interface RenderProps { title: string; content: ReactNode; footer?: ReactNode; onSubmit: (e: FormEvent) => void; step: SUBSCRIPTION_STEPS; } export interface SubscriptionContainerProps { topRef?: RefObject<HTMLDivElement>; app: ProductParam; step?: SUBSCRIPTION_STEPS; cycle?: Cycle; currency?: Currency; plan?: PLANS; planIDs?: PlanIDs; coupon?: string | null; disablePlanSelection?: boolean; disableThanksStep?: boolean; defaultAudience?: Audience; disableCycleSelector?: boolean; defaultSelectedProductPlans?: SelectedProductPlans; onSubscribed?: () => void; onUnsubscribed?: () => void; onCancel?: () => void; onCheck?: ( data: | { model: Model; newModel: Model; type: 'error'; error: any } | { model: Model; newModel: Model; type: 'success'; result: SubscriptionCheckResponse } ) => void; metrics: { source: Source; }; render: (renderProps: RenderProps) => ReactNode; subscription: SubscriptionModel; organization: Organization; plans: Plan[]; } const SubscriptionContainer = ({ topRef: customTopRef, app, step: maybeStep, cycle: maybeCycle, currency: maybeCurrency, coupon: maybeCoupon, plan, planIDs: maybePlanIDs, onSubscribed, onUnsubscribed, onCancel, onCheck, disablePlanSelection, disableCycleSelector: maybeDisableCycleSelector, disableThanksStep, defaultAudience = Audience.B2C, defaultSelectedProductPlans, metrics: outerMetricsProps, render, subscription, organization, plans, }: SubscriptionContainerProps) => { const TITLE = { [SUBSCRIPTION_STEPS.NETWORK_ERROR]: c('Title').t`Network error`, [SUBSCRIPTION_STEPS.PLAN_SELECTION]: c('Title').t`Select a plan`, [SUBSCRIPTION_STEPS.CUSTOMIZATION]: c('Title').t`Customize your plan`, [SUBSCRIPTION_STEPS.CHECKOUT]: c('new_plans: title').t`Review subscription and pay`, [SUBSCRIPTION_STEPS.UPGRADE]: '', [SUBSCRIPTION_STEPS.THANKS]: '', [SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION]: c('new_plans: title').t`Review subscription and pay`, }; const metricStepMap: Record<SUBSCRIPTION_STEPS, MetricsStep> = { [SUBSCRIPTION_STEPS.NETWORK_ERROR]: 'network-error', [SUBSCRIPTION_STEPS.PLAN_SELECTION]: 'plan-selection', [SUBSCRIPTION_STEPS.CUSTOMIZATION]: 'customization', [SUBSCRIPTION_STEPS.CHECKOUT]: 'checkout', [SUBSCRIPTION_STEPS.UPGRADE]: 'upgrade', [SUBSCRIPTION_STEPS.THANKS]: 'thanks', [SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION]: 'checkout-with-customization', }; const topRef = useRef<HTMLDivElement>(null); const api = useApi(); const [user] = useUser(); const { call } = useEventManager(); const { createModal } = useModals(); const { createNotification } = useNotifications(); const { cancelSubscriptionModals, cancelSubscription } = useCancelSubscriptionFlow({ subscription, user, }); const plansMap = toMap(plans, 'Name'); const [vpnServers] = useVPNServersCount(); const getCalendars = useGetCalendars(); const calendarSharingEnabled = !!useFeature(FeatureCode.CalendarSharingEnabled).feature?.Value; const sentinelPassplusEnabled = !!useFlag('SentinelPassPlus'); const { APP_NAME } = useConfig(); const [loading, withLoading] = useLoading(); const [loadingCheck, withLoadingCheck] = useLoading(); const [blockCycleSelector, withBlockCycleSelector] = useLoading(); const [blockAccountSizeSelector, withBlockAccountSizeSelector] = useLoading(); const [loadingGift, withLoadingGift] = useLoading(); const [checkResult, setCheckResult] = useState<SubscriptionCheckResponse>(); const [audience, setAudience] = useState(() => { if ((plan && getIsB2BPlan(plan)) || getHasB2BPlan(subscription)) { return Audience.B2B; } return defaultAudience; }); const planIDs = useMemo(() => { const subscriptionPlanIDs = getPlanIDs(subscription); if (plan) { return switchPlan({ planIDs: subscriptionPlanIDs, planID: plansMap[plan].Name, organization, plans, }); } return maybePlanIDs || subscriptionPlanIDs; }, [subscription, plansMap, organization, plans, maybePlanIDs]); const coupon = maybeCoupon || subscription.CouponCode || undefined; const [selectedProductPlans, setSelectedProductPlans] = useState( defaultSelectedProductPlans || getDefaultSelectedProductPlans(app, planIDs) ); const [model, setModel] = useState<Model>(() => { const step = (() => { // Users with VPN B2B plans must not have access to the checkout step. if (getHasVpnB2BPlan(subscription) && maybeStep === SUBSCRIPTION_STEPS.CHECKOUT) { return SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION; } return maybeStep ?? SUBSCRIPTION_STEPS.PLAN_SELECTION; })(); const cycle = (() => { if (maybeCycle) { return maybeCycle; } if (disablePlanSelection) { return subscription.Cycle || DEFAULT_CYCLE; } /** * Users that are on the 15 or 30-month cycle should not default to that, * e.g. when clicking "explore other plans" * */ return getNormalCycleFromCustomCycle(subscription.Cycle) || DEFAULT_CYCLE; })(); const currency = (() => { if (maybeCurrency) { return maybeCurrency; } return getCurrency(user, subscription, plans); })(); return { step, cycle, currency, coupon, planIDs, initialCheckComplete: false, }; }); const isVpnB2bPlan = !!model.planIDs[PLANS.VPN_PRO] || !!model.planIDs[PLANS.VPN_BUSINESS]; const [bitcoinValidated, setBitcoinValidated] = useState(false); const [awaitingBitcoinPayment, setAwaitingBitcoinPayment] = useState(false); const application = useMemo(() => { if (APP_NAME === APPS.PROTONVPN_SETTINGS) { return APPS.PROTONVPN_SETTINGS; } if (APP_NAME === APPS.PROTONACCOUNTLITE) { return APPS.PROTONACCOUNTLITE; } return APPS.PROTONACCOUNT; }, [APP_NAME]); const metricsProps = { ...outerMetricsProps, step: metricStepMap[model.step], fromPlan: isFreeSubscription(subscription) ? 'free' : ('paid' as FromPlan), application, }; const checkoutModifiers = useCheckoutModifiers(model, subscription, plansMap, checkResult); const amountDue = checkResult?.AmountDue || 0; const couponCode = checkResult?.Coupon?.Code; const couponDescription = checkResult?.Coupon?.Description; const creditsRemaining = (user.Credit + (checkResult?.Credit ?? 0)) / 100; const subscriptionCouponCode = subscription?.CouponCode; const latestValidCouponCodeRef = useRef(''); const giftCodeRef = useRef<HTMLInputElement>(null); const abortControllerRef = useRef<AbortController>(); const amount = model.step === SUBSCRIPTION_STEPS.CHECKOUT || model.step === SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION ? amountDue : 0; const currency = checkResult?.Currency || DEFAULT_CURRENCY; const handleUnsubscribe = async () => { if (hasVPN(subscription) || hasVPNPassBundle(subscription)) { if (subscription.Renew === Renew.Disabled) { onUnsubscribed?.(); return; } await cancelSubscription(); onUnsubscribed?.(); return; } // Start promise early const shouldCalendarPreventDowngradePromise = getShouldCalendarPreventSubscripitionChange({ hasPaidMail: hasPaidMail(user), willHavePaidMail: false, api, getCalendars, }); if (hasMigrationDiscount(subscription)) { await new Promise<void>((resolve, reject) => { createModal(<DiscountWarningModal type="downgrade" onClose={reject} onConfirm={resolve} />); }); } if (await shouldCalendarPreventDowngradePromise) { await new Promise<void>((resolve, reject) => { createModal(<CalendarDowngradeModal isDowngrade onConfirm={resolve} onClose={reject} />); }); } if (hasBonuses(organization)) { await new Promise<void>((resolve, reject) => { createModal(<LossLoyaltyModal organization={organization} onConfirm={resolve} onClose={reject} />); }); } if (organization.UsedMembers > 1) { await new Promise<void>((resolve, reject) => { createModal(<MemberDowngradeModal organization={organization} onConfirm={resolve} onClose={reject} />); }); } await api(deleteSubscription({})); await call(); onUnsubscribed?.(); createNotification({ text: c('Success').t`You have successfully unsubscribed` }); }; const handlePlanWarnings = async (planIDs: PlanIDs) => { const newPlanName = Object.keys(planIDs).find((planName) => plans.find((plan) => plan.Type === PLAN_TYPES.PLAN && plan.Name === planName) ); if (hasNewVisionary(subscription) && PLANS.NEW_VISIONARY !== newPlanName) { await new Promise<void>((resolve, reject) => { createModal( <NewVisionaryWarningModal type={!newPlanName ? 'downgrade' : 'switch'} onClose={reject} onConfirm={resolve} /> ); }); } }; const processSubscription = async (operationsOrValidToken: Operations | ValidatedBitcoinToken) => { if (isValidatedBitcoinToken(operationsOrValidToken)) { await api({ ...apiSubscribe( { Plans: model.planIDs, Codes: getCodes(model), Cycle: model.cycle, Currency: currency, Amount: amount, Payment: operationsOrValidToken.Payment, }, app ), timeout: 60000 * 2, }); } else { await operationsOrValidToken.subscribe(); } }; const handleSubscribe = async ( operationsOrValidToken: Operations | ValidatedBitcoinToken, context: OperationsSubscriptionData ) => { try { await handlePlanWarnings(context.Plans); } catch (e) { return; } if (!hasPlanIDs(context.Plans)) { return handleUnsubscribe(); } const shouldCalendarPreventSubscriptionChangePromise = getShouldCalendarPreventSubscripitionChange({ hasPaidMail: hasPaidMail(user), willHavePaidMail: willHavePaidMail(context.Plans, plans), api, getCalendars, }); if (await shouldCalendarPreventSubscriptionChangePromise) { return new Promise<void>((resolve, reject) => { const handleClose = () => { onCancel?.(); reject(); }; createModal(<CalendarDowngradeModal onConfirm={resolve} onClose={handleClose} />); }); } // When user has an error during checkout, we need to return him to the exact same step // Two possible cases: CHECKOUT and CHECKOUT_WITH_CUSTOMIZATION const checkoutStep = model.step; try { setModel((model) => ({ ...model, step: SUBSCRIPTION_STEPS.UPGRADE })); await processSubscription(operationsOrValidToken); await call(); void metrics.payments_subscription_total.increment({ ...metricsProps, status: 'success', }); if (disableThanksStep) { onSubscribed?.(); } else { setModel((model) => ({ ...model, step: SUBSCRIPTION_STEPS.THANKS })); } } catch (error: any) { const { Code = 0 } = error.data || {}; if (Code === API_CUSTOM_ERROR_CODES.PAYMENTS_SUBSCRIPTION_AMOUNT_MISMATCH) { await check(); // eslint-disable-line @typescript-eslint/no-use-before-define // translator: this message pops in a notification, in case user is waiting really too long, or does the checkout in another tab, which makes this ones not valid/expiring createNotification({ text: c('Error').t`Checkout expired, please try again`, type: 'error' }); } observeApiError(error, (status) => metrics.payments_subscription_total.increment({ ...metricsProps, status, }) ); setModel((model) => ({ ...model, step: checkoutStep })); throw error; } }; const paymentFacade = usePaymentFacade({ amount, currency, onChargeable: (operations, { context }) => { if (!context.subscription) { throw new Error('Missing subscription context'); } return withLoading(handleSubscribe(operations, context.subscription)); }, flow: 'subscription', }); const bitcoinLoading = paymentFacade.selectedMethodType === PAYMENT_METHOD_TYPES.BITCOIN && !bitcoinValidated && awaitingBitcoinPayment; const check = async (newModel: Model = model, wantToApplyNewGiftCode: boolean = false): Promise<boolean> => { const copyNewModel = { ...newModel, initialCheckComplete: true, }; if (copyNewModel.step === SUBSCRIPTION_STEPS.CUSTOMIZATION && !supportAddons(copyNewModel.planIDs)) { copyNewModel.step = SUBSCRIPTION_STEPS.CHECKOUT; } if (!hasPlanIDs(newModel.planIDs)) { setCheckResult(getFreeCheckResult(model.currency, model.cycle)); setModel(copyNewModel); return true; } try { abortControllerRef.current?.abort(); abortControllerRef.current = new AbortController(); const result = await api<SubscriptionCheckResponse>({ ...checkSubscription({ Plans: newModel.planIDs, Currency: newModel.currency, Cycle: newModel.cycle, Codes: getCodes(newModel), }), signal: abortControllerRef.current.signal, }); const { Gift = 0 } = result; const { Code = '' } = result.Coupon || {}; // Coupon can equal null if (wantToApplyNewGiftCode && newModel.gift?.toLowerCase() !== Code.toLowerCase() && !Gift) { createNotification({ text: c('Error').t`Invalid code`, type: 'error' }); giftCodeRef.current?.focus(); } if (Code) { latestValidCouponCodeRef.current = Code; } copyNewModel.coupon = Code || subscriptionCouponCode || latestValidCouponCodeRef.current; if (!Gift) { delete copyNewModel.gift; } setCheckResult(result); setModel(copyNewModel); onCheck?.({ model, newModel, type: 'success', result }); } catch (error: any) { if (error.name === 'OfflineError') { setModel({ ...model, step: SUBSCRIPTION_STEPS.NETWORK_ERROR }); } onCheck?.({ model, newModel, type: 'error', error }); return false; } return true; }; useEffect(() => { if (!model.initialCheckComplete) { return; } void metrics.payments_subscription_steps_total.increment(metricsProps); }, [model.step, model.initialCheckComplete]); useEffect(() => { // Trigger once to initialise the check values void withLoadingCheck(check()); }, []); useEffect(() => { // Each time the user switch between steps, scroll to the top if (customTopRef?.current) { customTopRef.current?.scrollIntoView?.(); } else { topRef?.current?.scrollIntoView?.(); } }, [model.step, customTopRef?.current, topRef?.current]); const process = async (processor?: PaymentProcessorHook) => withLoading(async () => { if (!processor) { return; } try { paymentFacade.paymentContext.setSubscriptionData({ Plans: model.planIDs, Codes: getCodes(model), Cycle: model.cycle, product: app, }); await processor.processPaymentToken(); } catch (e) { const error = getSentryError(e); if (error) { const context = { app, step: model.step, cycle: model.cycle, currency: model.currency, amount, coupon: model.coupon, planIDs, audience, processorType: paymentFacade.selectedProcessor?.meta.type, paymentMethod: paymentFacade.selectedMethodType, paymentMethodValue: paymentFacade.selectedMethodValue, }; captureMessage('Payments: failed to handle subscription', { level: 'error', extra: { error, context }, }); } } }); const handleChangeCycle = (cycle: Cycle) => { if (loadingCheck || cycle === model.cycle) { return; } const checkPromise = check({ ...model, cycle }); void withLoadingCheck(checkPromise); void withBlockAccountSizeSelector(checkPromise); }; const handleGift = (gift = '') => { if (loadingCheck) { return; } if (!gift) { const withoutGift = { ...model }; delete withoutGift.gift; return withLoadingGift(check(withoutGift)); } void withLoadingGift(check({ ...model, gift }, true)); }; const handleChangeCurrency = (currency: Currency) => { if (loadingCheck || currency === model.currency) { return; } void withLoadingCheck(check({ ...model, currency })); }; const backStep = model.step === SUBSCRIPTION_STEPS.CHECKOUT && !supportAddons(model.planIDs) ? SUBSCRIPTION_STEPS.PLAN_SELECTION : BACK[model.step]; const isFreePlanSelected = !hasPlanIDs(model.planIDs); const isFreeUserWithFreePlanSelected = user.isFree && isFreePlanSelected; const disableCycleSelector = isFreePlanSelected || maybeDisableCycleSelector || getIsCustomCycle(model.cycle); const handleCustomizationSubmit = () => { const run = async () => { let isSuccess = await check(); if (isSuccess) { setModel((old) => ({ ...old, step: SUBSCRIPTION_STEPS.CHECKOUT, })); } }; void withLoading(run()); }; const handleUpsellVPNPassBundle = () => { if (loadingCheck) { return; } let newModel: Model; if (model.planIDs[PLANS.VPN]) { newModel = { ...model, planIDs: { [PLANS.VPN_PASS_BUNDLE]: 1, }, }; } else { newModel = { ...model, planIDs: { [PLANS.VPN]: 1, }, }; } setModel(newModel); const checkPromise = check(newModel); void withLoadingCheck(checkPromise); void withBlockCycleSelector(checkPromise); }; const onSubmit = (e: FormEvent) => { e.preventDefault(); if (model.step === SUBSCRIPTION_STEPS.CUSTOMIZATION) { return; } if (loadingCheck || loadingGift) { return; } void withLoading(process(paymentFacade.selectedProcessor)); }; const content = ( <> {!customTopRef && <div ref={topRef} />} {model.step === SUBSCRIPTION_STEPS.NETWORK_ERROR && <GenericError />} {model.step === SUBSCRIPTION_STEPS.PLAN_SELECTION && ( <PlanSelection app={app} loading={loadingCheck} plans={plans} plansMap={plansMap} vpnServers={vpnServers} currency={model.currency} cycle={model.cycle} planIDs={model.planIDs} mode="modal" subscription={subscription} onChangePlanIDs={(planIDs) => withLoadingCheck( check({ ...model, planIDs, step: !!planIDs[PLANS.VPN_PRO] || !!planIDs[PLANS.VPN_BUSINESS] ? SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION : SUBSCRIPTION_STEPS.CUSTOMIZATION, }) ) } onChangeCycle={handleChangeCycle} onChangeCurrency={handleChangeCurrency} onChangeAudience={setAudience} audience={audience} selectedProductPlans={selectedProductPlans} onChangeSelectedProductPlans={setSelectedProductPlans} organization={organization} calendarSharingEnabled={calendarSharingEnabled} sentinelPassplusEnabled={sentinelPassplusEnabled} /> )} {model.step === SUBSCRIPTION_STEPS.CUSTOMIZATION && ( <div className="subscriptionCheckout-top-container"> <div className="flex-item-fluid w-full md:w-auto pr-4 md:pr-0 lg:pr-6 pt-6"> <div className="max-w-custom" style={{ '--max-w-custom': '50em' }}> <PlanCustomization loading={loadingCheck} currency={model.currency} cycle={model.cycle} plansMap={plansMap} planIDs={model.planIDs} organization={organization} onChangePlanIDs={(planIDs) => setModel({ ...model, planIDs })} currentSubscription={subscription} className="pb-7 mb-8" /> </div> </div> <div className="subscriptionCheckout-column bg-weak rounded"> <div className="subscriptionCheckout-container sticky-top" data-testid="subscription-checkout"> <SubscriptionCheckout submit={ <Button color="norm" loading={loading} onClick={handleCustomizationSubmit} fullWidth data-testid="continue-to-review" > {c('new_plans: action').t`Continue to review`} </Button> } checkResult={getOptimisticCheckResult({ cycle: model.cycle, planIDs: model.planIDs, plansMap, })} plansMap={plansMap} vpnServers={vpnServers} isOptimistic={true} loading={loadingCheck} currency={model.currency} cycle={model.cycle} planIDs={model.planIDs} subscription={subscription} onChangeCurrency={handleChangeCurrency} {...checkoutModifiers} /> </div> </div> </div> )} {model.step === SUBSCRIPTION_STEPS.CHECKOUT && ( <> <div className="subscriptionCheckout-top-container"> <div className="flex-item-fluid w-full md:w-auto pr-4 md:pr-0 lg:pr-6 pt-6"> <div className="mx-auto max-w-custom subscriptionCheckout-options" style={{ '--max-w-custom': '37em' }} > {(() => { if (isFreePlanSelected) { return null; } if (disableCycleSelector) { return ( <> <h2 className="text-2xl text-bold mb-4">{c('Label').t`New plan`}</h2> <div className="mb-8"> {(() => { const plan = getPlanFromCheckout(model.planIDs, plansMap); const result = getCheckout({ planIDs: model.planIDs, plansMap, checkResult, }); return ( <SubscriptionItemView title={plan?.Title} bottomLeft={getShortBillingText(model.cycle)} topRight={getSimplePriceString( model.currency, result.withDiscountPerMonth, getMonthlySuffix(model.planIDs) )} bottomRight={getDiscountPrice( result.discountPerCycle, model.currency )} loading={loadingCheck} /> ); })()} {canUpsellToVPNPassBundle( model.planIDs, model.cycle, couponCode ) && ( <VPNPassPromotionButton onClick={handleUpsellVPNPassBundle} currency={model.currency} cycle={model.cycle} /> )} {model.planIDs[PLANS.VPN_PASS_BUNDLE] && !hasPassPlus(subscription) && ( <Button className="flex flex-nowrap flex-align-items-center flex-justify-center" fullWidth color="weak" shape="outline" onClick={handleUpsellVPNPassBundle} > <Icon name="trash" size={14} /> <span className="ml-2"> {c('bf2023: Action').t`Remove ${PASS_APP_NAME}`} </span> </Button> )} </div> </> ); } return ( <> <h2 className="text-2xl text-bold mb-4"> {c('Label').t`Subscription options`} </h2> <div className="mb-8"> <SubscriptionCycleSelector mode="buttons" plansMap={plansMap} planIDs={model.planIDs} cycle={model.cycle} currency={model.currency} onChangeCycle={handleChangeCycle} disabled={loadingCheck} /> </div> </> ); })()} {/* avoid mounting/unmounting the component which re-triggers the hook */} <div className={amountDue ? undefined : 'hidden'}> <PaymentWrapper {...paymentFacade} onPaypalCreditClick={() => process(paymentFacade.paypalCredit)} noMaxWidth onBitcoinTokenValidated={async (data) => { setBitcoinValidated(true); await handleSubscribe(data, { Plans: model.planIDs, Cycle: model.cycle, product: app, }); }} onAwaitingBitcoinPayment={setAwaitingBitcoinPayment} hideSavedMethodsDetails={application === APPS.PROTONACCOUNTLITE} /> </div> <div className={amountDue || !checkResult ? 'hidden' : undefined}> <h2 className="text-2xl text-bold mb-4">{c('Label').t`Payment details`}</h2> <div className="mb-4">{c('Info').t`No payment is required at this time.`}</div> {checkResult?.Credit && creditsRemaining ? ( <div className="mb-4">{c('Info') .t`Please note that upon clicking the Confirm button, your account will have ${creditsRemaining} credits remaining.`}</div> ) : null} </div> </div> </div> <div className="subscriptionCheckout-column bg-weak rounded"> <div className="subscriptionCheckout-container sticky-top" data-testid="subscription-checkout" > <SubscriptionCheckout submit={ <SubscriptionSubmitButton currency={model.currency} onDone={onSubscribed} paypal={paymentFacade.paypal} step={model.step} loading={loading || bitcoinLoading} paymentMethodValue={paymentFacade.selectedMethodValue} checkResult={checkResult} className="w-full" disabled={isFreeUserWithFreePlanSelected} /> } plansMap={plansMap} checkResult={checkResult} vpnServers={vpnServers} loading={loadingCheck} currency={model.currency} subscription={subscription} cycle={model.cycle} planIDs={model.planIDs} gift={ <> {couponCode && ( <div className="flex flex-align-items-center mb-1"> <Icon name="gift" className="mr-2 mb-1" /> <Tooltip title={couponDescription}> <code>{couponCode.toUpperCase()}</code> </Tooltip> </div> )} {couponCode !== COUPON_CODES.BLACK_FRIDAY_2023 && ( <PaymentGiftCode giftCodeRef={giftCodeRef} key={ /* Reset the toggle state when a coupon code gets applied */ couponCode } giftCode={model.gift} onApply={handleGift} loading={loadingGift} /> )} </> } onChangeCurrency={handleChangeCurrency} nextSubscriptionStart={subscription.PeriodEnd} {...checkoutModifiers} /> </div> </div> </div> </> )} {model.step === SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION && ( <div className="subscriptionCheckout-top-container"> <div className="flex-item-fluid w-full md:w-auto pr-4 md:pr-0 lg:pr-6 pt-6"> <h2 className="text-2xl text-bold mb-6">{c('Label').t`Organization size`}</h2> <PlanCustomization loading={blockAccountSizeSelector} currency={model.currency} cycle={model.cycle} plansMap={plansMap} planIDs={model.planIDs} organization={organization} onChangePlanIDs={debounce((planIDs) => { const newModel = { ...model, planIDs }; setModel(newModel); const checkPromise = check(newModel); void withLoadingCheck(checkPromise); void withBlockCycleSelector(checkPromise); }, 300)} forceHideDescriptions showUsersTooltip={false} currentSubscription={subscription} className="mb-8" /> <div className="mx-auto max-w-custom subscriptionCheckout-options" style={{ '--max-w-custom': '37em' }} > {!disableCycleSelector && ( <> <h2 className="text-2xl text-bold mb-6">{c('Label').t`Select your plan`}</h2> <div className="mb-8"> <SubscriptionCycleSelector mode="buttons" plansMap={plansMap} planIDs={model.planIDs} cycle={model.cycle} currency={model.currency} onChangeCycle={handleChangeCycle} disabled={loadingCheck} faded={blockCycleSelector} /> </div> </> )} <h2 className="text-2xl text-bold mb-4">{c('Label').t`Payment details`}</h2> {/* avoid mounting/unmounting the component which re-triggers the hook */} <div className={amountDue ? undefined : 'hidden'}> <PaymentWrapper {...paymentFacade} onPaypalCreditClick={() => process(paymentFacade.paypalCredit)} noMaxWidth onBitcoinTokenValidated={async (data) => { setBitcoinValidated(true); await handleSubscribe(data, { Plans: model.planIDs, Cycle: model.cycle, product: app, }); }} onAwaitingBitcoinPayment={setAwaitingBitcoinPayment} hideFirstLabel={true} hideSavedMethodsDetails={application === APPS.PROTONACCOUNTLITE} /> </div> <div className={amountDue || !checkResult ? 'hidden' : undefined}> <div className="mb-4">{c('Info').t`No payment is required at this time.`}</div> {checkResult?.Credit && creditsRemaining ? ( <div className="mb-4">{c('Info') .t`Please note that upon clicking the Confirm button, your account will have ${creditsRemaining} credits remaining.`}</div> ) : null} </div> </div> </div> <div className="subscriptionCheckout-column bg-weak rounded"> <div className="subscriptionCheckout-container sticky-top" data-testid="subscription-checkout"> <SubscriptionCheckout submit={ <SubscriptionSubmitButton currency={model.currency} onDone={onSubscribed} paypal={paymentFacade.paypal} step={model.step} loading={loading || bitcoinLoading} paymentMethodValue={paymentFacade.selectedMethodValue} checkResult={checkResult} className="w-full" disabled={isFreeUserWithFreePlanSelected} /> } subscription={subscription} plansMap={plansMap} checkResult={checkResult} vpnServers={vpnServers} loading={loadingCheck} currency={model.currency} cycle={model.cycle} planIDs={model.planIDs} gift={ <> {couponCode && ( <div className="flex flex-align-items-center mb-1"> <Icon name="gift" className="mr-2 mb-1" /> <Tooltip title={couponDescription}> <code>{couponCode.toUpperCase()}</code> </Tooltip> </div> )} {couponCode !== COUPON_CODES.BLACK_FRIDAY_2023 && ( <PaymentGiftCode giftCodeRef={giftCodeRef} key={ /* Reset the toggle state when a coupon code gets applied */ couponCode } giftCode={model.gift} onApply={handleGift} loading={loadingGift} /> )} </> } onChangeCurrency={handleChangeCurrency} nextSubscriptionStart={subscription.PeriodEnd} showDiscount={false} enableDetailedAddons={true} showPlanDescription={false} {...checkoutModifiers} /> </div> </div> </div> )} {model.step === SUBSCRIPTION_STEPS.UPGRADE && ( <SubscriptionThanks showDownloads={!isVpnB2bPlan} loading={true} paymentMethodType={paymentFacade.selectedMethodType} /> )} {model.step === SUBSCRIPTION_STEPS.THANKS && ( <SubscriptionThanks showDownloads={!isVpnB2bPlan} paymentMethodType={paymentFacade.selectedMethodType} onClose={() => { onSubscribed?.(); }} /> )} </> ); const footer = (() => { if ((disablePlanSelection && backStep === SUBSCRIPTION_STEPS.PLAN_SELECTION) || backStep === undefined) { return undefined; } return ( <Button onClick={() => { setModel({ ...model, step: backStep }); }} >{c('Action').t`Back`}</Button> ); })(); return ( <> {cancelSubscriptionModals} {render({ onSubmit, title: TITLE[model.step], content, footer, step: model.step, })} </> ); }; export default SubscriptionContainer;
6,769
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionCycleSelector.test.tsx
import { render } from '@testing-library/react'; import { CYCLE, PLANS } from '@proton/shared/lib/constants'; import SubscriptionCycleSelector, { Props } from './SubscriptionCycleSelector'; let props: Props; beforeEach(() => { props = { onChangeCycle: jest.fn(), mode: 'buttons', currency: 'CHF', cycle: CYCLE.TWO_YEARS, minimumCycle: CYCLE.MONTHLY, planIDs: { mail2022: 1, }, plansMap: { mail2022: { ID: 'l8vWAXHBQmv0u7OVtPbcqMa4iwQaBqowINSQjPrxAr-Da8fVPKUkUcqAq30_BCxj1X0nW70HQRmAa-rIvzmKUA==', Type: 1, Name: PLANS.PLUS, Title: 'Mail Plus', MaxDomains: 1, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 499, '12': 4788, '24': 8376, }, DefaultPricing: { '1': 499, '12': 4788, '24': 8376, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 499, }, }, }; }); it('should render', () => { const { container } = render(<SubscriptionCycleSelector {...props} />); expect(container).not.toBeEmptyDOMElement(); }); it('should correctly display price per month', () => { const { queryByTestId } = render(<SubscriptionCycleSelector {...props} />); expect(queryByTestId('price-per-user-per-month-1')).toHaveTextContent('CHF 4.99/month'); expect(queryByTestId('price-per-user-per-month-12')).toHaveTextContent('CHF 3.99/month'); expect(queryByTestId('price-per-user-per-month-24')).toHaveTextContent('CHF 3.49/month'); }); it('should correctly display price per user per month', () => { const planIDs = { mailpro2022: 1, '1member-mailpro2022': 3, }; const plansMap = { mailpro2022: { ID: 'BKiAUbkGnUPiy2c3b0sBCK557OBnWD7ACqqX3VPoZqOOyeMdupoWcjrPDBHy3ANfFKHnJs6qdQrdvHj7zjon_g==', Type: 1, Name: 'mailpro2022', Title: 'Mail Essentials', MaxDomains: 3, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 799, '12': 8388, '24': 15576, }, DefaultPricing: { '1': 799, '12': 8388, '24': 15576, }, PeriodEnd: { '1': 1693576305, '12': 1722520305, '24': 1754056305, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 799, }, '1member-mailpro2022': { ID: 'FK4MKKIVJqOC9Pg_sAxCjNWf8PM9yGzrXO3eXq8sk5RJB6HtaRBNUEcnvJBrQVPAtrDSoTNq4Du3FpqIxyMhHQ==', Type: 0, Name: '1member-mailpro2022', Title: '+1 User', MaxDomains: 0, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 0, State: 1, Pricing: { '1': 799, '12': 8388, '24': 15576, }, DefaultPricing: { '1': 799, '12': 8388, '24': 15576, }, PeriodEnd: { '1': 1693576305, '12': 1722520305, '24': 1754056305, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 799, }, }; const { queryByTestId } = render( <SubscriptionCycleSelector {...props} plansMap={plansMap as any} planIDs={planIDs} /> ); expect(queryByTestId('price-per-user-per-month-1')).toHaveTextContent('CHF 7.99/user per month'); expect(queryByTestId('price-per-user-per-month-12')).toHaveTextContent('CHF 6.99/user per month'); expect(queryByTestId('price-per-user-per-month-24')).toHaveTextContent('CHF 6.49/user per month'); }); it('should correctly display price per user per month when there are non-user addons', () => { const planIDs = { bundlepro2022: 1, '1domain-bundlepro2022': 12, '1member-bundlepro2022': 8, }; const plansMap = { bundlepro2022: { ID: 'q6fRrEIn0nyJBE_-YSIiVf80M2VZhOuUHW5In4heCyOdV_nGibV38tK76fPKm7lTHQLcDiZtEblk0t55wbuw4w==', Type: 1, Name: 'bundlepro2022', Title: 'Business', MaxDomains: 10, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Pricing: { '1': 1299, '12': 13188, '24': 23976, }, DefaultPricing: { '1': 1299, '12': 13188, '24': 23976, }, PeriodEnd: { '1': 1693576305, '12': 1722520305, '24': 1754056305, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 1299, }, '1domain-bundlepro2022': { ID: '39hry1jlHiPzhXRXrWjfS6t3fqA14QbYfrbF30l2PYYWOhVpyJ33nhujM4z4SHtfuQqTx6e7oSQokrqhLMD8LQ==', Type: 0, Name: '1domain-bundlepro2022', Title: '+1 Domain for Business', MaxDomains: 1, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 0, MaxTier: 0, Services: 15, Features: 0, State: 1, Pricing: { '1': 150, '12': 1680, '24': 3120, }, DefaultPricing: { '1': 150, '12': 1680, '24': 3120, }, PeriodEnd: { '1': 1693576305, '12': 1722520305, '24': 1754056305, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 150, }, '1member-bundlepro2022': { ID: '0WjWEbOmKh7F2a1Snx2FJKA7a3Fm05p-nIZ0TqiHjDDUa6oHnsyWeeVXgSuzumCmFE8_asJsom9ZzGbx-eDecw==', Type: 0, Name: '1member-bundlepro2022', Title: '+1 User for Business', MaxDomains: 0, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 0, Services: 15, Features: 0, State: 1, Pricing: { '1': 1299, '12': 13188, '24': 23976, }, DefaultPricing: { '1': 1299, '12': 13188, '24': 23976, }, PeriodEnd: { '1': 1693576305, '12': 1722520305, '24': 1754056305, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 1299, }, }; props = { ...props, planIDs, plansMap: plansMap as any, }; const { queryByTestId } = render(<SubscriptionCycleSelector {...props} />); expect(queryByTestId('price-per-user-per-month-1')).toHaveTextContent('CHF 12.99/user per month'); expect(queryByTestId('price-per-user-per-month-12')).toHaveTextContent('CHF 10.99/user per month'); expect(queryByTestId('price-per-user-per-month-24')).toHaveTextContent('CHF 9.99/user per month'); }); it('should display the prices correctly for VPN Plus', () => { const planIDs = { vpn2022: 1, }; const plansMap = { vpn2022: { ID: 'pIJGEYyNFsPEb61otAc47_X8eoSeAfMSokny6dmg3jg2JrcdohiRuWSN2i1rgnkEnZmolVx4Np96IcwxJh1WNw==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'vpn2022', Title: 'VPN Plus', MaxDomains: 0, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 10, MaxTier: 2, Services: 4, Features: 0, State: 1, Pricing: { '1': 1149, '12': 7188, '15': 14985, '24': 11976, '30': 29970, }, DefaultPricing: { '1': 1149, '12': 7188, '15': 14985, '24': 11976, '30': 29970, }, PeriodEnd: { '1': 1693583725, '12': 1722527725, '15': 1730476525, '24': 1754063725, '30': 1769961325, }, Currency: 'CHF', Quantity: 1, Offers: [], Cycle: 1, Amount: 1149, Vendors: { Google: { Plans: { '12': 'giapaccount_vpn2022_12_renewing', }, CustomerID: 'cus_google_CpVjQymENRYZmBtWQMDw', }, Apple: { Plans: { '12': 'iosaccount_vpn2022_12_usd_non_renewing', }, CustomerID: '', }, }, }, }; props = { ...props, planIDs, plansMap: plansMap as any, }; const { queryByTestId } = render(<SubscriptionCycleSelector {...props} />); expect(queryByTestId('price-per-user-per-month-1')).toHaveTextContent('CHF 11.49/month'); expect(queryByTestId('price-per-user-per-month-12')).toHaveTextContent('CHF 5.99/month'); expect(queryByTestId('price-per-user-per-month-24')).toHaveTextContent('CHF 4.99/month'); });
6,770
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionCycleSelector.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { CYCLE, DEFAULT_CURRENCY, MEMBER_ADDON_PREFIX } from '@proton/shared/lib/constants'; import { getCheckout } from '@proton/shared/lib/helpers/checkout'; import { getSupportedAddons } from '@proton/shared/lib/helpers/planIDs'; import { TotalPricing, allCycles, getPricingFromPlanIDs, getTotalFromPricing, } from '@proton/shared/lib/helpers/subscription'; import { Currency, PlanIDs, PlansMap, SubscriptionCheckResponse } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { EllipsisLoader, Option, Price, Radio, SelectTwo } from '../../../components'; import InputField from '../../../components/v2/field/InputField'; import { getMonthFreeText } from '../../offers/helpers/offerCopies'; import { getShortBillingText } from '../helper'; export interface Props { cycle: CYCLE; minimumCycle?: CYCLE; mode: 'select' | 'buttons'; currency: Currency; onChangeCycle: (cycle: CYCLE) => void; plansMap: PlansMap; planIDs: PlanIDs; disabled?: boolean; faded?: boolean; } type TotalPricings = { [key in CYCLE]: TotalPricing; }; export const getDiscountPrice = (discount: number, currency: Currency) => { return discount ? ( <> {c('Subscription saving').t`Save`} <Price className="ml-1" currency={currency}> {discount} </Price> </> ) : null; }; const singleClassName = 'p-4 mb-4 border rounded bg-norm flex flex-nowrap flex-align-items-stretch border-primary border-2'; export const SubscriptionItemView = ({ title, loading, topRight, bottomLeft, bottomRight, }: { title: ReactNode; topRight: ReactNode; bottomLeft: ReactNode; bottomRight: ReactNode; loading?: boolean; }) => { return ( <div className={singleClassName}> <div className="flex-item-fluid pl-2"> <div className="flex flex-align-items-center"> <div className="flex-item-fluid-auto mr-4"> <strong className="text-lg">{title}</strong> </div> <strong className="text-lg flex-item-noshrink color-primary"> {loading ? <EllipsisLoader /> : topRight} </strong> </div> <div className="flex flex-align-items-center"> <span className="color-weak flex flex-item-fluid-auto"> {loading ? <EllipsisLoader /> : bottomLeft} </span> <span className="color-success flex flex-item-noshrink">{loading ? null : bottomRight}</span> </div> </div> </div> ); }; const CycleItemView = ({ loading, currency, text, total, monthlySuffix, totalPerMonth, discount, freeMonths, cycle, }: { loading?: boolean; currency: Currency; text: string; total: number; monthlySuffix: string; totalPerMonth: number; discount: number; freeMonths: number; cycle: CYCLE; }) => { return ( <div className="flex-item-fluid pl-2"> <div className="flex flex-align-items-center"> <div className="flex-item-fluid-auto mr-4"> <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"> {loading ? ( <EllipsisLoader /> ) : ( <> {c('Subscription price').t`For`} <Price className="ml-1" currency={currency} data-testid="subscription-total-price"> {total} </Price> </> )} </strong> </div> <div className="flex flex-align-items-center"> <span className="color-weak flex flex-item-fluid-auto" data-testid={`price-per-user-per-month-${cycle}`} > {loading ? ( <EllipsisLoader /> ) : ( <Price currency={currency} suffix={monthlySuffix} data-testid="price-value-per-user-per-month"> {totalPerMonth} </Price> )} </span> <span className="color-success flex flex-item-noshrink"> {loading ? null : getDiscountPrice(discount, currency)} </span> </div> </div> ); }; const CycleItem = ({ totals, currency, cycle, monthlySuffix, }: { totals: TotalPricings; monthlySuffix: string; cycle: CYCLE; currency: Currency; }) => { const replacementCycle = cycle; const freeMonths = 0; const { total, perUserPerMonth, discount } = totals[replacementCycle]; return ( <CycleItemView text={getShortBillingText(replacementCycle)} currency={currency} discount={discount} monthlySuffix={monthlySuffix} freeMonths={freeMonths} total={total} totalPerMonth={perUserPerMonth} cycle={cycle} /> ); }; export const getMonthlySuffix = (planIDs: PlanIDs) => { const supportedAddons = getSupportedAddons(planIDs); return Object.keys(supportedAddons).some((addon) => addon.startsWith(MEMBER_ADDON_PREFIX)) ? c('Suffix').t`/user per month` : c('Suffix').t`/month`; }; export const SubscriptionCheckoutCycleItem = ({ checkResult, plansMap, planIDs, loading, }: { checkResult: SubscriptionCheckResponse | undefined; plansMap: PlansMap; planIDs: PlanIDs; loading?: boolean; }) => { const cycle = checkResult?.Cycle || CYCLE.MONTHLY; const currency = checkResult?.Currency || DEFAULT_CURRENCY; const replacementCycle = cycle; const freeMonths = 0; const result = getCheckout({ planIDs, plansMap, checkResult }); return ( <div className={singleClassName}> <CycleItemView loading={loading} text={getShortBillingText(replacementCycle)} currency={currency} discount={result.discountPerCycle} monthlySuffix={getMonthlySuffix(planIDs)} freeMonths={freeMonths} total={result.withDiscountPerCycle} totalPerMonth={result.withDiscountPerMonth} cycle={cycle} /> </div> ); }; const SubscriptionCycleSelector = ({ cycle: cycleSelected, minimumCycle = CYCLE.MONTHLY, mode, onChangeCycle, currency, disabled, planIDs, plansMap, faded, }: Props) => { const filteredCycles = [CYCLE.YEARLY, CYCLE.MONTHLY].filter((cycle) => cycle >= minimumCycle); const cycles = [CYCLE.TWO_YEARS, ...filteredCycles]; const monthlySuffix = getMonthlySuffix(planIDs); const pricing = getPricingFromPlanIDs(planIDs, plansMap); const totals = allCycles.reduce<{ [key in CYCLE]: TotalPricing }>((acc, cycle) => { acc[cycle] = getTotalFromPricing(pricing, cycle); return acc; }, {} as any); const fadedClasses = clsx(faded && 'opacity-50 no-pointer-events-children'); if (cycles.length === 1) { const cycle = cycles[0]; return ( <div className={clsx(singleClassName, 'mb-2', fadedClasses)}> <CycleItem monthlySuffix={monthlySuffix} totals={totals} cycle={cycle} currency={currency} /> </div> ); } if (mode === 'select') { return ( <div className={fadedClasses}> <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].perUserPerMonth} </Price> } > {cycles.map((cycle) => { return ( <Option value={cycle} title={getShortBillingText(cycle)} key={cycle}> <div className="flex flex-justify-space-between"> <span className="flex-item-noshrink">{getShortBillingText(cycle)}</span> <span className={clsx([ 'flex-item-noshrink', cycle !== cycleSelected && 'color-success', ])} > {getDiscountPrice(totals[cycle].discount, currency)} </span> </div> </Option> ); })} </InputField> </div> ); } return ( <ul className={clsx('unstyled m-0 plan-cycle-selector', fadedClasses)}> {cycles.map((cycle) => { const isSelected = cycle === cycleSelected; return ( <li key={`${cycle}`} className="flex flex-align-items-stretch mb-4" data-testid={`cycle-${cycle}`}> <button className={clsx([ 'w-full p-4 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;
6,771
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionModalDisabled.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Prompt, PromptProps } from '../../../components'; const SubscriptionModalDisabled = (props: Omit<PromptProps, 'title' | 'buttons' | 'children'>) => { const learnMore = ( <Href href={getKnowledgeBaseUrl('/upgrading-to-new-proton-plan')}>{c('Link').t`Learn more`}</Href> ); return ( <Prompt {...props} title={c('new_plans: title').t`Improved plans coming soon!`} buttons={<Button color="norm" onClick={props.onClose}>{c('new_plans: action').t`Got it`}</Button>} > <div className="text-pre-wrap"> {c('Info') .t`We’re upgrading your current plan to an improved plan that offers more for the same price. While our systems are updating, you won’t be able to change it. We’ll email you as soon as it’s done.`}{' '} {learnMore} </div> </Prompt> ); }; export default SubscriptionModalDisabled;
6,772
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionModalProvider.test.tsx
import { render, waitFor } from '@testing-library/react'; import cloneDeep from 'lodash/cloneDeep'; import { mockOrganizationApi, mockPlansApi, mockSubscriptionApi, mockUserCache, subscriptionDefaultResponse, } from '@proton/components/hooks/helpers/test'; import { PLANS } from '@proton/shared/lib/constants'; import { Audience, External } from '@proton/shared/lib/interfaces'; import { apiMock, mockCache } from '@proton/testing'; import ApiContext from '../../api/apiContext'; import { CacheProvider } from '../../cache'; import EventManagerContext from '../../eventManager/context'; import SubscriptionContainer from './SubscriptionContainer'; import SubscriptionModalProvider, { OpenSubscriptionModalCallback, useSubscriptionModal, } from './SubscriptionModalProvider'; jest.mock('@proton/components/hooks/useModals'); jest.mock('@proton/components/components/portal/Portal'); jest.mock('@proton/components/containers/payments/subscription/SubscriptionContainer'); jest.mock('@proton/components/hooks/useFeature', () => () => ({})); beforeEach(() => { mockUserCache(); mockSubscriptionApi(); mockOrganizationApi(); mockPlansApi(); }); const defaultEventManager = { call: jest.fn() }; const Providers = ({ children, eventManager = defaultEventManager, api = apiMock, cache = mockCache }: any) => { return ( <EventManagerContext.Provider value={eventManager}> <ApiContext.Provider value={api}> <CacheProvider cache={cache}>{children}</CacheProvider> </ApiContext.Provider> </EventManagerContext.Provider> ); }; it('should render', async () => { const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account">My content</SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(container).toHaveTextContent('My content'); }); }); it('should render <SubscriptionModalDisabled> if there are legacy plans', async () => { const subscription = cloneDeep(subscriptionDefaultResponse); subscription.Subscription.Plans = [ { Name: PLANS.VPNBASIC, // that's a legacy plan } as any, ]; mockSubscriptionApi(subscription); let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({} as any); expect(container).toHaveTextContent('We’re upgrading your current plan to an improved plan'); }); it('should render <SubscriptionContainer> if there is no legacy plans', async () => { let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({} as any); expect(container).toHaveTextContent('SubscriptionContainer'); }); it('should render <SubscriptionContainer> with B2B default audience if it was selected in the callback', async () => { let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({ defaultAudience: Audience.B2B } as any); expect(SubscriptionContainer).toHaveBeenCalledWith( expect.objectContaining({ defaultAudience: Audience.B2B, }), {} ); expect(container).toHaveTextContent('SubscriptionContainer'); }); it('should render <SubscriptionContainer> with B2B default audience if plan is a B2B plan', async () => { let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({ plan: PLANS.BUNDLE_PRO } as any); expect(SubscriptionContainer).toHaveBeenCalledWith( expect.objectContaining({ defaultAudience: Audience.B2B, }), {} ); expect(container).toHaveTextContent('SubscriptionContainer'); }); it('should render <SubscriptionContainer> with B2B default audience if subscription has a B2B plan', async () => { const subscription = cloneDeep(subscriptionDefaultResponse); subscription.Subscription.Plans = [ { Name: PLANS.BUNDLE_PRO, } as any, ]; mockSubscriptionApi(subscription); let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({} as any); expect(SubscriptionContainer).toHaveBeenCalledWith( expect.objectContaining({ defaultAudience: Audience.B2B, }), {} ); expect(container).toHaveTextContent('SubscriptionContainer'); }); it('should render <SubscriptionContainer> with FAMILY default audience if it is selected', async () => { let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { container } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({ defaultAudience: Audience.FAMILY } as any); expect(SubscriptionContainer).toHaveBeenCalledWith( expect.objectContaining({ defaultAudience: Audience.FAMILY, }), {} ); expect(container).toHaveTextContent('SubscriptionContainer'); }); it('should render <InAppPurchaseModal> if subscription is managed externally', async () => { const subscription = cloneDeep(subscriptionDefaultResponse); subscription.Subscription.External = External.Android; mockSubscriptionApi(subscription); let openSubscriptionModal!: OpenSubscriptionModalCallback; const ContextReaderComponent = () => { const modal = useSubscriptionModal(); openSubscriptionModal = modal[0]; return null; }; const { getByTestId } = render( <Providers> <SubscriptionModalProvider app="proton-account"> <ContextReaderComponent /> </SubscriptionModalProvider> </Providers> ); await waitFor(() => { expect(openSubscriptionModal).toBeDefined(); }); openSubscriptionModal({} as any); expect(getByTestId('InAppPurchaseModal/text')).not.toBeEmptyDOMElement(); });
6,773
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionModalProvider.tsx
import { ReactNode, createContext, useContext, useRef } from 'react'; import { APP_NAMES } from '@proton/shared/lib/constants'; import { getHasLegacyPlans, isManagedExternally } from '@proton/shared/lib/helpers/subscription'; import { Nullable } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; import { ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, useModalState } from '../../../components'; import { useOrganization, usePlans, useSubscription } from '../../../hooks'; import InAppPurchaseModal from './InAppPurchaseModal'; import SubscriptionContainer, { SubscriptionContainerProps } from './SubscriptionContainer'; import SubscriptionModalDisabled from './SubscriptionModalDisabled'; import { SUBSCRIPTION_STEPS, subscriptionModalClassName } from './constants'; export interface OpenCallbackProps extends Pick< SubscriptionContainerProps, | 'step' | 'cycle' | 'currency' | 'plan' | 'planIDs' | 'coupon' | 'disablePlanSelection' | 'disableThanksStep' | 'defaultAudience' | 'disableCycleSelector' | 'defaultSelectedProductPlans' | 'metrics' > { hasClose?: boolean; onClose?: () => void; disableCloseOnEscape?: boolean; fullscreen?: boolean; onSubscribed?: () => void; onUnsubscribed?: () => void; } export type OpenSubscriptionModalCallback = (props: OpenCallbackProps) => void; type ContextProps = [OpenSubscriptionModalCallback, boolean]; const SubscriptionModalContext = createContext<ContextProps>([noop, false]); export const useSubscriptionModal = () => { return useContext(SubscriptionModalContext); }; interface Props { children: ReactNode; app: APP_NAMES; onClose?: () => void; } const SubscriptionModalProvider = ({ children, app, onClose }: Props) => { const [subscription, loadingSubscription] = useSubscription(); const [plans = [], loadingPlans] = usePlans(); const [organization, loadingOrganization] = useOrganization(); const loading = loadingSubscription || loadingPlans || loadingOrganization; const subscriptionProps = useRef<OpenCallbackProps | null>(null); const [modalState, setModalState, render] = useModalState(); let subscriptionModal: Nullable<JSX.Element> = null; if (render && subscriptionProps.current) { if (isManagedExternally(subscription)) { subscriptionModal = <InAppPurchaseModal subscription={subscription} {...modalState} />; } else if (getHasLegacyPlans(subscription)) { subscriptionModal = <SubscriptionModalDisabled {...modalState} />; } else { const { hasClose, onClose: subscriptionPropsOnClose, disableCloseOnEscape, fullscreen, onSubscribed, onUnsubscribed, ...rest } = subscriptionProps.current; const handleClose = () => { onClose?.(); subscriptionPropsOnClose?.(); modalState.onClose(); }; subscriptionModal = ( <SubscriptionContainer app={app} subscription={subscription} plans={plans} organization={organization} onSubscribed={() => { handleClose(); onSubscribed?.(); }} onUnsubscribed={() => { handleClose(); onUnsubscribed?.(); }} onCancel={handleClose} {...rest} render={({ onSubmit, title, content, footer, step }) => { return ( <ModalTwo className={clsx([ subscriptionModalClassName, [ SUBSCRIPTION_STEPS.PLAN_SELECTION, SUBSCRIPTION_STEPS.CUSTOMIZATION, SUBSCRIPTION_STEPS.CHECKOUT, SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION, ].includes(step) && 'subscription-modal--fixed-height', [SUBSCRIPTION_STEPS.PLAN_SELECTION].includes(step) && 'subscription-modal--large-width', [ SUBSCRIPTION_STEPS.CUSTOMIZATION, SUBSCRIPTION_STEPS.CHECKOUT, SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION, ].includes(step) && 'subscription-modal--medium-width', ])} data-testid="plansModal" {...modalState} onClose={handleClose} disableCloseOnEscape={disableCloseOnEscape} fullscreen={fullscreen} as="form" size="large" onSubmit={onSubmit} > <ModalTwoHeader title={title} hasClose={hasClose} /> <ModalTwoContent>{content}</ModalTwoContent> {footer && <ModalTwoFooter>{footer}</ModalTwoFooter>} </ModalTwo> ); }} /> ); } } return ( <> {subscriptionModal} <SubscriptionModalContext.Provider value={[ (props) => { if (loading || render) { return; } subscriptionProps.current = props; setModalState(true); }, loading, ]} > {children} </SubscriptionModalContext.Provider> </> ); }; export default SubscriptionModalProvider;
6,774
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionPanelManageUserButton.tsx
import { c } from 'ttag'; import { Button, ButtonLike } from '@proton/atoms/Button'; import { AppLink, SettingsLink } from '@proton/components/components'; import { useConfig, useOrganization, useSubscription, useUser } from '@proton/components/hooks'; import { APPS } from '@proton/shared/lib/constants'; import { hasOrganizationSetup, hasOrganizationSetupWithKeys } from '@proton/shared/lib/helpers/organization'; import { getHasVpnB2BPlan } from '@proton/shared/lib/helpers/subscription'; import { UserType } from '@proton/shared/lib/interfaces'; const InternalAppLink = () => { return ( <ButtonLike as={SettingsLink} className="mb-2" color="norm" path="/users-addresses" size="large" fullWidth>{c( 'familyOffer_2023:Family plan' ).t`Manage user accounts`}</ButtonLike> ); }; const SubscriptionPanelManageUserButton = () => { const [user] = useUser(); const [organization] = useOrganization(); const [subscription] = useSubscription(); const { APP_NAME } = useConfig(); const isAdmin = user.isAdmin && !user.isSubUser && user.Type !== UserType.EXTERNAL; if (!isAdmin || !(hasOrganizationSetup(organization) || hasOrganizationSetupWithKeys(organization))) { return null; } if (APP_NAME === APPS.PROTONVPN_SETTINGS && !getHasVpnB2BPlan(subscription)) { return ( <AppLink to="/mail/users-addresses" toApp={APPS.PROTONACCOUNT} target="_blank"> <Button className="mb-2" color="norm" size="large" fullWidth>{c('familyOffer_2023:Family plan') .t`Manage user accounts`}</Button> </AppLink> ); } return <InternalAppLink />; }; export default SubscriptionPanelManageUserButton;
6,775
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/SubscriptionSubmitButton.tsx
import { c } from 'ttag'; import { PAYMENT_METHOD_TYPES, PaymentMethodType } from '@proton/components/payments/core'; import { PaypalProcessorHook } from '@proton/components/payments/react-extensions/usePaypal'; import { Currency, SubscriptionCheckResponse } from '@proton/shared/lib/interfaces'; import { Price, PrimaryButton } from '../../../components'; import StyledPayPalButton from '../StyledPayPalButton'; import { SUBSCRIPTION_STEPS } from './constants'; interface Props { className?: string; currency: Currency; step: SUBSCRIPTION_STEPS; onDone?: () => void; checkResult?: SubscriptionCheckResponse; loading?: boolean; paymentMethodValue?: PaymentMethodType; paypal: PaypalProcessorHook; disabled?: boolean; } const SubscriptionSubmitButton = ({ className, paypal, currency, step, loading, paymentMethodValue, checkResult, disabled, onDone, }: Props) => { const amountDue = checkResult?.AmountDue || 0; if (step === SUBSCRIPTION_STEPS.CUSTOMIZATION) { return ( <PrimaryButton className={className} disabled={disabled} loading={loading} type="submit" data-testid="confirm" > {c('Action').t`Continue`} </PrimaryButton> ); } if (amountDue === 0) { return ( <PrimaryButton className={className} loading={loading} disabled={disabled} type="submit" data-testid="confirm" > {c('Action').t`Confirm`} </PrimaryButton> ); } if (paymentMethodValue === PAYMENT_METHOD_TYPES.PAYPAL) { return ( <StyledPayPalButton type="submit" data-testid="confirm" paypal={paypal} className={className} amount={amountDue} currency={currency} /> ); } if (!loading && paymentMethodValue === PAYMENT_METHOD_TYPES.CASH) { return ( <PrimaryButton className={className} disabled={disabled} loading={loading} onClick={onDone}> {c('Action').t`Done`} </PrimaryButton> ); } if (paymentMethodValue === PAYMENT_METHOD_TYPES.BITCOIN) { return ( <PrimaryButton className={className} disabled={true} loading={loading}> {c('Info').t`Awaiting transaction`} </PrimaryButton> ); } const price = ( <Price key="price" currency={currency}> {amountDue} </Price> ); return ( <PrimaryButton className={className} loading={loading} disabled={disabled} type="submit" data-testid="confirm"> {amountDue > 0 ? c('Action').jt`Pay ${price} now` : c('Action').t`Confirm`} </PrimaryButton> ); }; export default SubscriptionSubmitButton;
6,776
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/UnsubscribeButton.test.tsx
import { act, fireEvent, render, waitFor } from '@testing-library/react'; import cloneDeep from 'lodash/cloneDeep'; import { useModals } from '@proton/components/hooks'; import { mockOrganizationApi, mockPlansApi, mockSubscriptionApi, mockUserCache, mockUserVPNServersCountApi, subscriptionDefaultResponse, } from '@proton/components/hooks/helpers/test'; import { External } from '@proton/shared/lib/interfaces'; import { apiMock, mockCache } from '@proton/testing'; import ApiContext from '../../api/apiContext'; import { CacheProvider } from '../../cache'; import EventManagerContext from '../../eventManager/context'; import { NotificationsProvider } from '../../notifications'; import InAppPurchaseModal from './InAppPurchaseModal'; import UnsubscribeButton from './UnsubscribeButton'; jest.mock('@proton/components/hooks/useModals'); beforeEach(() => { mockUserVPNServersCountApi(); mockUserCache(); mockSubscriptionApi(); mockOrganizationApi(); mockPlansApi(); }); const defaultEventManager = { call: jest.fn() }; const Providers = ({ children, eventManager = defaultEventManager, api = apiMock, cache = mockCache }: any) => { return ( <EventManagerContext.Provider value={eventManager}> <ApiContext.Provider value={api}> <NotificationsProvider> <CacheProvider cache={cache}>{children}</CacheProvider> </NotificationsProvider> </ApiContext.Provider> </EventManagerContext.Provider> ); }; it('should render', async () => { const { container } = render( <Providers> <UnsubscribeButton>Unsubscribe</UnsubscribeButton> </Providers> ); await waitFor(() => {}); expect(container).toHaveTextContent('Unsubscribe'); }); it('should open <InAppPurchaseModal> modal if subscription is managed by Google', async () => { const subscription = cloneDeep(subscriptionDefaultResponse); subscription.Subscription.External = External.Android; mockSubscriptionApi(subscription); const { getByTestId } = render( <Providers> <UnsubscribeButton>Unsubscribe</UnsubscribeButton> </Providers> ); await waitFor(() => {}); await act(async () => { fireEvent.click(getByTestId('UnsubscribeButton')); }); const { createModal } = useModals(); const mockCreateModal: jest.Mock = createModal as any; expect(createModal).toHaveBeenCalled(); expect(mockCreateModal.mock.lastCall[0].type).toEqual(InAppPurchaseModal); });
6,777
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/UnsubscribeButton.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { Button, ButtonProps } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { deleteSubscription } from '@proton/shared/lib/api/payments'; import { getShouldCalendarPreventSubscripitionChange } from '@proton/shared/lib/calendar/plans'; import { PLANS, PLAN_SERVICES } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { toMap } from '@proton/shared/lib/helpers/object'; import { hasBonuses } from '@proton/shared/lib/helpers/organization'; import { getPlan, hasMigrationDiscount, hasNewVisionary, isManagedExternally, } from '@proton/shared/lib/helpers/subscription'; import { hasPaidMail } from '@proton/shared/lib/user/helpers'; import { useApi, useEventManager, useGetCalendars, useModals, useNotifications, useOrganization, usePlans, useSubscription, useUser, useVPNServersCount, } from '../../../hooks'; import DowngradeModal from '../DowngradeModal'; import LossLoyaltyModal from '../LossLoyaltyModal'; import MemberDowngradeModal from '../MemberDowngradeModal'; import { getShortPlan } from '../features/plan'; import CalendarDowngradeModal from './CalendarDowngradeModal'; import FeedbackDowngradeModal, { FeedbackDowngradeData, FeedbackDowngradeResult, isKeepSubscription, } from './FeedbackDowngradeModal'; import HighlightPlanDowngradeModal from './HighlightPlanDowngradeModal'; import InAppPurchaseModal from './InAppPurchaseModal'; import { DiscountWarningModal, NewVisionaryWarningModal } from './PlanLossWarningModal'; const { MAIL, VPN } = PLAN_SERVICES; interface Props extends Omit<ButtonProps, 'loading' | 'onClick'> { children: ReactNode; } const UnsubscribeButton = ({ className, children, ...rest }: Props) => { const api = useApi(); const [vpnServers] = useVPNServersCount(); const [user] = useUser(); const [subscription, loadingSubscription] = useSubscription(); const [organization] = useOrganization(); const [plans, loadingPlans] = usePlans(); const { createNotification, hideNotification } = useNotifications(); const { createModal } = useModals(); const { call } = useEventManager(); const getCalendars = useGetCalendars(); const [loading, withLoading] = useLoading(); const { PeriodEnd = 0 } = subscription || {}; const currentPlan = getPlan(subscription); const plansMap = toMap(plans, 'Name'); const handleUnsubscribe = async (data: FeedbackDowngradeData) => { const downgradeNotificationId = createNotification({ type: 'info', text: c('State').t`Downgrading your account, please wait`, expiration: 99999, }); try { await api(deleteSubscription(data)); await call(); createNotification({ text: c('Success').t`You have successfully unsubscribed` }); } finally { hideNotification(downgradeNotificationId); } }; const handleClick = async () => { if (user.isFree) { return createNotification({ type: 'error', text: c('Info').t`You already have a free account` }); } // Start promise early const shouldCalendarPreventDowngradePromise = getShouldCalendarPreventSubscripitionChange({ hasPaidMail: hasPaidMail(user), willHavePaidMail: false, api, getCalendars, }); if (hasMigrationDiscount(subscription)) { await new Promise<void>((resolve, reject) => { createModal(<DiscountWarningModal type="downgrade" onClose={reject} onConfirm={resolve} />); }); } if (hasNewVisionary(subscription)) { await new Promise<void>((resolve, reject) => { createModal(<NewVisionaryWarningModal type="downgrade" onClose={reject} onConfirm={resolve} />); }); } if (isManagedExternally(subscription)) { await new Promise<void>((_, reject) => { createModal(<InAppPurchaseModal onClose={reject} subscription={subscription} />); }); } const shortPlan = currentPlan ? getShortPlan(currentPlan.Name as PLANS, plansMap, { vpnServers }) : undefined; // We only show the plan downgrade modal for plans that are defined with features if (shortPlan) { await new Promise<void>((resolve, reject) => { createModal( <HighlightPlanDowngradeModal shortPlan={shortPlan} periodEnd={PeriodEnd} onConfirm={resolve} onClose={reject} /> ); }); } if (await shouldCalendarPreventDowngradePromise) { await new Promise<void>((resolve, reject) => { createModal(<CalendarDowngradeModal isDowngrade onConfirm={resolve} onClose={reject} />); }); } if (hasBonuses(organization)) { await new Promise<void>((resolve, reject) => { createModal(<LossLoyaltyModal organization={organization} onConfirm={resolve} onClose={reject} />); }); } if (organization.UsedMembers > 1) { await new Promise<void>((resolve, reject) => { createModal(<MemberDowngradeModal organization={organization} onConfirm={resolve} onClose={reject} />); }); } const hasMail = hasBit(user.Subscribed, MAIL); const hasVpn = hasBit(user.Subscribed, VPN); if (hasMail || hasVpn) { await new Promise<void>((resolve, reject) => { createModal(<DowngradeModal hasMail={hasMail} hasVpn={hasVpn} onConfirm={resolve} onClose={reject} />); }); } const downgradeFeedbackOrKeepSubscription = await new Promise<FeedbackDowngradeResult>((resolve, reject) => { createModal(<FeedbackDowngradeModal user={user} onResolve={resolve} onReject={reject} />); }); if (isKeepSubscription(downgradeFeedbackOrKeepSubscription)) { return; } return handleUnsubscribe(downgradeFeedbackOrKeepSubscription); }; return ( <Button disabled={loading || loadingPlans || loadingSubscription} className={className} onClick={() => withLoading(handleClick())} data-testid="UnsubscribeButton" {...rest} > {children} </Button> ); }; export default UnsubscribeButton;
6,778
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/UpgradeVpnSection.tsx
import { APP_NAMES } from '@proton/shared/lib/constants'; import { pick } from '@proton/shared/lib/helpers/object'; import { Loader } from '../../../components'; import { useLoad, usePlans, useSubscription, useUser, useVPNServersCount } from '../../../hooks'; import { SettingsSectionWide } from '../../account'; import { useSubscriptionModal } from './SubscriptionModalProvider'; import { getCurrency, resolveUpsellsToDisplay } from './helpers'; import { UpsellPanels } from './panels'; import './YourPlanSection.scss'; interface Props { app: APP_NAMES; } const UpgradeVpnSection = ({ app }: Props) => { const [user] = useUser(); const [plans = [], loadingPlans] = usePlans(); const [subscription, loadingSubscription] = useSubscription(); const [openSubscriptionModal] = useSubscriptionModal(); const [serversCount, serversCountLoading] = useVPNServersCount(); useLoad(); const loading = loadingSubscription || loadingPlans || serversCountLoading; if (loading) { return <Loader />; } const currency = getCurrency(user, subscription, plans); const upsells = resolveUpsellsToDisplay({ app, currency, subscription, plans, serversCount, openSubscriptionModal, ...pick(user, ['canPay', 'isFree', 'hasPaidMail']), }); return ( <SettingsSectionWide> <div className="grid-column-2 your-plan-section-container gap-8 pt-4" data-testid="vpn-upsell-panels"> <UpsellPanels upsells={upsells} subscription={subscription} /> </div> </SettingsSectionWide> ); }; export default UpgradeVpnSection;
6,779
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/VPNPassPromotionButton.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { CYCLE, PASS_APP_NAME } from '@proton/shared/lib/constants'; import { Currency } from '@proton/shared/lib/interfaces'; import Logo from '../../../components/logo/Logo'; import { getSimplePriceString } from '../../../components/price/helper'; import getBoldFormattedText from '../../../helpers/getBoldFormattedText'; import PromotionBanner from '../../banner/PromotionBanner'; interface VPNPassPromotionButtonProps { onClick: () => void; currency: Currency; cycle: CYCLE; } const VPNPassPromotionButton = ({ onClick, currency, cycle }: VPNPassPromotionButtonProps) => { const price = getSimplePriceString(currency, 100, c('Suffix').t`/month`); const priceNoSuffix = getSimplePriceString(currency, 100, ''); return ( <PromotionBanner mode="banner" className="pr-4" rounded contentCentered={false} description={ <> {cycle === CYCLE.MONTHLY ? getBoldFormattedText( c('bf2023: Action') .t`Subscribe for 15 months and get our **encrypted password manager** for only ${priceNoSuffix} extra per month!` ) : getBoldFormattedText( c('bf2023: Action').t`**Add our encrypted password manager** for only ${price}` )} <div className="mt-4"> <Button onClick={onClick} className="flex flex-nowrap flex-align-items-center flex-justify-center" fullWidth shape="outline" color="norm" > <Logo appName="proton-pass" variant="glyph-only" className="flex-item-noshrink" size={16} /> <span className="ml-2"> {cycle === CYCLE.MONTHLY ? c('bf2023: Action').t`Get the deal` : c('bf2023: Action').t`Add ${PASS_APP_NAME}`} </span> </Button> </div> </> } /> ); }; export default VPNPassPromotionButton;
6,780
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/YourPlanSection.scss
@import '~@proton/styles/scss/lib'; .your-plan-section-container { display: grid; & > div { block-size: fit-content; } @include media('<=medium') { grid-template-columns: repeat(1, 1fr); } } .grid-column-3 { grid-template-columns: repeat(3, 1fr); @include media('<=large') { grid-template-columns: repeat(2, 1fr); } @include media('<=medium') { grid-template-columns: repeat(1, 1fr); } } .grid-column-2 { grid-template-columns: repeat(2, 1fr); @include media('<=medium') { grid-template-columns: repeat(1, 1fr); } }
6,781
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/YourPlanSection.test.tsx
import { fireEvent, render, waitFor, within } from '@testing-library/react'; import { useAddresses, useCache, useCalendars, useConfig, useFeature, useOrganization, usePlans, useSubscription, useUser, useVPNServersCount, } from '@proton/components/hooks'; import usePendingUserInvitations from '@proton/components/hooks/usePendingUserInvitations'; import { APPS, PLANS } from '@proton/shared/lib/constants'; import YourPlanSection from './YourPlanSection'; import { addresses, calendars, organization, pendingInvite, plans, subscriptionB, subscriptionBusiness, user, vpnServersCount, } from './__mocks__/data'; import { SUBSCRIPTION_STEPS } from './constants'; jest.mock('@proton/components/hooks/useConfig'); const mockUseConfig = useConfig as jest.MockedFunction<any>; mockUseConfig.mockReturnValue({ APP_NAME: APPS.PROTONMAIL }); jest.mock('@proton/components/hooks/useUser'); const mockUseUser = useUser as jest.MockedFunction<any>; mockUseUser.mockReturnValue([user, false]); jest.mock('@proton/components/hooks/usePlans'); const mockUsePlans = usePlans as jest.MockedFunction<any>; mockUsePlans.mockReturnValue([plans, false]); jest.mock('@proton/components/hooks/useAddresses'); const mockUseAddresses = useAddresses as jest.MockedFunction<any>; mockUseAddresses.mockReturnValue([addresses, false]); jest.mock('@proton/components/hooks/useCalendars'); const mockUseCalendars = useCalendars as jest.MockedFunction<any>; mockUseCalendars.mockReturnValue([calendars, false]); jest.mock('@proton/components/hooks/useSubscription'); const mockUseSubscription = useSubscription as jest.MockedFunction<any>; mockUseSubscription.mockReturnValue([subscriptionB, false]); jest.mock('@proton/components/hooks/useOrganization'); const mockUseOrganization = useOrganization as jest.MockedFunction<any>; mockUseOrganization.mockReturnValue([[], false]); jest.mock('@proton/components/hooks/useVPNServersCount'); const mockUseVPNServersCount = useVPNServersCount as jest.MockedFunction<any>; mockUseVPNServersCount.mockReturnValue([vpnServersCount, false]); jest.mock('@proton/components/hooks/usePendingUserInvitations'); const mockUsePendingUserInvitations = usePendingUserInvitations as jest.MockedFunction<any>; mockUsePendingUserInvitations.mockReturnValue([[], false]); jest.mock('@proton/components/hooks/useLoad'); const mockOpenSubscriptionModal = jest.fn(); jest.mock('./SubscriptionModalProvider', () => ({ __esModule: true, useSubscriptionModal: () => [mockOpenSubscriptionModal], })); jest.mock('@proton/components/hooks/useFeature'); const mockUseFeature = useFeature as jest.MockedFunction<any>; mockUseFeature.mockReturnValue({ feature: { Value: true } }); jest.mock('@proton/components/hooks/useCache'); const mockUseCache = useCache as jest.MockedFunction<any>; mockUseCache.mockReturnValue({ get: jest.fn(), delete: jest.fn() }); describe('YourPlanSection', () => { beforeEach(() => { mockUseSubscription.mockReturnValue([subscriptionB, false]); mockUsePendingUserInvitations.mockReturnValue([[], false]); mockUseOrganization.mockReturnValue([{}, false]); }); afterEach(() => { mockUsePendingUserInvitations.mockRestore(); mockUseOrganization.mockRestore(); mockUseSubscription.mockRestore(); }); describe('when user has no pending invite', () => { it('should only render subscription panel and upsell panels', async () => { const { getByTestId } = render(<YourPlanSection app={APPS.PROTONMAIL} />); const dashboardPanelsContainer = getByTestId('dashboard-panels-container'); expect(dashboardPanelsContainer.childNodes).toHaveLength(2); const [subscriptionPanel, upsellPanel] = dashboardPanelsContainer.childNodes; // Subscription Panel expect(subscriptionPanel).toBeTruthy(); within(subscriptionPanel as HTMLElement).getByText('Proton Unlimited'); within(subscriptionPanel as HTMLElement).getByText('Edit billing details'); within(subscriptionPanel as HTMLElement).getByText('Explore other Proton plans'); // Upsell Panel expect(upsellPanel).toBeTruthy(); within(upsellPanel as HTMLElement).getByText('Proton Family'); const upsellButton = within(upsellPanel as HTMLElement).getByTestId('upsell-cta'); fireEvent.click(upsellButton); await waitFor(() => expect(mockOpenSubscriptionModal).toHaveBeenCalledTimes(1)); expect(mockOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: 24, plan: PLANS.FAMILY, step: SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: true, metrics: { source: 'upsells', }, }); }); }); describe('when user has pending invites', () => { it('should render subscription panel and pending invites, without upsells', async () => { mockUsePendingUserInvitations.mockReturnValueOnce([[pendingInvite], false]); const { getByTestId } = render(<YourPlanSection app={APPS.PROTONMAIL} />); const dashboardPanelsContainer = getByTestId('dashboard-panels-container'); expect(dashboardPanelsContainer.childNodes).toHaveLength(2); const [subscriptionPanel, invitePanel] = dashboardPanelsContainer.childNodes; // Subscription Panel expect(subscriptionPanel).toBeTruthy(); within(subscriptionPanel as HTMLElement).getByText('Proton Unlimited'); within(subscriptionPanel as HTMLElement).getByText('Edit billing details'); within(subscriptionPanel as HTMLElement).getByText('Explore other Proton plans'); // Upsell Panel expect(invitePanel).toBeTruthy(); within(invitePanel as HTMLElement).getByText('Pending invitation'); within(invitePanel as HTMLElement).getByText('Invitation from Test Org'); within(invitePanel as HTMLElement).getByText('View invitation'); }); }); describe('[business] when there is more than one user in organization', () => { it('should render subscription, usage and upsells', () => { mockUseOrganization.mockReturnValue([organization]); mockUseSubscription.mockReturnValue([subscriptionBusiness]); const { getByTestId } = render(<YourPlanSection app={APPS.PROTONMAIL} />); const dashboardPanelsContainer = getByTestId('dashboard-panels-container'); expect(dashboardPanelsContainer.childNodes).toHaveLength(3); const [subscriptionPanel, usagePanel, upsellPanel] = dashboardPanelsContainer.childNodes; // Subscription Panel expect(subscriptionPanel).toBeTruthy(); within(subscriptionPanel as HTMLElement).getByText('Proton Pro'); // Upsell Panel expect(upsellPanel).toBeTruthy(); within(upsellPanel as HTMLElement).getByText('Business'); // Usage Panel expect(usagePanel).toBeTruthy(); within(usagePanel as HTMLElement).getByText("Your account's usage"); }); }); });
6,782
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/YourPlanSection.tsx
import usePendingUserInvitations from '@proton/components/hooks/usePendingUserInvitations'; import { APP_NAMES } from '@proton/shared/lib/constants'; import { pick } from '@proton/shared/lib/helpers/object'; import { getHasVpnB2BPlan } from '@proton/shared/lib/helpers/subscription'; import clsx from '@proton/utils/clsx'; import { Loader } from '../../../components'; import { useAddresses, useCalendars, useLoad, useOrganization, usePlans, useSubscription, useUser, useVPNServersCount, } from '../../../hooks'; import { SettingsSectionExtraWide, SettingsSectionWide } from '../../account'; import MozillaInfoPanel from '../../account/MozillaInfoPanel'; import { useSubscriptionModal } from './SubscriptionModalProvider'; // The import below is used for the docs // eslint-disable-next-line @typescript-eslint/no-unused-vars import type UpgradeVpnSection from './UpgradeVpnSection'; import { getCurrency, resolveUpsellsToDisplay } from './helpers'; import { SubscriptionPanel, UpsellPanels, UsagePanel } from './panels'; import PendingInvitationsPanel from './panels/PendingInvitationsPanel'; import './YourPlanSection.scss'; interface Props { app: APP_NAMES; } const YourPlanSection = ({ app }: Props) => { const [user] = useUser(); const [plans = [], loadingPlans] = usePlans(); const [addresses] = useAddresses(); const [calendars] = useCalendars(); const [subscription, loadingSubscription] = useSubscription(); const [organization, loadingOrganization] = useOrganization(); const [serversCount, serversCountLoading] = useVPNServersCount(); const [invites = []] = usePendingUserInvitations(); const [openSubscriptionModal] = useSubscriptionModal(); useLoad(); const loading = loadingSubscription || loadingOrganization || loadingPlans || serversCountLoading; if (loading) { return <Loader />; } const { isManagedByMozilla } = subscription; if (isManagedByMozilla) { return <MozillaInfoPanel />; } const currency = getCurrency(user, subscription, plans); const upsells = resolveUpsellsToDisplay({ app, currency, subscription, plans, serversCount, openSubscriptionModal, ...pick(user, ['canPay', 'isFree', 'hasPaidMail']), }); const isVpnB2b = getHasVpnB2BPlan(subscription); /** * for VPN B2B, we display the upsells in {@link UpgradeVpnSection} */ const shouldRenderUpsells = !isVpnB2b; // VPN B2B plans must not have a usage panel const shouldRenderUsagePanel = organization.UsedMembers > 1 && !isVpnB2b; const shouldRenderPendingInvitation = Boolean(invites.length); const totalPanelsToDisplay = 1 + (+shouldRenderPendingInvitation || upsells.length) + +shouldRenderUsagePanel; // By default, for style consistency, we display every setting in `SettingsSectionWide` // But since 3 panels don't fit in this section (or are too tightly packed), // we use the extra wide one when we have > 2 panels to display const shouldRenderInLargeSection = totalPanelsToDisplay > 2; const SettingsSection = shouldRenderInLargeSection ? SettingsSectionExtraWide : SettingsSectionWide; // Either display pending invitations if any, or upsell(s) const invitationsOrUpsells = (() => { if (shouldRenderPendingInvitation) { return <PendingInvitationsPanel invites={invites} />; } if (shouldRenderUpsells) { return <UpsellPanels upsells={upsells} subscription={subscription} />; } return null; })(); return ( <SettingsSection> <div className={clsx( shouldRenderInLargeSection ? 'grid-column-3' : 'grid-column-2', 'your-plan-section-container gap-8 pt-4' )} data-testid="dashboard-panels-container" > {/* Subcription details */} <SubscriptionPanel app={app} currency={currency} subscription={subscription} organization={organization} user={user} addresses={addresses} vpnServers={serversCount} openSubscriptionModal={openSubscriptionModal} /> {/* Usage for plans with >1 Members */} {shouldRenderUsagePanel && ( <UsagePanel addresses={addresses} calendars={calendars} organization={organization} user={user} /> )} {invitationsOrUpsells} </div> </SettingsSection> ); }; export default YourPlanSection;
6,783
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/constants.ts
export enum SUBSCRIPTION_STEPS { NETWORK_ERROR, PLAN_SELECTION, CUSTOMIZATION, CHECKOUT, CHECKOUT_WITH_CUSTOMIZATION, UPGRADE, THANKS, } export const subscriptionModalClassName = 'subscription-modal';
6,784
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/index.ts
export { default as AutomaticSubscriptionModal } from './AutomaticSubscriptionModal'; export { default as DowngradeSubscriptionSection } from './DowngradeSubscriptionSection'; export { default as PlanCustomization } from './PlanCustomization'; export { default as PlanSelection } from './PlanSelection'; export { SubscriptionCheckoutCycleItem, default as SubscriptionCycleSelector } from './SubscriptionCycleSelector'; export { default as SubscriptionModalDisabled } from './SubscriptionModalDisabled'; export * from './SubscriptionModalProvider'; export { default as SubscriptionModalProvider } from './SubscriptionModalProvider'; export { default as UpgradeVpnSection } from './UpgradeVpnSection'; export { default as YourPlanSection } from './YourPlanSection'; export { default as CancelB2bSubscriptionSection } from './cancelB2bSubscription/CancelB2bSubscriptionSection'; export { CancelSubscriptionSection } from './cancelSubscription'; export * from './constants';
6,785
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/subscriptionEligbility.ts
import { ADDON_NAMES, COUPON_CODES, CYCLE, PLANS, isFreeSubscription } from '@proton/shared/lib/constants'; import { getPlan } from '@proton/shared/lib/helpers/subscription'; import type { Plan, PlansMap, SubscriptionModel, UserModel } from '@proton/shared/lib/interfaces'; import type { OfferConfig } from '../../offers/interface'; export interface PlanCombination { plan: Plan; coupon?: string; cycle: CYCLE; } export interface PlanCombinationWithDiscount extends PlanCombination { discount: number; } export type Eligibility = | { type: 'upsell'; planCombination: PlanCombinationWithDiscount; } | { type: 'sub-user'; } | { type: 'subscribed'; } | { type: 'bf-applied'; } | { type: 'pass-through'; } | { type: 'not-eligible'; }; const getSafePlan = (plansMap: PlansMap, planName: PLANS | ADDON_NAMES) => { const plan = plansMap?.[planName]; if (!plan) { throw new Error('Missing plan'); } return plan; }; const getVpnFifteenOffer = (plansMap: PlansMap): Eligibility => { const plan = getSafePlan(plansMap, PLANS.VPN); return { type: 'upsell', planCombination: { plan, cycle: CYCLE.FIFTEEN, discount: 52, }, }; }; const getVpnThirtyOffer = (plansMap: PlansMap): Eligibility => { const plan = getSafePlan(plansMap, PLANS.VPN); return { type: 'upsell', planCombination: { plan, cycle: CYCLE.THIRTY, discount: 60, }, }; }; const getVpnPassFifteenOffer = (plansMap: PlansMap): Eligibility => { const plan = getSafePlan(plansMap, PLANS.VPN_PASS_BUNDLE); return { type: 'upsell', planCombination: { plan, cycle: CYCLE.FIFTEEN, discount: 47, }, }; }; const getVpnPassThirtyOffer = (plansMap: PlansMap): Eligibility => { const plan = getSafePlan(plansMap, PLANS.VPN_PASS_BUNDLE); return { type: 'upsell', planCombination: { plan, cycle: CYCLE.THIRTY, discount: 55, }, }; }; const getBundleOffer = (plansMap: PlansMap): Eligibility => { const plan = getSafePlan(plansMap, PLANS.BUNDLE); return { type: 'upsell', planCombination: { plan, cycle: CYCLE.YEARLY, discount: 33, }, }; }; interface Combination { latest: { plan: PLANS; cycles: CYCLE[]; }; target: { plan: PLANS; cycles: CYCLE[]; }; result: () => Eligibility; } export const getEligibility = ({ user, offer, subscription, plansMap, eligibleBlackFridayConfigs, }: { user: UserModel; subscription: SubscriptionModel | null | undefined; offer: { plan: Plan; cycle: CYCLE; coupon?: string }; plansMap: PlansMap; eligibleBlackFridayConfigs: OfferConfig[]; }): Eligibility => { if (!user.canPay) { return { type: 'sub-user' }; } const latest = subscription?.UpcomingSubscription ?? subscription; const latestPlan = latest ? getPlan(latest) : undefined; const okResult = (): Eligibility => ({ type: 'pass-through' }); if (offer.coupon === COUPON_CODES.BLACK_FRIDAY_2023) { if ( eligibleBlackFridayConfigs.some((config) => { return config.deals.some((deal) => { return deal.cycle === offer.cycle && deal.planIDs[offer.plan.Name]; }); }) ) { return okResult(); } const getPlusUpsell = (from: PLANS, to: PLANS) => { return { latest: { plan: from, cycles: [CYCLE.MONTHLY, CYCLE.YEARLY, CYCLE.TWO_YEARS], }, target: { plan: to, cycles: [CYCLE.MONTHLY, CYCLE.FIFTEEN, CYCLE.THIRTY], }, result: () => getBundleOffer(plansMap), }; }; const vpnUpsells: Combination[] = [ { latest: { plan: PLANS.VPN, cycles: [CYCLE.MONTHLY], }, target: { plan: PLANS.VPN, cycles: [CYCLE.MONTHLY], }, result: () => getVpnFifteenOffer(plansMap), }, { latest: { plan: PLANS.VPN, cycles: [CYCLE.YEARLY, CYCLE.FIFTEEN], }, target: { plan: PLANS.VPN, cycles: [CYCLE.MONTHLY, CYCLE.FIFTEEN], }, result: () => getVpnThirtyOffer(plansMap), }, { latest: { plan: PLANS.VPN, cycles: [CYCLE.TWO_YEARS, CYCLE.THIRTY], }, target: { plan: PLANS.VPN, cycles: [CYCLE.MONTHLY, CYCLE.FIFTEEN, CYCLE.THIRTY], }, result: () => getBundleOffer(plansMap), }, { latest: { plan: PLANS.PASS_PLUS, cycles: [CYCLE.MONTHLY], }, target: { plan: PLANS.VPN, cycles: [CYCLE.MONTHLY, CYCLE.FIFTEEN], }, result: () => getVpnPassFifteenOffer(plansMap), }, { latest: { plan: PLANS.PASS_PLUS, cycles: [CYCLE.MONTHLY], }, target: { plan: PLANS.VPN, cycles: [CYCLE.THIRTY], }, result: () => getVpnPassThirtyOffer(plansMap), }, { latest: { plan: PLANS.PASS_PLUS, cycles: [CYCLE.YEARLY], }, target: { plan: PLANS.VPN, cycles: [CYCLE.MONTHLY, CYCLE.FIFTEEN], }, result: () => getVpnPassFifteenOffer(plansMap), }, { latest: { plan: PLANS.PASS_PLUS, cycles: [CYCLE.YEARLY], }, target: { plan: PLANS.VPN, cycles: [CYCLE.THIRTY], }, result: () => getVpnPassThirtyOffer(plansMap), }, { latest: { plan: PLANS.PASS_PLUS, cycles: [CYCLE.TWO_YEARS], }, target: { plan: PLANS.VPN, cycles: [CYCLE.MONTHLY, CYCLE.FIFTEEN, CYCLE.THIRTY], }, result: () => getVpnPassThirtyOffer(plansMap), }, { latest: { plan: PLANS.BUNDLE, cycles: [CYCLE.MONTHLY], }, target: { plan: PLANS.VPN, cycles: [CYCLE.MONTHLY, CYCLE.FIFTEEN, CYCLE.THIRTY], }, result: () => getBundleOffer(plansMap), }, { latest: { plan: PLANS.BUNDLE, cycles: [CYCLE.MONTHLY], }, target: { plan: PLANS.VPN_PASS_BUNDLE, cycles: [CYCLE.MONTHLY, CYCLE.FIFTEEN, CYCLE.THIRTY], }, result: () => getBundleOffer(plansMap), }, getPlusUpsell(PLANS.MAIL, PLANS.VPN), getPlusUpsell(PLANS.MAIL, PLANS.VPN_PASS_BUNDLE), getPlusUpsell(PLANS.DRIVE, PLANS.VPN), getPlusUpsell(PLANS.DRIVE, PLANS.VPN_PASS_BUNDLE), ]; const vpnPassUpsells: Combination[] = [ { latest: { plan: PLANS.VPN, cycles: [CYCLE.YEARLY], }, target: { plan: PLANS.VPN_PASS_BUNDLE, cycles: [CYCLE.FIFTEEN], }, result: () => getVpnPassThirtyOffer(plansMap), }, { latest: { plan: PLANS.VPN, cycles: [CYCLE.FIFTEEN], }, target: { plan: PLANS.VPN_PASS_BUNDLE, cycles: [CYCLE.FIFTEEN], }, result: () => getVpnPassThirtyOffer(plansMap), }, { latest: { plan: PLANS.VPN, cycles: [CYCLE.TWO_YEARS, CYCLE.THIRTY], }, target: { plan: PLANS.VPN_PASS_BUNDLE, cycles: [CYCLE.FIFTEEN, CYCLE.THIRTY], }, result: () => getBundleOffer(plansMap), }, { latest: { plan: PLANS.PASS_PLUS, cycles: [CYCLE.TWO_YEARS], }, target: { plan: PLANS.VPN_PASS_BUNDLE, cycles: [CYCLE.FIFTEEN], }, result: () => getVpnPassThirtyOffer(plansMap), }, ]; const bundle12Ok: Combination[] = [ { latest: { plan: PLANS.BUNDLE, cycles: [CYCLE.MONTHLY], }, target: { plan: PLANS.BUNDLE, cycles: [CYCLE.YEARLY], }, result: okResult, }, { latest: { plan: PLANS.MAIL, cycles: [CYCLE.MONTHLY, CYCLE.YEARLY, CYCLE.TWO_YEARS], }, target: { plan: PLANS.BUNDLE, cycles: [CYCLE.YEARLY], }, result: okResult, }, { latest: { plan: PLANS.DRIVE, cycles: [CYCLE.MONTHLY, CYCLE.YEARLY, CYCLE.TWO_YEARS], }, target: { plan: PLANS.BUNDLE, cycles: [CYCLE.YEARLY], }, result: okResult, }, { latest: { plan: PLANS.PASS_PLUS, cycles: [CYCLE.MONTHLY, CYCLE.YEARLY, CYCLE.TWO_YEARS], }, target: { plan: PLANS.BUNDLE, cycles: [CYCLE.YEARLY], }, result: okResult, }, { latest: { plan: PLANS.VPN, cycles: [CYCLE.MONTHLY, CYCLE.YEARLY, CYCLE.TWO_YEARS], }, target: { plan: PLANS.BUNDLE, cycles: [CYCLE.YEARLY], }, result: okResult, }, ]; // Assumes upsells are first const vpnPassBundleOk: Combination[] = [ { latest: { plan: PLANS.FREE, cycles: [], }, target: { plan: PLANS.VPN_PASS_BUNDLE, cycles: [CYCLE.FIFTEEN, CYCLE.THIRTY], }, result: okResult, }, { latest: { plan: PLANS.PASS_PLUS, cycles: [CYCLE.MONTHLY, CYCLE.YEARLY, CYCLE.TWO_YEARS], }, target: { plan: PLANS.VPN_PASS_BUNDLE, cycles: [CYCLE.FIFTEEN, CYCLE.THIRTY], }, result: okResult, }, { latest: { plan: PLANS.VPN, cycles: [CYCLE.MONTHLY, CYCLE.YEARLY, CYCLE.FIFTEEN, CYCLE.TWO_YEARS, CYCLE.THIRTY], }, target: { plan: PLANS.VPN_PASS_BUNDLE, cycles: [CYCLE.FIFTEEN, CYCLE.THIRTY], }, result: okResult, }, ]; const combinations: Combination[] = [...vpnUpsells, ...vpnPassUpsells, ...bundle12Ok, ...vpnPassBundleOk]; const combination = combinations.find((combination) => { const correctPlan = combination.latest.plan === PLANS.FREE ? isFreeSubscription(latest) : latestPlan?.Name === combination.latest.plan; const correctCycle = combination.latest.plan === PLANS.FREE ? true : combination.latest.cycles.includes(latest?.Cycle as any); return ( combination.target.plan === offer.plan.Name && combination.target.cycles.includes(offer.cycle) && correctPlan && correctCycle ); }); if (combination) { return combination.result(); } return { type: 'not-eligible' }; } return okResult(); };
6,786
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/useCheckoutModifiers.test.tsx
import { renderHook } from '@testing-library/react-hooks'; import { COUPON_CODES, CYCLE, PLANS } from '@proton/shared/lib/constants'; import { PlansMap, Renew, SubscriptionCheckResponse, SubscriptionModel } from '@proton/shared/lib/interfaces'; import { Model } from './SubscriptionContainer'; import { SUBSCRIPTION_STEPS } from './constants'; import { useCheckoutModifiers } from './useCheckoutModifiers'; describe('useCheckoutModifiers', () => { let model: Model; let subscriptionModel: SubscriptionModel; let checkResult: SubscriptionCheckResponse; const plansMap: PlansMap = { mail2022: { ID: 'Wb4NAqmiuqoA7kCHE28y92bBFfN8jaYQCLxHRAB96yGj-bh9SxguXC48_WSU-fRUjdAr-lx95c6rFLplgXyXYA==', Type: 1, Name: PLANS.MAIL, Title: 'Mail Plus', MaxDomains: 1, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 499, '12': 4788, '24': 8376, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 499, Offers: [], }, mailpro2022: { ID: 'rIJcBetavQi7h5qqN9nxrRnlojgl6HF6bAVG989deNJVVVx1nn2Ic3eyCVV2Adq11ddseZuWba9H5tmvLC727Q==', Type: 1, Name: PLANS.MAIL_PRO, Title: 'Mail Essentials', MaxDomains: 3, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 799, '12': 8388, '24': 15576, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 799, Offers: [], }, bundle2022: { ID: 'vl-JevUsz3GJc18CC1VOs-qDKqoIWlLiUePdrzFc72-BtxBPHBDZM7ayn8CNQ59Sk4XjDbwwBVpdYrPIFtOvIw==', Type: 1, Name: PLANS.BUNDLE, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 7, Features: 1, State: 1, Pricing: { '1': 1199, '12': 11988, '24': 19176, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 1199, Offers: [], }, }; beforeEach(() => { model = { step: SUBSCRIPTION_STEPS.CHECKOUT, planIDs: { [PLANS.MAIL]: 1, }, currency: 'CHF', cycle: CYCLE.MONTHLY, initialCheckComplete: false, }; subscriptionModel = { ID: 'id123', InvoiceID: 'id456', Cycle: CYCLE.MONTHLY, PeriodStart: Math.floor(Date.now() / 1000) - 1, PeriodEnd: Math.floor(Date.now() / 1000 + 30 * 24 * 60 * 60), CreateTime: Math.floor(Date.now() / 1000) - 1, CouponCode: null, Currency: 'CHF', Amount: 499, RenewAmount: 499, Discount: 0, isManagedByMozilla: false, External: 0, Renew: Renew.Enabled, Plans: [ { Amount: 499, Currency: 'CHF', Cycle: 1, Features: 1, ID: 'Wb4NAqmiuqoA7kCHE28y92bBFfN8jaYQCLxHRAB96yGj-bh9SxguXC48_WSU-fRUjdAr-lx95c6rFLplgXyXYA==', MaxAddresses: 10, MaxCalendars: 25, MaxDomains: 1, MaxMembers: 1, MaxSpace: 16106127360, MaxTier: 0, MaxVPN: 0, Name: PLANS.MAIL, Quantity: 1, Services: 1, State: 1, Title: 'Mail Plus', Type: 1, Pricing: null as any, Offers: [], }, ], }; checkResult = { Amount: 499, AmountDue: 499, Coupon: null, Currency: 'CHF', Cycle: CYCLE.MONTHLY, Additions: null, PeriodEnd: Math.floor(Date.now() / 1000 + 30 * 24 * 60 * 60), }; }); it('should return isProration === true when checkResult is undefined', () => { const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap)); expect(result.current.isProration).toEqual(true); }); it('should return isProration === true when user buys different plan', () => { model.planIDs = { [PLANS.MAIL_PRO]: 1, }; subscriptionModel.Plans[0].Name = PLANS.MAIL; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(true); }); it('should return isProration === true if user buys the same plan but proration is undefined', () => { checkResult.Proration = undefined; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(true); }); it('should return isProration === true if Proration exists and proration !== 0', () => { checkResult.Proration = -450; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(true); }); it('should return isProration === false if Proration exists and proration === 0', () => { checkResult.Proration = 0; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(false); }); it('should return isScheduledSubscription === false if checkResult is undefined', () => { const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap)); expect(result.current.isScheduledSubscription).toEqual(false); }); it('should return isProration true when user has trial', () => { subscriptionModel.CouponCode = COUPON_CODES.REFERRAL; checkResult.Proration = 0; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(true); }); describe('custom billings', () => { it('should return isScheduledSubscription === false if UnusedCredit !== 0', () => { checkResult.Proration = 0; checkResult.UnusedCredit = -20; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isScheduledSubscription).toEqual(false); }); it('should return isProration === false if UnusedCredit !== 0', () => { checkResult.Proration = 0; checkResult.UnusedCredit = -20; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isProration).toEqual(false); }); it('should return isCustomBilling === true if UnusedCredit !== 0', () => { checkResult.Proration = 0; checkResult.UnusedCredit = -20; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isCustomBilling).toEqual(true); }); it('should return isCustomBilling === false if UnusedCredit === 0', () => { checkResult.Proration = 150; checkResult.UnusedCredit = 0; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isCustomBilling).toEqual(false); }); it('should return isCustomBilling === false if UnusedCredit === 0 if Proration is 0 too', () => { checkResult.Proration = 0; checkResult.UnusedCredit = 0; const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap, checkResult)); expect(result.current.isCustomBilling).toEqual(false); }); it('should return isCustomBilling === false if checkResult is undefined', () => { const { result } = renderHook(() => useCheckoutModifiers(model, subscriptionModel, plansMap)); expect(result.current.isCustomBilling).toEqual(false); }); }); });
6,787
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/useCheckoutModifiers.tsx
import { useMemo } from 'react'; import { getCheckout } from '@proton/shared/lib/helpers/checkout'; import { getPlanIDs, isTrial } from '@proton/shared/lib/helpers/subscription'; import { PlansMap, SubscriptionCheckResponse, SubscriptionModel } from '@proton/shared/lib/interfaces'; import { Model } from './SubscriptionContainer'; export interface CheckoutModifiers { isProration: boolean; isScheduledSubscription: boolean; isCustomBilling: boolean; } export const useCheckoutModifiers = ( model: Model, subscription: SubscriptionModel, plansMap: PlansMap, checkResult?: SubscriptionCheckResponse ) => { const isProration = useMemo(() => { const checkout = getCheckout({ planIDs: getPlanIDs(subscription), plansMap, checkResult, }); const activePlan = checkout.planName as string; const selectedPlans = Object.keys(model.planIDs); const userBuysTheSamePlan = selectedPlans.includes(activePlan); // That's a catch-all scenario. Essentially, if user doesn't really have Proration, nor custom billings, // nor scheduled subscription, then we still claim that it's Proration. From the rendering perspective, // it's a convernient assumption, because then we pretend that it's Proration case with Proration === 0. // Essentially it means that we will render no additional UI specific to any of the three cases. // // Absence of checkResult means that it's not loaded yet. // If user doesn't buy the same plan, then custom billing and scheduled subscription are not applicable. // If Prorartion is undefined, then that's not a full checkResult. // If user has trial, then we just need to show the Proration UI with Proration === 0. if (!checkResult || !userBuysTheSamePlan || checkResult.Proration === undefined || isTrial(subscription)) { return true; } // The main indicator for the proration is non-zero Proration value. // However we must also ensure that it's not custom billings by checking that UnusedCredit is 0 or undefined. return ( checkResult.Proration !== 0 && (checkResult.UnusedCredit === 0 || checkResult.UnusedCredit === undefined) ); }, [subscription, model, checkResult]); const isCustomBilling = checkResult ? checkResult.UnusedCredit !== 0 : false; const isScheduledSubscription = !isProration && !isCustomBilling; return { isProration, isScheduledSubscription, isCustomBilling, }; };
6,788
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/__mocks__/SubscriptionContainer.tsx
const SubscriptionContainer = jest.fn().mockImplementation(() => <>SubscriptionContainer</>); export default SubscriptionContainer;
6,789
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/__mocks__/data.ts
import { PLANS, PLAN_TYPES } from '@proton/shared/lib/constants'; import { Organization, PendingInvitation, Plan, Subscription, User, VPNServersCountData, } from '@proton/shared/lib/interfaces'; import { PLANS_MAP } from '@proton/testing/data'; import { UpsellCta } from '../helpers'; export const plans = [ { Type: 1, Name: 'drive2022', Title: 'Drive Plus', MaxDomains: 0, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 214748364800, MaxMembers: 0, MaxVPN: 0, MaxTier: 0, Services: 2, Features: 0, State: 1, Pricing: { '1': 499, '12': 4788, '24': 8376, }, Currency: 'EUR', Quantity: 1, Offers: [], Cycle: 1, Amount: 499, }, { Type: 1, Name: 'mail2022', Title: 'Mail Plus', MaxDomains: 1, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 499, '12': 4788, '24': 8376, }, Currency: 'EUR', Quantity: 1, Offers: [], Cycle: 1, Amount: 499, }, { Type: 1, Name: 'pass2023', Title: 'Pass Plus', MaxDomains: 0, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 0, MaxTier: 0, Services: 8, Features: 0, State: 1, Pricing: { '1': 499, '12': 4788, '24': 7176, }, Currency: 'EUR', Quantity: 1, Offers: [], Cycle: 1, Amount: 499, }, { Type: 1, Name: 'mailpro2022', Title: 'Mail Essentials', MaxDomains: 3, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 799, '12': 8388, '24': 15576, }, Currency: 'EUR', Quantity: 1, Offers: [], Cycle: 1, Amount: 799, }, { Type: 1, Name: 'bundle2022', Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Pricing: { '1': 1199, '12': 11988, '24': 19176, }, Currency: 'EUR', Quantity: 1, Offers: [], Cycle: 1, Amount: 1199, }, { Type: 1, Name: 'bundlepro2022', Title: 'Business', MaxDomains: 10, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Pricing: { '1': 1299, '12': 13188, '24': 23976, }, Currency: 'EUR', Quantity: 1, Offers: [], Cycle: 1, Amount: 1299, }, { Type: 1, Name: 'family2022', Title: 'Proton Family', MaxDomains: 3, MaxAddresses: 90, MaxCalendars: 150, MaxSpace: 3298534883328, MaxMembers: 6, MaxVPN: 60, MaxTier: 2, Services: 15, Features: 1, State: 1, Pricing: { '1': 2999, '12': 28788, '24': 47976, }, Currency: 'EUR', Quantity: 1, Cycle: 1, Amount: 2999, }, PLANS_MAP[PLANS.VPN_PRO], PLANS_MAP[PLANS.VPN_BUSINESS], ] as unknown as Plan[]; export const mailPlusUpsell = { plan: PLANS.MAIL, planKey: PLANS.MAIL, title: 'Mail Plus', description: 'Secure email with advanced features for your everyday communications.', upsellRefLink: 'upsell_mail-button-mailplus-dashboard_settings', features: [ { text: ['', '15 GB', ' storage'], tooltip: 'Storage space is shared across Proton Mail, Proton Calendar, and Proton Drive', included: true, highlight: false, icon: 'storage', }, { text: '10 email addresses/aliases', tooltip: 'Create multiple email addresses for your online identities, e.g., JohnShopper@proton.me for shopping accounts, JohnNews@proton.me for news subscription', included: true, icon: 'envelope', }, { text: '1 custom email domain', tooltip: 'Use your own custom email domain addresses, e.g., you@yourname.com', included: true, icon: 'globe', }, { text: 'Unlimited folders, labels, and filters', included: true, icon: 'tag', }, { text: '25 calendars', tooltip: 'Create up to 25 calendars or add calendars from friends, family, colleagues, and organizations', included: true, icon: 'brand-proton-calendar', }, { icon: 'brand-proton-vpn', text: '1 VPN connection', included: true, }, { text: 'Proton Pass with 10 hide-my-email aliases', icon: 'pass-all-vaults', included: true, hideInDowngrade: true, }, ], otherCtas: [], price: { value: 349, currency: 'EUR', }, }; export const trialMailPlusUpsell = { ...mailPlusUpsell, title: 'Mail Plus Trial', otherCtas: [ { label: 'Explore all Proton plans', action: () => {}, color: 'norm', shape: 'ghost', }, ] as UpsellCta[], isTrialEnding: true, hasVPN: false, hasPaidMail: false, }; export const unlimitedUpsell = { plan: PLANS.BUNDLE, planKey: PLANS.BUNDLE, title: 'Proton Unlimited', description: 'Comprehensive privacy and security with all Proton services combined.', upsellRefLink: 'upsell_mail-button-unlimited-dashboard_settings', features: [ { text: ['', '500 GB', ' storage'], tooltip: 'Storage space is shared across Proton Mail, Proton Calendar, and Proton Drive', included: true, highlight: false, icon: 'storage', }, { text: '15 email addresses/aliases', tooltip: 'Create multiple email addresses for your online identities, e.g., JohnShopper@proton.me for shopping accounts, JohnNews@proton.me for news subscription', included: true, icon: 'envelope', }, { text: '3 custom email domains', tooltip: 'Use your own custom email domain addresses, e.g., you@yourname.com', included: true, icon: 'globe', }, { text: 'Proton Sentinel program', tooltip: `Provides the highest level of account security protection and specialist support`, included: true, icon: 'shield', }, { text: 'Unlimited folders, labels, and filters', included: true, icon: 'tag', }, { icon: 'brand-proton-calendar', included: true, text: '25 calendars', tooltip: 'Create up to 25 calendars or add calendars from friends, family, colleagues, and organizations', }, { icon: 'brand-proton-vpn', text: '10 high-speed VPN connections', included: true, }, { text: 'Proton Pass with unlimited hide-my-email aliases', icon: 'pass-all-vaults', included: true, hideInDowngrade: true, }, ], otherCtas: [], price: { value: 799, currency: 'EUR', }, }; export const familyUpsell = { plan: PLANS.FAMILY, planKey: PLANS.FAMILY, title: 'Proton Family', description: 'Protect your family’s privacy with all Proton services combined.', upsellRefLink: 'upsell_mail-button-family-dashboard_settings', features: [ { text: ['', '3 TB', ' storage'], tooltip: 'Storage space is shared between users across Proton Mail, Proton Calendar, and Proton Drive', included: true, highlight: false, icon: 'storage', }, { text: 'Up to 6 users', icon: 'users', included: true, }, { text: '90 email addresses/aliases', tooltip: 'Create up to 90 email addresses/aliases that you can assign to family members. Use them for online identities, e.g., JohnShopper@proton.me for shopping accounts.', included: true, icon: 'envelope', }, { text: 'Unlimited folders, labels, and filters', included: true, icon: 'tag', }, { icon: 'brand-proton-vpn', text: '10 high-speed VPN connections', included: true, }, { text: 'Proton Pass with unlimited hide-my-email aliases', icon: 'pass-all-vaults', included: true, hideInDowngrade: true, }, ], otherCtas: [], price: { value: 1999, currency: 'EUR' }, }; export const businessUpsell = { plan: PLANS.BUNDLE_PRO, planKey: PLANS.BUNDLE_PRO, title: 'Business', description: 'Privacy and security suite for businesses, including all premium Proton services.', upsellRefLink: 'upsell_mail-button-business-dashboard_settings', features: [ { icon: 'storage', text: 'Boost your storage space to 500 GB per user', }, { icon: 'envelope', text: '5 email addresses per user', }, { icon: 'globe', text: 'Cover more ground with support for 10 custom email domains', }, { icon: 'brand-proton-vpn', text: '10 high-speed VPN connections per user', }, { icon: 'checkmark-circle', text: 'Access advanced VPN features', }, ], otherCtas: [], price: { value: 999, currency: 'EUR', }, }; export const drivePlusUpsell = { plan: PLANS.DRIVE, planKey: PLANS.DRIVE, title: 'Drive Plus', description: 'Secure cloud storage that lets you store, sync, and share files easily and securely.', upsellRefLink: 'upsell_drive-button-drive-dashboard_settings', features: [ { text: ['', '200 GB', ' storage'], tooltip: 'Storage space is shared across Proton Mail, Proton Calendar, and Proton Drive', included: true, highlight: false, icon: 'storage', }, { text: '1 email address', tooltip: '', included: true, icon: 'envelope', }, { text: '3 calendars', tooltip: 'Create up to 3 calendars or add calendars from friends, family, colleagues, and organizations', included: true, icon: 'brand-proton-calendar', }, { text: '1 VPN connection', included: true, icon: 'brand-proton-vpn', }, { text: 'Priority support', included: true, icon: 'life-ring', }, ], otherCtas: [], price: { value: 349, currency: 'EUR', }, }; export const passPlusUpsell = { plan: PLANS.PASS_PLUS, planKey: PLANS.PASS_PLUS, title: 'Pass Plus', description: 'For next-level password management and identity protection.', upsellRefLink: 'upsell_pass-button-pass-dashboard_settings', features: [ { text: 'Unlimited logins and notes', icon: 'note', included: true, hideInDowngrade: true, }, { text: 'Unlimited devices', icon: 'mobile', included: true, hideInDowngrade: true, }, { text: 'Unlimited hide-my-email aliases', tooltip: 'Unique, on-the-fly email addresses that protect your online identity and let you control what lands in your inbox. From SimpleLogin by Proton.', included: true, icon: 'eye-slash', }, { text: '20 vaults', tooltip: 'Like a folder, a vault is a convenient way to organize your items. Sharing vaults with friends and family is in the works.', included: true, icon: 'vault', }, { text: 'Integrated 2FA authenticator', included: true, icon: 'key', }, { text: 'Custom fields', included: true, icon: 'pen-square', }, { text: 'Priority support', included: true, icon: 'life-ring', }, ], otherCtas: [], price: { value: 299, currency: 'EUR', }, }; export const vpnBusinessUpsell = { plan: PLANS.VPN_BUSINESS, planKey: PLANS.VPN_BUSINESS, title: 'VPN Business', description: 'Advanced network security and access management with dedicated secure Gateways', otherCtas: [], price: { value: 5397, currency: 'EUR', }, }; export const vpnEnterpriseUpsell = { planKey: 'VPN_ENTERPRISE', title: 'VPN Enterprise', description: 'Tailor-made solutions for larger organizations with specific security needs', }; export const subscription = { Plans: [ { Name: PLANS.MAIL, Type: PLAN_TYPES.PLAN, }, ], } as Subscription; // TODO: merge with subcription export const subscriptionB = { ID: 'PpErwjEKmPzaSJq7niHgapRGcJXdHg9xiDvVZd98OF1hXojWlmbuKMpxSZihUh-I9agIbYHw3bkZJ44KixWQNg==', InvoiceID: '8jJIlDHXg2jQYePRCBicfTKDbJwecy529KlYGdoqPGnAQ2ALW1RkH4dWFQ1vDIp9UryQ6ezSRiw0vEKmaTiX2g==', Cycle: 12, PeriodStart: 1685966060, PeriodEnd: 1717588460, CreateTime: 1685966060, CouponCode: null, Currency: 'EUR', Amount: 11988, Discount: 0, RenewAmount: 11988, Plans: [ { ID: 'tHdKCeJlgD7mv_W13BqEZeelMiptPIK6r8arzZFcQcLvBLNiogdGOGVyYOldyhzcnSzCPkvkWj-VtyDwSjIncg==', Name: PLANS.BUNDLE, Type: PLAN_TYPES.PLAN, Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Cycle: 12, Currency: 'EUR', Amount: 11988, Quantity: 1, }, ], } as Subscription; export const subscriptionBusiness = { Cycle: 12, Currency: 'EUR', Amount: 11988, Plans: [ { Name: PLANS.MAIL_PRO, Type: PLAN_TYPES.PLAN, Title: 'Proton Pro', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 15, Features: 1, State: 1, Cycle: 12, Currency: 'EUR', Amount: 11988, }, ], } as Subscription; export const organization = { UsedDomains: 1, MaxDomains: 3, UsedSpace: 987359925, MaxSpace: 1073741824, UsedAddresses: 7, MaxAddresses: 20, UsedMembers: 2, MaxMembers: 5, } as Organization; export const vpnServersCount = { free: { servers: 192, countries: 3, }, paid: { servers: 2950, countries: 65, }, } as VPNServersCountData; export const user = { MaxSpace: 1073741824, MaxUpload: 26214400, UsedSpace: 977359925, isAdmin: true, isFree: false, isMember: false, isPaid: true, isPrivate: true, isSubUser: false, isDelinquent: false, hasNonDelinquentScope: true, hasPaidMail: true, hasPaidVpn: true, canPay: true, } as unknown as User; export const pendingInvite = { ID: 'ZhhRDNTAVfX9seV5rWSw_2_4rP23tplH2ajNld9iOJc49qiL_cafDdQvHIG3dHXpYsbcmPUKdZjz3Bb7S81Uiw==', InviterEmail: 'testinvites@protontest.com', OrganizationName: 'Test Org', } as PendingInvitation; export const calendars = [ { ID: '2lBg7c-llitncK-rleyMCEBnuVHJPd9i5HrdMMZP7OMfioUGTx4Tqx2oGSQjD5vMg8639__wmj9vLZnk2c45sw==', }, { ID: '-5TcZlOQHrNakdQHZYduP2M4jyh3Q7j4YwSW-8ib8W3-dUSpdCQglfmOudMGY10c8Kclm--smRSqjz3CzLYLFw==', }, { ID: 'Msdl_ju-F7w3nO6dm2Y3GfiCFJQU3jLVD_0Dk4qPyrOYVgeyuwjFY9_DPAOZler_XwNcv27qxg70PkhvIqqGhw==', }, ]; export const addresses = [ { ID: 'A17MnOJQ4w_BkRoCb9o9RISXCRfIqCb3NaGUGeM9jyei4Zj2WtGVlyBzZqGhc_oSPv8qund-nP5ZXc-E9oYNAw==', Email: 'testas1@protonmail.com', Status: 1, Receive: 1, Send: 1, }, { ID: 'IRSyGs2rcuAUUUv_Rzur_H6PFPUoEpc4iB8pa4BPvuKAJap2BDqD8Rra0Jn1_iY9gLGV1cc0YjjZW34DPBTNaQ==', Email: 'testas1@pm.me', Status: 1, Receive: 1, Send: 1, }, ];
6,790
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelB2bSubscription/CancelB2bSubscriptionModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, Option, Prompt, SelectTwo, TextAreaTwo, useApi, useConfig, useErrorHandler, useFormErrors, useUser, } from '@proton/components'; import { getClientName } from '@proton/components/helpers/report'; import { reportCancelPlan } from '@proton/shared/lib/api/reports'; import { getBrowser, getOS } from '@proton/shared/lib/helpers/browser'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import noop from '@proton/utils/noop'; enum STEP { FORM, COMPLETED, } enum REASON { TOO_EXPENSIVE, MISSING_FEATURE, ANOTHER_SERVICE, OTHER, } const { TOO_EXPENSIVE, MISSING_FEATURE, ANOTHER_SERVICE, OTHER } = REASON; const reasons: { [key in REASON]: { tag: string; label: string } } = { [TOO_EXPENSIVE]: { tag: 'tag_1', label: c('VPN B2B cancellation reason').t`It’s too expensive`, }, [MISSING_FEATURE]: { tag: 'tag_2', label: c('VPN B2B cancellation reason').t`It’s missing a key feature`, }, [ANOTHER_SERVICE]: { tag: 'tag_3', label: c('VPN B2B cancellation reason').t`I found another service that I like better`, }, [OTHER]: { tag: 'tag_4', label: c('VPN B2B cancellation reason').t`Other`, }, }; export interface Props extends ModalProps {} const CancelB2bSubscriptionModal = ({ open, onClose, ...rest }: Props) => { const api = useApi(); const [user] = useUser(); const { APP_NAME, APP_VERSION, CLIENT_TYPE } = useConfig(); const errorHandler = useErrorHandler(); const [step, setStep] = useState(STEP.FORM); const [loading, setLoading] = useState(false); const [selectedReason, setSelectedReason] = useState<REASON>(); const [feedback, setFeedback] = useState(''); const { validator, onFormSubmit } = useFormErrors(); if (step === STEP.COMPLETED) { return ( <Prompt open={open} onClose={onClose} title={c('Title').t`Request sent`} buttons={[<Button color="norm" onClick={onClose}>{c('Action').t`Got it`}</Button>]} {...rest} > {c('Info').t`We'll get back to you shortly.`} </Prompt> ); } const handleSubmit = async () => { if (!onFormSubmit() || selectedReason === undefined) { return; } setLoading(true); try { const reason = reasons[selectedReason]; const browser = getBrowser(); const os = getOS(); const client = getClientName(APP_NAME); await api( reportCancelPlan({ Reason: reason.label, Message: feedback, Email: user.Email, OS: os.name, OSVersion: os.version, Browser: browser.name, BrowserVersion: browser.version, Client: client, ClientVersion: APP_VERSION, ClientType: CLIENT_TYPE, Tags: [reason.tag], }) ); setStep(STEP.COMPLETED); } catch (error) { errorHandler(error); setLoading(false); } }; return ( <Modal as={Form} open={open} onClose={loading ? noop : onClose} onSubmit={handleSubmit} {...rest}> <ModalHeader title={c('Title').t`Contact us`} /> <ModalContent> <InputFieldTwo as={SelectTwo} label={c('Label').t`Why would you like to cancel?`} placeholder={c('Placeholder').t`Please select the main reason`} id="reason" value={selectedReason} onValue={(value: unknown) => { setSelectedReason(value as REASON); }} error={validator([requiredValidator(selectedReason)])} disabled={loading} > {Object.entries(reasons).map(([value, { label }]) => ( <Option title={label} value={value} key={value} /> ))} </InputFieldTwo> <InputFieldTwo as={TextAreaTwo} id="feedback" label={c('Label').t`Please share any feedback to help us improve.`} value={feedback} onValue={setFeedback} error={validator([requiredValidator(feedback)])} rows={5} disabled={loading} /> </ModalContent> <ModalFooter> <Button onClick={onClose} disabled={loading}> {c('Action').t`Cancel`} </Button> <Button loading={loading} type="submit" color="norm"> {c('Action').t`Submit`} </Button> </ModalFooter> </Modal> ); }; export default CancelB2bSubscriptionModal;
6,791
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelB2bSubscription/CancelB2bSubscriptionSection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { useModalState } from '@proton/components/components'; import { SettingsParagraph, SettingsSection } from '@proton/components/containers'; import { useSubscription } from '@proton/components/hooks'; import CancelB2bSubscriptionModal from './CancelB2bSubscriptionModal'; const CancelB2bSubscriptionSection = () => { const [subscription, loadingSubscription] = useSubscription(); const [modalProps, setModalOpen, render] = useModalState(); if (!subscription) { return null; } return ( <> {render && <CancelB2bSubscriptionModal {...modalProps} />} <SettingsSection> <SettingsParagraph> {c('Info').t`To cancel your subscription, please reach out to us.`} </SettingsParagraph> <Button onClick={() => setModalOpen(true)} color="norm" shape="outline" disabled={loadingSubscription}> {c('Action').t`Contact us`} </Button> </SettingsSection> </> ); }; export default CancelB2bSubscriptionSection;
6,792
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/CancelSubscriptionModal.test.tsx
import { render } from '@testing-library/react'; import { subscriptionMock, upcomingSubscriptionMock } from '@proton/testing/data'; import { CancelSubscriptionModal } from './CancelSubscriptionModal'; jest.mock('@proton/components/components/portal/Portal'); const onResolve = jest.fn(); const onReject = jest.fn(); it('should render', () => { const { container } = render( <CancelSubscriptionModal subscription={subscriptionMock} onResolve={onResolve} onReject={onReject} open /> ); expect(container).not.toBeEmptyDOMElement(); }); it('should return status kept when clicking on keep subscription', () => { const { getByTestId } = render( <CancelSubscriptionModal subscription={subscriptionMock} onResolve={onResolve} onReject={onReject} open /> ); getByTestId('keepSubscription').click(); expect(onResolve).toHaveBeenCalledWith({ status: 'kept' }); }); it('should return status cancelled when clicking on cancel subscription', () => { const { getByTestId } = render( <CancelSubscriptionModal subscription={subscriptionMock} onResolve={onResolve} onReject={onReject} open /> ); getByTestId('cancelSubscription').click(); expect(onResolve).toHaveBeenCalledWith({ status: 'cancelled' }); }); it('should display end date of the current subscription', () => { const { container } = render( <CancelSubscriptionModal subscription={subscriptionMock} onResolve={onResolve} onReject={onReject} open /> ); expect(container).toHaveTextContent('expires on Jun 5, 2024'); }); it('should display the end date of the upcoming subscription if it exists', () => { const { container } = render( <CancelSubscriptionModal subscription={{ ...subscriptionMock, UpcomingSubscription: upcomingSubscriptionMock }} onResolve={onResolve} onReject={onReject} open /> ); expect(container).toHaveTextContent('expires on Jun 5, 2026'); });
6,793
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/CancelSubscriptionModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getPlanTitle, hasVPN, hasVPNPassBundle } from '@proton/shared/lib/helpers/subscription'; import { SubscriptionModel } from '@proton/shared/lib/interfaces'; import { ModalProps, Prompt, Time } from '../../../../components'; import { ModalTwoPromiseHandlers } from '../../../../components/modalTwo/useModalTwo'; import { CancelSubscriptionResult } from './types'; type PromiseHandlers = ModalTwoPromiseHandlers<CancelSubscriptionResult>; export type CancelSubscriptionModalProps = ModalProps & { subscription: SubscriptionModel; }; export const CancelSubscriptionModal = ({ subscription, onResolve, onReject, ...rest }: CancelSubscriptionModalProps & PromiseHandlers) => { const handleKeepSubscription = () => { onResolve({ status: 'kept' }); }; const handleCancelSubscription = () => { onResolve({ status: 'cancelled' }); }; const planTitle = getPlanTitle(subscription) ?? ''; const isVpn = hasVPN(subscription) || hasVPNPassBundle(subscription); const latestSubscription = subscription.UpcomingSubscription ?? subscription; const expiryDate = ( <Time format="PP" className="text-bold" key="expiry-time"> {latestSubscription.PeriodEnd} </Time> ); return ( <Prompt title={c('Title').t`Cancel subscription?`} buttons={[ <Button onClick={handleCancelSubscription} color="danger" data-testid="cancelSubscription"> {c('Action').t`Cancel subscription`} </Button>, <Button onClick={handleKeepSubscription} data-testid="keepSubscription">{c('Action') .t`Keep my Plus subscription`}</Button>, ]} onClose={handleKeepSubscription} {...rest} > <p>{c('Info') .jt`If you cancel, your ${planTitle} subscription will not be renewed when it expires on ${expiryDate}.`}</p> {isVpn && <p>{c('Info').t`You will lose access to Plus servers and features on this date.`}</p>} {!isVpn && <p>{c('Info').t`You will lose access to Plus features on this date.`}</p>} </Prompt> ); };
6,794
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/CancelSubscriptionSection.test.tsx
import { render } from '@testing-library/react'; import { mockSubscriptionCache, mockUserCache } from '@proton/components/hooks/helpers/test'; import { applyHOCs, withApi, withCache, withEventManager, withNotifications } from '@proton/testing/index'; import { CancelSubscriptionSection } from './CancelSubscriptionSection'; const CancelSubscriptionSectionContext = applyHOCs( withApi(), withEventManager(), withCache(), withNotifications() )(CancelSubscriptionSection); beforeEach(() => { jest.clearAllMocks(); mockSubscriptionCache(); mockUserCache(); }); it('should render', () => { const { container } = render(<CancelSubscriptionSectionContext />); expect(container).not.toBeEmptyDOMElement(); }); it('should return empty DOM element if no subscription', () => { mockSubscriptionCache(null as any); const { container } = render(<CancelSubscriptionSectionContext />); expect(container).toBeEmptyDOMElement(); });
6,795
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/CancelSubscriptionSection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { useSubscription, useUser } from '../../../../hooks'; import { SettingsParagraph, SettingsSection } from '../../../account'; import { useCancelSubscriptionFlow } from './useCancelSubscriptionFlow'; export const CancelSubscriptionSection = () => { const [subscription, loadingSubscription] = useSubscription(); const [user] = useUser(); const { cancelSubscriptionModals, cancelSubscription } = useCancelSubscriptionFlow({ subscription, user, }); if (!subscription) { return null; } return ( <> {cancelSubscriptionModals} <SettingsSection> <SettingsParagraph> {c('Info') .t`This will cancel your current paid subscription and you will lose any loyalty benefits you have accumulated.`} </SettingsParagraph> <Button onClick={cancelSubscription} data-testid="CancelSubsriptionButton" color="danger" shape="outline" disabled={loadingSubscription} > {c('Action').t`Cancel subscription`} </Button> </SettingsSection> </> ); };
6,796
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/index.ts
export * from './CancelSubscriptionModal'; export * from './CancelSubscriptionSection'; export * from './types'; export * from './useCancelSubscriptionFlow';
6,797
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/types.tsx
export type CancelSubscriptionResult = | { status: 'kept'; } | { status: 'cancelled'; };
6,798
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/useCancelSubscriptionFlow.test.tsx
import { render } from '@testing-library/react'; import { renderHook } from '@testing-library/react-hooks'; import userEvent from '@testing-library/user-event'; import { changeRenewState } from '@proton/shared/lib/api/payments'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Renew, SubscriptionModel, UserModel } from '@proton/shared/lib/interfaces'; import { componentWrapper as _componentWrapper, apiMock, hookWrapper, withApi, withConfig, withEventManager, withNotifications, } from '@proton/testing'; import { subscriptionMock } from '@proton/testing/data'; import { useCancelSubscriptionFlow } from './useCancelSubscriptionFlow'; jest.mock('@proton/components/components/portal/Portal'); const user: UserModel = { ID: 'user-123', } as UserModel; const providers = [withConfig(), withApi(), withEventManager(), withNotifications()]; const wrapper = hookWrapper(...providers); const componentWrapper = _componentWrapper(...providers); it('should return modals and cancelSubscription', () => { const { result } = renderHook( () => useCancelSubscriptionFlow({ subscription: subscriptionMock as SubscriptionModel, user }), { wrapper } ); expect(result.current.cancelSubscription).toBeDefined(); expect(result.current.cancelSubscriptionModals).toBeDefined(); }); it('should return subscription kept if no subscription', async () => { const { result } = renderHook(() => useCancelSubscriptionFlow({ subscription: undefined as any, user }), { wrapper, }); await expect(result.current.cancelSubscription()).resolves.toEqual({ status: 'kept', }); }); it('should return subscription kept if no user', async () => { const { result } = renderHook( () => useCancelSubscriptionFlow({ subscription: subscriptionMock as SubscriptionModel, user: undefined as any }), { wrapper } ); await expect(result.current.cancelSubscription()).resolves.toEqual({ status: 'kept', }); }); it('should return subscription kept if user closes the modal', async () => { const { result } = renderHook( () => useCancelSubscriptionFlow({ subscription: subscriptionMock as SubscriptionModel, user }), { wrapper } ); const cancelSubscriptionPromise = result.current.cancelSubscription(); const { getByTestId } = render(result.current.cancelSubscriptionModals); getByTestId('keepSubscription').click(); await expect(cancelSubscriptionPromise).resolves.toEqual({ status: 'kept', }); }); it('should return subscription kept if user closes the feedback modal', async () => { const { result } = renderHook( () => useCancelSubscriptionFlow({ subscription: subscriptionMock as SubscriptionModel, user }), { wrapper } ); const cancelSubscriptionPromise = result.current.cancelSubscription(); // Render the modal components returned by the hook const { getByTestId, rerender } = render(result.current.cancelSubscriptionModals, { wrapper: componentWrapper, }); getByTestId('cancelSubscription').click(); await wait(0); rerender(result.current.cancelSubscriptionModals); // Simulate user clicking the element to close the feedback modal getByTestId('cancelFeedback').click(); await expect(cancelSubscriptionPromise).resolves.toEqual({ status: 'kept', }); }); it('should send the API request for subscription cancellation and return the result', async () => { const { result } = renderHook( () => useCancelSubscriptionFlow({ subscription: subscriptionMock as SubscriptionModel, user }), { wrapper } ); const cancelSubscriptionPromise = result.current.cancelSubscription(); const { getByTestId, rerender, container, getByText } = render(result.current.cancelSubscriptionModals, { wrapper: componentWrapper, }); getByTestId('cancelSubscription').click(); await wait(0); rerender(result.current.cancelSubscriptionModals); await userEvent.click(container.querySelector('#reason') as HTMLButtonElement); await userEvent.click(getByText('I use a different Proton account')); getByTestId('submitFeedback').click(); await wait(0); rerender(result.current.cancelSubscriptionModals); expect(apiMock).toHaveBeenCalledWith( changeRenewState({ RenewalState: Renew.Disabled, CancellationFeedback: { Reason: 'DIFFERENT_ACCOUNT', Feedback: '', ReasonDetails: '', Context: 'mail', }, }) ); await expect(cancelSubscriptionPromise).resolves.toEqual({ status: 'cancelled', }); });
6,799