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/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/cancelSubscription/useCancelSubscriptionFlow.tsx
import { c } from 'ttag'; import { changeRenewState } from '@proton/shared/lib/api/payments'; import { Renew, SubscriptionModel, UserModel } from '@proton/shared/lib/interfaces'; import { useModalTwo } from '../../../../components/modalTwo'; import { useApi, useEventManager, useNotifications } from '../../../../hooks'; import FeedbackDowngradeModal, { FeedbackDowngradeModalProps, FeedbackDowngradeResult, isKeepSubscription, } from '../FeedbackDowngradeModal'; import { CancelSubscriptionModal, CancelSubscriptionModalProps } from './CancelSubscriptionModal'; import { CancelSubscriptionResult } from './types'; const SUBSCRIPTION_KEPT: CancelSubscriptionResult = { status: 'kept', }; export interface UseCancelSubscriptionFlowProps { subscription: SubscriptionModel; user: UserModel; } /** * This hook will handle cancellation flow. It will display the cancellation modal and the feedback modal. * Use this hook if you need to implement cancellation flow elsewhere. It will help to be consistent in terms of UX * and expectations of the internal stakeholders. * @returns {cancelSubscriptionModals, cancelSubscription} * cancelSubscriptionModals: the modals to display – just render them in your component by returning them * cancelSubscription: the function to call to cancel the subscription. */ export const useCancelSubscriptionFlow = ({ subscription, user }: UseCancelSubscriptionFlowProps) => { const api = useApi(); const eventManager = useEventManager(); const [cancelSubscriptionModal, showCancelSubscriptionModal] = useModalTwo< CancelSubscriptionModalProps, CancelSubscriptionResult >(CancelSubscriptionModal); const [feedbackDowngradeModal, showFeedbackDowngradeModal] = useModalTwo< FeedbackDowngradeModalProps, FeedbackDowngradeResult >(FeedbackDowngradeModal); const { createNotification, hideNotification } = useNotifications(); const modals = ( <> {cancelSubscriptionModal} {feedbackDowngradeModal} </> ); const cancelSubscription = async (): Promise<CancelSubscriptionResult> => { if (!subscription || !user) { return SUBSCRIPTION_KEPT; } const result = await showCancelSubscriptionModal({ subscription, }); if (result.status === 'kept') { return SUBSCRIPTION_KEPT; } const feedback = await showFeedbackDowngradeModal({ user }); if (isKeepSubscription(feedback)) { return SUBSCRIPTION_KEPT; } const cancelNotificationId = createNotification({ type: 'info', text: c('State').t`Cancelling your subscription, please wait`, expiration: 99999, }); try { await api( changeRenewState({ RenewalState: Renew.Disabled, CancellationFeedback: feedback, }) ); await eventManager.call(); createNotification({ text: c('Success').t`You have successfully cancelled your subscription.` }); } finally { hideNotification(cancelNotificationId); } return result; }; return { cancelSubscriptionModals: modals, cancelSubscription, }; };
6,800
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/helpers/VpnEnterpriseAction.tsx
import { c } from 'ttag'; import { ButtonLike } from '@proton/atoms/Button'; import { vpnEnterpriseContactUrl } from './vpnEnterpriseContactUrl'; const VpnEnterpriseAction = ({ ...props }) => { return ( <ButtonLike as="a" color="norm" href={vpnEnterpriseContactUrl} fullWidth {...props}> {c('Action').t`Get in touch`} </ButtonLike> ); }; export default VpnEnterpriseAction;
6,801
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/helpers/dashboard-upsells.test.ts
import { APPS, COUPON_CODES, CYCLE, PLANS, PLAN_TYPES } from '@proton/shared/lib/constants'; import { Subscription } from '@proton/shared/lib/interfaces'; import { businessUpsell, drivePlusUpsell, familyUpsell, mailPlusUpsell, passPlusUpsell, plans, subscription, trialMailPlusUpsell, unlimitedUpsell, vpnBusinessUpsell, vpnEnterpriseUpsell, } from '../__mocks__/data'; import { SUBSCRIPTION_STEPS } from '../constants'; import { resolveUpsellsToDisplay } from './dashboard-upsells'; describe('resolveUpsellsToDisplay', () => { let mockedOpenSubscriptionModal: jest.Mock; let base: Parameters<typeof resolveUpsellsToDisplay>[0]; beforeEach(() => { mockedOpenSubscriptionModal = jest.fn(); base = { app: APPS.PROTONMAIL, currency: 'EUR', subscription, plans, serversCount: { paid: { servers: 100, countries: 10, }, free: { servers: 10, countries: 1, }, }, canPay: true, isFree: true, hasPaidMail: false, openSubscriptionModal: mockedOpenSubscriptionModal, }; }); describe('Free Mail', () => { it('should return MailPlus + Unlimited (recommended) upsells', () => { const upsells = resolveUpsellsToDisplay(base); expect(upsells).toMatchObject([mailPlusUpsell, { ...unlimitedUpsell, isRecommended: true }]); upsells[0].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ disablePlanSelection: true, plan: PLANS.MAIL, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); upsells[1].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(2); expect(mockedOpenSubscriptionModal).toHaveBeenLastCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.BUNDLE, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Free Trial', () => { it('should return MailPlus + Unlimited (recommended) upsells', () => { const upsells = resolveUpsellsToDisplay({ ...base, subscription: { ...base.subscription, CouponCode: COUPON_CODES.REFERRAL, PeriodEnd: 1718870501, } as Subscription, }); // .toMatchObject can't match functions, so we need to remove them const trialMailPlusUpsellWithoutAction = { ...trialMailPlusUpsell, otherCtas: trialMailPlusUpsell.otherCtas.map(({ action, ...rest }) => rest), }; expect(upsells).toMatchObject([ trialMailPlusUpsellWithoutAction, { ...unlimitedUpsell, isRecommended: true }, ]); upsells[0].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ disablePlanSelection: true, plan: PLANS.MAIL, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); upsells[1].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(2); expect(mockedOpenSubscriptionModal).toHaveBeenLastCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.BUNDLE, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Mail Plus', () => { it('should return Unlimited (recommended) + Family upsells', () => { const upsells = resolveUpsellsToDisplay({ ...base, isFree: false, hasPaidMail: true, }); expect(upsells).toMatchObject([ { ...unlimitedUpsell, isRecommended: true, features: unlimitedUpsell.features.filter(({ text }) => text !== '25 calendars'), }, familyUpsell, ]); upsells[0].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.BUNDLE, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); upsells[1].onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(2); expect(mockedOpenSubscriptionModal).toHaveBeenLastCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.FAMILY, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Unlimited', () => { it('should return Family upsell', () => { const [upsell] = resolveUpsellsToDisplay({ ...base, isFree: false, hasPaidMail: true, subscription: { Plans: [ { Name: PLANS.BUNDLE, Type: PLAN_TYPES.PLAN, }, ], } as Subscription, }); expect(upsell).toMatchObject(familyUpsell); upsell.onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.FAMILY, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Essentials', () => { it('should return Business upsell', () => { const [upsell] = resolveUpsellsToDisplay({ ...base, isFree: false, hasPaidMail: true, subscription: { Plans: [ { Name: PLANS.MAIL_PRO, Type: PLAN_TYPES.PLAN, }, ], } as Subscription, }); expect(upsell).toMatchObject(businessUpsell); upsell.onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.BUNDLE_PRO, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Free Drive', () => { it('should return Drive upsell', () => { const [upsell] = resolveUpsellsToDisplay({ ...base, app: APPS.PROTONDRIVE, isFree: true, }); expect(upsell).toMatchObject(drivePlusUpsell); upsell.onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.DRIVE, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('Free Pass', () => { it('should return Pass upsell', () => { const [upsell] = resolveUpsellsToDisplay({ ...base, app: APPS.PROTONPASS, isFree: true, }); expect(upsell).toMatchObject(passPlusUpsell); upsell.onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.PASS_PLUS, step: SUBSCRIPTION_STEPS.CHECKOUT, metrics: { source: 'upsells', }, }); }); }); describe('VPN Essentials', () => { it('should return VPN Business and VPN Enterprise upselss', () => { const upsells = resolveUpsellsToDisplay({ ...base, subscription: { Plans: [ { Name: PLANS.VPN_PRO, Type: PLAN_TYPES.PLAN, }, ], } as Subscription, app: APPS.PROTONACCOUNT, isFree: false, }); const [upsell1, upsell2] = upsells; expect(upsell1).toMatchObject(vpnBusinessUpsell); upsell1.onUpgrade(); expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); expect(mockedOpenSubscriptionModal).toHaveBeenCalledWith({ cycle: CYCLE.TWO_YEARS, disablePlanSelection: true, plan: PLANS.VPN_BUSINESS, step: SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION, metrics: { source: 'upsells', }, }); expect(upsell2).toMatchObject(vpnEnterpriseUpsell); expect(upsell2.ignoreDefaultCta).toEqual(true); expect(upsell2.otherCtas).toHaveLength(1); upsell2.onUpgrade(); // that's right, the VPN Enterprise upsell should not call the modal. It must have noop because it has // custom CTA. The 1 comes from the previous call expect(mockedOpenSubscriptionModal).toHaveBeenCalledTimes(1); }); }); describe('VPN Business', () => { it('should return VPN Enterprise upsell', () => { const [upsell] = resolveUpsellsToDisplay({ ...base, subscription: { Plans: [ { Name: PLANS.VPN_BUSINESS, Type: PLAN_TYPES.PLAN, }, ], } as Subscription, app: APPS.PROTONACCOUNT, isFree: false, }); expect(upsell).toMatchObject(vpnEnterpriseUpsell); expect(upsell.ignoreDefaultCta).toEqual(true); expect(upsell.otherCtas).toHaveLength(1); upsell.onUpgrade(); expect(mockedOpenSubscriptionModal).not.toHaveBeenCalled(); }); }); });
6,802
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/helpers/dashboard-upsells.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { ButtonLikeProps } from '@proton/atoms/Button'; import { MAX_CALENDARS_PAID } from '@proton/shared/lib/calendar/constants'; import { APPS, APP_NAMES, BRAND_NAME, CYCLE, DASHBOARD_UPSELL_PATHS, FAMILY_MAX_USERS, FREE_VPN_CONNECTIONS, PLANS, UPSELL_COMPONENT, } from '@proton/shared/lib/constants'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { toMap } from '@proton/shared/lib/helpers/object'; import { getHasLegacyPlans, hasBundle, hasDrive, hasMail, hasMailPro, hasPassPlus, hasVPN, hasVPNPassBundle, hasVpnBusiness, hasVpnPro, isTrial, } from '@proton/shared/lib/helpers/subscription'; import { getUpsellRefFromApp } from '@proton/shared/lib/helpers/upsell'; import { Currency, Plan, Subscription, VPNServersCountData } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import { getNCalendarsFeature } from '../../features/calendar'; import { getStorageBoostFeatureB2B, getStorageFeature } from '../../features/drive'; import { getSentinel, getUsersFeature } from '../../features/highlights'; import { PlanCardFeatureDefinition } from '../../features/interface'; import { getB2BNDomainsFeature, getFoldersAndLabelsFeature, getNAddressesFeature, getNAddressesFeatureB2B, getNDomainsFeature, } from '../../features/mail'; import { FREE_PASS_ALIASES, getProtonPassFeature } from '../../features/pass'; import { getShortPlan, getVPNEnterprisePlan } from '../../features/plan'; import { getAdvancedVPNFeature, getB2BHighSpeedVPNConnectionsFeature, getDedicatedAccountManagerVPNFeature, getDedicatedServersVPNFeature, getHighSpeedVPNConnectionsFeature, getVPNConnectionsFeature, } from '../../features/vpn'; import { OpenSubscriptionModalCallback } from '../SubscriptionModalProvider'; import { SUBSCRIPTION_STEPS } from '../constants'; import VpnEnterpriseAction from './VpnEnterpriseAction'; const cycle = CYCLE.TWO_YEARS; export interface UpsellFeature extends Omit<PlanCardFeatureDefinition, 'status' | 'highlight' | 'included'> { status?: PlanCardFeatureDefinition['status']; included?: PlanCardFeatureDefinition['included']; } type MaybeUpsellFeature = UpsellFeature | undefined; export type ButtonShape = ButtonLikeProps<'button'>['shape']; export type ButtonColor = ButtonLikeProps<'button'>['color']; /** * CTA stands for Call To Action. That's meant to be used with buttons that will start the upgrading flow. * For example, "Buy plan XYZ for $X/month" */ export interface UpsellCta { label: string | string[]; action: () => void; fullWidth?: boolean; shape?: ButtonShape; color?: ButtonColor; } export function isUpsellCta(item: any): item is UpsellCta { return item && typeof item === 'object' && 'label' in item && 'action' in item; } interface Price { value: number; currency: Currency; } export interface Upsell { plan?: PLANS; /** * Unique key for React rednering. */ planKey: string; title: string; description: string; isRecommended?: boolean; features: UpsellFeature[]; /** * If there is a fully custom plan, like VPN Enterprise, then there is no need for price. * It can be used together with ignoreDefaultCta */ price?: Price; onUpgrade: () => void; defaultCtaOverrides?: Partial<UpsellCta>; otherCtas: (UpsellCta | ReactNode)[]; upsellRefLink?: string; isTrialEnding?: boolean; /** * The default CTA won't be rendered at all if this is true. */ ignoreDefaultCta?: boolean; } type MaybeUpsell = Upsell | null; type GetUpsellArgs = { plan: PLANS; plansMap: { [key in PLANS]: Plan }; currency: Currency; app: APP_NAMES; upsellPath: DASHBOARD_UPSELL_PATHS; serversCount: VPNServersCountData; } & Partial<Upsell>; type GetPlanUpsellArgs = Omit<GetUpsellArgs, 'plan' | 'upsellPath' | 'otherCtas'> & { hasPaidMail?: boolean; hasVPN: boolean; openSubscriptionModal: OpenSubscriptionModalCallback; }; const getUpsell = ({ plan, plansMap, serversCount, currency, upsellPath, app, ...upsellFields }: GetUpsellArgs) => { const fullPlan = plansMap[plan]; const shortPlan = getShortPlan(plan, plansMap, { vpnServers: serversCount }); if (!shortPlan) { return null; } const upsellRefLink = getUpsellRefFromApp({ app: APPS.PROTONACCOUNT, fromApp: app, feature: upsellPath, component: UPSELL_COMPONENT.BUTTON, }); return { plan, planKey: plan, title: upsellFields.isTrialEnding ? c('new_plans: Title').t`${shortPlan.title} Trial` : shortPlan.title, description: shortPlan.description, upsellRefLink, price: { value: (fullPlan.Pricing[cycle] || 0) / cycle, currency }, features: (upsellFields.features ?? shortPlan.features).filter((item) => isTruthy(item)), onUpgrade: () => {}, otherCtas: [], ...upsellFields, }; }; const getMailPlusUpsell = ({ plansMap, openSubscriptionModal, isTrialEnding, ...rest }: GetPlanUpsellArgs): MaybeUpsell => { const mailPlusPlan = plansMap[PLANS.MAIL]; const features: MaybeUpsellFeature[] = [ getStorageFeature(mailPlusPlan?.MaxSpace ?? 15), getNAddressesFeature({ n: 10 }), getNDomainsFeature({ n: 1 }), getFoldersAndLabelsFeature('unlimited'), getNCalendarsFeature(MAX_CALENDARS_PAID), getVPNConnectionsFeature(FREE_VPN_CONNECTIONS), getProtonPassFeature(FREE_PASS_ALIASES), ]; return getUpsell({ plan: PLANS.MAIL, plansMap, upsellPath: DASHBOARD_UPSELL_PATHS.MAILPLUS, features: features.filter((item): item is UpsellFeature => isTruthy(item)), otherCtas: isTrialEnding ? [ { label: c('new_plans: Action').t`Explore all ${BRAND_NAME} plans`, color: 'norm', shape: 'ghost', action: () => openSubscriptionModal({ step: SUBSCRIPTION_STEPS.PLAN_SELECTION, metrics: { source: 'upsells', }, }), }, ] : [], isTrialEnding, onUpgrade: () => openSubscriptionModal({ plan: PLANS.MAIL, step: SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: true, metrics: { source: 'upsells', }, }), ...rest, }); }; const getDriveUpsell = ({ plansMap, openSubscriptionModal, ...rest }: GetPlanUpsellArgs): MaybeUpsell => { return getUpsell({ plan: PLANS.DRIVE, plansMap, upsellPath: DASHBOARD_UPSELL_PATHS.DRIVE, onUpgrade: () => openSubscriptionModal({ cycle, plan: PLANS.DRIVE, step: SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: true, metrics: { source: 'upsells', }, }), ...rest, }); }; const getVPNUpsell = ({ plansMap, openSubscriptionModal, ...rest }: GetPlanUpsellArgs): MaybeUpsell => { return getUpsell({ plan: PLANS.VPN, plansMap, upsellPath: DASHBOARD_UPSELL_PATHS.VPN, onUpgrade: () => openSubscriptionModal({ cycle, plan: PLANS.VPN, step: SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: true, metrics: { source: 'upsells', }, }), ...rest, }); }; const getPassUpsell = ({ plansMap, openSubscriptionModal, ...rest }: GetPlanUpsellArgs): MaybeUpsell => { return getUpsell({ plan: PLANS.PASS_PLUS, plansMap, upsellPath: DASHBOARD_UPSELL_PATHS.PASS, onUpgrade: () => openSubscriptionModal({ cycle, plan: PLANS.PASS_PLUS, step: SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: true, metrics: { source: 'upsells', }, }), ...rest, }); }; /** * Upsell for Bundle (a.k.a Unlimited) */ const getBundleUpsell = ({ plansMap, hasPaidMail, hasVPN, openSubscriptionModal, ...rest }: GetPlanUpsellArgs): MaybeUpsell => { const bundlePlan = plansMap[PLANS.BUNDLE]; const features: MaybeUpsellFeature[] = [ getStorageFeature(bundlePlan?.MaxSpace ?? 500), getNAddressesFeature({ n: 15 }), getNDomainsFeature({ n: 3 }), getSentinel(), getFoldersAndLabelsFeature('unlimited'), hasPaidMail ? undefined : getNCalendarsFeature(MAX_CALENDARS_PAID), hasVPN ? undefined : getHighSpeedVPNConnectionsFeature(), getProtonPassFeature(), ]; return getUpsell({ plan: PLANS.BUNDLE, plansMap, upsellPath: DASHBOARD_UPSELL_PATHS.UNLIMITED, features: features.filter((item): item is UpsellFeature => isTruthy(item)), onUpgrade: () => openSubscriptionModal({ cycle, plan: PLANS.BUNDLE, step: SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: true, metrics: { source: 'upsells', }, }), ...rest, }); }; const getFamilyUpsell = ({ plansMap, hasVPN, hasPaidMail, openSubscriptionModal, currency, app, serversCount, }: GetPlanUpsellArgs): MaybeUpsell => { const familyPlan = plansMap[PLANS.FAMILY]; if (!familyPlan) { return null; } const features: MaybeUpsellFeature[] = [ getStorageFeature(familyPlan.MaxSpace, { family: true }), getUsersFeature(FAMILY_MAX_USERS), getNAddressesFeature({ n: familyPlan.MaxAddresses, family: true }), getFoldersAndLabelsFeature('unlimited'), hasPaidMail ? undefined : getNCalendarsFeature(MAX_CALENDARS_PAID), hasVPN ? undefined : getHighSpeedVPNConnectionsFeature(), getProtonPassFeature(), ]; return getUpsell({ plan: PLANS.FAMILY, plansMap, currency, serversCount, app, upsellPath: DASHBOARD_UPSELL_PATHS.FAMILY, features: features.filter((item): item is UpsellFeature => isTruthy(item)), onUpgrade: () => openSubscriptionModal({ cycle, plan: PLANS.FAMILY, step: SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: true, metrics: { source: 'upsells', }, }), }); }; const getBundleProUpsell = ({ plansMap, openSubscriptionModal, ...rest }: GetPlanUpsellArgs): MaybeUpsell => { const bundleProPlan = plansMap[PLANS.BUNDLE_PRO]; const businessStorage = humanSize(bundleProPlan?.MaxSpace ?? 500, undefined, undefined, 0); const features: UpsellFeature[] = [ getStorageBoostFeatureB2B(businessStorage), getNAddressesFeatureB2B({ n: 5 }), getB2BNDomainsFeature(), getB2BHighSpeedVPNConnectionsFeature(), getAdvancedVPNFeature(), ]; return getUpsell({ plan: PLANS.BUNDLE_PRO, plansMap, features, upsellPath: DASHBOARD_UPSELL_PATHS.BUSINESS, onUpgrade: () => openSubscriptionModal({ cycle, plan: PLANS.BUNDLE_PRO, step: SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: true, metrics: { source: 'upsells', }, }), ...rest, }); }; const getVpnBusinessUpsell = ({ plansMap, openSubscriptionModal, ...rest }: GetPlanUpsellArgs): MaybeUpsell => { const features: UpsellFeature[] = [getDedicatedServersVPNFeature()]; return getUpsell({ plan: PLANS.VPN_BUSINESS, plansMap, features, upsellPath: DASHBOARD_UPSELL_PATHS.BUSINESS, onUpgrade: () => openSubscriptionModal({ cycle, plan: PLANS.VPN_BUSINESS, step: SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION, disablePlanSelection: true, metrics: { source: 'upsells', }, }), defaultCtaOverrides: { shape: 'solid', color: 'norm', }, ...rest, }); }; const getVpnEnterpriseUpsell = (serversCount: VPNServersCountData): Upsell => { const vpnEnteriprisePlan = getVPNEnterprisePlan(serversCount); return { planKey: 'VPN_ENTERPRISE', title: vpnEnteriprisePlan.title, description: vpnEnteriprisePlan.description, features: [getDedicatedServersVPNFeature(serversCount), getDedicatedAccountManagerVPNFeature()], ignoreDefaultCta: true, otherCtas: [<VpnEnterpriseAction shape="outline" size="large" />], // because we have a custom CTA (<VpnEnterpriseAction />), the onUpgrade callback will never be used onUpgrade: noop, }; }; const hasOnePlusSubscription = (subscription: Subscription) => { return ( hasMail(subscription) || hasDrive(subscription) || hasPassPlus(subscription) || hasVPN(subscription) || hasVPNPassBundle(subscription) ); }; export const resolveUpsellsToDisplay = ({ app, subscription, plans, serversCount, canPay, isFree, ...rest }: { app: APP_NAMES; currency: Currency; subscription?: Subscription; plans: Plan[]; serversCount: VPNServersCountData; canPay?: boolean; isFree?: boolean; hasPaidMail?: boolean; openSubscriptionModal: OpenSubscriptionModalCallback; }): Upsell[] => { const resolve = () => { if (!canPay || !subscription || getHasLegacyPlans(subscription)) { return []; } const upsellsPayload = { app, plansMap: toMap(plans, 'Name'), hasVPN: hasVPN(subscription) || hasVPNPassBundle(subscription), serversCount, ...rest, }; const hasMailFree = isFree && app === APPS.PROTONMAIL; const hasDriveFree = isFree && app === APPS.PROTONDRIVE; const hasPassFree = isFree && app === APPS.PROTONPASS; const hasVPNFree = isFree && app === APPS.PROTONVPN_SETTINGS; switch (true) { case Boolean(isTrial(subscription) && subscription.PeriodEnd): return [ getMailPlusUpsell({ ...upsellsPayload, isTrialEnding: true }), getBundleUpsell({ ...upsellsPayload, isRecommended: true }), ]; case Boolean(hasMailFree): return [ getMailPlusUpsell({ ...upsellsPayload }), getBundleUpsell({ ...upsellsPayload, isRecommended: true }), ]; case Boolean(hasDriveFree): return [getDriveUpsell(upsellsPayload)]; case Boolean(hasPassFree): return [getPassUpsell(upsellsPayload)]; case Boolean(hasVPNFree): return [getVPNUpsell(upsellsPayload)]; case Boolean(isFree || hasOnePlusSubscription(subscription)): return [getBundleUpsell({ ...upsellsPayload, isRecommended: true }), getFamilyUpsell(upsellsPayload)]; case hasBundle(subscription): return [getFamilyUpsell(upsellsPayload)]; case hasMailPro(subscription): return [getBundleProUpsell(upsellsPayload)]; case hasVpnPro(subscription): return [getVpnBusinessUpsell(upsellsPayload), getVpnEnterpriseUpsell(serversCount)]; case hasVpnBusiness(subscription): return [getVpnEnterpriseUpsell(serversCount)]; default: return []; } }; return resolve().filter((maybeUpsell): maybeUpsell is Upsell => isTruthy(maybeUpsell)); };
6,803
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/helpers/index.ts
export * from './dashboard-upsells'; export * from './payment'; export * from './vpnEnterpriseContactUrl';
6,804
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/helpers/payment.test.ts
import { FREE_SUBSCRIPTION } from '@proton/shared/lib/constants'; import { Renew } from '@proton/shared/lib/interfaces'; import { subscriptionMock, upcomingSubscriptionMock } from '@proton/testing/data'; import { subscriptionExpires } from './payment'; describe('subscriptionExpires()', () => { it('should handle the case when subscription is not loaded yet', () => { expect(subscriptionExpires()).toEqual({ subscriptionExpiresSoon: false, renewDisabled: false, renewEnabled: true, expirationDate: null, }); }); it('should handle the case when subscription is free', () => { expect(subscriptionExpires(FREE_SUBSCRIPTION as any)).toEqual({ subscriptionExpiresSoon: false, renewDisabled: false, renewEnabled: true, expirationDate: null, }); }); it('should handle non-expiring subscription', () => { expect(subscriptionExpires(subscriptionMock)).toEqual({ subscriptionExpiresSoon: false, planName: 'Proton Unlimited', renewDisabled: false, renewEnabled: true, expirationDate: null, }); }); it('should handle expiring subscription', () => { expect( subscriptionExpires({ ...subscriptionMock, Renew: Renew.Disabled, }) ).toEqual({ subscriptionExpiresSoon: true, planName: 'Proton Unlimited', renewDisabled: true, renewEnabled: false, expirationDate: subscriptionMock.PeriodEnd, }); }); it('should handle the case when the upcoming subscription expires', () => { expect( subscriptionExpires({ ...subscriptionMock, UpcomingSubscription: { ...upcomingSubscriptionMock, Renew: Renew.Disabled, }, }) ).toEqual({ subscriptionExpiresSoon: true, planName: 'Proton Unlimited', renewDisabled: true, renewEnabled: false, expirationDate: upcomingSubscriptionMock.PeriodEnd, }); }); it('should handle the case when the upcoming subscription does not expire', () => { expect( subscriptionExpires({ ...subscriptionMock, UpcomingSubscription: { ...upcomingSubscriptionMock, Renew: Renew.Enabled, }, }) ).toEqual({ subscriptionExpiresSoon: false, planName: 'Proton Unlimited', renewDisabled: false, renewEnabled: true, expirationDate: null, }); }); });
6,805
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/helpers/payment.ts
import { ProductParam } from '@proton/shared/lib/apps/product'; import { APPS, DEFAULT_CURRENCY, FreeSubscription, PLANS, isFreeSubscription } from '@proton/shared/lib/constants'; import { Audience, Plan, PlanIDs, Renew, Subscription, SubscriptionModel, UserModel, } from '@proton/shared/lib/interfaces'; export const getCurrency = ( user: UserModel | undefined, subscription: Subscription | undefined, plans: Plan[] | undefined ) => { return user?.Currency || subscription?.Currency || plans?.[0]?.Currency || DEFAULT_CURRENCY; }; export const getDefaultSelectedProductPlans = (appName: ProductParam, planIDs: PlanIDs) => { let defaultB2CPlan = PLANS.MAIL; if (appName === APPS.PROTONVPN_SETTINGS) { defaultB2CPlan = PLANS.VPN; } else if (appName === APPS.PROTONDRIVE) { defaultB2CPlan = PLANS.DRIVE; } else if (appName === APPS.PROTONPASS) { defaultB2CPlan = PLANS.PASS_PLUS; } const matchingB2CPlan = [PLANS.MAIL, PLANS.VPN, PLANS.DRIVE].find((x) => planIDs[x]); const matchingB2BPlan = [PLANS.MAIL_PRO, PLANS.DRIVE_PRO].find((x) => planIDs[x]); const defaultB2BPlan = PLANS.MAIL_PRO; return { [Audience.B2C]: matchingB2CPlan || defaultB2CPlan, [Audience.B2B]: matchingB2BPlan || defaultB2BPlan, [Audience.FAMILY]: PLANS.FAMILY, }; }; export type SelectedProductPlans = ReturnType<typeof getDefaultSelectedProductPlans>; interface FreeSubscriptionResult { subscriptionExpiresSoon: false; renewDisabled: false; renewEnabled: true; expirationDate: null; } type SubscriptionResult = { renewDisabled: boolean; renewEnabled: boolean; planName: string; } & ( | { subscriptionExpiresSoon: true; expirationDate: number; } | { subscriptionExpiresSoon: false; expirationDate: null; } ); export function subscriptionExpires(): FreeSubscriptionResult; export function subscriptionExpires(subscription: undefined | null): FreeSubscriptionResult; export function subscriptionExpires(subscription: FreeSubscription): FreeSubscriptionResult; export function subscriptionExpires(subscription: SubscriptionModel): SubscriptionResult; export function subscriptionExpires( subscription?: SubscriptionModel | FreeSubscription | null ): FreeSubscriptionResult | SubscriptionResult { if (!subscription || isFreeSubscription(subscription)) { return { subscriptionExpiresSoon: false, renewDisabled: false, renewEnabled: true, expirationDate: null, }; } const latestSubscription = subscription.UpcomingSubscription ?? subscription; const renewDisabled = latestSubscription.Renew === Renew.Disabled; const renewEnabled = latestSubscription.Renew === Renew.Enabled; const subscriptionExpiresSoon = renewDisabled; const planName = latestSubscription.Plans?.[0]?.Title; if (subscriptionExpiresSoon) { return { subscriptionExpiresSoon, renewDisabled, renewEnabled, planName, expirationDate: latestSubscription.PeriodEnd, }; } else { return { subscriptionExpiresSoon, renewDisabled, renewEnabled, planName, expirationDate: null, }; } }
6,806
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/helpers/vpnEnterpriseContactUrl.ts
export const vpnEnterpriseContactUrl = 'https://protonvpn.com/business/contact';
6,807
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/modal-components/CheckoutRow.test.tsx
import { render } from '@testing-library/react'; import CheckoutRow, { Props } from './CheckoutRow'; let props: Props; beforeEach(() => { props = { title: 'My Checkout Title', amount: 999, }; }); it('should render', () => { const { container } = render(<CheckoutRow {...props} />); expect(container).not.toBeEmptyDOMElement(); }); it('should render free if amount is 0 and there is no currency', () => { props.amount = 0; props.currency = undefined; const { container } = render(<CheckoutRow {...props} />); expect(container).toHaveTextContent(props.title as string); expect(container).toHaveTextContent('Free'); }); it('should render loading state', () => { props.loading = true; const { container } = render(<CheckoutRow {...props} />); expect(container).toHaveTextContent(props.title as string); expect(container).toHaveTextContent('Loading'); }); it('should render price with suffix', () => { props.suffix = '/year'; props.currency = 'CHF'; const { container } = render(<CheckoutRow {...props} />); expect(container).toHaveTextContent(`My Checkout TitleCHF 9.99/year`); }); it('should render price with suffix on next line', () => { props.suffix = '/year'; props.currency = 'CHF'; props.suffixNextLine = true; const { getByTestId } = render(<CheckoutRow {...props} />); expect(getByTestId('next-line-suffix')).toHaveTextContent('/year'); });
6,808
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/modal-components/CheckoutRow.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { Currency } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { EllipsisLoader, Price } from '../../../../components'; export interface Props { title: ReactNode; amount: number; currency?: Currency; className?: string; suffix?: ReactNode; suffixNextLine?: boolean; loading?: boolean; 'data-testid'?: string; star?: boolean; } const CheckoutRow = ({ title, amount = 0, currency, className = '', suffix, suffixNextLine = false, loading = false, star, 'data-testid': dataTestId, }: Props) => { if (amount === 0 && !currency) { return ( <div className={clsx(['flex flex-nowrap flex-justify-space-between mb-4', className])}> <div className="pr-2">{title}</div> <span>{c('Price').t`Free`}</span> </div> ); } return ( <> <div className={clsx(['flex flex-nowrap flex-justify-space-between', !suffixNextLine && 'mb-4', className])} > <div className="pr-2">{title}</div> {loading ? ( <EllipsisLoader /> ) : ( <span> <Price currency={currency} suffix={suffixNextLine ? null : suffix} data-testid={dataTestId}> {amount} </Price> {star ? '*' : null} </span> )} </div> {suffixNextLine ? ( <div className="mb-4 flex flex-justify-end" data-testid="next-line-suffix"> {suffix} </div> ) : null} </> ); }; export default CheckoutRow;
6,809
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/modal-components/SubscriptionCheckout.spec.tsx
import { render } from '@testing-library/react'; import { CYCLE } from '@proton/shared/lib/constants'; import { SubscriptionCheckResponse } from '@proton/shared/lib/interfaces'; import SubscriptionCheckout from './SubscriptionCheckout'; jest.mock('../../../../hooks', () => ({ useConfig: jest.fn().mockReturnValue({ APP_NAME: 'proton-account', }), })); jest.mock('../../Checkout', () => ({ children }: any) => <>{children}</>); describe('SubscriptionCheckout', () => { let checkResult: SubscriptionCheckResponse; beforeEach(() => { checkResult = { Amount: 499, AmountDue: 499, Coupon: null, Currency: 'CHF', Cycle: CYCLE.MONTHLY, Additions: null, PeriodEnd: Math.floor(Date.now() / 1000 + 30 * 24 * 60 * 60), }; }); const dummyServers = { free: { servers: 0, countries: 0 }, paid: { servers: 0, countries: 0 } }; it('should display Proration if it is available and isProration is true', () => { checkResult.Proration = -451; let { container } = render( <SubscriptionCheckout checkResult={checkResult} plansMap={{}} vpnServers={dummyServers} isOptimistic={true} currency="CHF" cycle={CYCLE.MONTHLY} planIDs={{}} onChangeCurrency={() => {}} isProration={true} isCustomBilling={false} isScheduledSubscription={false} ></SubscriptionCheckout> ); expect(container).toHaveTextContent('Proration'); expect(container).toHaveTextContent('-CHF 4.51'); }); it('should display Proration if it is available and isProration is true', () => { checkResult.Proration = -451; let { container } = render( <SubscriptionCheckout checkResult={checkResult} plansMap={{}} vpnServers={dummyServers} isOptimistic={true} currency="CHF" cycle={CYCLE.MONTHLY} planIDs={{}} onChangeCurrency={() => {}} isProration={true} isCustomBilling={false} isScheduledSubscription={false} ></SubscriptionCheckout> ); expect(container).toHaveTextContent('Proration'); expect(container).toHaveTextContent('-CHF 4.51'); }); it('should not display proration if isProration is false', () => { checkResult.Proration = -451; let { container } = render( <SubscriptionCheckout checkResult={checkResult} plansMap={{}} vpnServers={dummyServers} isOptimistic={true} currency="CHF" cycle={CYCLE.MONTHLY} planIDs={{}} onChangeCurrency={() => {}} isProration={false} isCustomBilling={false} isScheduledSubscription={false} ></SubscriptionCheckout> ); expect(container).not.toHaveTextContent('Proration'); expect(container).not.toHaveTextContent('-CHF 4.51'); }); it('should display next start date if proration must be hidden', () => { checkResult.Proration = 0; let { container } = render( <SubscriptionCheckout checkResult={checkResult} plansMap={{}} vpnServers={dummyServers} isOptimistic={true} currency="CHF" cycle={CYCLE.MONTHLY} planIDs={{}} onChangeCurrency={() => {}} nextSubscriptionStart={1668868986} isProration={false} isCustomBilling={false} isScheduledSubscription={true} ></SubscriptionCheckout> ); expect(container).toHaveTextContent('Start date'); expect(container).not.toHaveTextContent('Proration'); }); it('should display positive proration', () => { checkResult = { ...checkResult, AmountDue: 4085, Proration: 127583, Amount: 199750, Cycle: 1, CouponDiscount: 0, Gift: 0, Currency: 'CHF', UnusedCredit: 0, Credit: -323248, Coupon: null, }; let { container } = render( <SubscriptionCheckout checkResult={checkResult} plansMap={{}} vpnServers={{ free: { countries: 0, servers: 0 }, paid: { countries: 0, servers: 0 } }} isOptimistic={true} currency="CHF" cycle={CYCLE.MONTHLY} planIDs={{}} onChangeCurrency={() => {}} nextSubscriptionStart={1668868986} isProration={true} isCustomBilling={false} isScheduledSubscription={false} ></SubscriptionCheckout> ); expect(container).toHaveTextContent('Proration'); expect(container).toHaveTextContent('CHF 1275.83'); expect(container).not.toHaveTextContent('-CHF 1275.83'); }); /** * An example when credits are negative: * - you have 10 credits on the account * - you upgrade to a 5$/month plan * - you should see credits -5 in the <SubscriptionCheckout> */ it('should display negative credits value', () => { checkResult = { ...checkResult, AmountDue: 0, Proration: -19149, Amount: 8376, Cycle: 24, CouponDiscount: 0, Gift: 0, Currency: 'CHF', UnusedCredit: 0, Credit: -10773, Coupon: null, }; let { container } = render( <SubscriptionCheckout checkResult={checkResult} plansMap={{}} vpnServers={{ free: { countries: 0, servers: 0 }, paid: { countries: 0, servers: 0 } }} isOptimistic={true} currency="CHF" cycle={CYCLE.MONTHLY} planIDs={{}} onChangeCurrency={() => {}} nextSubscriptionStart={1668868986} isProration={false} isCustomBilling={false} isScheduledSubscription={false} ></SubscriptionCheckout> ); expect(container).toHaveTextContent('Credit'); expect(container).toHaveTextContent('-CHF 107.73'); }); /** * Example when credits are positive: * - you have 0 credits * - you have a plan that's 10/mo * - move to a plan that's 5/mo * - you should see credits 5 (these will end up on your account balance) */ it('should display positive credits value', () => { checkResult = { ...checkResult, AmountDue: 0, Proration: -19149, Amount: 8376, Cycle: 24, CouponDiscount: 0, Gift: 0, Currency: 'CHF', UnusedCredit: 0, Credit: 10773, Coupon: null, }; let { container } = render( <SubscriptionCheckout checkResult={checkResult} plansMap={{}} vpnServers={{ free: { countries: 0, servers: 0 }, paid: { countries: 0, servers: 0 } }} isOptimistic={true} currency="CHF" cycle={CYCLE.MONTHLY} planIDs={{}} onChangeCurrency={() => {}} nextSubscriptionStart={1668868986} isProration={false} isCustomBilling={false} isScheduledSubscription={false} ></SubscriptionCheckout> ); expect(container).toHaveTextContent('Credit'); expect(container).not.toHaveTextContent('-CHF 107.73'); expect(container).toHaveTextContent('CHF 107.73'); }); });
6,810
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/modal-components/SubscriptionCheckout.tsx
import { ReactNode, useMemo } from 'react'; import { c } from 'ttag'; import { APPS, COUPON_CODES, CYCLE, MEMBER_ADDON_PREFIX, PLANS } from '@proton/shared/lib/constants'; import { AddonDescription, Included, RequiredCheckResponse, getCheckout, getDiscountText, getWhatsIncluded, } from '@proton/shared/lib/helpers/checkout'; import { hasPlanIDs } from '@proton/shared/lib/helpers/planIDs'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Currency, Cycle, PlanIDs, PlansMap, Subscription, VPNServersCountData } from '@proton/shared/lib/interfaces'; import { Badge, Collapsible, CollapsibleContent, CollapsibleHeader, CollapsibleHeaderIconButton, Icon, Info, Price, } from '../../../../components'; import { useConfig } from '../../../../hooks'; import Checkout from '../../Checkout'; import { getBlackFridayRenewalNoticeText, getRenewalNoticeText } from '../../RenewalNotice'; import StartDateCheckoutRow from '../../StartDateCheckoutRow'; import { getTotalBillingText } from '../../helper'; import { CheckoutModifiers } from '../useCheckoutModifiers'; import CheckoutRow from './CheckoutRow'; const PlanDescription = ({ list }: { list: Included[] }) => { return ( <div className="mt-8"> <hr /> <Collapsible> <CollapsibleHeader className="text-semibold" suffix={ <CollapsibleHeaderIconButton> <Icon name="chevron-down" /> </CollapsibleHeaderIconButton> } > {c('Action').t`What do I get?`} </CollapsibleHeader> <CollapsibleContent> {list.map((item) => { if (item.type === 'value') { return ( <div key={`${item.text}${item.type}`} className="flex flex-nowrap mb-2"> <div className="flex-item-fluid-auto text-ellipsis mr-4">{item.text}</div> <div className="flex-item-fluid-auto flex-item-noshrink text-right"> {item.value} </div> </div> ); } if (item.type === 'text') { return ( <div key={`${item.text}${item.type}`} className="flex flex-nowrap mb-2"> <div className="flex-item-fluid-auto text-ellipsis">{item.text}</div> </div> ); } return null; })} </CollapsibleContent> </Collapsible> </div> ); }; const BilledText = ({ cycle }: { cycle: Cycle }) => { let text: string = useMemo(() => { switch (cycle) { case CYCLE.TWO_YEARS: return c('Subscription').t`Billed every 2 years`; case CYCLE.YEARLY: return c('Subscription').t`Billed yearly`; case CYCLE.MONTHLY: return c('Subscription').t`Billed monthly`; case CYCLE.FIFTEEN: return c('Subscription').t`Billed for 15 months`; case CYCLE.THIRTY: return c('Subscription').t`Billed for 30 months`; } }, [cycle]); return <span className="color-weak text-sm">{text}</span>; }; const AddonTooltip = ({ addon, pricePerAddon, currency, }: { addon: AddonDescription; pricePerAddon: number; currency: Currency; }) => { const price = <Price currency={currency}>{pricePerAddon}</Price>; let text: ReactNode; if (addon.name.startsWith('1domain')) { text = c('Addon').jt`${price} per domain`; } else if (addon.name.startsWith(MEMBER_ADDON_PREFIX)) { text = c('Addon').jt`${price} per user`; } else if (addon.name.startsWith('1ip')) { text = c('Addon').jt`${price} per dedicated server`; } else { return null; } return <Info title={text} className="ml-2" />; }; interface BaseProps { submit?: ReactNode; loading?: boolean; plansMap: PlansMap; vpnServers: VPNServersCountData; checkResult: RequiredCheckResponse | undefined; currency: Currency; cycle: Cycle; gift?: ReactNode; onChangeCurrency: (currency: Currency) => void; planIDs: PlanIDs; isOptimistic?: boolean; nextSubscriptionStart?: number; showDiscount?: boolean; enableDetailedAddons?: boolean; showPlanDescription?: boolean; subscription?: Subscription; } type Props = BaseProps & CheckoutModifiers; const SubscriptionCheckout = ({ submit = c('Action').t`Pay`, plansMap, vpnServers, currency, cycle, onChangeCurrency, gift, isOptimistic, planIDs, checkResult, loading, subscription, nextSubscriptionStart, showDiscount = true, enableDetailedAddons = false, showPlanDescription = true, isScheduledSubscription, isProration, isCustomBilling, }: Props) => { const { APP_NAME } = useConfig(); const isVPN = APP_NAME === APPS.PROTONVPN_SETTINGS; const { planTitle, usersTitle, discountPercent, withDiscountPerCycle, addons, membersPerMonth, withDiscountPerMonth, addonsPerMonth, } = getCheckout({ planIDs, plansMap, checkResult, }); if (!checkResult) { return null; } const isFreePlanSelected = !hasPlanIDs(planIDs); const hasGuarantee = !!planIDs?.[PLANS.VPN] || !!planIDs?.[PLANS.VPN_PRO] || !!planIDs?.[PLANS.VPN_BUSINESS] || !!planIDs?.[PLANS.VPN_PASS_BUNDLE]; const proration = checkResult.Proration ?? 0; const credit = checkResult.Credit ?? 0; const amount = checkResult.Amount || 0; const amountDue = checkResult.AmountDue || 0; const giftValue = Math.abs(checkResult.Gift || 0); const list = getWhatsIncluded({ planIDs, plansMap, vpnServers }); const membersAmount = (() => { if (enableDetailedAddons) { return membersPerMonth; } if (isCustomBilling) { return membersPerMonth + addonsPerMonth; } return withDiscountPerMonth; })(); const hasBFDiscount = checkResult.Coupon?.Code === COUPON_CODES.BLACK_FRIDAY_2023; return ( <Checkout currency={currency} onChangeCurrency={onChangeCurrency} loading={loading} hasGuarantee={hasGuarantee} hasPayments={!isOptimistic} description={showPlanDescription ? <PlanDescription list={list} /> : null} hiddenRenewNotice={ hasBFDiscount && ( <div className="color-weak"> *{' '} {getBlackFridayRenewalNoticeText({ price: withDiscountPerCycle, cycle, plansMap, planIDs, currency, })} </div> ) } renewNotice={ !isFreePlanSelected && getRenewalNoticeText({ renewCycle: cycle, isCustomBilling, isScheduledSubscription, subscription, }) } > <div className="mb-4 flex flex-column"> <strong className="mb-1">{planTitle}</strong> <BilledText cycle={cycle} /> </div> <CheckoutRow title={ <> {usersTitle} {showDiscount && discountPercent > 0 && ( <Badge type="success" tooltip={getDiscountText()} className="ml-2 text-semibold"> -{discountPercent}% </Badge> )} </> } amount={membersAmount} currency={currency} suffix={<span className="color-weak text-sm">{c('Suffix').t`/month`}</span>} suffixNextLine={enableDetailedAddons} loading={loading} data-testid="price" /> {enableDetailedAddons ? addons.map((addon) => { return ( <CheckoutRow key={addon.name} title={ <> {addon.title} <AddonTooltip addon={addon} pricePerAddon={(addon.pricing[cycle] || 0) / cycle} currency={currency} /> </> } amount={(addon.quantity * (addon.pricing[cycle] || 0)) / cycle} currency={currency} loading={loading} /> ); }) : addons.map((addon) => { return ( <div className="mb-4" key={addon.name}> + {addon.title} </div> ); })} {!isFreePlanSelected && ( <> <div className="mb-4"> <hr /> </div> <CheckoutRow className="text-semibold" title={<span className="mr-2">{getTotalBillingText(cycle)}</span>} amount={withDiscountPerCycle} currency={currency} loading={loading} data-testid="price" star={hasBFDiscount} /> </> )} {isProration && proration !== 0 && ( <CheckoutRow title={ <span className="inline-flex flex-align-items-center"> <span className="mr-2">{c('Label').t`Proration`}</span> <Info title={ proration < 0 ? c('Info').t`Credit for the unused portion of your previous plan subscription` : c('Info').t`Balance from your previous subscription` } url={ isVPN ? 'https://protonvpn.com/support/vpn-credit-proration/' : getKnowledgeBaseUrl('/credit-proration-coupons') } /> </span> } amount={proration} currency={currency} data-testid="proration-value" /> )} {isScheduledSubscription && nextSubscriptionStart && ( <StartDateCheckoutRow nextSubscriptionStart={nextSubscriptionStart} /> )} {credit !== 0 && <CheckoutRow title={c('Title').t`Credits`} amount={credit} currency={currency} />} {giftValue > 0 && <CheckoutRow title={c('Title').t`Gift`} amount={-giftValue} currency={currency} />} {!isOptimistic && ( <> <div className="mb-4"> <hr /> </div> <CheckoutRow title={c('Title').t`Amount due`} amount={amountDue} currency={currency} loading={loading} className="text-bold m-0 text-2xl" data-testid="subscription-amout-due" /> </> )} <div className="my-4">{submit}</div> {!isOptimistic && amount > 0 && gift ? gift : null} </Checkout> ); }; export default SubscriptionCheckout;
6,811
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/modal-components/SubscriptionThanks.tsx
import { c } from 'ttag'; import { CircleLoader, Href } from '@proton/atoms'; import { PAYMENT_METHOD_TYPES, PlainPaymentMethodType } from '@proton/components/payments/core'; import { APPS } from '@proton/shared/lib/constants'; import appStoreSvg from '@proton/styles/assets/img/illustrations/app-store.svg'; import playStoreSvg from '@proton/styles/assets/img/illustrations/play-store.svg'; import mailThanksSvg from '@proton/styles/assets/img/illustrations/thank-you-mail.svg'; import vpnThanksSvg from '@proton/styles/assets/img/illustrations/thank-you-vpn.svg'; import { PrimaryButton } from '../../../../components'; import { useConfig } from '../../../../hooks'; interface Props { onClose?: () => void; paymentMethodType?: PlainPaymentMethodType; loading?: boolean; showDownloads?: boolean; } const SubscriptionThanks = ({ paymentMethodType, onClose, loading, showDownloads = true }: Props) => { const { APP_NAME } = useConfig(); const isVPN = APP_NAME === APPS.PROTONVPN_SETTINGS; return ( <div className="relative"> {loading && ( <div className="text-center absolute absolute-center pb-14"> <CircleLoader size="large" className="color-primary" /> </div> )} <div className={loading ? 'visibility-hidden' : undefined}> <h1 className="text-center mb-0"> <img src={isVPN ? vpnThanksSvg : mailThanksSvg} alt="Thanks" /> </h1> {paymentMethodType && [PAYMENT_METHOD_TYPES.CASH, PAYMENT_METHOD_TYPES.BITCOIN].includes(paymentMethodType as any) ? ( <p className="text-center mb-4">{c('Info') .t`Your account will be updated once the payment is cleared.`}</p> ) : ( <p className="text-center mb-4 text-bold text-xl" data-testid="successfull-update">{c('Info') .t`Account successfully updated`}</p> )} {showDownloads && ( <> <p className="text-center mb-8" data-testid="more-info">{c('Info') .t`Download your favorite app today and take privacy with you everywhere you go.`}</p> <div className="mt-4 mb-8 text-center"> <Href href={ isVPN ? 'https://play.google.com/store/apps/details?id=ch.protonvpn.android' : 'https://play.google.com/store/apps/details?id=ch.protonmail.android' } className="mr-8" > <img width="150" src={playStoreSvg} alt="Play Store" /> </Href> <Href href={ isVPN ? 'https://itunes.apple.com/us/app/protonvpn-fast-secure-vpn/id1437005085' : 'https://apps.apple.com/app/protonmail-encrypted-email/id979659905' } > <img width="150" src={appStoreSvg} alt="App Store" /> </Href> </div> </> )} <div className="text-center pb-7"> <PrimaryButton fullWidth onClick={onClose} data-testid="modal:close">{c('Action') .t`Close`}</PrimaryButton> </div> </div> </div> ); }; export default SubscriptionThanks;
6,812
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/Panel.test.tsx
import { render, screen } from '@testing-library/react'; import Panel from './Panel'; describe('Panel', () => { it('should display panel title + its content', () => { render( <Panel title="test title"> <>Test content</> </Panel> ); expect(screen.getByRole('heading', { level: 2, name: /test title/ })); expect(screen.getByText('Test content')); }); });
6,813
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/Panel.tsx
import { ReactNode } from 'react'; import clsx from '@proton/utils/clsx'; type Props = { children: ReactNode; className?: string; 'data-testid'?: string; titleDataTestId?: string; secondaryTitleElement?: ReactNode; } & ( | { title: string; titleElement?: never; } | { title?: never; titleElement: ReactNode; } ); const Panel = ({ children, title, titleElement, className, 'data-testid': dataTestId, titleDataTestId, secondaryTitleElement, }: Props) => { const titleElementToRender = titleElement ?? ( <h2 className="h3 m-0 pt-0 pb-1"> <strong data-testid={titleDataTestId}>{title}</strong> </h2> ); return ( <div className={clsx( 'relative border rounded px-6 py-5 flex-align-self-start order-1 lg:order-0 panel', className )} data-testid={dataTestId} > <div className="flex flex-justify-space-between flex-align-items-baseline"> {titleElementToRender} {secondaryTitleElement} </div> {children} </div> ); }; export default Panel;
6,814
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/PendingInvitationsPanel.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { useModalState } from '@proton/components/components'; import { useCache } from '@proton/components/hooks'; import useUid from '@proton/components/hooks/useUid'; import { PendingInvitation } from '@proton/shared/lib/interfaces'; import { UserInvitationModel } from '@proton/shared/lib/models'; import PendingInvitationModal from '../PendingInvitationModal'; interface Props { invites: PendingInvitation[]; } const PendingInvitationPanel = ({ invites }: Props) => { const [selectedInvitation, setSelectedInvitation] = useState<PendingInvitation>(); const [invitationModal, setInvitationModal, renderInvitationModal] = useModalState(); const uid = useUid('pending-invitation-dashboard'); const cache = useCache(); useEffect(() => { // Force refresh the invitations when user navigates back to the dashboard if (cache.get(UserInvitationModel.key)) { cache.delete(UserInvitationModel.key); } }, []); const handleInvitationClick = (invitation: PendingInvitation) => { setSelectedInvitation(invitation); setInvitationModal(true); }; if (invites.length === 0) { return null; } return ( <> <div className="border rounded px-6 py-5"> <div className="flex flex-wrap flex-item-space-between"> <h3 className="text-lg mb-6"> <strong> {invites.length === 1 ? c('familyOffer_2023:Family plan').t`Pending invitation` : c('familyOffer_2023:Family plan').t`Pending invitations`} </strong> </h3> {invites && ( <section className="w-full border-top border-weak"> {invites.map((invitation) => ( <div key={invitation.ID} className="border-bottom border-weak py-2"> <div>{c('familyOffer_2023:Family plan') .t`Invitation from ${invitation.OrganizationName}`}</div> <Button className="p-0" shape="underline" color="norm" onClick={() => handleInvitationClick(invitation)} >{c('familyOffer_2023:Action').t`View invitation`}</Button> </div> ))} </section> )} </div> </div> {selectedInvitation && renderInvitationModal && ( <PendingInvitationModal invite={selectedInvitation} {...invitationModal} key={uid} /> )} </> ); }; export default PendingInvitationPanel;
6,815
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/SubscriptionPanel.tsx
import { ReactNode } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { MAX_CALENDARS_FREE, MAX_CALENDARS_PAID } from '@proton/shared/lib/calendar/constants'; import { APPS, APP_NAMES, BRAND_NAME, CYCLE, FREE_VPN_CONNECTIONS, PLANS, PLAN_NAMES, VPN_CONNECTIONS, } from '@proton/shared/lib/constants'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { getHasB2BPlan, getHasVpnB2BPlan, getPrimaryPlan, getVPNDedicatedIPs, hasPassPlus, hasVPN, hasVPNPassBundle, hasVpnBusiness, isTrial, } from '@proton/shared/lib/helpers/subscription'; import { Address, Currency, Organization, Subscription, UserModel, VPNServersCountData, } from '@proton/shared/lib/interfaces'; import { FREE_PLAN } from '@proton/shared/lib/subscription/freePlans'; import { getFreeServers, getPlusServers } from '@proton/shared/lib/vpn/features'; import clsx from '@proton/utils/clsx'; import isTruthy from '@proton/utils/isTruthy'; import percentage from '@proton/utils/percentage'; import { Icon, IconName, Meter, Price, StripedItem, StripedList } from '../../../../components'; import { PlanCardFeatureDefinition } from '../../features/interface'; import { FREE_PASS_ALIASES, FREE_VAULTS, PASS_PLUS_VAULTS, get2FAAuthenticator, getCustomFields, getDevices, getHideMyEmailAliases, getLoginsAndNotes, getVaultSharing, getVaults, } from '../../features/pass'; import { getB2BHighSpeedVPNConnectionsText, getFreeVPNConnectionTotal, getHighSpeedVPNConnectionsText, getVPNConnectionsFeature, getVPNConnectionsText, } from '../../features/vpn'; import { OpenSubscriptionModalCallback } from '../SubscriptionModalProvider'; import SubscriptionPanelManageUserButton from '../SubscriptionPanelManageUserButton'; import { SUBSCRIPTION_STEPS } from '../constants'; import Panel from './Panel'; interface Item extends Omit<PlanCardFeatureDefinition, 'status' | 'highlight' | 'included'> { status?: PlanCardFeatureDefinition['status']; included?: PlanCardFeatureDefinition['included']; actionElement?: ReactNode; dataTestId?: string; } interface SubscriptionListProps { items: Item[]; } const SubscriptionItems = ({ items }: SubscriptionListProps) => { return ( <> {items.map( ({ icon = 'checkmark', text, included = true, status = 'available', tooltip, actionElement, dataTestId, }) => { if (!included) { return null; } const key = typeof text === 'string' ? text : `${tooltip}-${icon}-${included}-${status}`; return ( <StripedItem key={key} className={clsx(status === 'coming-soon' && 'color-weak')} left={<Icon className={clsx(included && 'color-success')} size={20} name={icon} />} > <div className="flex flex-justify-space-between flex-align-items-baseline" data-testid={dataTestId} > {text} {actionElement} </div> </StripedItem> ); } )} </> ); }; const ActionButtons = ({ user, subscription, openSubscriptionModal, }: { user: UserModel; subscription?: Subscription; openSubscriptionModal: OpenSubscriptionModalCallback; }) => { /** * Since all the components here are used in the same context, we can use the same metrics source for all of them. */ const metrics = { source: 'plans' as 'plans', }; const handleCustomizeSubscription = () => openSubscriptionModal({ step: SUBSCRIPTION_STEPS.CUSTOMIZATION, disablePlanSelection: true, metrics, }); const handleExplorePlans = () => { openSubscriptionModal({ step: SUBSCRIPTION_STEPS.PLAN_SELECTION, metrics, }); }; const handleEditPayment = () => openSubscriptionModal({ step: SUBSCRIPTION_STEPS.CHECKOUT, disablePlanSelection: true, metrics, }); return ( <> { // translator: Edit billing details is a button when you want to edit the billing details of your current plan, in the dashboard. user.isPaid && user.canPay ? ( <Button onClick={handleEditPayment} className="mb-2" size="large" color="weak" fullWidth data-testid="edit-billing-details" >{c('Action').t`Edit billing details`}</Button> ) : null } {user.isPaid && user.canPay && getHasB2BPlan(subscription) ? ( <Button onClick={handleCustomizeSubscription} className="mb-2" color="weak" size="large" shape="outline" data-testid="customize-plan" fullWidth >{c('Action').t`Customize plan`}</Button> ) : null} {user.canPay ? ( <Button onClick={handleExplorePlans} size="large" shape={user.isPaid ? 'ghost' : 'outline'} color={user.isPaid ? 'norm' : 'weak'} fullWidth data-testid="explore-other-plan" >{c('Action').t`Explore other ${BRAND_NAME} plans`}</Button> ) : null} </> ); }; interface Props { app: APP_NAMES; user: UserModel; currency: Currency; subscription?: Subscription; organization?: Organization; vpnServers: VPNServersCountData; addresses?: Address[]; openSubscriptionModal: OpenSubscriptionModalCallback; } const SubscriptionPanel = ({ app, currency, vpnServers, subscription, organization, user, addresses, openSubscriptionModal, }: Props) => { const primaryPlan = getPrimaryPlan(subscription, app); const planTitle = primaryPlan?.Title || PLAN_NAMES[FREE_PLAN.Name as PLANS]; const cycle = subscription?.Cycle ?? CYCLE.MONTHLY; const amount = (subscription?.Amount ?? 0) / cycle; const hasAddresses = Array.isArray(addresses) && addresses.length > 0; const { UsedDomains = 0, MaxDomains = 0, UsedSpace = user.UsedSpace, MaxSpace = user.MaxSpace, UsedAddresses: OrganizationUsedAddresses, MaxAddresses: OrganizationMaxAddresses, UsedMembers = 1, MaxMembers = 1, } = organization || {}; const humanUsedSpace = humanSize(UsedSpace); const humanMaxSpace = humanSize(MaxSpace); const UsedAddresses = hasAddresses ? OrganizationUsedAddresses || 1 : 0; const MaxAddresses = OrganizationMaxAddresses || 1; if (!user.canPay) { return null; } // Hide this panel for trial case if (subscription && isTrial(subscription)) { return null; } const storageItem = ( <StripedItem left={<Icon className="color-success" name="storage" size={20} />}> <span className="block">{c('Label').t`${humanUsedSpace} of ${humanMaxSpace}`}</span> <Meter className="my-4" aria-hidden="true" value={Math.ceil(percentage(MaxSpace, UsedSpace))} /> </StripedItem> ); const getVpnAppFree = () => { const items: Item[] = [ getVPNConnectionsFeature(FREE_VPN_CONNECTIONS), { icon: 'earth', text: getFreeServers(vpnServers.free.servers, vpnServers.free.countries), }, ]; return ( <StripedList alternate="odd"> <SubscriptionItems items={items} /> </StripedList> ); }; const getVpnPlusItems = (): Item[] => { const maxVpn = 10; return [ { icon: 'brand-proton-vpn', text: c('Subscription attribute').ngettext( msgid`High-speed VPN on ${maxVpn} device`, `High-speed VPN on ${maxVpn} devices`, maxVpn ), }, { icon: 'shield', text: c('Subscription attribute').t`Built-in ad blocker (NetShield)`, }, { icon: 'play', text: c('Subscription attribute').t`Access to streaming services globally`, }, { icon: 'earth', text: getPlusServers(vpnServers.paid.servers, vpnServers.paid.countries), }, ]; }; const getVpnPass = () => { const vpnItems = getVpnPlusItems(); const items: Item[] = [ ...vpnItems, getLoginsAndNotes(), getHideMyEmailAliases('unlimited'), get2FAAuthenticator(true), getVaultSharing(10), ]; return ( <StripedList alternate="odd"> <SubscriptionItems items={items} /> </StripedList> ); }; const getVpnPlus = () => { const items = getVpnPlusItems(); return ( <StripedList alternate="odd"> <SubscriptionItems items={items} /> </StripedList> ); }; const getPassAppFree = () => { /** * To be added when pass endpoint is ready */ // const getNumberOfEmailAliases = (usedAliases: number, totalAliases: number) => { // return c('new_plans: feature').ngettext( // msgid`${usedAliases} of ${totalAliases} hide-my-email alias`, // `${usedAliases} of ${totalAliases} hide-my-email aliases`, // totalAliases // ); // }; const items: Item[] = [ /** * To be added when pass endpoint is ready */ // { // icon: 'eye-slash', // text: getNumberOfEmailAliases(usedAliases, maxAliases), // }, getLoginsAndNotes(), getDevices(), getVaults(FREE_VAULTS), getHideMyEmailAliases(FREE_PASS_ALIASES), ]; return ( <StripedList> {storageItem} <SubscriptionItems items={items} /> </StripedList> ); }; const getPassAppPassPlus = () => { const items: Item[] = [ getHideMyEmailAliases('unlimited'), getVaults(PASS_PLUS_VAULTS), getCustomFields(true), getLoginsAndNotes(), getDevices(), ]; return ( <StripedList> {storageItem} <SubscriptionItems items={items} /> </StripedList> ); }; const getVpnB2B = () => { const ipAddresses = getVPNDedicatedIPs(subscription); const getMoreButton = ( <Button color="norm" shape="outline" size="small" className="px-2" data-testid="get-more-btn" onClick={() => openSubscriptionModal({ step: SUBSCRIPTION_STEPS.CHECKOUT_WITH_CUSTOMIZATION, disablePlanSelection: true, metrics: { source: 'vpn-get-more', }, }) } > { // translator: "Get more" means "Upgrade my business plan to get more user, more dedicated servers, etc" c('Action').t`Get more` } </Button> ); const items: Item[] = [ { icon: 'users' as IconName, text: c('Subscription attribute').ngettext( msgid`${UsedMembers} of ${MaxMembers} user`, `${UsedMembers} of ${MaxMembers} users`, MaxMembers ), actionElement: getMoreButton, dataTestId: 'users', }, { icon: 'servers', text: c('Subscription attribute').ngettext( msgid`${ipAddresses} dedicated server`, `${ipAddresses} dedicated servers`, ipAddresses ), actionElement: hasVpnBusiness(subscription) ? getMoreButton : null, dataTestId: 'servers', }, ].filter(isTruthy) as Item[]; return ( <StripedList alternate="odd"> <SubscriptionItems items={items} /> </StripedList> ); }; const getDefault = () => { const items: (Item | false)[] = [ (MaxMembers > 1 || getHasB2BPlan(subscription)) && { icon: 'users', text: c('Subscription attribute').ngettext( msgid`${UsedMembers} of ${MaxMembers} user`, `${UsedMembers} of ${MaxMembers} users`, MaxMembers ), }, { icon: 'envelope', text: MaxAddresses === 1 && UsedAddresses === 1 ? c('Subscription attribute').t`1 email address` : c('Subscription attribute').ngettext( msgid`${UsedAddresses} of ${MaxAddresses} email address`, `${UsedAddresses} of ${MaxAddresses} email addresses`, MaxAddresses ), }, !!MaxDomains && { icon: 'globe', text: c('Subscription attribute').ngettext( msgid`${UsedDomains} of ${MaxDomains} custom domain`, `${UsedDomains} of ${MaxDomains} custom domains`, MaxDomains ), }, { icon: 'calendar-checkmark', text: (() => { if (MaxMembers > 1) { const n = user.hasPaidMail ? MAX_CALENDARS_PAID : MAX_CALENDARS_FREE; return c('Subscription attribute').ngettext( msgid`${n} calendar per user`, `${n} calendars per user`, n ); } const n = user.hasPaidMail ? MAX_CALENDARS_PAID : MAX_CALENDARS_FREE; return c('Subscription attribute').ngettext(msgid`${n} calendar`, `${n} calendars`, n); })(), }, { icon: 'brand-proton-vpn', text: (() => { if (user.hasPaidVpn) { if (MaxMembers > 1) { return getB2BHighSpeedVPNConnectionsText(VPN_CONNECTIONS); } return getHighSpeedVPNConnectionsText(VPN_CONNECTIONS); } if (MaxMembers > 1) { return getFreeVPNConnectionTotal(); } return getVPNConnectionsText(1); })(), }, ]; return ( <StripedList> {storageItem} <SubscriptionItems items={items.filter(isTruthy)} /> </StripedList> ); }; const planPriceElement = (user.hasPaidMail || user.hasPaidVpn) && ( <Price className="h3 color-weak" currency={currency} suffix={subscription && amount ? c('Suffix').t`/month` : ''} data-testid="plan-price" > {amount} </Price> ); const planTitleElement = ( <h2 className="h3 m-0 pt-0 pb-1"> <strong data-testid="plan-name">{planTitle}</strong> </h2> ); const hasVpnB2BPlan = getHasVpnB2BPlan(subscription); // For the VPN B2B plan, we don't want to show the action buttons // The user can still open the subscription or customization flow using the other buttons, e.g. "Get more" users const showActionButtons = !hasVpnB2BPlan; return ( <Panel data-testid="current-plan" titleDataTestId="plan-name" titleElement={planTitleElement} secondaryTitleElement={planPriceElement} // If there are no action buttons, we want to reduce the bottom padding of the panel // On the other hand, if there are action buttons, we want to keep the additional space // after between the last button and the border className={clsx(!showActionButtons && 'p-6 pb-1')} > {(() => { if (user.isFree && app === APPS.PROTONVPN_SETTINGS) { return getVpnAppFree(); } if (hasVPN(subscription)) { return getVpnPlus(); } if (hasVPNPassBundle(subscription)) { return getVpnPass(); } if (user.isFree && app === APPS.PROTONPASS) { return getPassAppFree(); } if (hasPassPlus(subscription)) { return getPassAppPassPlus(); } if (getHasVpnB2BPlan(subscription)) { return getVpnB2B(); } return getDefault(); })()} <SubscriptionPanelManageUserButton /> {showActionButtons ? ( <ActionButtons user={user} subscription={subscription} openSubscriptionModal={openSubscriptionModal} /> ) : null} </Panel> ); }; export default SubscriptionPanel;
6,816
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/UpsellPanel.scss
.border-recommended { border-width: 3px; } .recommended-label { inset-block-start: 0; inset-inline-start: 50%; transform: translateX(-50%) translateY(-50%); width: 10em }
6,817
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/UpsellPanel.test.tsx
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { useActiveBreakpoint } from '@proton/components/hooks'; import { omit } from '@proton/shared/lib/helpers/object'; import UpsellPanel, { UpsellPanelProps } from './UpsellPanel'; jest.mock('@proton/components/hooks/useActiveBreakpoint'); const mockUseActiveBreakpoint = useActiveBreakpoint as jest.MockedFn<typeof useActiveBreakpoint>; describe('UpsellBox', () => { beforeEach(() => { mockUseActiveBreakpoint.mockReturnValue({ isNarrow: false } as any); }); const handleUpgrade = jest.fn(); const upsellBoxBaseProps: UpsellPanelProps = { title: 'Upgrade to Plus', features: [ { icon: 'storage', text: `10GB total storage`, }, { icon: 'envelope', text: `10 email addresses/aliases`, }, { icon: 'tag', text: `Unlimited folders, labels, and filters`, }, ], ctas: [ { label: 'From 3.99€', action: handleUpgrade, shape: 'outline', }, ], }; it('should correctly render a basic upsell box', () => { const { container } = render( <UpsellPanel {...upsellBoxBaseProps}>Upgrade to Plus pack to access to more services</UpsellPanel> ); // should have basic style expect(container.firstChild).toHaveClass('border-strong'); // should not have `recommended` label const recommendedLabel = screen.queryByText('Recommended'); expect(recommendedLabel).toBeNull(); // header expect(screen.getByText('Upgrade to Plus')); expect(screen.getByText('Upgrade to Plus pack to access to more services')); // features expect(screen.getByText('10GB total storage')); expect(screen.getByText('10 email addresses/aliases')); expect(screen.getByText('Unlimited folders, labels, and filters')); // actions const button = screen.getByText('From 3.99€'); expect(button).toHaveClass('button-outline-weak'); }); it('should correctly handle upsell click action', async () => { render(<UpsellPanel {...upsellBoxBaseProps} />); const button = screen.getByText('From 3.99€'); fireEvent.click(button); await waitFor(() => expect(handleUpgrade).toHaveBeenCalledTimes(1)); }); describe('isRecommended is true', () => { it('should render with primary border', () => { const { container } = render(<UpsellPanel {...upsellBoxBaseProps} isRecommended />); // should have basic style expect(container.firstChild).toHaveClass('border-primary'); expect(container.firstChild).toHaveClass('border-recommended'); // should have label rendered expect(screen.getByText('Recommended')); }); describe('when action button is outline', () => { it('should render with primary border and buttons', () => { render( <UpsellPanel {...omit(upsellBoxBaseProps, ['ctas'])} ctas={[ { label: 'From 3.99€', action: handleUpgrade, shape: 'outline', }, ]} isRecommended /> ); // actions const button = screen.getByText('From 3.99€'); expect(button).toHaveClass('button-solid-norm'); }); }); describe('when action button is other than outline/solid', () => { it('should not change color and shape of the button', () => { render( <UpsellPanel {...omit(upsellBoxBaseProps, ['ctas'])} ctas={[ { label: 'From 3.99€', action: handleUpgrade, shape: 'ghost', color: 'norm', }, ]} isRecommended /> ); // actions const button = screen.getByText('From 3.99€'); expect(button).toHaveClass('button-ghost-norm'); }); }); }); describe('when one item as a tooltip', () => { it('should render a tooltip in the DOM', () => { render( <UpsellPanel {...omit(upsellBoxBaseProps, ['features'])} features={[ { icon: 'envelope', text: `10 email addresses/aliases`, tooltip: 'You can use those aliases on different website to protect your main email', }, ]} /> ); expect(screen.getByText('10 email addresses/aliases')); expect( screen.getByText('More info: You can use those aliases on different website to protect your main email') ); }); }); describe('when a children is provided', () => { it('should render the children', () => { render( <UpsellPanel {...upsellBoxBaseProps}> <div>Hello world, here is a testing child</div> </UpsellPanel> ); screen.getAllByText('Hello world, here is a testing child'); }); }); describe('when screenview is narrow', () => { it('should not display the feature but a button to toggle their display', async () => { mockUseActiveBreakpoint.mockReturnValue({ isNarrow: true } as any); render(<UpsellPanel {...upsellBoxBaseProps} />); // features should be hidden at first expect(screen.queryByText('10GB total storage')).toBeNull(); expect(screen.queryByText('10 email addresses/aliases')).toBeNull(); expect(screen.queryByText('Unlimited folders, labels, and filters')).toBeNull(); const showBtn = screen.getByText('See plan features'); fireEvent.click(showBtn); // features should be displayed expect(screen.getByText('10GB total storage')); expect(screen.getByText('10 email addresses/aliases')); expect(screen.getByText('Unlimited folders, labels, and filters')); const hideBtn = screen.getByText('Hide plan features'); fireEvent.click(hideBtn); // features should be hidden again expect(screen.queryByText('10GB total storage')).toBeNull(); expect(screen.queryByText('10 email addresses/aliases')).toBeNull(); expect(screen.queryByText('Unlimited folders, labels, and filters')).toBeNull(); }); }); });
6,818
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/UpsellPanel.tsx
import { ReactNode, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Icon, InlineLinkButton, StripedItem, StripedList } from '@proton/components/components'; import { useActiveBreakpoint } from '@proton/components/hooks'; import clsx from '@proton/utils/clsx'; import { ButtonColor, ButtonShape, UpsellCta, UpsellFeature, isUpsellCta } from '../helpers'; import Panel from './Panel'; import './UpsellPanel.scss'; export interface UpsellPanelProps { title: string; children?: ReactNode; features: UpsellFeature[]; isRecommended?: boolean; ctas?: (UpsellCta | ReactNode)[]; } type GetButtonColorAndShape = (opt: Pick<UpsellCta, 'color' | 'shape'> & Pick<UpsellPanelProps, 'isRecommended'>) => { shape?: ButtonShape; color?: ButtonColor; }; const getButtonColorAndShape: GetButtonColorAndShape = ({ color, shape, isRecommended }) => { // If button has another shape, then with don't want to compell a color on `recommended` state if (!isRecommended || (shape && !['solid', 'outline'].includes(shape))) { return { color, shape }; } return { color: 'norm', shape: 'solid' }; }; const UpsellPanel = ({ title, features, children, ctas = [], isRecommended }: UpsellPanelProps) => { const [isExpanded, setIsExpanded] = useState(false); const toggleExpand = () => setIsExpanded((prev) => !prev); const { isNarrow } = useActiveBreakpoint(); return ( <Panel className={clsx(isRecommended ? 'border-primary border-recommended' : 'border-strong')} title={title}> {/* `Recommended` label */} {isRecommended && ( <label className="recommended-label absolute color-invert bg-primary rounded-full px-2 py-1 flex flex-align-items-center"> <Icon name="star" className="mr-1" /> {c('upsell panel').t`Recommended`} </label> )} {children} {isNarrow && ( <div className="w-full text-center my-6 flex"> <InlineLinkButton className="mx-auto" onClick={() => toggleExpand()}> {isExpanded ? ( <> <span>{c('Action').t`Hide plan features`}</span> <Icon name="chevron-up" className="ml-2" /> </> ) : ( <> <span>{c('Action').t`See plan features`}</span> <Icon name="chevron-down" className="ml-2" /> </> )} </InlineLinkButton> </div> )} {(!isNarrow || isExpanded) && ( <StripedList alternate="odd"> {features.map(({ icon = 'checkmark', text, tooltip, included = true, status = 'available' }) => { if (!included) { return null; } const key = typeof text === 'string' ? text : `${tooltip}-${icon}-${included}-${status}`; return ( <StripedItem key={key} className={clsx(status === 'coming-soon' && 'color-weak')} left={<Icon className={clsx(included && 'color-success')} size={20} name={icon} />} tooltip={tooltip} > {text} </StripedItem> ); })} </StripedList> )} <div className="flex column gap-4"> {ctas.map((cta) => { if (isUpsellCta(cta)) { return ( <Button key={`upsell-action-${cta.label}`} data-testid="upsell-cta" size="large" {...getButtonColorAndShape({ shape: cta.shape, color: cta.color, isRecommended })} onClick={cta.action} fullWidth > {cta.label} </Button> ); } return cta; })} </div> </Panel> ); }; export default UpsellPanel;
6,819
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/UpsellPanels.test.tsx
import { render, screen, within } from '@testing-library/react'; import { COUPON_CODES } from '@proton/shared/lib/constants'; import { Subscription } from '@proton/shared/lib/interfaces'; import { familyUpsell, subscription, trialMailPlusUpsell, unlimitedUpsell } from '../__mocks__/data'; import { Upsell } from '../helpers'; import UpsellPanels from './UpsellPanels'; describe('UpsellPanel', () => { it('should display panels with correct details', async () => { const { container } = render( <UpsellPanels subscription={subscription} upsells={[ { ...unlimitedUpsell, onUpgrade: jest.fn(), isRecommended: true } as Upsell, { ...familyUpsell, onUpgrade: jest.fn() } as Upsell, ]} /> ); expect(container.childNodes).toHaveLength(2); const unlimitedUpsellPanel = container.childNodes[0] as HTMLElement; const familyUpsellPanel = container.childNodes[1] as HTMLElement; expect(within(unlimitedUpsellPanel).getByText('Recommended')); // 1rst upsell - title expect(within(unlimitedUpsellPanel).getByText('Proton Unlimited')); // description expect( within(unlimitedUpsellPanel).getByText( 'Comprehensive privacy and security with all Proton services combined.' ) ); // features within(unlimitedUpsellPanel).getByText('500 GB storage'); expect(within(unlimitedUpsellPanel).getByText('15 email addresses/aliases')); expect(within(unlimitedUpsellPanel).getByText('3 custom email domains')); expect(within(unlimitedUpsellPanel).getByText('Unlimited folders, labels, and filters')); expect(within(unlimitedUpsellPanel).getByText('25 calendars')); expect(within(unlimitedUpsellPanel).getByText('10 high-speed VPN connections')); expect(within(unlimitedUpsellPanel).getByText('Proton Pass with unlimited hide-my-email aliases')); expect(within(familyUpsellPanel).queryByText('Recommended')).toBeNull(); // 2nd upsell - title expect(within(familyUpsellPanel).getByText('Proton Family')); // description expect(within(familyUpsellPanel).getByText('Protect your family’s privacy with all Proton services combined.')); // features expect(within(familyUpsellPanel).getByText('3 TB storage')); expect(within(familyUpsellPanel).getByText('Up to 6 users')); expect(within(familyUpsellPanel).getByText('90 email addresses/aliases')); expect(within(familyUpsellPanel).getByText('Unlimited folders, labels, and filters')); expect(within(familyUpsellPanel).getByText('10 high-speed VPN connections')); expect(within(familyUpsellPanel).getByText('Proton Pass with unlimited hide-my-email aliases')); }); it('should display warning for trial period end', () => { render( <UpsellPanels subscription={ { ...subscription, CouponCode: COUPON_CODES.REFERRAL, PeriodEnd: 1718870501, } as Subscription } upsells={[{ ...trialMailPlusUpsell, onUpgrade: jest.fn() } as unknown as Upsell]} /> ); screen.getByText('Your trial ends June 20, 2024'); }); });
6,820
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/UpsellPanels.tsx
import { format, fromUnixTime } from 'date-fns'; import { c } from 'ttag'; import { ButtonLikeShape } from '@proton/atoms/Button'; import { Price } from '@proton/components/components'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { Subscription } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { Upsell } from '../helpers'; import UpsellPanel from './UpsellPanel'; interface Props { upsells: Upsell[]; subscription: Subscription; } const UpsellPanels = ({ upsells, subscription }: Props) => { const formattedPeriodEndDate = format(fromUnixTime(subscription?.PeriodEnd || 0), 'MMMM d, y'); return ( <> {upsells.map((upsell) => { const getPriceElement = (upsell: Upsell) => { if (!upsell.price) { return null; } const { value, currency } = upsell.price; return ( <Price key="plan-price" currency={currency} suffix={c('new_plans: Plan frequency').t`/month`}> {value} </Price> ); }; const getDefaultCta = (upsell: Upsell) => { const price = getPriceElement(upsell); let label: string | string[]; if (!price) { label = c('new_plans: Action').t`Upgrade`; } else { label = c('new_plans: Action').jt`From ${price}`; } return { shape: 'outline' as ButtonLikeShape, action: upsell.onUpgrade, label, ...upsell.defaultCtaOverrides, }; }; const defaultCta = upsell.ignoreDefaultCta ? null : getDefaultCta(upsell); const ctas = [defaultCta, ...upsell.otherCtas].filter(isTruthy); return ( <UpsellPanel key={`upsell-${upsell.plan}`} title={upsell.title} features={upsell.features} isRecommended={upsell.isRecommended} ctas={ctas} > {/* Warning when user is in Trial period for a plan */} {upsell.isTrialEnding ? ( <> <h4>{c('new_plans: Info').t`Your trial ends ${formattedPeriodEndDate}`}</h4> <div className="color-weak"> {c('new_plans: Info') .t`To continue to use ${MAIL_APP_NAME} with premium features, choose your subscription and payment options.`} <br /> <br /> {c('new_plans: Info') .t`Otherwise access to your account will be limited, and your account will eventually be disabled.`} </div> </> ) : ( <div className="color-weak text-lg">{upsell.description}</div> )} </UpsellPanel> ); })} </> ); }; export default UpsellPanels;
6,821
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/UsagePanel.tsx
import { PropsWithChildren } from 'react'; import { c, msgid } from 'ttag'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { Address, Organization, UserModel } from '@proton/shared/lib/interfaces'; import { Calendar } from '@proton/shared/lib/interfaces/calendar'; import isTruthy from '@proton/utils/isTruthy'; import percentage from '@proton/utils/percentage'; import { Icon, IconName, Meter, StripedItem, StripedList } from '../../../../components'; import Panel from './Panel'; interface Item { icon: IconName; text: string; } interface Props { organization?: Organization; user: UserModel; addresses?: Address[]; calendars?: Calendar[]; } const UsagePanel = ({ addresses, calendars, organization, user, children }: PropsWithChildren<Props>) => { const { UsedMembers = 0 } = organization || {}; if (UsedMembers <= 1) { return null; } const humanUsedSpace = humanSize(user.UsedSpace); const humanMaxSpace = humanSize(user.MaxSpace); const UsedAddresses = addresses?.length; const UsedCalendars = calendars?.length; const maxVpn = 10; const items: (Item | false)[] = [ UsedAddresses !== undefined && { icon: 'envelope', text: c('Subscription attribute').ngettext( msgid`${UsedAddresses} address`, `${UsedAddresses} addresses`, UsedAddresses ), }, UsedCalendars !== undefined && { icon: 'calendar-checkmark', text: c('Subscription attribute').ngettext( msgid`${UsedCalendars} calendar`, `${UsedCalendars} calendars`, UsedCalendars ), }, { icon: 'brand-proton-vpn', text: user.hasPaidVpn ? c('Subscription attribute').ngettext( msgid`${maxVpn} high-speed VPN connection`, `${maxVpn} high-speed VPN connections`, maxVpn ) : c('Subscription attribute').t`1 VPN connection`, }, ]; return ( <Panel title={c('new_plans: Title').t`Your account's usage`} data-testid="your-account-usage"> <StripedList> <StripedItem left={<Icon className="color-success" name="storage" size={20} />}> <span id="usedSpaceLabel" className="block">{c('new_plans: Label') .t`${humanUsedSpace} of ${humanMaxSpace}`}</span> <Meter className="my-4" aria-hidden="true" value={Math.ceil(percentage(user.MaxSpace, user.UsedSpace))} /> </StripedItem> {items.filter(isTruthy).map((item) => { return ( <StripedItem key={item.icon} left={<Icon className="color-success" name={item.icon} size={20} />} > {item.text} </StripedItem> ); })} </StripedList> {children} </Panel> ); }; export default UsagePanel;
6,822
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/subscription/panels/index.ts
export { default as UpsellPanel } from './UpsellPanel'; export { default as UpsellPanels } from './UpsellPanels'; export { default as UsagePanel } from './UsagePanel'; export { default as SubscriptionPanel } from './SubscriptionPanel';
6,823
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/privacy/PrivacySection.tsx
import React from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import metrics from '@proton/metrics'; import { updateCrashReports, updateTelemetry } from '@proton/shared/lib/api/settings'; import { setMetricsEnabled } from '@proton/shared/lib/helpers/metrics'; import { setSentryEnabled } from '@proton/shared/lib/helpers/sentry'; import noop from '@proton/utils/noop'; import { Toggle } from '../../components'; import { useApi, useEventManager, useUserSettings } from '../../hooks'; import { SettingsLayout, SettingsLayoutLeft, SettingsLayoutRight, SettingsParagraph, SettingsSectionWide, } from '../account'; const PrivacySection = () => { const [userSettings] = useUserSettings(); const [loadingTelemetry, withLoadingTelemetry] = useLoading(); const [loadingCrashReports, withLoadingCrashReports] = useLoading(); const api = useApi(); const { call } = useEventManager(); const telemetryEnabled = !!userSettings?.Telemetry; const crashReportsEnabled = !!userSettings?.CrashReports; return ( <SettingsSectionWide> <SettingsParagraph> {c('Info') .t`To continuously improve our services, we sometimes collect data to monitor the proper functioning of our applications. This information is not shared with any 3rd-party services.`} </SettingsParagraph> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="telemetry" className="text-semibold"> <span className="mr-2">{c('Label').t`Collect usage diagnostics`}</span> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <Toggle id="telemetry" checked={telemetryEnabled} onChange={({ target }) => { const handleChange = async (value: boolean) => { await api(updateTelemetry({ Telemetry: Number(value) })); await call(); setMetricsEnabled(value); metrics.setReportMetrics(value); }; withLoadingTelemetry(handleChange(target.checked)).catch(noop); }} loading={loadingTelemetry} /> </SettingsLayoutRight> </SettingsLayout> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="crashReports" className="text-semibold"> <span className="mr-2">{c('Label').t`Send crash reports`}</span> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <Toggle id="crashReports" checked={crashReportsEnabled} onChange={({ target }) => { const handleChange = async (value: boolean) => { await api(updateCrashReports({ CrashReports: Number(value) })); await call(); setSentryEnabled(value); }; withLoadingCrashReports(handleChange(target.checked)).catch(noop); }} loading={loadingCrashReports} /> </SettingsLayoutRight> </SettingsLayout> </SettingsSectionWide> ); }; export default PrivacySection;
6,824
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/privacy/index.ts
export { default as PrivacySection } from './PrivacySection';
6,825
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/AccountRecoverySection.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateResetEmail, updateResetPhone } from '@proton/shared/lib/api/settings'; import { Loader, Toggle } from '../../components'; import { useEventManager, useModals, useMyCountry, useNotifications, useUserSettings } from '../../hooks'; import { SettingsSection } from '../account'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; import AuthModal from '../password/AuthModal'; import RecoveryEmail from './email/RecoveryEmail'; import RecoveryPhone from './phone/RecoveryPhone'; const AccountRecoverySection = () => { const { createModal } = useModals(); const [userSettings, loadingUserSettings] = useUserSettings(); const [loadingEmailReset, withLoadingEmailReset] = useLoading(); const [loadingPhoneReset, withLoadingPhoneReset] = useLoading(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const [defaultCountry, loadingCountry] = useMyCountry(); if (loadingUserSettings || !userSettings || loadingCountry) { return <Loader />; } const handleChangePasswordEmailToggle = async (value: number) => { if (value && !userSettings.Email.Value) { return createNotification({ type: 'error', text: c('Error').t`Please set a recovery email first`, }); } await new Promise((resolve, reject) => { createModal(<AuthModal onCancel={reject} onSuccess={resolve} config={updateResetEmail(value)} />); }); await call(); }; const handleChangePasswordPhoneToggle = async (value: number) => { if (value && !userSettings.Phone.Value) { return createNotification({ type: 'error', text: c('Error').t`Please set a recovery phone number first` }); } await new Promise((resolve, reject) => { createModal( <AuthModal onCancel={reject} onSuccess={resolve} config={updateResetPhone({ Reset: value })} /> ); }); await call(); }; return ( <SettingsSection> <SettingsLayout> <SettingsLayoutLeft> <label className="pt-0 mb-2 md:mb-0 text-semibold" htmlFor="recovery-email-input"> {c('Label').t`Recovery email address`} </label> </SettingsLayoutLeft> <SettingsLayoutRight className="flex-item-fluid"> <RecoveryEmail className="mb-4 md:mb-0" email={userSettings.Email} hasReset={!!userSettings.Email.Reset} hasNotify={!!userSettings.Email.Notify} /> <div className="flex flex-align-items-center"> <Toggle className="mr-2" loading={loadingEmailReset} checked={!!userSettings.Email.Reset && !!userSettings.Email.Value} id="passwordEmailResetToggle" onChange={({ target: { checked } }) => withLoadingEmailReset(handleChangePasswordEmailToggle(+checked)) } /> <label htmlFor="passwordEmailResetToggle" className="flex-item-fluid"> {c('Label').t`Allow recovery by email`} </label> </div> </SettingsLayoutRight> </SettingsLayout> <hr className="my-8" /> <SettingsLayout> <SettingsLayoutLeft> <label className="pt-0 mb-2 md:mb-0 text-semibold" htmlFor="phoneInput"> {c('label').t`Recovery phone number`} </label> </SettingsLayoutLeft> <SettingsLayoutRight className="flex-item-fluid"> <RecoveryPhone className="mb-4 md:mb-0" defaultCountry={defaultCountry} phone={userSettings.Phone} hasReset={!!userSettings.Phone.Reset} /> <div className="flex flex-align-items-center"> <Toggle className="mr-2" loading={loadingPhoneReset} checked={!!userSettings.Phone.Reset && !!userSettings.Phone.Value} id="passwordPhoneResetToggle" onChange={({ target: { checked } }) => withLoadingPhoneReset(handleChangePasswordPhoneToggle(+checked)) } /> <label htmlFor="passwordPhoneResetToggle" className="flex-item-fluid"> {c('Label').t`Allow recovery by phone`} </label> </div> </SettingsLayoutRight> </SettingsLayout> </SettingsSection> ); }; export default AccountRecoverySection;
6,826
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/ConfirmDisableSessionRecoveryModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import useLoading from '@proton/hooks/useLoading'; import metrics, { observeApiError } from '@proton/metrics'; import { updateSessionAccountRecovery } from '@proton/shared/lib/api/sessionRecovery'; import noop from '@proton/utils/noop'; import { Prompt } from '../../components'; import { useApi, useEventManager } from '../../hooks'; interface Props { onClose: () => void; open: boolean; } const ConfirmDisableSessionRecoveryModal = ({ open, onClose }: Props) => { const api = useApi(); const { call } = useEventManager(); const [submitting, withSubmitting] = useLoading(); const handleDisableSessionRecoveryToggle = async () => { try { await api(updateSessionAccountRecovery({ SessionAccountRecovery: 0 })); await call(); onClose(); metrics.core_session_recovery_settings_update_total.increment({ status: 'success', }); } catch (error) { observeApiError(error, (status) => metrics.core_session_recovery_settings_update_total.increment({ status, }) ); } }; const handleClose = submitting ? noop : onClose; return ( <Prompt open={open} onClose={handleClose} title={c('session_recovery:disable:title').t`Disable password reset?`} buttons={[ <Button color="danger" loading={submitting} onClick={() => { void withSubmitting(handleDisableSessionRecoveryToggle()); }} > {c('session_recovery:disable:action').t`Disable password reset`} </Button>, <Button onClick={onClose} disabled={submitting}>{c('Action').t`Cancel`}</Button>, ]} > <p> {c('session_recovery:disable:info') .t`You will no longer be able to request a password reset from your account settings.`} </p> <p>{c('session_recovery:disable:info').t`Make sure you have access to a recovery method.`}</p> </Prompt> ); }; export default ConfirmDisableSessionRecoveryModal;
6,827
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/DailyEmailNotificationToggle.test.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import DailyEmailNotificationToggle from './DailyEmailNotificationToggle'; describe('DailyEmailNotificationToggle', () => { describe('when annot enable', () => { it('should have disabled attribute', () => { const { container } = render( <DailyEmailNotificationToggle canEnable={false} isEnabled={false} onChange={jest.fn()} id="test-toggle" /> ); const input = container.querySelector('#test-toggle'); expect(input).toHaveAttribute('disabled', ''); }); }); describe('when can enable', () => { it('should check checkbox if enabled', () => { const { container } = render( <DailyEmailNotificationToggle canEnable={true} isEnabled={true} onChange={jest.fn()} id="test-toggle" /> ); const input = container.querySelector('#test-toggle'); expect(input).not.toHaveAttribute('disabled'); expect(input).toHaveAttribute('checked', ''); }); it('should emit onChange on click', async () => { const mockOnChange = jest.fn(); const { container } = render( <DailyEmailNotificationToggle canEnable={true} isEnabled={true} onChange={mockOnChange} id="test-toggle" /> ); const input = container.querySelector('#test-toggle'); fireEvent.click(input as HTMLElement); await waitFor(() => expect(mockOnChange).toHaveBeenCalledTimes(1)); }); }); });
6,828
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/DailyEmailNotificationToggle.tsx
import { useLoading } from '@proton/hooks'; import { Toggle } from '../../components'; interface DailyEmailNotificationToggleProps { id: string; isEnabled: boolean; canEnable: boolean; className?: string; onChange: () => Promise<void>; } const DailyEmailNotificationToggle = ({ id, isEnabled, canEnable, className, onChange, }: DailyEmailNotificationToggleProps) => { const [isNotifyEmailApiCallLoading, withLoading] = useLoading(); return ( <Toggle id={id} className={className} loading={isNotifyEmailApiCallLoading} checked={isEnabled} disabled={!canEnable} onChange={() => withLoading(onChange())} /> ); }; export default DailyEmailNotificationToggle;
6,829
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/DataRecoverySection.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { updateDeviceRecovery } from '@proton/shared/lib/api/settingsRecovery'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { MNEMONIC_STATUS } from '@proton/shared/lib/interfaces'; import { Icon, Info, Toggle, useModalState } from '../../components'; import { useApi, useEventManager, useFeature, useHasOutdatedRecoveryFile, useIsMnemonicAvailable, useIsRecoveryFileAvailable, useRecoverySecrets, useSearchParamsEffect, useUser, useUserSettings, } from '../../hooks'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; import SettingsParagraph from '../account/SettingsParagraph'; import SettingsSection from '../account/SettingsSection'; import { FeatureCode } from '../features'; import { DisableMnemonicModal, GenerateMnemonicModal } from '../mnemonic'; import ExportRecoveryFileButton from './ExportRecoveryFileButton'; import VoidRecoveryFilesModal from './VoidRecoveryFilesModal'; const DataRecoverySection = () => { const [user] = useUser(); const [userSettings] = useUserSettings(); const { call } = useEventManager(); const api = useApi(); const trustedDeviceRecoveryFeature = useFeature<boolean>(FeatureCode.TrustedDeviceRecovery); const [isRecoveryFileAvailable] = useIsRecoveryFileAvailable(); const [isMnemonicAvailable, loadingIsMnemonicAvailable] = useIsMnemonicAvailable(); const [disableMnemonicModal, setDisableMnemonicModalOpen, renderDisableMnemonicModal] = useModalState(); const [generateMnemonicModal, setGenerateMnemonicModalOpen, renderGenerateMnemonicModal] = useModalState(); const [generateMnemonicModalButton, setGenerateMnemonicModalButtonOpen, renderGenerateMnemonicModalButton] = useModalState(); const [voidRecoveryFilesModal, setVoidRecoveryFilesModalOpen, renderVoidRecoveryFilesModal] = useModalState(); const hasOutdatedRecoveryFile = useHasOutdatedRecoveryFile(); const recoverySecrets = useRecoverySecrets(); const canRevokeRecoveryFiles = recoverySecrets?.length > 0; const [loadingDeviceRecovery, withLoadingDeviceRecovery] = useLoading(); useSearchParamsEffect( (params) => { if (!isMnemonicAvailable) { return; } const actionParam = params.get('action'); if (!actionParam) { return; } if (actionParam === 'generate-recovery-phrase') { if (user.MnemonicStatus === MNEMONIC_STATUS.SET || user.MnemonicStatus === MNEMONIC_STATUS.OUTDATED) { setGenerateMnemonicModalButtonOpen(true); } else { setGenerateMnemonicModalOpen(true); } params.delete('action'); return params; } }, [loadingIsMnemonicAvailable] ); const handleChangeDeviceRecoveryToggle = async (checked: boolean) => { await api(updateDeviceRecovery({ DeviceRecovery: Number(checked) })); await call(); }; return ( <> {renderDisableMnemonicModal && <DisableMnemonicModal {...disableMnemonicModal} />} {renderGenerateMnemonicModalButton && ( <GenerateMnemonicModal confirmStep {...generateMnemonicModalButton} /> )} {renderGenerateMnemonicModal && <GenerateMnemonicModal {...generateMnemonicModal} />} {renderVoidRecoveryFilesModal && ( <VoidRecoveryFilesModal trustedDeviceRecovery={trustedDeviceRecoveryFeature.feature?.Value} {...voidRecoveryFilesModal} /> )} <SettingsSection> <SettingsParagraph> {c('Info') .t`Activate at least one data recovery method to make sure you can continue to access the contents of your ${BRAND_NAME} Account if you lose your password.`} <br /> <Href href={getKnowledgeBaseUrl('/set-account-recovery-methods#how-to-enable-a-recovery-phrase')}> {c('Link').t`Learn more about data recovery`} </Href> </SettingsParagraph> {isMnemonicAvailable && ( <> {user.MnemonicStatus === MNEMONIC_STATUS.OUTDATED && ( <p className="color-danger"> <Icon className="mr-2 float-left mt-1" name="exclamation-circle-filled" size={14} /> {c('Warning') .t`Your recovery phrase is outdated. It can't recover new data if you reset your account again.`} </p> )} <SettingsLayout> <SettingsLayoutLeft> <label className="pt-0 mb-2 md:mb-0 text-semibold" htmlFor="mnemonicToggle"> <span className="mr-2">{c('label').t`Recovery phrase`}</span> <Info title={c('Info') .t`A recovery phrase lets you access your account and recover your encrypted messages if you forget your password`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="flex-item-fluid pt-2"> {user.MnemonicStatus === MNEMONIC_STATUS.OUTDATED ? ( <Button color="norm" onClick={() => setGenerateMnemonicModalButtonOpen(true)}> {c('Action').t`Update recovery phrase`} </Button> ) : ( <> <div className="flex flex-align-items-center"> <Toggle className="mr-2" loading={disableMnemonicModal.open || generateMnemonicModal.open} checked={user.MnemonicStatus === MNEMONIC_STATUS.SET} id="mnemonicToggle" onChange={({ target: { checked } }) => { if (checked) { setGenerateMnemonicModalOpen(true); } else { setDisableMnemonicModalOpen(true); } }} /> <label data-testid="account:recovery:mnemonicToggle" htmlFor="mnemonicToggle" className="flex-item-fluid" > {c('Label').t`Allow recovery by recovery phrase`} </label> </div> {user.MnemonicStatus === MNEMONIC_STATUS.SET && ( <Button className="mt-4" shape="outline" onClick={() => setGenerateMnemonicModalButtonOpen(true)} > {c('Action').t`Generate new recovery phrase`} </Button> )} </> )} </SettingsLayoutRight> </SettingsLayout> </> )} {isMnemonicAvailable && isRecoveryFileAvailable && <hr className="my-8" />} {isRecoveryFileAvailable && ( <> {trustedDeviceRecoveryFeature.feature?.Value && ( <SettingsLayout> <SettingsLayoutLeft> <label className="pt-0 mb-2 md:mb-0 text-semibold" htmlFor="deviceRecoveryToggle"> <span className="mr-2">{c('label').t`Trusted device recovery`}</span> <Info title={c('Info') .t`We securely store recovery information on your trusted device to prevent you from losing your data`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="flex-item-fluid pt-2"> <div className="flex flex-align-items-center"> <Toggle className="mr-2" loading={loadingDeviceRecovery} checked={!!userSettings.DeviceRecovery} id="deviceRecoveryToggle" onChange={({ target: { checked } }) => withLoadingDeviceRecovery(handleChangeDeviceRecoveryToggle(checked)) } /> <label htmlFor="deviceRecoveryToggle" className="flex-item-fluid" data-testid="account:recovery:trustedDevice" > {c('Label').t`Allow recovery using a trusted device`} </label> </div> </SettingsLayoutRight> </SettingsLayout> )} <SettingsLayout> <SettingsLayoutLeft> <span className="pt-0 mb-2 md:mb-0 text-semibold"> <span className="mr-2">{c('Title').t`Recovery file`}</span> <Info title={c('Info') .t`A recovery file lets you unlock and view your data after an account reset`} /> </span> </SettingsLayoutLeft> <SettingsLayoutRight> <ExportRecoveryFileButton className="block" color="norm"> {hasOutdatedRecoveryFile ? c('Action').t`Update recovery file` : c('Action').t`Download recovery file`} </ExportRecoveryFileButton> {canRevokeRecoveryFiles && ( <Button className="mt-4" color="danger" shape="underline" onClick={() => setVoidRecoveryFilesModalOpen(true)} > {c('Action').t`Void all recovery files`} </Button> )} </SettingsLayoutRight> </SettingsLayout> {hasOutdatedRecoveryFile && ( <p className="color-danger flex flex-nowrap"> <Icon className="mr-2 flex-item-noshrink mt-0.5" name="exclamation-circle-filled" size={14} /> <span className="flex-item-fluid">{c('Warning') .t`Your recovery file is outdated. It can't recover new data if you reset your account again.`}</span> </p> )} </> )} </SettingsSection> </> ); }; export default DataRecoverySection;
6,830
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/ExportRecoveryFileButton.tsx
import { c } from 'ttag'; import { Button, ButtonProps } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { setNewRecoverySecret } from '@proton/shared/lib/api/settingsRecovery'; import { exportRecoveryFile, generateRecoverySecret, validateRecoverySecret, } from '@proton/shared/lib/recoveryFile/recoveryFile'; import { useApi, useEventManager, useNotifications, usePrimaryRecoverySecret, useUserKeys } from '../../hooks'; interface Props extends Omit<ButtonProps, 'onClick'> {} const ExportRecoveryFileButton = ({ loading: loadingProp, children = c('Action').t`Download recovery file`, ...rest }: Props) => { const api = useApi(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const [userKeys, loadingUserKeys] = useUserKeys(); const primaryRecoverySecret = usePrimaryRecoverySecret(); const [loading, withLoading] = useLoading(); const exportRecoveryFileWithNotification: typeof exportRecoveryFile = async (args) => { await exportRecoveryFile(args); createNotification({ text: c('Info').t`Recovery file downloaded` }); }; const handleClick = async () => { const primaryUserKey = userKeys[0]; if (!primaryUserKey) { return; } if (!primaryRecoverySecret) { const { recoverySecret, signature } = await generateRecoverySecret(primaryUserKey.privateKey); await api( setNewRecoverySecret({ RecoverySecret: recoverySecret, Signature: signature, }) ); await exportRecoveryFileWithNotification({ recoverySecret, userKeys }); await call(); return; } const valid = await validateRecoverySecret(primaryRecoverySecret, primaryUserKey.publicKey); if (!valid) { createNotification({ text: c('Info').t`Unable to verify recovery file signature. Please contact support.`, type: 'error', }); return; } await exportRecoveryFileWithNotification({ recoverySecret: primaryRecoverySecret.RecoverySecret, userKeys, }); }; return ( <Button onClick={() => withLoading(handleClick())} loading={loadingUserKeys || loading || loadingProp} {...rest} > {children} </Button> ); }; export default ExportRecoveryFileButton;
6,831
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/OverviewSection.tsx
import { reactivateKeysProcess } from '@proton/shared/lib/keys'; import noop from '@proton/utils/noop'; import { useModalState } from '../../components'; import { useAddresses, useAddressesKeys, useApi, useAuthentication, useEventManager, useFeature, useSearchParamsEffect, useUser, useUserKeys, } from '../../hooks'; import { FeatureCode } from '../features/FeaturesContext'; import { useKTVerifier } from '../keyTransparency'; import ReactivateKeysModal from '../keys/reactivateKeys/ReactivateKeysModal'; import { getAllKeysReactivationRequests } from '../keys/reactivateKeys/getAllKeysToReactive'; import RecoverDataCard from './RecoverDataCard'; import RecoverDataConfirmModal from './RecoverDataConfirmModal'; import RecoveryCard from './RecoveryCard'; interface Props { ids: { account: string; data: string; }; } const OverviewSection = ({ ids }: Props) => { const { call } = useEventManager(); const authentication = useAuthentication(); const api = useApi(); const [User] = useUser(); const [Addresses] = useAddresses(); const [userKeys] = useUserKeys(); const [addressesKeys] = useAddressesKeys(); const allKeysToReactivate = getAllKeysReactivationRequests(addressesKeys, User, userKeys); const { keyTransparencyVerify, keyTransparencyCommit } = useKTVerifier(api, async () => User); const [reactivateKeyProps, setReactivateKeyModalOpen, renderReactivateKeys] = useModalState(); const [confirmProps, setDismissConfirmModalOpen, renderConfirm] = useModalState(); const { feature: hasDismissedRecoverDataCard } = useFeature(FeatureCode.DismissedRecoverDataCard); useSearchParamsEffect( (params) => { if (params.get('action') === 'recover-data' && allKeysToReactivate.length) { setReactivateKeyModalOpen(true); params.delete('action'); return params; } }, [allKeysToReactivate] ); return ( <> {renderReactivateKeys && ( <ReactivateKeysModal userKeys={userKeys} keyReactivationRequests={allKeysToReactivate} onProcess={async (keyReactivationRecords, onReactivation) => { await reactivateKeysProcess({ api, user: User, userKeys, addresses: Addresses, keyReactivationRecords, keyPassword: authentication.getPassword(), onReactivation, keyTransparencyVerify, }); await keyTransparencyCommit(userKeys).catch(noop); return call(); }} {...reactivateKeyProps} /> )} {renderConfirm && <RecoverDataConfirmModal {...confirmProps} />} {!!allKeysToReactivate.length && hasDismissedRecoverDataCard?.Value === false && ( <RecoverDataCard className="mb-8" onReactivate={() => setReactivateKeyModalOpen(true)} onDismiss={() => setDismissConfirmModalOpen(true)} /> )} <RecoveryCard ids={ids} /> </> ); }; export default OverviewSection;
6,832
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/RecoverDataCard.tsx
import { c } from 'ttag'; import { Button, Card, Href } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import clsx from '@proton/utils/clsx'; import { Icon } from '../../components'; import { SettingsSectionTitle } from '../account'; interface Props { onDismiss: () => void; onReactivate: () => void; className?: string; } const RecoverDataCard = ({ onDismiss, onReactivate, className }: Props) => { return ( <Card rounded background={false} className={clsx('max-w-custom', className)} style={{ '--max-w-custom': '46em' }} > <SettingsSectionTitle className="h3 flex flex-align-items-center flex-nowrap"> <Icon className="flex-item-noshrink color-danger" name="exclamation-circle-filled" size={18} /> <span className="ml-2">{c('Title').t`Data locked`}</span> </SettingsSectionTitle> <p>{c('Info').t`It appears some of your data is encrypted and locked.`}</p> <ul> <li> {c('Info') .t`If you recently reset your password, you can use a data recovery method to unlock your data`} </li> <li> {c('Info').t`If this is due to an old password reset, you can stop the message from showing again`} </li> </ul> <p className="mb-2"> <Href href={getKnowledgeBaseUrl('/recover-encrypted-messages-files')}> {c('Link').t`How to unlock data`} </Href> </p> <Button color="norm" onClick={onReactivate} className="mr-4 mt-4">{c('Action').t`Unlock data`}</Button> <Button className="mt-4" onClick={onDismiss}>{c('Action').t`Don't show again`}</Button> </Card> ); }; export default RecoverDataCard;
6,833
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/RecoverDataConfirmModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Prompt, PromptProps, SettingsLink } from '../../components'; import { useFeature } from '../../hooks'; import { FeatureCode } from '../features/FeaturesContext'; const RecoverDataConfirmModal = (props: Omit<PromptProps, 'open' | 'title' | 'buttons' | 'children'>) => { const [dismissing, setDismissing] = useState(false); const { update: setDismissedRecoverDataCard } = useFeature(FeatureCode.DismissedRecoverDataCard); const boldDataLocked = ( <b key="data-locked-bold-text">{ // translator: Full sentence is 'The Data locked message will no longer be shown, but you can still unlock your data under Encryption and keys.' c('Info').t`Data locked` }</b> ); const encryptionAndKeysLink = ( <SettingsLink path="/encryption-keys" key="link">{ // translator: Full sentence is 'The Data locked message will no longer be shown, but you can still unlock your data under Encryption and keys.' c('Link').t`Encryption and keys` }</SettingsLink> ); return ( <Prompt {...props} title={c('Title').t`Don't show again?`} buttons={[ <Button color="danger" onClick={async () => { setDismissing(true); await setDismissedRecoverDataCard(true); setDismissing(false); props.onClose?.(); }} loading={dismissing} > {c('Action').t`Don't show again`} </Button>, <Button onClick={props.onClose}>{c('Action').t`Cancel`}</Button>, ]} > <p> { // translator: Full sentence is 'The Data locked message will no longer be shown, but you can still unlock your data under Encryption and keys.' c('Info') .jt`The ${boldDataLocked} message will no longer be shown, but you can still unlock your data under ${encryptionAndKeysLink}.` } </p> </Prompt> ); }; export default RecoverDataConfirmModal;
6,834
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/RecoveryCard.tsx
import { c } from 'ttag'; import { Card, Href } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { MNEMONIC_STATUS } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { Loader } from '../../components'; import { useHasOutdatedRecoveryFile, useIsDataRecoveryAvailable, useIsMnemonicAvailable, useRecoverySecrets, useRecoveryStatus, useUser, useUserSettings, } from '../../hooks'; import useIsRecoveryFileAvailable from '../../hooks/useIsRecoveryFileAvailable'; import { SettingsSectionTitle } from '../account'; import RecoveryCardStatus, { RecoveryCardStatusProps } from './RecoveryCardStatus'; interface Props { ids: { account: string; data: string; }; } const RecoveryCard = ({ ids }: Props) => { const [user] = useUser(); const [userSettings, loadingUserSettings] = useUserSettings(); const [{ accountRecoveryStatus, dataRecoveryStatus }, loadingRecoveryStatus] = useRecoveryStatus(); const [isRecoveryFileAvailable, loadingIsRecoveryFileAvailable] = useIsRecoveryFileAvailable(); const [isMnemonicAvailable, loadingIsMnemonicAvailable] = useIsMnemonicAvailable(); const [isDataRecoveryAvailable, loadingIsDataRecoveryAvailable] = useIsDataRecoveryAvailable(); const hasOutdatedRecoveryFile = useHasOutdatedRecoveryFile(); const recoverySecrets = useRecoverySecrets(); if ( loadingRecoveryStatus || loadingIsDataRecoveryAvailable || loadingIsRecoveryFileAvailable || loadingIsMnemonicAvailable || loadingUserSettings ) { return <Loader />; } const boldImperative = ( <b key="imperative-bold-text">{ // translator: Full sentence is 'If you lose your login details and need to reset your account, it’s imperative that you have both an account recovery and data recovery method in place, otherwise you might not be able to access any of your emails, contacts, or files.' c('Info').t`it’s imperative` }</b> ); const boldAccountAndRecovery = ( <b key="account-and-recovery-bold-text">{ // translator: Full sentence is 'If you lose your login details and need to reset your account, it’s imperative that you have both an account recovery and data recovery method in place, otherwise you might not be able to access any of your emails, contacts, or files.' c('Info').t`account recovery and data recovery method` }</b> ); const boldAccountRecovery = ( <b key="account-recovery-bold-text">{ // translator: Full sentence is 'If you lose your login details and need to reset your account, it’s imperative that you have an account recovery method in place.' c('Info').t`account recovery method` }</b> ); const accountStatusProps: RecoveryCardStatusProps = (() => { if (accountRecoveryStatus === 'complete') { return { type: 'success', statusText: c('Info').t`Your account recovery method is set`, callToActions: [], }; } const emailCTA = { text: !!userSettings.Email.Value && !userSettings.Email.Reset ? c('Info').t`Allow recovery by email` : c('Info').t`Add a recovery email address`, path: `/recovery#${ids.account}`, }; const phoneCTA = { text: !!userSettings.Phone.Value && !userSettings.Phone.Reset ? c('Info').t`Allow recovery by phone` : c('Info').t`Add a recovery phone number`, path: `/recovery#${ids.account}`, }; if (user.MnemonicStatus === MNEMONIC_STATUS.SET) { return { type: 'info', statusText: c('Info').t`To ensure continuous access to your account, set an account recovery method`, callToActions: [emailCTA, phoneCTA], }; } return { type: 'warning', statusText: c('Info').t`No account recovery method set; you are at risk of losing access to your account`, callToActions: [emailCTA, phoneCTA], }; })(); const dataStatusProps: RecoveryCardStatusProps | undefined = (() => { if (!isRecoveryFileAvailable && !isMnemonicAvailable) { return; } const recoveryFileCTA = isRecoveryFileAvailable && { text: c('Info').t`Download recovery file`, path: `/recovery#${ids.data}`, }; const updateRecoveryFileCTA = isRecoveryFileAvailable && { text: c('Info').t`Update recovery file`, path: `/recovery#${ids.data}`, }; const recoveryPhraseCTA = isMnemonicAvailable && { text: c('Info').t`Set recovery phrase`, path: `/recovery#${ids.data}`, }; const updateRecoveryPhraseCTA = isMnemonicAvailable && { text: c('Info').t`Update recovery phrase`, path: `/recovery#${ids.data}`, }; if (user.MnemonicStatus === MNEMONIC_STATUS.OUTDATED && hasOutdatedRecoveryFile) { return { type: 'danger', statusText: c('Info').t`Outdated recovery methods; update to ensure access to your data`, callToActions: [updateRecoveryPhraseCTA, updateRecoveryFileCTA].filter(isTruthy), }; } if (user.MnemonicStatus === MNEMONIC_STATUS.OUTDATED) { return { type: 'danger', statusText: c('Info').t`Outdated recovery phrase; update to ensure access to your data`, callToActions: [updateRecoveryPhraseCTA, recoverySecrets.length === 0 && recoveryFileCTA].filter( isTruthy ), }; } if (hasOutdatedRecoveryFile) { return { type: 'danger', statusText: c('Info').t`Outdated recovery file; update to ensure access to your data`, callToActions: [ user.MnemonicStatus !== MNEMONIC_STATUS.SET && recoveryPhraseCTA, updateRecoveryFileCTA, ].filter(isTruthy), }; } if (dataRecoveryStatus === 'complete') { return { type: 'success', statusText: c('Info').t`Your data recovery method is set`, callToActions: [], }; } return { type: 'warning', statusText: c('Info').t`No data recovery method set; you are at risk of losing access to your data`, callToActions: [recoveryPhraseCTA, recoveryFileCTA].filter(isTruthy), }; })(); return ( <Card rounded background={false} className="max-w-custom" style={{ '--max-w-custom': '46em' }}> <SettingsSectionTitle className="h3">{c('Title') .t`Take precautions to avoid data loss!`}</SettingsSectionTitle> <p> {isDataRecoveryAvailable ? // translator: Full sentence is 'If you lose your login details and need to reset your account, it’s imperative that you have both an account recovery and data recovery method in place, otherwise you might not be able to access any of your emails, contacts, or files.' c('Info') .jt`If you lose your password and need to reset your account, ${boldImperative} that you have both an ${boldAccountAndRecovery} in place, otherwise you might not be able to access any of your emails, contacts, or files.` : // translator: Full sentence is 'If you lose your login details and need to reset your account, it’s imperative that you have an account recovery method in place.' c('Info') .jt`If you lose your password and need to reset your account, ${boldImperative} that you have an ${boldAccountRecovery} in place.`} <br /> <Href href={getKnowledgeBaseUrl('/set-account-recovery-methods')}> {c('Link').t`Why set recovery methods?`} </Href> </p> <h3 className="text-bold text-rg mb-4">{c('Title').t`Your recovery status`}</h3> <ul className="unstyled m-0"> <li> <RecoveryCardStatus {...accountStatusProps} /> </li> {dataStatusProps && ( <li className="mt-2"> <RecoveryCardStatus {...dataStatusProps} /> </li> )} </ul> </Card> ); }; export default RecoveryCard;
6,835
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/RecoveryCardStatus.tsx
import { ButtonLike } from '@proton/atoms'; import { Icon, SettingsLink } from '../../components'; import RecoveryStatusIcon from './RecoveryStatusIcon'; import RecoveryStatusText from './RecoveryStatusText'; export interface RecoveryCardStatusProps { type: 'info' | 'success' | 'warning' | 'danger'; statusText: string; callToActions?: { text: string; path: string; }[]; } const RecoveryCardStatus = ({ type, statusText, callToActions: items = [] }: RecoveryCardStatusProps) => { return ( <> <span className="flex flex-align-items-center flex-nowrap"> <RecoveryStatusIcon className="flex-item-noshrink" type={type} /> <RecoveryStatusText className="ml-4" type={type}> {statusText} </RecoveryStatusText> </span> {items.length > 0 && ( <ul className="unstyled ml-14"> {items.map(({ text, path }) => { return ( <li key={text} className="flex flex-align-items-center flex-nowrap"> <span className="mr-2">{text}</span> <ButtonLike as={SettingsLink} icon path={path} shape="ghost" color="norm" size="small" title={text} > <Icon name="arrow-right" alt={text} /> </ButtonLike> </li> ); })} </ul> )} </> ); }; export default RecoveryCardStatus;
6,836
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/RecoveryStatus.ts
type RecoveryStatus = 'complete' | 'intermediate' | 'incomplete'; export default RecoveryStatus;
6,837
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/RecoveryStatusIcon.tsx
import clsx from '@proton/utils/clsx'; import Icon, { IconName, IconProps } from '../../components/icon/Icon'; interface Props extends Omit<IconProps, 'name' | 'size'> { type: 'info' | 'success' | 'warning' | 'danger'; } const RecoveryStatusIcon = ({ type, className, ...rest }: Props) => { let config: { name: IconName; className: string } = { name: 'info-circle-filled', className: 'color-info', }; if (type === 'success') { config = { name: 'checkmark-circle-filled', className: 'color-success', }; } if (type === 'warning') { config = { name: 'exclamation-circle-filled', className: 'color-warning', }; } if (type === 'danger') { config = { name: 'exclamation-circle-filled', className: 'color-danger', }; } return <Icon className={clsx([config.className, className])} name={config.name} size={18} {...rest} />; }; export default RecoveryStatusIcon;
6,838
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/RecoveryStatusText.tsx
import { HTMLAttributes } from 'react'; import clsx from '@proton/utils/clsx'; interface Props extends HTMLAttributes<HTMLSpanElement> { type: 'info' | 'success' | 'warning' | 'danger'; } const RecoveryStatusText = ({ type, className, ...rest }: Props) => { return <span className={clsx([`color-${type}`, className])} {...rest} />; }; export default RecoveryStatusText;
6,839
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/SessionRecoverySection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import useLoading from '@proton/hooks/useLoading'; import metrics, { observeApiError } from '@proton/metrics'; import { updateSessionAccountRecovery } from '@proton/shared/lib/api/sessionRecovery'; import { Toggle, useModalState } from '../../components'; import { useApi, useEventManager, useHasRecoveryMethod, useIsSessionRecoveryEnabled, useIsSessionRecoveryInitiationAvailable, useNotifications, } from '../../hooks'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; import SettingsParagraph from '../account/SettingsParagraph'; import SettingsSection from '../account/SettingsSection'; import InitiateSessionRecoveryModal from '../account/sessionRecovery/InitiateSessionRecoveryModal'; import ConfirmDisableSessionRecoveryModal from './ConfirmDisableSessionRecoveryModal'; const SessionRecoverySection = () => { const api = useApi(); const { call } = useEventManager(); const [loadingSessionRecovery, withLoadingSessionRecovery] = useLoading(); const [sessionRecoveryModal, setSessionRecoveryModalOpen, renderSessionRecoveryModal] = useModalState(); const [ confirmDisableSessionRecoveryModal, setConfirmDisableSessionRecoveryModalOpen, renderConfirmDisableSessionRecoveryModal, ] = useModalState(); const [hasRecoveryMethod, loadingUseHasRecoveryMethod] = useHasRecoveryMethod(); const isSessionRecoveryEnabled = useIsSessionRecoveryEnabled(); const isSessionRecoveryInitiationAvailable = useIsSessionRecoveryInitiationAvailable(); const { createNotification } = useNotifications(); const handleEnableSessionRecoveryToggle = async () => { try { await api(updateSessionAccountRecovery({ SessionAccountRecovery: 1 })); await call(); metrics.core_session_recovery_settings_update_total.increment({ status: 'success', }); } catch (error) { observeApiError(error, (status) => metrics.core_session_recovery_settings_update_total.increment({ status, }) ); } }; return ( <> {renderSessionRecoveryModal && <InitiateSessionRecoveryModal confirmedStep {...sessionRecoveryModal} />} {renderConfirmDisableSessionRecoveryModal && ( <ConfirmDisableSessionRecoveryModal {...confirmDisableSessionRecoveryModal} /> )} <SettingsSection> <SettingsParagraph> {c('session_recovery:settings:action') .t`Request a password reset from your Account settings. No recovery method needed.`} </SettingsParagraph> <SettingsLayout> <SettingsLayoutLeft> <label className="pt-0 mb-2 md:mb-0 text-semibold" htmlFor="signedInReset"> <span className="mr-2">{c('session_recovery:settings:action') .t`Allow password reset from settings`}</span> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="flex-item-fluid pt-2"> <div className="flex flex-align-items-center"> <Toggle loading={loadingSessionRecovery} checked={isSessionRecoveryEnabled} disabled={loadingUseHasRecoveryMethod} id="signedInReset" onChange={({ target: { checked } }) => { if (!hasRecoveryMethod && !checked) { createNotification({ text: c('session_recovery:settings:action') .t`To disallow password reset, you must have a recovery method set up.`, }); return; } if (!checked) { setConfirmDisableSessionRecoveryModalOpen(true); return; } void withLoadingSessionRecovery(handleEnableSessionRecoveryToggle()); }} /> </div> {isSessionRecoveryInitiationAvailable && ( <Button className="mt-4" color="norm" onClick={() => setSessionRecoveryModalOpen(true)}> {c('session_recovery:settings:action').t`Request password reset`} </Button> )} </SettingsLayoutRight> </SettingsLayout> </SettingsSection> </> ); }; export default SessionRecoverySection;
6,840
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/VoidRecoveryFilesModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { deleteRecoverySecrets } from '@proton/shared/lib/api/settingsRecovery'; import { ModalProps, Prompt } from '../../components'; import { useApi, useEventManager, useNotifications } from '../../hooks'; interface Props extends Omit<ModalProps, 'children' | 'size'> { /** * Remove when TrustedDeviceRecovery feature is removed */ trustedDeviceRecovery: boolean | undefined; } const VoidRecoveryFilesModal = ({ trustedDeviceRecovery, onClose, ...rest }: Props) => { const { call } = useEventManager(); const api = useApi(); const { createNotification } = useNotifications(); const [revoking, withRevoking] = useLoading(); const handleVoidClick = async () => { await api(deleteRecoverySecrets()); await call(); createNotification({ type: 'info', text: c('Info').t`Recovery files have been voided` }); onClose?.(); }; return ( <Prompt {...rest} title={c('Action').t`Void all recovery files?`} buttons={[ <Button color="danger" loading={revoking} onClick={() => withRevoking(handleVoidClick())}> {c('Action').t`Void`} </Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} > <p className="m-0"> {trustedDeviceRecovery ? c('Info') .t`You won’t be able to recover locked data using your downloaded recovery files. This will also void trusted device-recovery information.` : c('Info').t`You won’t be able to recover locked data using your downloaded recovery files.`} </p> </Prompt> ); }; export default VoidRecoveryFilesModal;
6,841
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/getOverallStatus.ts
import RecoveryStatus from './RecoveryStatus'; interface Props { accountRecoveryStatus: RecoveryStatus; dataRecoveryStatus: RecoveryStatus; isDataRecoveryAvailable: boolean; } const getOverallStatus = ({ accountRecoveryStatus, dataRecoveryStatus, isDataRecoveryAvailable, }: Props): RecoveryStatus => { if (accountRecoveryStatus !== 'complete') { return 'incomplete'; } if (isDataRecoveryAvailable && dataRecoveryStatus !== 'complete') { return 'intermediate'; } return 'complete'; }; export default getOverallStatus;
6,842
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/index.ts
export { default as AccountRecoverySection } from './AccountRecoverySection'; export { default as DataRecoverySection } from './DataRecoverySection'; export { default as SessionRecoverySection } from './SessionRecoverySection'; export { default as OverviewSection } from './OverviewSection'; export { default as getOverallStatus } from './getOverallStatus';
6,843
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/email/ConfirmRemoveEmailModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, } from '../../../components'; interface Props extends ModalProps { onConfirm: () => void; hasReset: boolean; hasNotify: boolean; } const ConfirmRemoveEmailModal = ({ hasReset, hasNotify, onConfirm, onClose, ...rest }: Props) => { return ( <Modal onClose={onClose} {...rest}> <ModalHeader title={c('Title').t`Confirm address`} /> <ModalContent> <Alert type="warning"> {hasReset && !hasNotify && c('Warning').t`By deleting this address, you will no longer be able to recover your account.`} {hasNotify && !hasReset && c('Warning') .t`By deleting this address, you will no longer be able to receive daily email notifications.`} {hasNotify && hasReset && c('Warning') .t`By deleting this address, you will no longer be able to recover your account or receive daily email notifications.`} <br /> <br /> {c('Warning').t`Are you sure you want to delete this address?`} </Alert> </ModalContent> <ModalFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" onClick={() => { onConfirm(); onClose?.(); }} > {c('Action').t`Confirm`} </Button> </ModalFooter> </Modal> ); }; export default ConfirmRemoveEmailModal;
6,844
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/email/RecoveryEmail.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { updateEmail } from '@proton/shared/lib/api/settings'; import { emailValidator } from '@proton/shared/lib/helpers/formValidators'; import { SETTINGS_STATUS, UserSettings } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import isTruthy from '@proton/utils/isTruthy'; import { Icon, InputFieldTwo, useFormErrors, useModalState } from '../../../components'; import { useEventManager, useNotifications } from '../../../hooks'; import AuthModal from '../../password/AuthModal'; import ConfirmRemoveEmailModal from './ConfirmRemoveEmailModal'; import VerifyRecoveryEmailModal from './VerifyRecoveryEmailModal'; interface Props { email: UserSettings['Email']; hasReset: boolean; hasNotify: boolean; className?: string; } const RecoveryEmail = ({ email, hasReset, hasNotify, className }: Props) => { const [input, setInput] = useState(email.Value || ''); const { createNotification } = useNotifications(); const { call } = useEventManager(); const { validator, onFormSubmit } = useFormErrors(); const [verifyRecoveryEmailModal, setVerifyRecoveryEmailModalOpen, renderVerifyRecoveryEmailModal] = useModalState(); const [authModal, setAuthModal, renderAuthModal] = useModalState(); const [confirmModal, setConfirmModal, renderConfirmModal] = useModalState(); const loading = renderVerifyRecoveryEmailModal || renderConfirmModal || renderAuthModal; const confirmStep = !input && (hasReset || hasNotify); return ( <> {renderAuthModal && ( <AuthModal {...authModal} onCancel={undefined} onSuccess={async () => { await call(); createNotification({ text: c('Success').t`Email updated` }); }} config={updateEmail({ Email: input })} /> )} {renderConfirmModal && ( <ConfirmRemoveEmailModal hasReset={hasReset} hasNotify={hasNotify} {...confirmModal} onConfirm={() => { setAuthModal(true); }} /> )} {renderVerifyRecoveryEmailModal && <VerifyRecoveryEmailModal email={email} {...verifyRecoveryEmailModal} />} <form className={clsx(['flex flex-wrap on-mobile-flex-column', className])} onSubmit={(e) => { e.preventDefault(); if (!onFormSubmit()) { return; } if (confirmStep) { setConfirmModal(true); } else { setAuthModal(true); } }} > <div className="mr-0 mb-4 md:mr-4 flex-item-fluid min-w-custom" style={{ '--min-w-custom': '14em' }} title={email.Value || ''} > <InputFieldTwo type="email" autoComplete="email" id="recovery-email-input" disableChange={loading} value={input || ''} error={validator([input && emailValidator(input)].filter(isTruthy))} onValue={setInput} assistiveText={ email.Value && (email.Status !== SETTINGS_STATUS.VERIFIED ? ( <> <Icon className="color-danger flex-item-noshrink aligntop mr-1" name="exclamation-circle-filled" /> <span className="color-norm mr-2">{c('Recovery Email') .t`Email address not yet verified.`}</span> <button className="link" type="button" onClick={() => setVerifyRecoveryEmailModalOpen(true)} aria-label={c('Recovery Email') .t`Verify now this recovery email address: ${email.Value}`} > {c('Recovery Email').t`Verify now`} </button> </> ) : ( <> <Icon className="color-success flex-item-noshrink aligntop mr-1" name="checkmark-circle-filled" /> <span className="mr-2">{c('Recovery Email') .t`Email address has been verified.`}</span> </> )) } /> </div> <div className="mb-2"> <Button type="submit" shape="outline" disabled={(email.Value || '') === input} loading={loading} data-testid="account:recovery:emailSubmit" > {c('Action').t`Save`} </Button> </div> </form> </> ); }; export default RecoveryEmail;
6,845
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/email/VerifyRecoveryEmailModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { postVerifySend } from '@proton/shared/lib/api/verify'; import { UserSettings } from '@proton/shared/lib/interfaces'; import { ModalProps, Prompt } from '../../../components'; import { useApi, useNotifications } from '../../../hooks'; export const getVerificationSentText = (address: string) => { return c('Email verification').t`Verification email sent to ${address}`; }; interface Props extends ModalProps { email: UserSettings['Email']; } const VerifyRecoveryEmailModal = ({ email, onClose, ...rest }: Props) => { const [loading, setLoading] = useState(false); const api = useApi(); const { createNotification } = useNotifications(); const handleSendVerificationEmailClick = async () => { setLoading(true); await api(postVerifySend({ Type: 'recovery_email' })); createNotification({ type: 'success', text: getVerificationSentText(email.Value), }); onClose?.(); }; return ( <Prompt title={c('Recovery Email').t`Verify recovery email?`} buttons={[ <Button loading={loading} shape="solid" color="norm" onClick={handleSendVerificationEmailClick}>{c( 'Recovery Email' ).t`Verify with email`}</Button>, <Button onClick={onClose} disabled={loading}>{c('Recovery Email').t`Cancel`}</Button>, ]} {...rest} > {c('Recovery Email') .t`Verifying your email address increases your account security and allows additional options for recovery.`} </Prompt> ); }; export default VerifyRecoveryEmailModal;
6,846
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/phone/ConfirmRemovePhoneModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, } from '../../../components'; interface Props extends ModalProps { onConfirm: () => void; } const ConfirmRemovePhoneModal = ({ onConfirm, onClose, ...rest }: Props) => { return ( <Modal onClose={onClose} {...rest}> <ModalHeader title={c('Title').t`Confirm phone number`} /> <ModalContent> <Alert type="warning"> {c('Warning').t`By deleting this phone number, you will no longer be able to recover your account.`} <br /> <br /> {c('Warning').t`Are you sure you want to delete the phone number?`} </Alert> </ModalContent> <ModalFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" onClick={() => { onConfirm(); onClose?.(); }} > {c('Action').t`Confirm`} </Button> </ModalFooter> </Modal> ); }; export default ConfirmRemovePhoneModal;
6,847
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/phone/RecoveryPhone.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { updatePhone } from '@proton/shared/lib/api/settings'; import { SETTINGS_STATUS, UserSettings } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { Icon, InputFieldTwo, PhoneInput, useFormErrors, useModalState } from '../../../components'; import { useEventManager, useNotifications } from '../../../hooks'; import AuthModal from '../../password/AuthModal'; import ConfirmRemovePhoneModal from './ConfirmRemovePhoneModal'; import VerifyRecoveryPhoneModal from './VerifyRecoveryPhoneModal'; interface Props { phone: UserSettings['Phone']; hasReset: boolean; defaultCountry?: string; className?: string; } const RecoveryPhone = ({ phone, hasReset, defaultCountry, className }: Props) => { const [input, setInput] = useState(phone.Value || ''); const { createNotification } = useNotifications(); const { call } = useEventManager(); const { onFormSubmit } = useFormErrors(); const [verifyRecoveryPhoneModal, setVerifyRecoveryPhoneModalOpen, renderVerifyRecoveryPhoneModal] = useModalState(); const [confirmModal, setConfirmModal, renderConfirmModal] = useModalState(); const [authModal, setAuthModal, renderAuthModal] = useModalState(); const confirmStep = !input && hasReset; const loading = renderConfirmModal || renderAuthModal || renderVerifyRecoveryPhoneModal; return ( <> {renderConfirmModal && ( <ConfirmRemovePhoneModal {...confirmModal} onConfirm={() => { setAuthModal(true); }} /> )} {renderAuthModal && ( <AuthModal {...authModal} onCancel={undefined} onSuccess={async () => { await call(); createNotification({ text: c('Success').t`Phone number updated` }); }} config={updatePhone({ Phone: input })} /> )} {renderVerifyRecoveryPhoneModal && <VerifyRecoveryPhoneModal phone={phone} {...verifyRecoveryPhoneModal} />} <form className={clsx(['flex flex-wrap on-mobile-flex-column', className])} onSubmit={(e) => { e.preventDefault(); if (!onFormSubmit()) { return; } if (confirmStep) { setConfirmModal(true); } else { setAuthModal(true); } }} > <div className="mr-0 mb-4 md:mr-4 flex-item-fluid min-w-custom" style={{ '--min-w-custom': '14em' }}> <InputFieldTwo as={PhoneInput} id="phoneInput" disableChange={loading} defaultCountry={defaultCountry} value={input} onChange={setInput} aria-label={c('label').t`Recovery phone number`} assistiveText={ phone.Value && (phone.Status !== SETTINGS_STATUS.VERIFIED ? ( <> <Icon className="color-danger flex-item-noshrink aligntop mr-1" name="exclamation-circle-filled" /> <span className="color-norm mr-2">{c('Recovery Phone') .t`Phone number not yet verified.`}</span> <button className="link" type="button" onClick={() => setVerifyRecoveryPhoneModalOpen(true)} aria-label={c('Recovery Phone') .t`Verify this recovery phone number now: ${phone.Value}`} > {c('Recovery Phone').t`Verify now`} </button> </> ) : ( <> <Icon className="color-success flex-item-noshrink aligntop mr-1" name="checkmark-circle-filled" /> <span className="mr-2">{c('Recovery Phone') .t`Phone number has been verified.`}</span> </> )) } /> </div> <div className="mb-2"> <Button shape="outline" type="submit" disabled={(phone.Value || '') === input} loading={loading} data-testid="account:recovery:phoneSubmit" > {c('Action').t`Save`} </Button> </div> </form> </> ); }; export default RecoveryPhone;
6,848
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/recovery/phone/VerifyRecoveryPhoneModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { postVerifyPhone } from '@proton/shared/lib/api/verify'; import { UserSettings } from '@proton/shared/lib/interfaces'; import { ModalProps, Prompt } from '../../../components'; import { useApi } from '../../../hooks'; interface Props extends ModalProps { phone: UserSettings['Phone']; } const VerifyRecoveryPhoneModal = ({ phone, onClose, ...rest }: Props) => { const [loading, setLoading] = useState(false); const api = useApi(); const handleSendVerificationPhoneClick = async () => { setLoading(true); try { // PostVerifyPhone will call /core/v4/verify/phone which should return error 9001 Human Verification. // The client will then display the verify modal and replay the endpoint to submit the token and verify the phone number. await api(postVerifyPhone()); } catch (error) {} onClose?.(); }; return ( <Prompt title={c('Recovery Phone').t`Verify recovery phone?`} buttons={[ <Button loading={loading} shape="solid" color="norm" onClick={handleSendVerificationPhoneClick}>{c( 'Recovery Phone' ).t`Verify by SMS`}</Button>, <Button onClick={onClose} disabled={loading}>{c('Recovery Phone').t`Cancel`}</Button>, ]} {...rest} > {c('Recovery Phone') .t`Verifying your phone number increases your account security and allows additional options for recovery.`} </Prompt> ); }; export default VerifyRecoveryPhoneModal;
6,849
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/ReferralFeaturesList.tsx
import { c } from 'ttag'; import { Icon, Info, StripedItem, StripedList } from '@proton/components'; import { CALENDAR_APP_NAME, DRIVE_APP_NAME, MAIL_APP_NAME } from '@proton/shared/lib/constants'; import humanSize from '@proton/shared/lib/helpers/humanSize'; const ReferralFeaturesList = () => { const storageSize = humanSize(15 * 1024 ** 3, undefined, undefined, 0); return ( <StripedList> <StripedItem left={<Icon className="color-success" name="storage" size={20} />}> {c('Info').t`${storageSize} storage`} <Info className="ml-2" title={c('Info') .t`Storage space is shared across ${MAIL_APP_NAME}, ${CALENDAR_APP_NAME}, and ${DRIVE_APP_NAME}.`} /> </StripedItem> <StripedItem left={<Icon className="color-success" name="envelope" size={20} />}> {c('Info').t`10 email addresses`} </StripedItem> <StripedItem left={<Icon className="color-success" name="tag" size={20} />}> {c('Info').t`Unlimited folders, labels, and filters`} </StripedItem> <StripedItem left={<Icon className="color-success" name="paper-plane-horizontal" size={20} />}> {c('Info').t`Unlimited messages`} </StripedItem> <StripedItem left={<Icon className="color-success" name="globe" size={20} />}> {c('Info').t`Support for 1 custom email domain`} </StripedItem> <StripedItem left={<Icon className="color-success" name="life-ring" size={20} />}> {c('Info').t`Priority support`} </StripedItem> <StripedItem left={<Icon className="color-success" name="brand-proton-calendar" size={20} />}> {CALENDAR_APP_NAME} </StripedItem> </StripedList> ); }; export default ReferralFeaturesList;
6,850
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/ReferralHowItWorks.scss
@import '~@proton/styles/scss/lib'; .steps-vertical { &-item { padding-block-end: 1.5em; background: linear-gradient( 90deg, transparent 0%, transparent rem(15), var(--background-strong) rem(15), var(--background-strong) rem(17), transparent rem(17) ); &--next-done { background: linear-gradient( 90deg, transparent 0%, transparent rem(15), var(--signal-success) rem(15), var(--signal-success) rem(17), transparent rem(17) ); } &-text { margin-block-start: rem(-2); // small trick to compensate line-height, for vertical centering } &:last-child { background: none; } } &-icon-container { inline-size: rem(32); block-size: rem(32); } }
6,851
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/ReferralHowItWorks.tsx
import { addMonths, format } from 'date-fns'; import { c } from 'ttag'; import { VerticalStep, VerticalSteps } from '@proton/atoms/VerticalSteps'; import { dateLocale } from '@proton/shared/lib/i18n'; import { Icon } from '../../components'; const ReferralHowItWorks = () => { // NOTE API plan to return subscription start date with GET /plans route const startDate = addMonths(new Date(), 1); const startText = format(startDate, 'PP', { locale: dateLocale }); return ( <VerticalSteps> <VerticalStep icon={<Icon name="checkmark" className="m-auto" size={16} />} title={c('info').t`Create an email address`} description={c('info').t`Your new email address is ready to go!`} status="passed" /> <VerticalStep icon={<Icon name="lock" className="m-auto" size={16} />} title={c('info').t`Try Mail Plus`} description={c('info').t`Enjoy secure, easy-to-use emailing with plenty of premium features.`} status="done" /> <VerticalStep icon={<Icon name="bell" className="m-auto" size={16} />} title={c('info').t`Day 27: Trial reminder`} description={c('info').t`We’ll email you before your trial ends. Cancel anytime.`} /> <VerticalStep icon={<Icon name="calendar-today" className="m-auto" size={16} />} title={c('info').t`Day 30: Trial ends`} // translator: Your subscription starts on Apr 29, 1453. description={c('info').t`Your subscription starts on ${startText}.`} /> </VerticalSteps> ); }; export default ReferralHowItWorks;
6,852
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/ReferralInvitesContext.tsx
import { Dispatch, SetStateAction, createContext, useContext, useState } from 'react'; import { Referral } from '@proton/shared/lib/interfaces'; import useReferralRewardStatus, { UseReferralStatusReducerState } from './hooks/useReferralRewardStatus'; import useReferrals, { UseReferralsReducerState } from './hooks/useReferrals'; interface ReferralProgramContext { invitedReferralsState: [Referral[], Dispatch<SetStateAction<Referral[]>>]; fetchedReferrals: UseReferralsReducerState; fetchedReferralStatus: UseReferralStatusReducerState; } const referralContext = createContext<ReferralProgramContext | undefined>(undefined); export const useReferralInvitesContext = () => { const context = useContext(referralContext); if (context === undefined) { throw new Error('Component should be wrapped inside ReferralContextProvider'); } return context; }; export const ReferralInvitesContextProvider = ({ children }: { children: React.ReactNode }) => { const fetchedReferrals = useReferrals(); const fetchedReferralStatus = useReferralRewardStatus(); const invitedReferralsState = useState<Referral[]>([]); return ( <referralContext.Provider value={{ fetchedReferrals, invitedReferralsState, fetchedReferralStatus, }} > {children} </referralContext.Provider> ); };
6,853
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/ReferralSpotlight.tsx
import { ReactElement, RefObject } from 'react'; import { c } from 'ttag'; import { SettingsLink, Spotlight } from '@proton/components'; import { APPS, BRAND_NAME, DEFAULT_CURRENCY, REFERRAL_PROGRAM_MAX_AMOUNT } from '@proton/shared/lib/constants'; import { humanPriceWithCurrency } from '@proton/shared/lib/helpers/humanPrice'; import { UserModel } from '@proton/shared/lib/interfaces'; import starImg from '@proton/styles/assets/img/illustrations/spotlight-stars.svg'; interface Props { children: ReactElement; anchorRef: RefObject<HTMLElement>; show: boolean; onDisplayed: () => void; onClose: () => void; user?: UserModel; } const ReferralSpotlight = ({ children, show, onDisplayed, anchorRef, user }: Props) => { const credits = humanPriceWithCurrency(REFERRAL_PROGRAM_MAX_AMOUNT, user?.Currency || DEFAULT_CURRENCY); return ( <Spotlight show={show} onDisplayed={onDisplayed} style={{ maxWidth: '25rem' }} content={ <> <div className="flex flex-nowrap my-2"> <div className="flex-item-noshrink mr-4"> <img src={starImg} alt="star" className="w-custom" style={{ '--w-custom': '4em' }} /> </div> <div> <p className="mt-0 mb-2 text-bold">{c('Spotlight').t`Invite friends to ${BRAND_NAME}`}</p> <p className="m-0">{c('Spotlight').t`Get up to ${credits} in credits.`}</p> <SettingsLink path="/referral" app={APPS.PROTONMAIL}>{c('Link') .t`Learn more`}</SettingsLink> </div> </div> </> } anchorRef={anchorRef} > {children} </Spotlight> ); }; export default ReferralSpotlight;
6,854
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/index.ts
export { default as InviteSection } from './invite/InviteSection'; export { default as RewardSection } from './rewards/RewardSection'; export { default as ReferralModal } from './modals/ReferralModal'; export { default as ReferralSpotlight } from './ReferralSpotlight'; export { default as ReferralFeaturesList } from './ReferralFeaturesList'; export { default as ReferralHowItWorks } from './ReferralHowItWorks'; export { ReferralInvitesContextProvider, useReferralInvitesContext } from './ReferralInvitesContext'; export * from './modals/helper';
6,855
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/helpers/fetchAllReferralsByOffset.test.ts
import { Api } from '@proton/shared/lib/interfaces'; import fetchAllReferralsByOffset from './fetchAllReferralsByOffset'; interface ApiResults { Referrals: number[]; Total: number; } describe('fetchAllReferralsByOffset', () => { it('Should make 1 call if total is inferior to limit', async () => { const apiSpy = jest.fn<Promise<ApiResults>, [Api]>(() => Promise.resolve({ Total: 10, Referrals: new Array(10), }) ); const { Referrals } = await fetchAllReferralsByOffset(apiSpy as Api); expect(apiSpy).toHaveBeenCalledTimes(1); expect(Referrals?.length).toBe(10); }); it('Should make 2 call if total is superior to limit', async () => { const LIMIT = 5; const TOTAL = 10; const CALLS_NUMBER = 2; const apiSpy = jest.fn<Promise<ApiResults>, [Api]>(() => Promise.resolve({ Total: 10, Referrals: new Array(LIMIT), }) ); const { Referrals } = await fetchAllReferralsByOffset(apiSpy as Api, { Limit: LIMIT, Offset: 0 }); expect(Referrals?.length).toBe(TOTAL); expect(apiSpy).toHaveBeenCalledTimes(CALLS_NUMBER); }); it('Should make 5 calls (4 of 100 and 1 of 60)', async () => { const TOTAL = 460; const CALLS_NUMBER = 5; let calls = 0; const apiSpy = jest.fn<Promise<ApiResults>, [Api]>(() => { calls += 1; return Promise.resolve({ Total: TOTAL, Referrals: calls < CALLS_NUMBER ? new Array(100) : new Array(60), }); }); const { Referrals } = await fetchAllReferralsByOffset(apiSpy as Api); expect(Referrals?.length).toBe(TOTAL); expect(apiSpy).toHaveBeenCalledTimes(CALLS_NUMBER); }); });
6,856
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/helpers/fetchAllReferralsByOffset.ts
import { getReferrals } from '@proton/shared/lib/api/core/referrals'; import { Api, Referral } from '@proton/shared/lib/interfaces'; import range from '@proton/utils/range'; interface ReferralApiResult { Total: number; Referrals: Referral[]; } const fetchAllReferralsByOffset = async ( api: Api, params?: { Offset?: number; Limit?: number } ): Promise<ReferralApiResult> => { const offset = params?.Offset ?? 0; const limit = params?.Limit ?? 100; const firstResults = await api<ReferralApiResult>(getReferrals({ Offset: offset, Limit: limit })); const total = firstResults.Total; if (!total || limit > total) { return firstResults; } const referrals = [...(firstResults?.Referrals || [])]; const numberOfCalls = Math.ceil((total - limit) / limit); const promises = range(0, numberOfCalls).map((_, index) => { const nextOffset = limit * (index + 1); return api<ReferralApiResult>(getReferrals({ Offset: nextOffset, Limit: limit })); }); const nextResults = await Promise.all(promises); nextResults.forEach((nextResult) => { referrals.push(...(nextResult?.Referrals || [])); }); return { Referrals: referrals, Total: total, }; }; export default fetchAllReferralsByOffset;
6,857
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/hooks/useAvailableDomains.ts
import { useEffect, useState } from 'react'; import { useLoading } from '@proton/hooks'; import { queryAvailableDomains } from '@proton/shared/lib/api/domains'; import { Api } from '@proton/shared/lib/interfaces'; import { useApi } from '../../../hooks'; const fetchDomains = async (api: Api) => { const result = await api<{ Domains: string[] }>(queryAvailableDomains()); return result.Domains; }; const useAvailableDomains = (): [domains: string[], isLoading: boolean] => { const [isLoading, withLoading] = useLoading(); const [domains, setDomains] = useState<string[]>([]); const api = useApi(); useEffect(() => { void withLoading(fetchDomains(api)) .then((fetchedDomains) => { setDomains(Array.isArray(fetchedDomains) ? fetchedDomains : []); }) .catch(() => { setDomains([]); }); }, [api]); return [domains, isLoading]; }; export default useAvailableDomains;
6,858
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/hooks/useReferralRewardStatus.ts
import { Reducer, useEffect, useReducer } from 'react'; import { getReferralsStatus } from '@proton/shared/lib/api/core/referrals'; import { ReferralStatus } from '@proton/shared/lib/interfaces'; import { useApi } from '../../../hooks'; type Action = { type: 'success'; payload: ReferralStatus } | { type: 'error' }; export interface UseReferralStatusReducerState { rewards: ReferralStatus['RewardMonths']; rewardsLimit: ReferralStatus['RewardMonthsLimit']; emailsAvailable: ReferralStatus['EmailsAvailable']; loading: boolean; } const useReferralRewardStatus = () => { const api = useApi(); const [referralState, dispatch] = useReducer<Reducer<UseReferralStatusReducerState, Action>>( (prevState, action) => { if (action.type === 'error') { return { ...prevState, loading: false }; } const payload = action.payload; return { loading: false, rewards: payload.RewardMonths || 0, rewardsLimit: payload.RewardMonthsLimit || 0, emailsAvailable: payload.EmailsAvailable || 0, }; }, { loading: true, rewards: 0, rewardsLimit: 0, emailsAvailable: 0, } ); useEffect(() => { const fetchReferrals = async () => { try { const apiResults = await api<{ Code: number; Status: ReferralStatus }>(getReferralsStatus()); dispatch({ type: 'success', payload: apiResults.Status }); } catch (error: any) { dispatch({ type: 'error' }); } }; void fetchReferrals(); }, []); return referralState; }; export default useReferralRewardStatus;
6,859
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/hooks/useReferrals.ts
import { Reducer, useEffect, useReducer } from 'react'; import { Referral } from '@proton/shared/lib/interfaces'; import { useApi } from '../../../hooks'; import fetchAllReferralsByOffset from '../helpers/fetchAllReferralsByOffset'; interface ReferralApiResult { Referrals?: Referral[]; Total?: number; } type Action = { type: 'success'; payload: ReferralApiResult } | { type: 'error' }; export interface UseReferralsReducerState { referrals: Referral[]; loading: boolean; total: number; } const getDefaultState = () => ({ loading: true, referrals: [], total: 0, }); const useReferrals = () => { const api = useApi(); const [referralState, dispatch] = useReducer<Reducer<UseReferralsReducerState, Action>>((prevState, action) => { if (action.type === 'error') { return { ...prevState, loading: false }; } if (action.type === 'success') { const apiResult = action.payload; return { loading: false, referrals: apiResult.Referrals || [], total: apiResult.Total || 0, }; } return getDefaultState(); }, getDefaultState()); useEffect(() => { const fetchReferrals = async () => { try { const apiResults = await fetchAllReferralsByOffset(api); dispatch({ type: 'success', payload: apiResults }); } catch (error: any) { dispatch({ type: 'error' }); } }; void fetchReferrals(); }, []); return referralState; }; export default useReferrals;
6,860
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/InviteSection.scss
@import '~@proton/styles/scss/lib'; .invite-section { @include media('<=#{em(1200, 16)}') { flex-direction: column; & > * { inline-size: 100%; flex-basis: auto; } } &-share-link { @include media('<=#{em(800, 16)}') { flex-direction: column; & > * { inline-size: 100%; flex-basis: auto; } } } } .referral-program-invite-input { flex-basis: 7em; .field { block-size: auto; padding: 0; border: none; border-radius: 0; background: inherit; box-shadow: none; } }
6,861
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/InviteSection.tsx
import { SettingsSectionWide } from '@proton/components'; import clsx from '@proton/utils/clsx'; import InviteSendEmail from './InviteSendEmail'; import InviteShareLink from './InviteShareLink'; import InviteActions from './inviteActions/InviteActions'; import './InviteSection.scss'; const BorderedBox = ({ children, className }: { children: React.ReactNode; className?: string }) => ( <div className={clsx([className, 'border rounded p-5'])}>{children}</div> ); const InviteSection = () => { return ( <SettingsSectionWide> <div className="flex flex-justify-space-between gap-4 mb-8 invite-section"> <BorderedBox className="flex-item-fluid"> <InviteShareLink /> </BorderedBox> <BorderedBox className="flex-item-fluid"> <InviteSendEmail /> </BorderedBox> </div> <InviteActions /> </SettingsSectionWide> ); }; export default InviteSection;
6,862
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/InviteSendEmail.tsx
import { useEffect, useMemo, useRef, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { AddressesAutocomplete, Icon, useApi, useContactEmails, useNotifications } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { sendEmailInvitation } from '@proton/shared/lib/api/core/referrals'; import { Recipient, Referral } from '@proton/shared/lib/interfaces'; import { useReferralInvitesContext } from '../ReferralInvitesContext'; import InviteSendEmailRecipient from './InviteSendEmailRecipient'; import { deduplicateRecipients, filterContactEmails, isValidEmailAdressToRefer } from './helpers'; interface SendEmailInvitationResult { Code: number; Referrals: Referral[]; } const InviteSendEmail = () => { const api = useApi(); const { invitedReferralsState: [invitedReferrals, setInvitedReferrals], fetchedReferralStatus: { emailsAvailable }, } = useReferralInvitesContext(); const anchorRef = useRef<HTMLInputElement>(null); const [recipients, setRecipients] = useState<Recipient[]>([]); const [hasInvalidRecipients, setHasInvalidRecipients] = useState<boolean>(false); const [contactEmails, contactEmailIsLoading] = useContactEmails(); const { createNotification } = useNotifications(); const [apiLoading, withLoading] = useLoading(); const filteredContactEmails = useMemo(() => { if (!contactEmails || contactEmailIsLoading) { return []; } return filterContactEmails(contactEmails); }, [contactEmails, contactEmailIsLoading]); const handleSendEmails = () => { if (!recipients.length) { createNotification({ text: c('Warning').t`Please add at least one recipient.`, type: 'warning' }); return; } const emails = recipients .filter((recipient) => isValidEmailAdressToRefer(recipient.Address)) .map((recipient) => recipient.Address); const emailSendLimitNumber = emailsAvailable - invitedReferrals.length; if (emails.length > emailSendLimitNumber) { createNotification({ type: 'warning', text: c('Info').ngettext( msgid`You can't send more than ${emailSendLimitNumber} email invite for the next 24 hours`, `You can't send more than ${emailSendLimitNumber} email invites for the next 24 hours`, emailSendLimitNumber ), }); return; } const request = api<SendEmailInvitationResult>(sendEmailInvitation({ emails })); void withLoading(request).then((result) => { if (result?.Referrals && result?.Referrals.length) { createNotification({ text: c('Info').ngettext( msgid`Invite successfully sent`, `Invites successfully sent`, result.Referrals.length ), }); setInvitedReferrals(result.Referrals); } setRecipients([]); }); }; const onAutocompleteKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => { if (event.key === 'Backspace' && event.currentTarget.value.length === 0 && recipients.length > 0) { const lastRecipient = recipients[recipients.length - 1]; const nextRecipients = recipients.filter((recipient) => recipient.Address !== lastRecipient.Address); if (lastRecipient) { setRecipients(nextRecipients); } } }; const onAutocompleteAddRecipient = (addedRecipients: Recipient[]) => { const dedupRecipients = deduplicateRecipients(addedRecipients, recipients); setRecipients(dedupRecipients); }; useEffect(() => { if (recipients.some((recipient) => !isValidEmailAdressToRefer(recipient.Address))) { setHasInvalidRecipients(true); return; } setHasInvalidRecipients(false); }, [recipients]); return ( <div> <h2 className="h3 text-bold" id="id_desc_invite_email">{c('Label').t`Invite via email`}</h2> <div className="flex gap-2 flex-nowrap flex-align-items-end on-mobile-flex-column rounded"> <div className="flex-item-fluid-auto"> <div className="addresses-wrapper field h-auto flex gap-2 px-2" onClick={() => { anchorRef.current?.focus(); }} > {recipients.map((recipient) => ( <InviteSendEmailRecipient key={recipient.Address} recipient={recipient} isValid={isValidEmailAdressToRefer(recipient.Address)} onDeleteRecipient={(e) => { e.stopPropagation(); setRecipients(recipients.filter((rec) => rec.Address !== recipient.Address)); }} /> ))} <div className="flex-item-fluid flex referral-program-invite-input"> <AddressesAutocomplete id="recipientsAutocomplete" className="border-none p-1" ref={anchorRef} anchorRef={anchorRef} loading={contactEmailIsLoading} recipients={recipients} contactEmails={filteredContactEmails} hasEmailPasting hasAddOnBlur onAddRecipients={onAutocompleteAddRecipient} onKeyDown={onAutocompleteKeyDown} aria-labelledby="id_desc_invite_email" /> </div> </div> </div> <div className="flex-item-noshrink text-right"> <Button title={c('Button').t`Invite`} color="norm" onClick={handleSendEmails} loading={apiLoading || contactEmailIsLoading} disabled={hasInvalidRecipients} > <span className="flex flex-nowrap flex-align-items-center"> <Icon name="paper-plane-horizontal" className="mr-1 flex-item-noshrink" />{' '} {c('Button').t`Send`} </span> </Button> </div> </div> </div> ); }; export default InviteSendEmail;
6,863
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/InviteSendEmailRecipient.tsx
import { MouseEventHandler } from 'react'; import { c } from 'ttag'; import { Icon, Tooltip } from '@proton/components'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { Recipient } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { isProtonAddress } from './helpers'; interface Props { recipient: Recipient; onDeleteRecipient: MouseEventHandler; isValid: boolean; } const getErrorMessage = (emailAddress: string) => { if (isProtonAddress(emailAddress)) { return c('Info').t`You cannot refer ${MAIL_APP_NAME} users`; } return c('Info').t`${emailAddress} is invalid`; }; const InviteSendEmailRecipient = ({ recipient, onDeleteRecipient, isValid }: Props) => { const emailAddress = recipient.Address; return ( <div className={clsx([ 'flex flex-nowrap flex-row flex-align-items-stretch max-w-full rounded-sm bg-weak overflow-hidden', !isValid && 'color-danger', ])} key={recipient.Address} > <Tooltip title={!isValid ? getErrorMessage(emailAddress) : undefined}> <span className="flex flex-align-items-center px-2"> <span className="text-ellipsis">{recipient.Address}</span> </span> </Tooltip> <Tooltip title={c('Action').t`Remove`}> <button onClick={onDeleteRecipient} className="flex flex-item-noshrink px-1 interactive"> <Icon name="cross-small" className="m-auto" alt={c('Action').t`Remove`} /> </button> </Tooltip> </div> ); }; export default InviteSendEmailRecipient;
6,864
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/InviteShareLink.tsx
import { useCallback } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon, TwitterButton, useNotifications } from '@proton/components'; import { useUserSettings } from '@proton/components/hooks'; import { textToClipboard } from '@proton/shared/lib/helpers/browser'; import throttle from '@proton/utils/throttle'; const InviteShareLink = () => { const [userSettings, loadingUserSettings] = useUserSettings(); const { createNotification } = useNotifications(); const referrerLink = userSettings.Referral?.Link || ''; const onCopyButtonClick = useCallback( throttle( () => { textToClipboard(referrerLink); createNotification({ text: c('Info').t`Referral link copied to your clipboard`, }); }, 1500, { leading: true, trailing: false } ), [referrerLink] ); if (loadingUserSettings) { return null; } return ( <div> <h2 className="h3 text-bold">{c('Label').t`Your referral link`}</h2> <div className="invite-section-share-link flex flex-align-items-stretch gap-2"> <div className="flex-item-fluid flex flex-align-items-center p-2 user-select border rounded" title={referrerLink} > <span className="text-ellipsis">{referrerLink}</span> </div> <div className="flex gap-2 flex-nowrap flex-justify-end"> <Button color="norm" onClick={onCopyButtonClick} title={c('Info').t`Copy your referral link`}> <span className="flex flex-nowrap flex-align-items-center"> <Icon name="link" className="mr-1 flex-item-noshrink" /> {c('Button').t`Copy`} </span> </Button> <TwitterButton href={encodeURI( 'https://twitter.com/intent/tweet?text=' + c('Info') .t`I’ve been using @ProtonMail and thought you might like it. It’s a secure email service that protects your privacy. Sign up with my referral link to get 1 month of premium features for free: ${referrerLink}` )} target="_blank" > <span className="flex flex-nowrap flex-align-items-center"> <Icon name="brand-twitter" className="mr-1 flex-item-noshrink" /> {c('Button').t`Tweet`} </span> </TwitterButton> </div> </div> </div> ); }; export default InviteShareLink;
6,865
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/helpers.test.ts
import { isValidEmailAdressToRefer } from './helpers'; describe('Referral helpers', () => { const addresses: [string, boolean][] = [ ['guillaume@protonmail.com', false], ['guillaume@pm.me', false], ['guillaume@protonmail.ch', false], ['guillaume@yahoo.fr', true], ['àaaaa@yahoo.fr', false], ]; describe('isValidEmailAddress', () => { it.each(addresses)('%s should be %p', (address, expectedResult) => { expect(isValidEmailAdressToRefer(address)).toBe(expectedResult); }); }); });
6,866
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/helpers.ts
import { PROTONMAIL_DOMAINS, getEmailParts, validateEmailAddress } from '@proton/shared/lib/helpers/email'; import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; export const isProtonAddress = (address: string) => { const [, domain] = getEmailParts(address); return PROTONMAIL_DOMAINS.includes(domain); }; export const isValidEmailAdressToRefer = (address: string) => { const isValid = validateEmailAddress(address); return isValid && !isProtonAddress(address); }; export const filterContactEmails = (contactEmails: ContactEmail[]) => { return contactEmails.filter((contact) => { if (isValidEmailAdressToRefer(contact.Email)) { return true; } return false; }); }; export const deduplicateRecipients = (addedRecipients: Recipient[], recipients: Recipient[]) => { let addedAddresses: string[] = []; const deduplicatedAddedRecipients = addedRecipients.filter((addedRecipient, _, array) => { // If recipient has no addresses if (!addedRecipient.Address) { return false; } // And not added two times in the same paste. Ex: paste "test@test.fr,test@test.fr,test@test.fr" if ( array.filter((arrayRecipient) => arrayRecipient.Address === addedRecipient.Address).length > 1 && addedAddresses.includes(addedRecipient.Address) ) { return false; } // Is not inside the current recipient list if (recipients.some((recipient) => recipient.Address === addedRecipient.Address)) { return false; } addedAddresses.push(addedRecipient.Address); return true; }); return [...recipients, ...deduplicatedAddedRecipients]; };
6,867
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/inviteActions/InviteActions.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { FeatureCode, InlineLinkButton, useFeature } from '@proton/components'; import clsx from '@proton/utils/clsx'; import InviteHowItWorks from './InviteHowItWorks'; import ReferralSignatureToggle from './ReferralSignatureToggle'; const InviteActions = () => { const isOpen = useFeature<boolean>(FeatureCode.ReferralExplanationOpened); const [showHowItWorksSection, setShowHowItWorksSection] = useState<boolean | null>(false); const handleCloseSection = () => { setShowHowItWorksSection(false); if (isOpen.feature?.Value === true) { void isOpen.update(false); } }; useEffect(() => { const featureValue = isOpen.feature?.Value; if (isOpen.loading === false && featureValue !== undefined && featureValue !== null) { setShowHowItWorksSection(!!featureValue); } }, [isOpen.loading, isOpen.feature?.Value]); return ( <> <div className={clsx([ 'flex flex-justify-space-between flex-align-items-center', showHowItWorksSection && 'mb-8', ])} > <ReferralSignatureToggle /> {!showHowItWorksSection && ( <div className="ml-auto pl-4"> <InlineLinkButton onClick={() => { setShowHowItWorksSection(true); }} > {c('Title').t`How does it work?`} </InlineLinkButton> </div> )} </div> {showHowItWorksSection && <InviteHowItWorks handleClose={handleCloseSection} />} </> ); }; export default InviteActions;
6,868
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/inviteActions/InviteHowItWorks.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { Icon } from '@proton/components'; import { BRAND_NAME, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; interface Props { handleClose: () => void; } const InviteHowItWorks = ({ handleClose }: Props) => { const planName = PLAN_NAMES[PLANS.MAIL]; return ( <div className="relative rounded p-7 bg-primary"> <Button className="absolute top right" icon shape="ghost" onClick={handleClose} title={c('Action').t`Close`} > <Icon name="cross" alt={c('Action').t`Close`} /> </Button> <h2 className="text-bold">{c('Title').t`How to refer a friend and get credits`}</h2> <ol className="flex flex-nowrap gap-4 unstyled on-tablet-flex-column mb-8"> <li className="flex-item-fluid"> <h3 className="mb-2 text-bold">{c('Info').t`1. Invite friends to ${BRAND_NAME}`}</h3> {c('Info').t`Just send them your personal referral link.`} </li> <li className="flex-item-fluid"> <h3 className="mb-2 text-bold">{ // translator: full sentense would be "They try Mail Plus" c('Info').t`2. They try ${planName}` }</h3> {c('Info').t`They'll receive a free month of ${planName}.`} </li> <li className="flex-item-fluid"> <h3 className="mb-2 text-bold">{c('Info').t`3. You earn credits`}</h3> {c('Info').t`When they subscribe to a plan, you'll get credits to use on your subscription.`} </li> </ol> <p className="text-sm mb-0"> <Href href={getKnowledgeBaseUrl('/referral-program')}>{c('Link').t`Learn more`}</Href> </p> </div> ); }; export default InviteHowItWorks;
6,869
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/invite/inviteActions/ReferralSignatureToggle.tsx
import { Fragment, useCallback, useEffect, useState } from 'react'; import { c } from 'ttag'; import { Info, Toggle, useApi, useMailSettings, useUserSettings } from '@proton/components'; import { useLoading } from '@proton/hooks'; import useIsMounted from '@proton/hooks/useIsMounted'; import { updatePMSignatureReferralLink } from '@proton/shared/lib/api/mailSettings'; import { PM_SIGNATURE_REFERRAL } from '@proton/shared/lib/mail/mailSettings'; import { getProtonMailSignature } from '@proton/shared/lib/mail/signature'; const ReferralSignatureToggle = () => { const [showShareLinkFooter, setShowShareLinkFooter] = useState(0); const [mailSettings, loadingMailSettings] = useMailSettings(); const [userSettings, loadingUserSettings] = useUserSettings(); const api = useApi(); const [loading, loadingCallback] = useLoading(); const isMounted = useIsMounted(); const toggleReferralSignature = useCallback((nextValue: 0 | 1) => { void loadingCallback( api( updatePMSignatureReferralLink( nextValue ? PM_SIGNATURE_REFERRAL.ENABLED : PM_SIGNATURE_REFERRAL.DISABLED ) ) ).then(() => { if (isMounted()) { setShowShareLinkFooter(nextValue); } }); }, []); useEffect(() => { if (loadingMailSettings === false && mailSettings?.PMSignatureReferralLink !== undefined) { setShowShareLinkFooter(mailSettings?.PMSignatureReferralLink); } }, [loadingMailSettings]); if (loadingMailSettings || !mailSettings?.PMSignature || loadingUserSettings || !userSettings.Referral?.Link) { return null; } const signature = ( <Fragment key={'signature'}> <br /> <br /> <div dangerouslySetInnerHTML={{ __html: getProtonMailSignature({ isReferralProgramLinkEnabled: true, referralProgramUserLink: userSettings.Referral?.Link, }), }} /> <br /> </Fragment> ); return ( <div className="flex flex-align-items-center"> <Toggle id="toggleSharedFooterLink" title={c('Button').t`Add link to your email footer`} checked={showShareLinkFooter === 1} onChange={() => toggleReferralSignature(showShareLinkFooter === 0 ? 1 : 0)} loading={loading} disabled={loading} /> <label htmlFor="toggleSharedFooterLink" className="pl-4"> <span className="mr-2">{c('Button').t`Add link to your email footer`}</span> </label> <Info title={ /* * translators: Signature is the default mail siganture : Sent with protonmail secure email. * the word "protonmail" is the "link" we are talking about. */ c('Tooltip') .jt`Sets the following footer in the emails you send: ${signature} The link points to your referral link. The footer will appear below your signature. You can personalise your signature anytime in the settings.` } /> </div> ); }; export default ReferralSignatureToggle;
6,870
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/modals/ReferralModal.tsx
import { useEffect } from 'react'; import { format } from 'date-fns'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { FeatureCode, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, ReferralFeaturesList, useFeature, useSettingsLink, } from '@proton/components'; import { PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { dateLocale } from '@proton/shared/lib/i18n'; import emptyMailboxSvg from '@proton/styles/assets/img/illustrations/empty-mailbox.svg'; interface Props extends ModalProps<'div'> { endDate: Date; } const ReferralModal = ({ endDate, ...rest }: Props) => { const planName = PLAN_NAMES[PLANS.MAIL]; const settingsLink = useSettingsLink(); const { feature, update } = useFeature(FeatureCode.SeenReferralModal); useEffect(() => { if (!open) { return; } if (feature?.Value === false) { void update(true); } }, [open]); const handlePlan = (plan: PLANS, target: 'compare' | 'checkout') => { const params = new URLSearchParams(); params.set('plan', plan); params.set('type', 'referral'); params.set('target', target); settingsLink(`/dashboard?${params.toString()}`); }; const formattedEndDate = format(endDate, 'P', { locale: dateLocale }); return ( <ModalTwo {...rest}> <ModalTwoHeader title={ // translator: complete sentence would be : Your free trial ends soon, on 01/01/2022 c('Title').t`Your free trial ends soon, on ${formattedEndDate}` } /> <ModalTwoContent> <p>{ // translator: complete sentence would be "Upgrade today to avoid losing the following Mail Plus benefits" c('Info').t`Upgrade today to avoid losing the following ${planName} benefits.` }</p> <div className="flex flex-justify-center"> <img src={emptyMailboxSvg} alt="Mailbox image" /> </div> <ReferralFeaturesList /> </ModalTwoContent> <ModalTwoFooter> {/** TODO */} <Button onClick={() => { rest.onClose?.(); handlePlan(PLANS.MAIL, 'compare'); }} shape="outline" >{c('Info').t`Other options`}</Button> <Button color="norm" onClick={() => { rest.onClose?.(); handlePlan(PLANS.MAIL, 'checkout'); }} >{ // translator: full sentence could be "Continue with Plus" c('Info').t`Continue with ${planName}` }</Button> </ModalTwoFooter> </ModalTwo> ); }; export default ReferralModal;
6,871
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/modals/helper.ts
import { addDays, fromUnixTime, subDays } from 'date-fns'; import { isTrial } from '@proton/shared/lib/helpers/subscription'; import { Subscription } from '@proton/shared/lib/interfaces'; import { Feature } from '../../features'; export const getShouldOpenReferralModal = ({ subscription, feature, }: { subscription: Subscription | undefined; feature: Feature<boolean> | undefined; }) => { if (!subscription?.PeriodEnd || !isTrial(subscription)) { return { open: false, endDate: new Date() }; } const endDate = fromUnixTime(subscription.PeriodEnd); const startDate = fromUnixTime(subscription.CreateTime); const nowDate = new Date(); // Should be in trial since a week const isExperienced = addDays(startDate, 7) < nowDate; // 3 days before the end of the trial const willExpire = subDays(endDate, 3) < nowDate; const open = (isExperienced && feature?.Value === false) || willExpire; return { open, endDate }; };
6,872
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards/RewardSection.tsx
import { c } from 'ttag'; import { Card } from '@proton/atoms'; import { Loader, SettingsSectionWide } from '@proton/components'; import { PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { useReferralInvitesContext } from '../ReferralInvitesContext'; import RewardsProgress from './RewardsProgress'; import { getDeduplicatedReferrals } from './helpers'; import RewardsTable from './table/RewardsTable'; const RewardSection = () => { const { invitedReferralsState: [invitedReferrals], fetchedReferrals: { referrals, total, loading: loadingReferrals }, fetchedReferralStatus: { rewards, rewardsLimit, loading: loadingRewards }, } = useReferralInvitesContext(); const dedupReferrals = getDeduplicatedReferrals(referrals, invitedReferrals); const plusPlanName = PLAN_NAMES[PLANS.MAIL]; const showRewardSection = rewards > 0 || total > 0; const reachedRewardLimit = rewards === rewardsLimit && total > 0; if (loadingRewards || loadingReferrals) { return <Loader />; } return ( <SettingsSectionWide> {reachedRewardLimit ? ( <Card rounded className="text-center mb-8"> <strong>{c('Description') .t`Congratulations! You've earned the maximum of ${rewardsLimit} free months of ${plusPlanName}.`}</strong> <br /> {c('Description').t`You can continue to invite friends, but you wont be able to earn more credits`} </Card> ) : ( <p className="color-weak">{c('Description').t`Track the status and activity of your referrals.`}</p> )} {showRewardSection && ( <div className="border-bottom pb-4 mb-14"> <RewardsProgress rewardsLimit={rewardsLimit} rewards={rewards} /> </div> )} <RewardsTable referrals={dedupReferrals} hasReachedRewardLimit={reachedRewardLimit} loading={loadingReferrals} /> </SettingsSectionWide> ); }; export default RewardSection;
6,873
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards/RewardsProgress.tsx
import { c } from 'ttag'; import { Meter, usePlans, useUser } from '@proton/components'; import { CYCLE, PLANS } from '@proton/shared/lib/constants'; import { humanPriceWithCurrency } from '@proton/shared/lib/helpers/humanPrice'; interface Props { rewards: number; rewardsLimit: number; } const RewardsProgress = ({ rewards, rewardsLimit }: Props) => { const [user] = useUser(); const [plans = []] = usePlans(); const mailPlusPlan = plans.find(({ Name }) => Name === PLANS.MAIL); const price = Math.round((mailPlusPlan?.Pricing[CYCLE.MONTHLY] || 0) / 100) * 100; // Price rounded to 500 const current = humanPriceWithCurrency(rewards * price, user.Currency); const total = humanPriceWithCurrency(rewardsLimit * price, user.Currency); return ( <div className="flex flex-justify-space-between flex-align-items-center gap-4 on-tablet-flex-column"> <div className="flex-item-fluid"> <b>{c('Info').t`Credits earned`}</b> </div> <div className="flex-item-fluid">{rewards > 0 && <Meter value={rewards} max={rewardsLimit} />}</div> <div className="flex-item-fluid text-right">{ // translator: Full sentence can be something like this : "$30 of $90" c('Info').t`${current} of ${total}` }</div> </div> ); }; export default RewardsProgress;
6,874
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards/helpers.ts
import { Referral } from '@proton/shared/lib/interfaces'; import uniqueBy from '@proton/utils/uniqueBy'; /** * Deduplicate referrals from API and optimistic referrals results * by taking API result first in consideration * @param referrals The referrals loaded from API call * @param invitedReferrals The referrals invited * @returns array of deduplicated referrals */ export const getDeduplicatedReferrals = (apiReferrals: Referral[], optimisticReferrals: Referral[]) => { return uniqueBy<Referral>([...optimisticReferrals, ...apiReferrals], ({ ReferralID }) => ReferralID); };
6,875
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards/table/ActivityCell.tsx
import { c, msgid } from 'ttag'; import { Referral, ReferralState } from '@proton/shared/lib/interfaces'; interface Props { referral: Referral; } const ActivityCell = ({ referral }: Props) => { let message: React.ReactNode = null; switch (referral.State) { case ReferralState.INVITED: message = referral.Email ? // translator : We're in a table cell displaying an activity status. // Value can be `Invited via email` or `Signed up via your link` or `Signed up` // Here the user referee has been invited via mail c('User referee invited via email').t`Invited via email` : // translator : We're in a table cell displaying an activity status. // Value can be `Invited via email` or `Signed up via your link` or `Signed up` // Here the user referee signed up using his referral link c('User referee signed up using referral link').t`Signed up via your link`; break; case ReferralState.SIGNED_UP: case ReferralState.TRIAL: // translator : We are in a table cell. A user referee has signed up message = c('Info').t`Signed up`; break; case ReferralState.COMPLETED: case ReferralState.REWARDED: const rewardMonths = referral.ReferredUserSubscriptionCycle || 0; if (rewardMonths === 1) { message = c('Info').t`Paid for a monthly plan`; } // translator : We are in a table cell. We inform user that a referred user has paid for a plan message = c('Info').ngettext( msgid`Paid for a ${rewardMonths} month plan`, `Paid for a ${rewardMonths} months plan`, rewardMonths ); break; } return <>{message}</>; }; export default ActivityCell;
6,876
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards/table/DateCell.tsx
import { format, fromUnixTime } from 'date-fns'; import { dateLocale } from '@proton/shared/lib/i18n'; import { Referral, ReferralState } from '@proton/shared/lib/interfaces'; interface Props { referral: Referral; } const DateCell = ({ referral }: Props) => { let nextDate = null; switch (referral.State) { case ReferralState.INVITED: nextDate = referral.CreateTime; break; case ReferralState.SIGNED_UP: nextDate = referral.SignupTime; break; case ReferralState.TRIAL: nextDate = referral.TrialTime; break; case ReferralState.COMPLETED: nextDate = referral.CompleteTime; break; case ReferralState.REWARDED: nextDate = referral.RewardTime; break; } return <>{nextDate ? format(fromUnixTime(referral.CreateTime), 'P', { locale: dateLocale }) : null}</>; }; export default DateCell;
6,877
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards/table/RewardCell.tsx
import { c } from 'ttag'; import { ThemeColorUnion } from '@proton/colors'; import { Referral, ReferralState } from '@proton/shared/lib/interfaces'; interface Props { referral: Referral; hasReachedRewardLimit: boolean; } const RewardCell = ({ referral, hasReachedRewardLimit }: Props) => { let reward: string | React.ReactNode = '-'; let textColor: ThemeColorUnion | undefined; switch (referral.State) { case ReferralState.SIGNED_UP: case ReferralState.TRIAL: if (!hasReachedRewardLimit) { reward = c('Label').t`Pending`; textColor = 'warning'; } break; case ReferralState.COMPLETED: if (!hasReachedRewardLimit) { /* * translator : We are in a table cell. * A user referee have signed up or completed a subscription. * "Credits pending" means a variable number of reward. Can be 0, 1 or 3. * And at this stage we have no variables allowing us to know the amount. */ reward = c('Label').t`Pending`; textColor = 'warning'; } break; case ReferralState.REWARDED: /* * translator : We are in a table cell. * A user referee have signed up or completed a subscription * We show the reward user has been credited. * Example : "3 months credited" */ reward = c('Label').t`Awarded`; textColor = 'success'; break; } return <div className={textColor ? `color-${textColor}` : undefined}>{reward}</div>; }; export default RewardCell;
6,878
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards/table/RewardsTable.tsx
import { c } from 'ttag'; import { Table, TableBody, TableHeader, TableRow } from '@proton/components'; import { Referral, ReferralState } from '@proton/shared/lib/interfaces'; import { Loader } from '../../../../components'; import ActivityCell from './ActivityCell'; import DateCell from './DateCell'; import RewardCell from './RewardCell'; import UserCell from './UserCell'; interface Props { loading?: boolean; referrals: Referral[]; hasReachedRewardLimit: boolean; } const RewardsTable = ({ loading, referrals, hasReachedRewardLimit }: Props) => { if (loading) { return <Loader />; } return ( <> <Table responsive="cards"> <TableHeader cells={[c('Label').t`User`, c('Label').t`Date`, c('Label').t`Activity`, c('Label').t`Credits`]} /> {referrals.length > 0 && ( <TableBody loading={loading}> {referrals.map((referral) => ( <TableRow key={referral.ReferralID} className={[ReferralState.REWARDED].includes(referral.State) ? 'text-bold' : ''} labels={[ c('Label').t`User`, c('Label').t`Date`, c('Label').t`Activity`, c('Label').t`Credits`, ]} cells={[ <UserCell key={`${referral.ReferralID}-date`} referral={referral} />, <DateCell key={`${referral.ReferralID}-date`} referral={referral} />, <ActivityCell key={`${referral.ReferralID}-activity`} referral={referral} />, <RewardCell key={`${referral.ReferralID}-reward`} referral={referral} hasReachedRewardLimit={hasReachedRewardLimit} />, ]} /> ))} </TableBody> )} </Table> </> ); }; export default RewardsTable;
6,879
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards
petrpan-code/ProtonMail/WebClients/packages/components/containers/referral/rewards/table/UserCell.tsx
import { c } from 'ttag'; import { Icon } from '@proton/components'; import { Referral } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; interface Props { referral: Referral; } const UserCell = ({ referral }: Props) => ( <div className="flex flex-nowrap flex-align-items-center"> <span className="hidden md:flex flex-item-noshrink mr-4"> <Icon name={referral.Email ? 'envelope' : 'link'} /> </span> <span className={clsx([referral.Email && 'text-ellipsis'])} title={referral.Email || undefined}> {referral.Email ? referral.Email : c('Info').t`Public link invite`} </span> </div> ); export default UserCell;
6,880
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/resetPassword/interface.ts
import { AuthResponse } from '@proton/shared/lib/authentication/interface'; import { APP_NAMES } from '@proton/shared/lib/constants'; import { Address, Api, DecryptedKey, KeyTransparencyActivation, ResetSelfAudit } from '@proton/shared/lib/interfaces'; import { AuthSession } from '../login/interface'; export enum STEPS { LOADING, REQUEST_RECOVERY_METHODS = 1, NO_RECOVERY_METHODS, REQUEST_RESET_TOKEN, VALIDATE_RESET_TOKEN, NEW_PASSWORD, ERROR, DONE, } // Login is valid for external accounts export type RecoveryMethod = 'email' | 'sms' | 'login' | 'mnemonic'; export type AccountType = 'internal' | 'external'; export interface ValidateResetTokenResponse { Addresses: Address[]; ToMigrate: 0 | 1; } interface MnemonicData { api: Api; decryptedUserKeys: DecryptedKey[]; authResponse: AuthResponse; } export interface ResetCacheResult { appName: APP_NAMES; username: string; persistent: boolean; Methods: RecoveryMethod[]; type: AccountType; method?: RecoveryMethod; value?: string; token?: string; resetResponse?: ValidateResetTokenResponse; mnemonicData?: MnemonicData; hasTrustedDeviceRecovery: boolean; ktActivation: KeyTransparencyActivation; setupVPN: boolean; resetSelfAudit: ResetSelfAudit; } export type ResetActionResponse = | { to: STEPS.DONE; session: AuthSession; } | { to: STEPS.NO_RECOVERY_METHODS; error?: string; } | { cache: ResetCacheResult; to: Exclude<STEPS, STEPS.DONE | STEPS.NO_RECOVERY_METHODS>; };
6,881
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/resetPassword/resetActions.ts
import { CryptoProxy } from '@proton/crypto'; import { getAllAddresses } from '@proton/shared/lib/api/addresses'; import { auth, authMnemonic, getMnemonicAuthInfo } from '@proton/shared/lib/api/auth'; import { queryAvailableDomains } from '@proton/shared/lib/api/domains'; import { resetKeysRoute } from '@proton/shared/lib/api/keys'; import { requestLoginResetToken } from '@proton/shared/lib/api/reset'; import { getSettings } from '@proton/shared/lib/api/settings'; import { GetMnemonicResetData, getMnemonicReset, mnemonicReset } from '@proton/shared/lib/api/settingsMnemonic'; import { getRecoveryMethods, getUser } from '@proton/shared/lib/api/user'; import { AuthResponse, InfoResponse } from '@proton/shared/lib/authentication/interface'; import { persistSession } from '@proton/shared/lib/authentication/persistedSessionHelper'; import { APP_NAMES } from '@proton/shared/lib/constants'; import { API_CUSTOM_ERROR_CODES } from '@proton/shared/lib/errors'; import { Api, KeyTransparencyActivation, ResetSelfAudit, UserSettings, User as tsUser, } from '@proton/shared/lib/interfaces'; import { generateKeySaltAndPassphrase, getDecryptedUserKeysHelper, getRequiresPasswordSetup, getResetAddressesKeysV2, handleSetupAddressKeys, } from '@proton/shared/lib/keys'; import { mnemonicToBase64RandomBytes } from '@proton/shared/lib/mnemonic'; import { attemptDeviceRecovery, getIsDeviceRecoveryAvailable, removeDeviceRecovery, storeDeviceRecovery, } from '@proton/shared/lib/recoveryFile/deviceRecovery'; import { srpAuth, srpVerify } from '@proton/shared/lib/srp'; import { computeKeyPassword, generateKeySalt } from '@proton/srp'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import { createPreAuthKTVerifier } from '../keyTransparency'; import { AccountType, RecoveryMethod, ResetActionResponse, ResetCacheResult, STEPS, ValidateResetTokenResponse, } from './interface'; export const handleNewPassword = async ({ password, cache, api, }: { password: string; cache: ResetCacheResult; api: Api; }): Promise<ResetActionResponse> => { const { username, token, resetResponse, persistent, appName, ktActivation, hasTrustedDeviceRecovery, resetSelfAudit, } = cache; if (!resetResponse || !token) { throw new Error('Missing response'); } const { Addresses: addresses } = resetResponse; const { preAuthKTVerify, preAuthKTCommit } = createPreAuthKTVerifier(ktActivation, api); const { passphrase, salt } = await generateKeySaltAndPassphrase(password); const { addressKeysPayload, userKeyPayload, onSKLPublishSuccess } = await getResetAddressesKeysV2({ addresses, passphrase, preAuthKTVerify, }); await srpVerify({ api, credentials: { password }, config: resetKeysRoute({ Username: username, Token: token, KeySalt: salt, PrimaryKey: userKeyPayload, AddressKeys: addressKeysPayload, }), }); if (onSKLPublishSuccess) { await onSKLPublishSuccess(); } const authResponse = await srpAuth({ api, credentials: { username, password }, config: auth({ Username: username }, persistent), }).then((response): Promise<AuthResponse> => response.json()); let user = await api<{ User: tsUser }>(getUser()).then(({ User }) => User); let keyPassword = passphrase; if (user.Keys.length === 0) { if (getRequiresPasswordSetup(user, cache.setupVPN)) { const [domains, addresses] = await Promise.all([ api<{ Domains: string[] }>(queryAvailableDomains('signup')).then(({ Domains }) => Domains), await getAllAddresses(api), ]); keyPassword = await handleSetupAddressKeys({ api, username, password, addresses, domains, preAuthKTVerify, }); // Refetch the user to update the keys that got generated user = await api<{ User: tsUser }>(getUser()).then(({ User }) => User); } } let trusted = false; if (hasTrustedDeviceRecovery && keyPassword) { const addresses = await getAllAddresses(api); const numberOfReactivatedKeys = await attemptDeviceRecovery({ api, user, addresses, keyPassword, preAuthKTVerify, }).catch(noop); if (numberOfReactivatedKeys !== undefined && numberOfReactivatedKeys > 0) { // Refetch user with new reactivated keys user = await api<{ User: tsUser }>(getUser()).then(({ User }) => User); } // Store device recovery information if (persistent) { const userKeys = await getDecryptedUserKeysHelper(user, keyPassword); const isDeviceRecoveryAvailable = getIsDeviceRecoveryAvailable({ user, addresses, userKeys, appName, }); if (isDeviceRecoveryAvailable) { const userSettings = await api<{ UserSettings: UserSettings }>(getSettings()).then( ({ UserSettings }) => UserSettings ); if (userSettings.DeviceRecovery) { await storeDeviceRecovery({ api, user, userKeys }); trusted = true; } } } else { removeDeviceRecovery(user.ID); } } await persistSession({ ...authResponse, persistent, trusted, User: user, keyPassword, api }); await preAuthKTCommit(user.ID); await resetSelfAudit(user, keyPassword, addresses); return { to: STEPS.DONE, session: { ...authResponse, persistent, trusted, User: user, loginPassword: password, keyPassword, flow: 'reset', }, }; }; export const handleNewPasswordMnemonic = async ({ password, cache, }: { password: string; cache: ResetCacheResult; }): Promise<ResetActionResponse> => { if (!cache.mnemonicData) { throw new Error('Missing data'); } const { persistent } = cache; const { api, decryptedUserKeys, authResponse } = cache.mnemonicData; const keySalt = generateKeySalt(); const keyPassword = await computeKeyPassword(password, keySalt); const reEncryptedUserKeys = await Promise.all( decryptedUserKeys.map(async ({ ID, privateKey }) => { const privateKeyArmored = await CryptoProxy.exportPrivateKey({ privateKey: privateKey, passphrase: keyPassword, }); return { ID, PrivateKey: privateKeyArmored, }; }) ); await srpVerify({ api, credentials: { password }, config: mnemonicReset({ KeysSalt: keySalt, UserKeys: reEncryptedUserKeys, }), }); const trusted = false; const user = await api<{ User: tsUser }>(getUser()).then(({ User }) => User); await persistSession({ ...authResponse, persistent, trusted, User: user, keyPassword, api }); return { to: STEPS.DONE, session: { ...authResponse, persistent, trusted, User: user, loginPassword: password, keyPassword, flow: 'reset', }, }; }; const handleMnemonic = async ({ username, cache, api, mnemonic, }: { username: string; cache: ResetCacheResult; api: Api; mnemonic: string; }): Promise<ResetActionResponse> => { const randomBytes = await mnemonicToBase64RandomBytes(mnemonic); const info = await api<InfoResponse>(getMnemonicAuthInfo(username)); const authResponse = await srpAuth({ info, api, config: authMnemonic(username, cache.persistent), credentials: { username, password: randomBytes, }, }).then((response): Promise<AuthResponse> => response.json()); const { MnemonicUserKeys } = await api<GetMnemonicResetData>(getMnemonicReset()); const decryptedUserKeys = ( await Promise.all( MnemonicUserKeys.map(async ({ ID, PrivateKey, Salt }) => { const keyPassword = await computeKeyPassword(randomBytes, Salt); const privateKey = await CryptoProxy.importPrivateKey({ armoredKey: PrivateKey, passphrase: keyPassword, }).catch(noop); if (!privateKey) { return; } const publicKey = await CryptoProxy.importPublicKey({ binaryKey: await CryptoProxy.exportPublicKey({ key: privateKey, format: 'binary' }), }); return { ID, privateKey, publicKey, }; }) ) ).filter(isTruthy); if (!decryptedUserKeys.length) { return { cache, to: STEPS.ERROR, }; } return { cache: { ...cache, username, method: 'mnemonic', value: mnemonic, mnemonicData: { decryptedUserKeys, api, authResponse, }, }, to: STEPS.NEW_PASSWORD, }; }; export const handleRequestToken = async ({ cache, method, value, username, api, }: { cache: ResetCacheResult; method: RecoveryMethod; value: string; username: string; api: Api; }): Promise<ResetActionResponse> => { if (method === 'mnemonic') { return handleMnemonic({ cache, username, mnemonic: value, api, }); } if (method === 'sms') { await api(requestLoginResetToken({ Username: username, Phone: value })); } if (method === 'email') { await api(requestLoginResetToken({ Username: username, Email: value })); } return { cache: { ...cache, username, method, value, }, to: STEPS.VALIDATE_RESET_TOKEN, }; }; export const handleValidateResetToken = async ({ resetResponse, cache, token, }: { resetResponse: ValidateResetTokenResponse; cache: ResetCacheResult; token: string; }): Promise<ResetActionResponse> => { return { to: STEPS.NEW_PASSWORD, cache: { ...cache, token, resetResponse, }, }; }; export const handleRequestRecoveryMethods = async ({ setupVPN, appName, username, persistent, api, hasTrustedDeviceRecovery, ktActivation, resetSelfAudit, }: { setupVPN: boolean; appName: APP_NAMES; username: string; persistent: boolean; api: Api; hasTrustedDeviceRecovery: boolean; ktActivation: KeyTransparencyActivation; resetSelfAudit: ResetSelfAudit; }): Promise<ResetActionResponse> => { try { const { Type, Methods }: { Type: AccountType; Methods: RecoveryMethod[] } = await api( getRecoveryMethods(username) ); if (Type === 'external' && Methods.length === 1 && Methods.includes('login')) { await api(requestLoginResetToken({ Username: username, Email: username })); return { cache: { setupVPN, appName, username, persistent, value: username, method: 'email', Methods, type: Type, hasTrustedDeviceRecovery, ktActivation, resetSelfAudit, }, to: STEPS.VALIDATE_RESET_TOKEN, }; } if (!Methods.length) { return { error: '', to: STEPS.NO_RECOVERY_METHODS, }; } return { cache: { setupVPN, appName, username, persistent, Methods, type: Type, hasTrustedDeviceRecovery, ktActivation, resetSelfAudit, }, to: STEPS.REQUEST_RESET_TOKEN, }; } catch (error: any) { const { data: { Code, Error } = { Code: 0, Error: '' } } = error; if ([API_CUSTOM_ERROR_CODES.NO_RESET_METHODS].includes(Code)) { return { error: Error, to: STEPS.NO_RECOVERY_METHODS, }; } throw error; } };
6,882
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/rightToLeft/Provider.tsx
import React, { useEffect, useState } from 'react'; import RightToLeftContext from './context'; const getIsRTL = (lang: string) => { return /^fa/.test(lang); }; interface Props { children: React.ReactNode; } const Provider = ({ children }: Props) => { const state = useState(getIsRTL(document.documentElement.lang)); const [isRTL, setRTL] = state; useEffect(() => { const observer = new MutationObserver((e) => { if (e.some(({ attributeName }) => attributeName === 'lang')) { setRTL(getIsRTL(document.documentElement.lang)); } }); observer.observe(document.documentElement, { attributes: true }); return () => { observer.disconnect(); }; }, []); useEffect(() => { document.documentElement.dir = isRTL ? 'rtl' : 'ltr'; }, [isRTL]); return <RightToLeftContext.Provider value={state}>{children}</RightToLeftContext.Provider>; }; export default Provider;
6,883
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/rightToLeft/context.ts
import { Dispatch, SetStateAction, createContext } from 'react'; export default createContext<[boolean, Dispatch<SetStateAction<boolean>>]>([] as any);
6,884
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/rightToLeft/index.ts
export { default as useRightToLeft } from './useRightToLeft'; export { default as RightToLeftProvider } from './Provider';
6,885
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/rightToLeft/useRightToLeft.tsx
import { useContext } from 'react'; import Context from './context'; const useRightToLeft = () => useContext(Context); export default useRightToLeft;
6,886
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/security/AddressVerificationSection.tsx
import { c } from 'ttag'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { BetaBadge, Info } from '../../components'; import { useFeature } from '../../hooks'; import { SettingsSection } from '../account'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; import { FeatureCode } from '../features'; import { KtFeatureEnum } from '../keyTransparency/ktStatus'; import KTToggle from './KTToggle'; import PromptPinToggle from './PromptPinToggle'; const AddressVerificationSection = () => { const { feature } = useFeature(FeatureCode.KeyTransparencyAccount); const showKTSetting = feature?.Value === KtFeatureEnum.ENABLE_UI; return ( <SettingsSection> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="prompt-pin-toggle" className="text-semibold"> <span className="mr-2">{c('Label').t`Prompt to trust keys`}</span> <Info url={getKnowledgeBaseUrl('/address-verification')} title={c('Tooltip prompt to trust keys') .t`When receiving an email from another ${MAIL_APP_NAME} user who does not have trusted keys in your contacts, a banner will ask if you want to enable trusted keys.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <PromptPinToggle id="prompt-pin-toggle" /> </SettingsLayoutRight> </SettingsLayout> {showKTSetting ? ( <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="kt-toggle" className="text-semibold"> <span className="mr-2">{c('Label').t`Verify keys with Key Transparency`}</span> <BetaBadge className="mr-2" /> <Info url={getKnowledgeBaseUrl('/key-transparency')} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <KTToggle id="kt-toggle" /> </SettingsLayoutRight> </SettingsLayout> ) : null} </SettingsSection> ); }; export default AddressVerificationSection;
6,887
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/security/ExternalPGPSettingsSection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { updateAttachPublicKey, updatePGPScheme, updateSign } from '@proton/shared/lib/api/mailSettings'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { ATTACH_PUBLIC_KEY, DEFAULT_MAILSETTINGS, SIGN } from '@proton/shared/lib/mail/mailSettings'; import { Info, Prompt, PromptProps, Toggle, useModalState } from '../../components'; import { useApi, useEventManager, useMailSettings, useNotifications } from '../../hooks'; import { SettingsParagraph, SettingsSection } from '../account'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; import PGPSchemeSelect from './PGPSchemeSelect'; interface AutomaticallySignModalProps extends Omit<PromptProps, 'title' | 'buttons' | 'children'> { onConfirm: (value: boolean) => void; } const AutomaticallySignModal = ({ onConfirm, ...rest }: AutomaticallySignModalProps) => { return ( <Prompt title={c('Title').t`Automatically sign outgoing messages?`} buttons={[ <Button color="norm" onClick={() => { onConfirm(true); rest.onClose?.(); }} data-testid="automatically-sign-modal:confirm" >{c('Action').t`Yes`}</Button>, <Button onClick={() => { onConfirm(false); rest.onClose?.(); }} >{c('Action').t`No`}</Button>, ]} {...rest} > {c('Info') .t`PGP clients are more likely to automatically detect your PGP keys if outgoing messages are signed.`} </Prompt> ); }; const ExternalPGPSettingsSection = () => { const [{ Sign, AttachPublicKey, PGPScheme } = DEFAULT_MAILSETTINGS] = useMailSettings(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const api = useApi(); const [loadingSign, withLoadingSign] = useLoading(); const [loadingAttach, withLoadingAttach] = useLoading(); const [loadingScheme, withLoadingScheme] = useLoading(); const [automaticallySignModalProps, setAutomaticallySignModalOpen, renderAutomaticallySign] = useModalState(); const handleChangeSign = async (value: number) => { await api(updateSign(value)); await call(); createNotification({ text: c('Info').t`Encryption setting updated` }); }; const handleAttachPublicKey = async (value: number) => { await api(updateAttachPublicKey(value)); await call(); createNotification({ text: c('Info').t`Encryption setting updated` }); }; const handleChangeScheme = async (value: number) => { await api(updatePGPScheme(value)); await call(); createNotification({ text: c('Info').t`Encryption setting updated` }); }; const handleAutomaticallySign = async (shouldSign: boolean) => { await Promise.all([ shouldSign ? api(updateSign(SIGN.ENABLED)) : undefined, api(updateAttachPublicKey(ATTACH_PUBLIC_KEY.ENABLED)), ]); await call(); createNotification({ text: c('Info').t`Encryption setting updated` }); }; return ( <SettingsSection> {renderAutomaticallySign && ( <AutomaticallySignModal onConfirm={(shouldSign) => { const promise = handleAutomaticallySign(shouldSign); if (shouldSign) { withLoadingSign(promise); } withLoadingAttach(promise); }} {...automaticallySignModalProps} /> )} <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/how-to-use-pgp')}> {c('Info').t`Only change these settings if you are using PGP with non-${BRAND_NAME} recipients.`} </SettingsParagraph> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="signToggle" className="text-semibold"> <span className="mr-2">{c('Label').t`Sign external messages`}</span> <Info url={getKnowledgeBaseUrl('/what-is-a-digital-signature')} title={c('Tooltip sign external messages') .t`Automatically sign all your outgoing messages so users can verify the authenticity of your messages. This is done in combination with the default PGP settings which can be configured below.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <Toggle id="signToggle" checked={!!Sign} onChange={(e) => { withLoadingSign(handleChangeSign(+e.target.checked)); }} loading={loadingSign} /> </SettingsLayoutRight> </SettingsLayout> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="attachPublicKeyToggle" className="text-semibold"> <span className="mr-2">{c('Label').t`Attach public key`}</span> <Info url={getKnowledgeBaseUrl('/how-to-use-pgp')} title={c('Tooltip automatically attach public key') .t`This automatically adds your public key to each message you send. Recipients can use this to verify the authenticity of your messages and send encrypted messages to you.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <Toggle id="attachPublicKeyToggle" checked={!!AttachPublicKey} onChange={(e) => { const newValue = +e.target.checked; if (newValue && !Sign) { setAutomaticallySignModalOpen(true); } else { withLoadingAttach(handleAttachPublicKey(newValue)); } }} loading={loadingAttach} /> </SettingsLayoutRight> </SettingsLayout> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="PGPSchemeSelect" className="text-semibold"> <span className="mr-2">{c('Label').t`Default PGP scheme`}</span> <Info url={getKnowledgeBaseUrl('/pgp-mime-pgp-inline')} title={c('Tooltip default pgp scheme') .t`Select the default PGP settings used to sign or encrypt messages with non-${BRAND_NAME} PGP users. Note that Inline PGP forces plain text messages.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight> <PGPSchemeSelect id="PGPSchemeSelect" pgpScheme={PGPScheme} onChange={(e) => { withLoadingScheme(handleChangeScheme(+e.target.value)); }} disabled={loadingScheme} /> </SettingsLayoutRight> </SettingsLayout> </SettingsSection> ); }; export default ExternalPGPSettingsSection;
6,888
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/security/KTToggle.spec.tsx
import { fireEvent, render } from '@testing-library/react'; import { updateKT } from '@proton/shared/lib/api/mailSettings'; import { KEY_TRANSPARENCY_SETTING } from '@proton/shared/lib/mail/mailSettings'; import { applyHOCs, mockUseApi, mockUseEventManager, mockUseMailSettings, mockUseNotifications, withApi, withEventManager, withNotifications, } from '@proton/testing'; import KTToggle from './KTToggle'; const KTToggleContext = applyHOCs(withApi(), withEventManager(), withNotifications())(KTToggle); describe('KTToggle', () => { let mockedApi: jest.Mock; let mockedCall: jest.Mock; beforeEach(() => { mockedApi = jest.fn(); mockedCall = jest.fn(); mockUseApi(mockedApi); mockUseEventManager({ call: mockedCall }); mockUseMailSettings(); mockUseNotifications(); }); const setup = () => { const utils = render(<KTToggleContext />); return { ...utils, }; }; describe('when we toggle the component', () => { it('should call the API', () => { const { getByRole } = setup(); const toggle = getByRole('checkbox'); fireEvent.click(toggle); expect(mockedApi).toHaveBeenCalledWith(updateKT(KEY_TRANSPARENCY_SETTING.ENABLED)); }); }); });
6,889
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/security/KTToggle.tsx
import { ChangeEvent } from 'react'; import { c } from 'ttag'; import useLoading from '@proton/hooks/useLoading'; import { updateKT } from '@proton/shared/lib/api/mailSettings'; import { DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/mailSettings'; import { Toggle } from '../../components'; import { useApi, useEventManager, useMailSettings, useNotifications } from '../../hooks'; interface Props { id?: string; } const KTToggle = ({ id }: Props) => { const { createNotification } = useNotifications(); const { call } = useEventManager(); const api = useApi(); const [loading, withLoading] = useLoading(); const [{ KT } = DEFAULT_MAILSETTINGS] = useMailSettings(); const handleChange = async ({ target }: ChangeEvent<HTMLInputElement>) => { await api(updateKT(+target.checked)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; return <Toggle id={id} loading={loading} checked={!!KT} onChange={(e) => withLoading(handleChange(e))} />; }; export default KTToggle;
6,890
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/security/PGPSchemeSelect.tsx
import { ChangeEvent } from 'react'; import { PACKAGE_TYPE } from '@proton/shared/lib/mail/mailSettings'; import { Select } from '../../components'; interface Props { pgpScheme: number; id: string; onChange: (event: ChangeEvent<HTMLSelectElement>) => void; disabled: boolean; } const PGPSchemeSelect = ({ id, pgpScheme, onChange, disabled, ...rest }: Props) => { const options = [ { value: PACKAGE_TYPE.SEND_PGP_MIME, text: 'PGP/MIME' }, { value: PACKAGE_TYPE.SEND_PGP_INLINE, text: 'PGP/Inline' }, ]; return <Select id={id} value={pgpScheme} options={options} disabled={disabled} onChange={onChange} {...rest} />; }; export default PGPSchemeSelect;
6,891
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/security/PromptPinToggle.spec.tsx
import { fireEvent, render } from '@testing-library/react'; import { updatePromptPin } from '@proton/shared/lib/api/mailSettings'; import { applyHOCs, mockUseApi, mockUseEventManager, mockUseMailSettings, mockUseNotifications, withApi, withEventManager, withNotifications, } from '@proton/testing'; import PromptPinToggle from './PromptPinToggle'; const PromptPinToggleContext = applyHOCs(withApi(), withEventManager(), withNotifications())(PromptPinToggle); describe('PromptPinToggle', () => { let mockedApi: jest.Mock; let mockedCall: jest.Mock; beforeEach(() => { mockedApi = jest.fn(); mockedCall = jest.fn(); mockUseApi(mockedApi); mockUseEventManager({ call: mockedCall }); mockUseMailSettings(); mockUseNotifications(); }); const setup = () => { const utils = render(<PromptPinToggleContext />); return { ...utils, }; }; describe('when we toggle the component', () => { it('should call the API', () => { const { getByRole } = setup(); const toggle = getByRole('checkbox'); fireEvent.click(toggle); expect(mockedApi).toHaveBeenCalledWith(updatePromptPin(1)); }); }); });
6,892
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/security/PromptPinToggle.tsx
import { ChangeEvent } from 'react'; import { c } from 'ttag'; import useLoading from '@proton/hooks/useLoading'; import { updatePromptPin } from '@proton/shared/lib/api/mailSettings'; import { DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/mailSettings'; import { Toggle } from '../../components'; import { useApi, useEventManager, useMailSettings, useNotifications } from '../../hooks'; interface Props { id?: string; } const PromptPinToggle = ({ id }: Props) => { const { createNotification } = useNotifications(); const { call } = useEventManager(); const api = useApi(); const [loading, withLoading] = useLoading(); const [{ PromptPin } = DEFAULT_MAILSETTINGS] = useMailSettings(); const handleChange = async ({ target }: ChangeEvent<HTMLInputElement>) => { await api(updatePromptPin(+target.checked)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; return <Toggle id={id} loading={loading} checked={!!PromptPin} onChange={(e) => withLoading(handleChange(e))} />; }; export default PromptPinToggle;
6,893
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/security/index.ts
export { default as ExternalPGPSettingsSection } from './ExternalPGPSettingsSection'; export { default as AddressVerificationSection } from './AddressVerificationSection'; export { default as PGPSchemeSelect } from './PGPSchemeSelect';
6,894
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/sentinel/SentinelSection.tsx
import { c } from 'ttag'; import { PromotionButton } from '@proton/components/components/button/PromotionButton'; import { useLoading } from '@proton/hooks'; import { disableHighSecurity, enableHighSecurity } from '@proton/shared/lib/api/settings'; import { APP_NAMES, PLANS, PLAN_NAMES, PROTON_SENTINEL_NAME, SHARED_UPSELL_PATHS, UPSELL_COMPONENT, } from '@proton/shared/lib/constants'; import { getUpsellRefFromApp } from '@proton/shared/lib/helpers/upsell'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { isProtonSentinelEligible } from '@proton/shared/lib/helpers/userSettings'; import { SETTINGS_PROTON_SENTINEL_STATE } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import { Toggle, useSettingsLink } from '../../components'; import { useApi, useConfig, useEventManager, useNotifications, useUserSettings } from '../../hooks'; import { SettingsParagraph, SettingsSectionWide } from '../account'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; import { useFlag } from '../unleash'; interface Props { app: APP_NAMES; } const SentinelSection = ({ app }: Props) => { const { APP_NAME } = useConfig(); const goToSettings = useSettingsLink(); const [userSettings] = useUserSettings(); const api = useApi(); const [loadingSentinel, withLoadingSentinel] = useLoading(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const protonSentinel = userSettings.HighSecurity.Value; const sentinelEligible = isProtonSentinelEligible(userSettings); const sentinelPassplusEnabled = !!useFlag('SentinelPassPlus'); const handleHighSecurity = async (newHighSecurityState: Boolean) => { if (newHighSecurityState) { await api(enableHighSecurity()); createNotification({ text: c('Notification').t`${PROTON_SENTINEL_NAME} has been enabled` }); } else { await api(disableHighSecurity()); createNotification({ text: c('Notification').t`${PROTON_SENTINEL_NAME} has been disabled` }); } await call(); }; const handleUpgrade = () => { const upsellRef = getUpsellRefFromApp({ app: APP_NAME, feature: SHARED_UPSELL_PATHS.SENTINEL, component: UPSELL_COMPONENT.BUTTON, fromApp: app, }); goToSettings(`/upgrade?ref=${upsellRef}`, undefined, false); }; const getUpgradeMessage = () => { if (sentinelPassplusEnabled) { return ( <> {/* translator: full sentence with pass plus: "Upgrade to Pass Plus, Proton Unlimited, Proton Family, or Business plan to get access to Proton Sentinel." */} {c('Info').t`Upgrade to ${PLAN_NAMES[PLANS.PASS_PLUS]}, ${PLAN_NAMES[PLANS.BUNDLE]}, ${ PLAN_NAMES[PLANS.FAMILY] }, or ${PLAN_NAMES[PLANS.BUNDLE_PRO]} plan to get access to ${PROTON_SENTINEL_NAME}.`} ; </> ); } return ( <> {/* translator: full sentence: "Upgrade to Proton Unlimited, Proton Family, or Business plan to get access to Proton Sentinel." */} {c('Info').t`Upgrade to ${PLAN_NAMES[PLANS.BUNDLE]}, ${PLAN_NAMES[PLANS.FAMILY]}, or ${ PLAN_NAMES[PLANS.BUNDLE_PRO] } plan to get access to ${PROTON_SENTINEL_NAME}.`} ; </> ); }; return ( <SettingsSectionWide> <SettingsParagraph large={true} learnMoreUrl={getKnowledgeBaseUrl('/proton-sentinel')}> <p className="mt-0">{c('Info') .t`${PROTON_SENTINEL_NAME} is an advanced account protection program powered by sophisticated AI systems and specialists working around the clock to protect you from bad actors and security threats.`}</p> <p className="mb-0">{c('Info') .t`Public figures, journalists, executives, and others who may be the target of cyber attacks are highly encouraged to enable ${PROTON_SENTINEL_NAME}.`}</p> {!sentinelEligible && <p className="mb-0">{getUpgradeMessage()}</p>} </SettingsParagraph> {sentinelEligible ? ( <> <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor="high-security-toggle"> <span className="mr-2">{c('Log preference').t`Enable ${PROTON_SENTINEL_NAME}`}</span> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <Toggle id="high-security-toggle" disabled={false} loading={loadingSentinel} checked={protonSentinel === SETTINGS_PROTON_SENTINEL_STATE.ENABLED} onChange={({ target }) => { withLoadingSentinel(handleHighSecurity(target.checked)).catch(noop); }} /> </SettingsLayoutRight> </SettingsLayout> </> ) : ( <SettingsParagraph> <PromotionButton iconName="upgrade" iconGradient={true} onClick={handleUpgrade}> {/* translator: full sentence: "Upgrade to enable Proton Sentinel." */} {c('Action').t`Upgrade to enable ${PROTON_SENTINEL_NAME}`} </PromotionButton> </SettingsParagraph> )} </SettingsSectionWide> ); }; export default SentinelSection;
6,895
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/sentinel/index.ts
export { default as SentinelSection } from './SentinelSection';
6,896
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/sessions/SessionAction.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { Badge } from '../../components'; import { Session } from './interface'; interface Props { session: Session; onRevoke?: () => Promise<void>; currentUID: string; } const SessionAction = ({ session, onRevoke, currentUID }: Props) => { const [loading, withLoading] = useLoading(); if (currentUID === session.UID) { return <Badge type="origin" className="mr-0">{c('Badge for user sessions table').t`Current session`}</Badge>; } if (!onRevoke) { return null; } return ( <Button size="small" shape="outline" loading={loading} onClick={() => withLoading(onRevoke())}> {c('Action for user session').t`Revoke`} </Button> ); }; export default SessionAction;
6,897
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/sessions/SessionsSection.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import useIsMounted from '@proton/hooks/useIsMounted'; import { querySessions, revokeOtherSessions, revokeSession } from '@proton/shared/lib/api/auth'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import noop from '@proton/utils/noop'; import { Pagination, Prompt, Table, TableBody, TableHeader, TableRow, Time, useModalState, usePagination, } from '../../components'; import { useApi, useAuthentication, useNotifications } from '../../hooks'; import { SettingsParagraph, SettingsSectionWide } from '../account'; import SessionAction from './SessionAction'; import { Session } from './interface'; const PAGE_SIZE = 10; const SessionsSection = () => { const { createNotification } = useNotifications(); const isMounted = useIsMounted(); const api = useApi(); const authentication = useAuthentication(); const [confirmProps, setConfirm, renderConfirm] = useModalState(); const [loading, withLoading] = useLoading(); const [loadingRevokeAll, withLoadingRevokeAll] = useLoading(); const [state, setState] = useState<{ sessions: Session[]; total: number }>({ sessions: [], total: 0 }); const { page, list, onNext, onPrevious, onSelect } = usePagination(state.sessions, 1, PAGE_SIZE); const handleRevoke = async (UID: string) => { await api(revokeSession(UID)); setState(({ sessions }) => { const newSessions = sessions.filter(({ UID: otherUID }) => UID !== otherUID); return { sessions: newSessions, total: sessions.length, }; }); createNotification({ text: c('Success').t`Session revoked` }); }; const handleRevokeAllSessions = async () => { await api(revokeOtherSessions()); const selfUID = authentication.getUID(); setState(({ sessions }) => { const newSessions = sessions.filter(({ UID: otherUID }) => selfUID === otherUID); return { sessions: newSessions, total: sessions.length, }; }); createNotification({ text: c('Success').t`Sessions revoked` }); }; useEffect(() => { const fetchSessions = async () => { const { Sessions } = await api<{ Sessions: Session[] }>(querySessions()); if (isMounted()) { setState({ sessions: Sessions.reverse(), total: Sessions.length }); // Most recent, first } }; withLoading(fetchSessions()).catch(noop); }, []); const currentUID = authentication.getUID(); return ( <> {renderConfirm && ( <Prompt {...confirmProps} title={c('Action').t`Revoke all other sessions`} buttons={[ <Button color="norm" onClick={() => { withLoadingRevokeAll(handleRevokeAllSessions()).catch(noop); confirmProps.onClose(); }} > {c('Action').t`Revoke all other sessions`} </Button>, <Button onClick={confirmProps.onClose}>{c('Action').t`Cancel`}</Button>, ]} > {c('Info').t`Do you want to revoke all other sessions than the current one?`} </Prompt> )} <SettingsSectionWide> <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/log-out-all-other-sessions')}> {c('Info') .t`Unless you sign out of your account or change your password, your session will remain active. Sessions expire after 60 days of inactivity.`} </SettingsParagraph> <div className="flex flex-justify-space-between flex-align-items-start mb-4"> <div className="mb-4 md:mb-0"> <Button shape="outline" onClick={() => setConfirm(true)} loading={loadingRevokeAll}> {c('Action').t`Revoke all other sessions`} </Button> </div> <Pagination page={page} total={state.total} limit={PAGE_SIZE} onNext={onNext} onPrevious={onPrevious} onSelect={onSelect} /> </div> <Table hasActions responsive="cards"> <TableHeader cells={[c('Title').t`App`, c('Title').t`Date`, c('Title').t`Action`]} /> <TableBody loading={loading} colSpan={3}> {list.map((session) => { const key = session.UID; return ( <TableRow key={key} labels={[c('Title').t`App`, c('Title').t`Date`, '']} cells={[ session.LocalizedClientName, <Time format="PPp" key={1}> {session.CreateTime} </Time>, <SessionAction key={2} session={session} currentUID={currentUID} onRevoke={session.Revocable ? () => handleRevoke(session.UID) : undefined} />, ]} /> ); })} </TableBody> </Table> </SettingsSectionWide> </> ); }; export default SessionsSection;
6,898
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/sessions/index.ts
export { default as SessionsSection } from './SessionsSection'; export { default as SessionAction } from './SessionAction';
6,899