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/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Free/configuration.ts
import { FeatureCode } from '@proton/components/containers/features'; import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getUnlimitedVPNFeatures, getVPNFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import bannerImage from './BF-VPN-App-Modal-996x176-60.png'; import bannerImage2x from './BF-VPN-App-Modal-1992x352-60.png'; import Layout from './Layout'; const config: OfferConfig = { ID: 'black-friday-2023-vpn-free', autoPopUp: 'each-time', featureCode: FeatureCode.OfferBlackFriday2023VPNFree, images: { bannerImage, bannerImage2x, }, darkBackground: true, deals: [ { ref: 'bf_23_vpn-free-modal-v15p', dealName: PLAN_NAMES[PLANS.VPN], planIDs: { [PLANS.VPN]: 1, }, cycle: CYCLE.FIFTEEN, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getVPNFeatures, popular: 3, mobileOrder: 2, isGuaranteed: true, }, { ref: 'bf_23_vpn-free-modal-v30p', dealName: PLAN_NAMES[PLANS.VPN], planIDs: { [PLANS.VPN]: 1, }, cycle: CYCLE.THIRTY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getVPNFeatures, popular: 1, mobileOrder: 1, isGuaranteed: true, }, { ref: 'bf_23_vpn-free-modal-u12', dealName: PLAN_NAMES[PLANS.BUNDLE], planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getUnlimitedVPNFeatures, popular: 2, mobileOrder: 3, isGuaranteed: true, }, ], layout: Layout, }; export default config;
6,600
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Free/eligibility.ts
import { fromUnixTime, isBefore } from 'date-fns'; import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { APPS } from '@proton/shared/lib/constants'; import { isManagedExternally } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, Subscription, UserModel } from '@proton/shared/lib/interfaces'; import { FREE_DOWNGRADER_LIMIT } from '../../helpers/offerPeriods'; interface Props { subscription?: Subscription; protonConfig: ProtonConfig; user: UserModel; lastSubscriptionEnd?: number; } const isEligible = ({ subscription, protonConfig, user, lastSubscriptionEnd = 0 }: Props) => { const parentApp = getAppFromPathnameSafe(window.location.pathname); const hasValidApp = protonConfig?.APP_NAME === APPS.PROTONVPN_SETTINGS || (protonConfig?.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONVPN_SETTINGS); const { canPay, isDelinquent, isFree } = user; const notDelinquent = !isDelinquent; const isNotExternal = !isManagedExternally(subscription); return ( hasValidApp && isNotExternal && canPay && notDelinquent && isFree && isBefore(fromUnixTime(lastSubscriptionEnd), FREE_DOWNGRADER_LIMIT) ); }; export default isEligible;
6,601
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Free/index.ts
export { default as blackFriday2023VPNFreeConfig } from './configuration'; export { default as useBlackFriday2023VPNFree } from './useOffer'; export { default as blackFriday2023VPNFreeEligibility } from './eligibility';
6,602
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Free/useOffer.ts
import { useConfig, useLastSubscriptionEnd, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, subscriptionLoading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const [lastSubscriptionEnd, lastSubscriptionEndLoading] = useLastSubscriptionEnd(); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || subscriptionLoading || lastSubscriptionEndLoading; const isEligible = getIsEligible({ subscription, protonConfig, user, lastSubscriptionEnd }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,603
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Monthly/Layout.tsx
import BlackFridayFooter from '../../components/blackFriday/BlackFridayFooter'; import BlackFridayTitle from '../../components/blackFriday/BlackFridayTitle'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <BlackFridayTitle /> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <BlackFridayFooter {...props} /> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,604
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Monthly/configuration.ts
import { FeatureCode } from '@proton/components/containers/features'; import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getUnlimitedVPNFeatures, getVPNFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import bannerImage from './BF-VPN-App-Modal-996x176-60.png'; import bannerImage2x from './BF-VPN-App-Modal-1992x352-60.png'; import Layout from './Layout'; const config: OfferConfig = { ID: 'black-friday-2023-vpn-monthly', autoPopUp: 'each-time', featureCode: FeatureCode.OfferBlackFriday2023VPNMonthly, images: { bannerImage, bannerImage2x, }, darkBackground: true, canBeDisabled: true, deals: [ { ref: 'bf_23_vpn-1m-modal-v15p', dealName: PLAN_NAMES[PLANS.VPN], planIDs: { [PLANS.VPN]: 1, }, cycle: CYCLE.FIFTEEN, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getVPNFeatures, isGuaranteed: true, }, { ref: 'bf_23_vpn-1m-modal-v30p', dealName: PLAN_NAMES[PLANS.VPN], planIDs: { [PLANS.VPN]: 1, }, cycle: CYCLE.THIRTY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getVPNFeatures, popular: 1, isGuaranteed: true, }, { ref: 'bf_23_vpn-1m-modal-u12', dealName: PLAN_NAMES[PLANS.BUNDLE], planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getUnlimitedVPNFeatures, isGuaranteed: true, }, ], layout: Layout, }; export default config;
6,605
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Monthly/eligibility.ts
import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { APPS, PLANS } from '@proton/shared/lib/constants'; import { getPlan, hasMonthly, isManagedExternally } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, SubscriptionModel, UserModel } from '@proton/shared/lib/interfaces'; interface Props { subscription: SubscriptionModel; protonConfig: ProtonConfig; user: UserModel; } const isEligible = ({ subscription, protonConfig, user }: Props) => { const parentApp = getAppFromPathnameSafe(window.location.pathname); const plan = getPlan(subscription); const hasVPN = plan?.Name === PLANS.VPN; const isMonthly = hasMonthly(subscription); const hasValidApp = protonConfig?.APP_NAME === APPS.PROTONVPN_SETTINGS || (protonConfig?.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONVPN_SETTINGS); const { canPay, isDelinquent } = user; const notDelinquent = !isDelinquent; const isNotExternal = !isManagedExternally(subscription); return hasValidApp && isNotExternal && canPay && notDelinquent && hasVPN && isMonthly; }; export default isEligible;
6,606
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Monthly/index.ts
export { default as blackFriday2023VPNMonthlyConfig } from './configuration'; export { default as useBlackFriday2023VPNMonthly } from './useOffer'; export { default as blackFriday2023VPNMonthlyEligibility } from './eligibility';
6,607
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Monthly/useOffer.ts
import { useConfig, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, subscriptionLoading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || subscriptionLoading; const isEligible = getIsEligible({ subscription, protonConfig, user }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,608
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023TwoYears/Layout.tsx
import BlackFridayFooter from '../../components/blackFriday/BlackFridayFooter'; import BlackFridayTitle from '../../components/blackFriday/BlackFridayTitle'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <BlackFridayTitle /> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <BlackFridayFooter {...props} /> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,609
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023TwoYears/configuration.ts
import { FeatureCode } from '@proton/components/containers/features'; import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getUnlimitedVPNFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import sideImage from './BF-VPN-App-Modal-400x1200-33.png'; import sideImage2x from './BF-VPN-App-Modal-800x2400-33.png'; import Layout from './Layout'; const config: OfferConfig = { ID: 'black-friday-2023-vpn-two-years', autoPopUp: 'each-time', featureCode: FeatureCode.OfferBlackFriday2023VPNTwoYears, images: { sideImage, sideImage2x, }, canBeDisabled: true, deals: [ { ref: 'bf_23_vpn-2y-modal-u12', dealName: PLAN_NAMES[PLANS.BUNDLE], planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getUnlimitedVPNFeatures, isGuaranteed: true, }, ], layout: Layout, }; export default config;
6,610
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023TwoYears/eligibility.ts
import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { APPS, PLANS } from '@proton/shared/lib/constants'; import { getPlan, hasThirty, hasTwoYears, isManagedExternally } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, SubscriptionModel, UserModel } from '@proton/shared/lib/interfaces'; interface Props { subscription: SubscriptionModel; protonConfig: ProtonConfig; user: UserModel; } const isEligible = ({ subscription, protonConfig, user }: Props) => { const parentApp = getAppFromPathnameSafe(window.location.pathname); const plan = getPlan(subscription); const hasVPN = plan?.Name === PLANS.VPN; const isTwoYears = hasTwoYears(subscription); const isThirty = hasThirty(subscription); const hasValidApp = protonConfig?.APP_NAME === APPS.PROTONVPN_SETTINGS || (protonConfig?.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONVPN_SETTINGS); const { canPay, isDelinquent } = user; const notDelinquent = !isDelinquent; const isNotExternal = !isManagedExternally(subscription); return hasValidApp && isNotExternal && canPay && notDelinquent && hasVPN && (isTwoYears || isThirty); }; export default isEligible;
6,611
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023TwoYears/index.ts
export { default as blackFriday2023VPNTwoYearsConfig } from './configuration'; export { default as useBlackFriday2023VPNTwoYears } from './useOffer'; export { default as blackFriday2023VPNTwoYearsEligibility } from './eligibility';
6,612
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023TwoYears/useOffer.ts
import { useConfig, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, subscriptionLoading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || subscriptionLoading; const isEligible = getIsEligible({ subscription, protonConfig, user }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,613
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Yearly/Layout.tsx
import BlackFridayFooter from '../../components/blackFriday/BlackFridayFooter'; import BlackFridayTitle from '../../components/blackFriday/BlackFridayTitle'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <BlackFridayTitle /> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <BlackFridayFooter {...props} /> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,614
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Yearly/configuration.ts
import { FeatureCode } from '@proton/components/containers/features'; import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getUnlimitedVPNFeatures, getVPNFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import bannerImage from './BF-VPN-App-Modal-996x176-60.png'; import bannerImage2x from './BF-VPN-App-Modal-1992x352-60.png'; import Layout from './Layout'; const config: OfferConfig = { ID: 'black-friday-2023-vpn-yearly', autoPopUp: 'each-time', featureCode: FeatureCode.OfferBlackFriday2023VPNYearly, images: { bannerImage, bannerImage2x, }, canBeDisabled: true, darkBackground: true, deals: [ { ref: 'bf_23_vpn-1y-modal-v30p', dealName: PLAN_NAMES[PLANS.VPN], planIDs: { [PLANS.VPN]: 1, }, cycle: CYCLE.THIRTY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getVPNFeatures, popular: 1, isGuaranteed: true, }, { ref: 'bf_23_vpn-1y-modal-u12', dealName: PLAN_NAMES[PLANS.BUNDLE], planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getUnlimitedVPNFeatures, isGuaranteed: true, }, ], layout: Layout, }; export default config;
6,615
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Yearly/eligibility.ts
import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { APPS, PLANS } from '@proton/shared/lib/constants'; import { getPlan, hasFifteen, hasYearly, isManagedExternally } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, SubscriptionModel, UserModel } from '@proton/shared/lib/interfaces'; interface Props { subscription: SubscriptionModel; protonConfig: ProtonConfig; user: UserModel; } const isEligible = ({ subscription, protonConfig, user }: Props) => { const parentApp = getAppFromPathnameSafe(window.location.pathname); const plan = getPlan(subscription); const hasVPN = plan?.Name === PLANS.VPN; const isYearly = hasYearly(subscription); const isFifteen = hasFifteen(subscription); const hasValidApp = protonConfig?.APP_NAME === APPS.PROTONVPN_SETTINGS || (protonConfig?.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONVPN_SETTINGS); const { canPay, isDelinquent } = user; const notDelinquent = !isDelinquent; const isNotExternal = !isManagedExternally(subscription); return hasValidApp && isNotExternal && canPay && notDelinquent && hasVPN && (isYearly || isFifteen); }; export default isEligible;
6,616
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Yearly/index.ts
export { default as blackFriday2023VPNYearlyConfig } from './configuration'; export { default as useBlackFriday2023VPNYearly } from './useOffer'; export { default as blackFriday2023VPNYearlyEligibility } from './eligibility';
6,617
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Yearly/useOffer.ts
import { useConfig, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, subscriptionLoading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || subscriptionLoading; const isEligible = getIsEligible({ subscription, protonConfig, user }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,618
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/goUnlimited2022/Layout.tsx
import { c } from 'ttag'; import { PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import OfferTitle from '../../components/shared/OfferTitle'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { const planName = PLAN_NAMES[PLANS.BUNDLE]; return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <OfferTitle>{c('specialoffer: Title').t`Upgrade and save more with 2 years of ${planName}`}</OfferTitle> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <p className="text-sm text-center mb-4 color-weak">{c('specialoffer: Footer') .t`This subscription will automatically renew every 2 years at the same rate until it is cancelled.`}</p> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,619
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/goUnlimited2022/configuration.ts
import { c } from 'ttag'; import { FeatureCode } from '@proton/components/containers/features'; import { CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getUnlimitedDealFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import Layout from './Layout'; import sideImage from './Unlimited-400x1200.png'; import sideImage2x from './Unlimited-800x2400.png'; const config: OfferConfig = { ID: 'go-unlimited-2022', featureCode: FeatureCode.OfferGoUnlimited2022, canBeDisabled: true, deals: [ { ref: 'upsell_mail-modal-go_unlimited', dealName: PLAN_NAMES[PLANS.BUNDLE], planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.TWO_YEARS, popular: 1, features: getUnlimitedDealFeatures, getCTAContent: () => c('specialoffer: Action, Unlimited is a plan name').t`Go Unlimited`, }, ], layout: Layout, getCTAContent: () => c('specialoffer: Action, Unlimited is a plan name').t`Go Unlimited`, shapeButton: 'outline', images: { sideImage, sideImage2x, }, }; export default config;
6,620
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/goUnlimited2022/eligibility.ts
import { addDays, fromUnixTime, isBefore } from 'date-fns'; import { APPS, PLANS } from '@proton/shared/lib/constants'; import { getPlan, isManagedExternally, isTrial } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, Subscription, UserModel } from '@proton/shared/lib/interfaces'; interface Props { user: UserModel; subscription?: Subscription; protonConfig: ProtonConfig; } const isEligible = ({ user, subscription, protonConfig }: Props) => { const isValidApp = protonConfig?.APP_NAME === APPS.PROTONMAIL || protonConfig?.APP_NAME === APPS.PROTONACCOUNT; const createDate = subscription?.CreateTime ? fromUnixTime(subscription.CreateTime) : new Date(); const plan = getPlan(subscription); return ( [PLANS.MAIL, PLANS.VPN].includes(plan?.Name as PLANS) && !isTrial(subscription) && isBefore(createDate, addDays(new Date(), -7)) && user.canPay && isValidApp && !user.isDelinquent && !isManagedExternally(subscription) ); }; export default isEligible;
6,621
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/goUnlimited2022/index.ts
export { default as goUnlimited2022Config } from './configuration'; export { default as useGoUnlimited2022 } from './useOffer';
6,622
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/goUnlimited2022/useOffer.ts
import { useConfig, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, loading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || loading; const isEligible = getIsEligible({ user, subscription, protonConfig }) && isActive; const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,623
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/mailTrial2023/Layout.tsx
import { format, fromUnixTime } from 'date-fns'; import { c } from 'ttag'; import { useSubscription } from '@proton/components/hooks'; import { dateLocale } from '@proton/shared/lib/i18n'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import OfferTitle from '../../components/shared/OfferTitle'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { const [subscription] = useSubscription(); const { PeriodEnd = 0 } = subscription || {}; const textDate = format(fromUnixTime(PeriodEnd), 'PPP', { locale: dateLocale }); return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <OfferTitle>{c('Title').t`Your Mail Plus free trial ends on ${textDate}`}</OfferTitle> <p className="text-center">{c('Info') .t`Upgrade now to get premium features, products and storage at a special price`}</p> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <p className="text-sm text-center mb-4 color-weak">{c('specialoffer: Footer') .t`This subscription will automatically renew every 2 years at the same rate until it is cancelled.`}</p> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,624
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/mailTrial2023/configuration.ts
import { c } from 'ttag'; import { FeatureCode } from '@proton/components/containers/features'; import { CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getMailPlusInboxFeatures, getUnlimitedFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import Layout from './Layout'; import bannerImage from './upsell_mail-plus-free-trial.png'; import bannerImage2x from './upsell_mail-plus-free-trial@2x.png'; const config: OfferConfig = { ID: 'mail-trial-2023', featureCode: FeatureCode.OfferMailTrial2023, deals: [ { ref: 'plus_referral_trial-modal-m1', dealName: PLAN_NAMES[PLANS.MAIL], planIDs: { [PLANS.MAIL]: 1, }, cycle: CYCLE.YEARLY, features: getMailPlusInboxFeatures, getCTAContent: () => c('Action').t`Upgrade now`, }, { ref: 'plus_referral_trial-modal-u2', dealName: PLAN_NAMES[PLANS.BUNDLE], planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.TWO_YEARS, popular: 1, features: getUnlimitedFeatures, getCTAContent: () => c('Action').t`Upgrade now`, }, { ref: 'plus_referral_trial-modal-u1', dealName: PLAN_NAMES[PLANS.BUNDLE], planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.YEARLY, features: getUnlimitedFeatures, getCTAContent: () => c('Action').t`Upgrade now`, }, ], layout: Layout, getCTAContent: () => c('Action').t`Upgrade`, shapeButton: 'outline', images: { bannerImage, bannerImage2x, }, }; export default config;
6,625
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/mailTrial2023/eligibility.ts
import { isTrial } from '@proton/shared/lib/helpers/subscription'; import { Subscription } from '@proton/shared/lib/interfaces'; interface Props { subscription?: Subscription; } const isEligible = ({ subscription }: Props) => { return isTrial(subscription); }; export default isEligible;
6,626
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/mailTrial2023/index.ts
export { default as mailTrial2023Config } from './configuration'; export { default as useMailTrial2023 } from './useOffer';
6,627
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/mailTrial2023/useOffer.ts
import { useSubscription } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [subscription, loadingSubscription] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const isLoading = flagsLoading || loadingSubscription; const isEligible = getIsEligible({ subscription }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,628
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/OnboardingContent.tsx
import { HTMLProps, ReactNode } from 'react'; export interface Props extends HTMLProps<HTMLDivElement> { description?: ReactNode; children?: ReactNode; img?: ReactNode; } const OnboardingContent = ({ description, img, children, title, ...rest }: Props) => { return ( <div {...rest}> {img && <div className="pb-4 text-center m-auto w-full">{img}</div>} {title && <h1 className="mb-2 text-2xl text-bold text-center">{title}</h1>} {description && <div className="mb-8 text-center color-weak">{description}</div>} {children && <div className="mb-8">{children}</div>} </div> ); }; export default OnboardingContent;
6,629
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/OnboardingDiscoverApps.tsx
import { c } from 'ttag'; import { BRAND_NAME, CALENDAR_SHORT_APP_NAME, DRIVE_SHORT_APP_NAME, MAIL_SHORT_APP_NAME, VPN_SHORT_APP_NAME, } from '@proton/shared/lib/constants'; import onboardingDiscover from '@proton/styles/assets/img/onboarding/discover.svg'; import OnboardingContent, { Props as OnboardingContentProps } from './OnboardingContent'; const OnboardingDiscoverApps = (props: Omit<OnboardingContentProps, 'decription' | 'img'>) => { return ( <OnboardingContent title={c('Onboarding Proton').t`Discover all ${BRAND_NAME} services`} description={c('Onboarding Proton') .t`Use the app selector in the top left to access all ${BRAND_NAME} services: ${MAIL_SHORT_APP_NAME}, ${VPN_SHORT_APP_NAME}, ${CALENDAR_SHORT_APP_NAME} and ${DRIVE_SHORT_APP_NAME}.`} img={<img src={onboardingDiscover} alt={c('Onboarding Proton').t`Discover all ${BRAND_NAME} services`} />} {...props} /> ); }; export default OnboardingDiscoverApps;
6,630
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/OnboardingModal.scss
@import '~@proton/styles/scss/lib'; .onboarding-modal { &#{&} { --size: #{rem(394)}; } min-block-size: rem(300); }
6,631
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/OnboardingModal.tsx
import { isValidElement, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { updateFlags, updateWelcomeFlags } from '@proton/shared/lib/api/settings'; import { hasNewVisionary, hasVisionary } from '@proton/shared/lib/helpers/subscription'; import { PROTON_THEMES_MAP, ThemeTypes } from '@proton/shared/lib/themes/themes'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import range from '@proton/utils/range'; import { ModalTwoContent as ModalContent, ModalTwo, StepDot, StepDots, useSettingsLink } from '../../components'; import { useApi, useOrganization, useSubscription, useUser, useUserSettings, useWelcomeFlags } from '../../hooks'; import { useTheme } from '../themes/ThemeProvider'; import OnboardingDiscoverApps from './OnboardingDiscoverApps'; import OnboardingSetupOrganization from './OnboardingSetupOrganization'; import OnboardingStep from './OnboardingStep'; import OnboardingThemes from './OnboardingThemes'; import { OnboardingStepProps, OnboardingStepRenderCallback } from './interface'; import './OnboardingModal.scss'; interface Props { onClose?: () => void; onExit?: () => void; onDone?: () => void; children?: ((props: OnboardingStepRenderCallback) => JSX.Element)[]; showGenericSteps?: boolean; } const OnboardingModal = ({ children, showGenericSteps, onDone, ...rest }: Props) => { const [user] = useUser(); const [userSettings] = useUserSettings(); const goToSettings = useSettingsLink(); const [organization, loadingOrganization] = useOrganization(); const [subscription, loadingSubscription] = useSubscription(); const theme = useTheme(); const onboardingThemesSelection = [ThemeTypes.Duotone, ThemeTypes.Snow, ThemeTypes.Carbon, ThemeTypes.Monokai].map( (id) => PROTON_THEMES_MAP[id] ); const api = useApi(); const [welcomeFlags] = useWelcomeFlags(); let isLastStep = false; const canSetupOrganization = !loadingOrganization && !loadingSubscription && user.isAdmin && organization.MaxMembers > 1 && organization.UsedMembers === 1 && !organization.HasKeys && !hasNewVisionary(subscription) && !hasVisionary(subscription); const [step, setStep] = useState(0); const handleNext = () => { if (isLastStep) { if (welcomeFlags.isWelcomeFlow) { // Set generic welcome to true api(updateFlags({ Welcomed: 1 })).catch(noop); } if (!userSettings.WelcomeFlag) { // Set product specific welcome to true api(updateWelcomeFlags()).catch(noop); } onDone?.(); rest?.onClose?.(); return; } setStep((step) => step + 1); }; const handleBack = () => { setStep((step) => step - 1); }; const handleThemeChange = (newThemeType: ThemeTypes) => { theme.setTheme(newThemeType); }; const setupOrganizationStep = ( <OnboardingStep> <OnboardingSetupOrganization /> <footer> <div className="flex flex-nowrap mb-4"> <Button size="large" color="weak" className="mr-4" fullWidth onClick={handleBack}>{c('Action') .t`Back`}</Button> <Button size="large" color="norm" fullWidth onClick={() => { goToSettings('/multi-user-support', undefined, true); handleNext(); }} > {c('Action').t`Start setup`} </Button> </div> <Button size="large" color="norm" shape="ghost" className="mb-4" fullWidth onClick={handleNext}>{c( 'Action' ).t`Skip`}</Button> </footer> </OnboardingStep> ); const themesStep = ( <OnboardingStep> <OnboardingThemes themeIdentifier={theme.information.theme} themes={onboardingThemesSelection} onChange={handleThemeChange} /> <footer className="flex flex-nowrap"> <Button size="large" color="weak" className="mr-4" fullWidth onClick={handleBack}>{c('Action') .t`Back`}</Button> <Button size="large" color="norm" fullWidth onClick={handleNext}> {c('Action').t`Next`} </Button> </footer> </OnboardingStep> ); const discoverAppsStep = ( <OnboardingStep> <OnboardingDiscoverApps /> <footer className="flex flex-nowrap"> <Button size="large" className="mr-4" fullWidth onClick={handleBack}>{c('Action').t`Back`}</Button> <Button size="large" color="norm" fullWidth onClick={handleNext}> {c('Action').t`Get started`} </Button> </footer> </OnboardingStep> ); const displayGenericSteps = welcomeFlags?.hasGenericWelcomeStep || showGenericSteps; const genericSteps = displayGenericSteps ? [canSetupOrganization && setupOrganizationStep, themesStep, discoverAppsStep].filter(isTruthy) : []; const productSteps = children ? (Array.isArray(children) ? children : [children]) .map( (renderCallback) => renderCallback?.({ onNext: handleNext, onBack: handleBack, displayGenericSteps, }) ?? null ) .filter((x) => x !== null) : []; const steps = [...productSteps, ...genericSteps]; isLastStep = steps.length - 1 === step; const childStep = steps[step]; const hasDots = steps.length > 1 && step < steps.length; if (!steps.length) { rest?.onClose?.(); } if (!isValidElement<OnboardingStepProps>(childStep)) { throw new Error('Missing step'); } return ( <ModalTwo {...rest} size="small" className="onboarding-modal"> <ModalContent className="m-8"> {childStep} {hasDots ? ( <div className="text-center"> <StepDots value={step} ulClassName="mb-0"> {range(0, steps.length).map((index) => ( <StepDot key={index} index={index} aria-controls={`onboarding-${index}`} onClick={() => { setStep(index); }} /> ))} </StepDots> </div> ) : null} </ModalContent> </ModalTwo> ); }; export default OnboardingModal;
6,632
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/OnboardingSetDisplayName.tsx
import { c } from 'ttag'; import onboardingDisplayName from '@proton/styles/assets/img/onboarding/display-name.svg'; import { InputFieldTwo } from '../../components'; import OnboardingContent, { Props as OnboardingContentProps } from './OnboardingContent'; interface Props extends Omit<OnboardingContentProps, 'img' | 'text' | 'description'> { displayName: string; setDisplayName: (displayName: string) => void; displayNameError?: string; } const OnboardingSetDisplayName = ({ displayName, setDisplayName, displayNameError, ...rest }: Props) => { return ( <OnboardingContent description={c('Onboarding Proton') .t`This is what people will see when you send them an email, invite them to an event, or share a file with them.`} img={<img src={onboardingDisplayName} alt={c('Onboarding Proton').t`Choose a display name`} />} title={c('Onboarding Proton').t`Choose a display name`} {...rest} > <InputFieldTwo id="displayName" label={c('Label').t`Display name`} autoFocus placeholder={c('Placeholder').t`e.g. Julia Smith`} value={displayName} onValue={setDisplayName} error={displayNameError} /> </OnboardingContent> ); }; export default OnboardingSetDisplayName;
6,633
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/OnboardingSetupOrganization.tsx
import { c } from 'ttag'; import useSubscription from '@proton/components/hooks/useSubscription'; import { hasFamily } from '@proton/shared/lib/helpers/subscription'; import onboardingFamilyPlan from '@proton/styles/assets/img/onboarding/familyPlan.svg'; import onboardingOrganization from '@proton/styles/assets/img/onboarding/organization.svg'; import OnboardingContent, { Props as OnboardingContentProps } from './OnboardingContent'; const OnboardingSetupOrganization = (props: Omit<OnboardingContentProps, 'description' | 'img'>) => { const [subscription] = useSubscription(); const hasFamilyPlan = hasFamily(subscription); const title = hasFamilyPlan ? c('familyOffer_2023:Onboarding Proton').t`Set up your family account` : c('Onboarding Proton').t`Set up your organization`; const description = hasFamilyPlan ? c('familyOffer_2023:Onboarding Proton').t`Configure your family account and invite users ` : c('Onboarding Proton') .t`Configure your organization, link your domain name, and create accounts to ensure all members of your organization are protected.`; const imgAlt = hasFamilyPlan ? c('familyOffer_2023:Onboarding Proton').t`Set up your family` : c('Onboarding Proton').t`Set up your organization`; const img = hasFamilyPlan ? onboardingFamilyPlan : onboardingOrganization; return ( <OnboardingContent title={title} description={description} img={<img src={img} alt={imgAlt} />} {...props} /> ); }; export default OnboardingSetupOrganization;
6,634
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/OnboardingStep.tsx
import { OnboardingStepProps } from './interface'; const OnboardingStep = ({ children }: OnboardingStepProps) => { return <>{children}</>; }; export default OnboardingStep;
6,635
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/OnboardingThemes.tsx
import { c } from 'ttag'; import { ThemeTypes } from '@proton/shared/lib/themes/themes'; import ThemeCards, { Theme } from '../themes/ThemeCards'; import OnboardingContent, { Props as OnboardingContentProps } from './OnboardingContent'; interface Props extends Omit<OnboardingContentProps, 'decription' | 'onChange'> { themes: Theme[]; themeIdentifier: ThemeTypes; onChange: (identifier: ThemeTypes) => void; } const OnboardingThemes = ({ themes, themeIdentifier, onChange, ...rest }: Props) => { return ( <OnboardingContent title={c('Onboarding Proton').t`Select a theme`} description={c('Onboarding Proton') .t`More theming options are available in your account Settings > Appearance.`} {...rest} > <ThemeCards list={themes} themeIdentifier={themeIdentifier} onChange={onChange} size="large" /> </OnboardingContent> ); }; export default OnboardingThemes;
6,636
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/OnboardingWelcome.tsx
import { c } from 'ttag'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import welcomeImage from '@proton/styles/assets/img/onboarding/proton-welcome.svg'; import OnboardingContent, { Props as OnboardingContentProps } from './OnboardingContent'; const OnboardingWelcome = (props: Omit<OnboardingContentProps, 'decription' | 'img'>) => { return ( <OnboardingContent title={c('Onboarding Proton').t`Welcome to ${BRAND_NAME}`} description={c('Onboarding Proton') .t`Our mission is to build an internet where you are in control of your data and your privacy. We have recently updated ${BRAND_NAME} - welcome to the secure internet.`} img={<img src={welcomeImage} alt={c('Onboarding Proton').t`Welcome to ${BRAND_NAME}`} />} {...props} /> ); }; export default OnboardingWelcome;
6,637
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/index.ts
export { default as OnboardingContent } from './OnboardingContent'; export { default as OnboardingModal } from './OnboardingModal'; export { default as OnboardingStep } from './OnboardingStep'; export * from './interface';
6,638
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/onboarding/interface.ts
import { ReactNode } from 'react'; export interface OnboardingStepProps { children: ReactNode; } export interface OnboardingStepRenderCallback { onNext: () => void; onBack?: () => void; displayGenericSteps?: boolean; }
6,639
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/ChangeOrganizationKeysModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { CryptoProxy } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { updateOrganizationKeysLegacy, updateOrganizationKeysV2 } from '@proton/shared/lib/api/organization'; import { ENCRYPTION_CONFIGS, ENCRYPTION_TYPES } from '@proton/shared/lib/constants'; import { confirmPasswordValidator, passwordLengthValidator } from '@proton/shared/lib/helpers/formValidators'; import { CachedOrganizationKey, Member } from '@proton/shared/lib/interfaces'; import { generateOrganizationKeys, getHasMigratedAddressKeys, getReEncryptedPublicMemberTokensPayloadLegacy, getReEncryptedPublicMemberTokensPayloadV2, } from '@proton/shared/lib/keys'; import noop from '@proton/utils/noop'; import { Alert, Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, PasswordInputTwo, useFormErrors, } from '../../components'; import { useApi, useAuthentication, useEventManager, useGetAddresses, useModals, useNotifications } from '../../hooks'; import AuthModal from '../password/AuthModal'; interface Props extends ModalProps { hasOtherAdmins: boolean; publicMembers: Member[]; organizationKey: CachedOrganizationKey; mode?: 'reset'; } const ChangeOrganizationKeysModal = ({ onClose, mode, hasOtherAdmins, publicMembers, organizationKey, ...rest }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createModal } = useModals(); const { createNotification } = useNotifications(); const authentication = useAuthentication(); const { validator, onFormSubmit } = useFormErrors(); const getAddresses = useGetAddresses(); const [loading, withLoading] = useLoading(); const [newPassword, setNewPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const handleSubmit = async () => { const { privateKey, privateKeyArmored, backupKeySalt, backupArmoredPrivateKey } = await generateOrganizationKeys({ keyPassword: authentication.getPassword(), backupPassword: newPassword, encryptionConfig: ENCRYPTION_CONFIGS[ENCRYPTION_TYPES.CURVE25519], }); // Check this case for safety. if (publicMembers.length >= 1 && !organizationKey.privateKey) { throw new Error('Private members received without an existing organization key.'); } const addresses = await getAddresses(); const publicKey = await CryptoProxy.importPublicKey({ armoredKey: privateKeyArmored }); let apiConfig: any; if (getHasMigratedAddressKeys(addresses)) { apiConfig = updateOrganizationKeysV2({ PrivateKey: privateKeyArmored, BackupPrivateKey: backupArmoredPrivateKey, BackupKeySalt: backupKeySalt, Members: organizationKey.privateKey ? await getReEncryptedPublicMemberTokensPayloadV2({ api, publicMembers, oldOrganizationKey: organizationKey, newOrganizationKey: { privateKey, publicKey }, }) : [], }); } else { apiConfig = updateOrganizationKeysLegacy({ PrivateKey: privateKeyArmored, BackupPrivateKey: backupArmoredPrivateKey, BackupKeySalt: backupKeySalt, Tokens: organizationKey.privateKey ? await getReEncryptedPublicMemberTokensPayloadLegacy({ api, publicMembers, oldOrganizationKey: organizationKey, newOrganizationKey: { privateKey, publicKey }, }) : [], }); } await new Promise((resolve, reject) => { createModal(<AuthModal onCancel={reject} onSuccess={resolve} config={apiConfig} />); }); await call(); createNotification({ text: c('Success').t`Keys updated` }); onClose?.(); }; const handleClose = loading ? noop : onClose; return ( <Modal as={Form} onSubmit={() => { if (!onFormSubmit()) { return; } void withLoading(handleSubmit()); }} onClose={handleClose} {...rest} > <ModalHeader title={ mode === 'reset' ? c('Title').t`Reset organization keys` : c('Title').t`Change organization keys` } /> <ModalContent> { <> {hasOtherAdmins && ( <Alert className="mb-4">{c('Info') .t`Other administrators exist in your organization, you are responsible for communicating the new password to them.`}</Alert> )} <Alert className="mb-4" type="warning"> {c('Info') .t`Do NOT forget this password. If you forget it, you will not be able to manage your organization.`} <br /> {c('Info') .t`Save your password somewhere safe. Click on icon to confirm that you have typed your password correctly.`} </Alert> <InputFieldTwo id="organizationPassword" as={PasswordInputTwo} label={c('Label').t`New organization password`} placeholder={c('Placeholder').t`Password`} value={newPassword} onValue={setNewPassword} error={validator([passwordLengthValidator(newPassword)])} autoComplete="new-password" autoFocus /> <InputFieldTwo id="confirmPassword" as={PasswordInputTwo} label={c('Label').t`Confirm organization password`} placeholder={c('Placeholder').t`Confirm`} value={confirmPassword} onValue={setConfirmPassword} error={validator([ passwordLengthValidator(newPassword), confirmPasswordValidator(newPassword, confirmPassword), ])} autoComplete="new-password" /> </> } </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={loading}> {c('Action').t`Close`} </Button> <Button loading={loading} type="submit" color="norm"> {c('Action').t`Save`} </Button> </ModalFooter> </Modal> ); }; export default ChangeOrganizationKeysModal;
6,640
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/ChangeOrganizationPasswordModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { PrivateKeyReference } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { updateBackupKey } from '@proton/shared/lib/api/organization'; import { confirmPasswordValidator, passwordLengthValidator } from '@proton/shared/lib/helpers/formValidators'; import { getBackupKeyData } from '@proton/shared/lib/keys'; import noop from '@proton/utils/noop'; import { Alert, Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, PasswordInputTwo, useFormErrors, useModalState, } from '../../components'; import { useEventManager, useNotifications } from '../../hooks'; import AuthModal from '../password/AuthModal'; interface Props extends ModalProps { hasOtherAdmins: boolean; organizationKey: PrivateKeyReference; } const ChangeOrganizationPasswordModal = ({ hasOtherAdmins, organizationKey, onClose, ...rest }: Props) => { const { call } = useEventManager(); const [loadingPromise, withLoading] = useLoading(); const [newPassword, setNewPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const { createNotification } = useNotifications(); const { validator, onFormSubmit } = useFormErrors(); const [config, setConfig] = useState<any>(undefined); const [authModal, setAuthModalOpen, renderAuthModal] = useModalState(); const handleSubmit = async () => { const { backupKeySalt, backupArmoredPrivateKey } = await getBackupKeyData({ backupPassword: newPassword, organizationKey, }); const config = updateBackupKey({ PrivateKey: backupArmoredPrivateKey, KeySalt: backupKeySalt }); setConfig(config); setAuthModalOpen(true); }; const loading = loadingPromise || renderAuthModal; const handleClose = loading ? noop : onClose; return ( <> {renderAuthModal && config && ( <AuthModal {...authModal} onCancel={undefined} onSuccess={async () => { await call(); createNotification({ text: c('Success').t`Password updated` }); onClose?.(); }} config={config} /> )} <Modal as={Form} onSubmit={() => { if (!onFormSubmit()) { return; } void withLoading(handleSubmit()); }} onClose={handleClose} {...rest} > <ModalHeader title={c('Title').t`Change organization password`} /> <ModalContent> {hasOtherAdmins && ( <div className="mb-4"> {c('Info') .t`Other administrators exist in your organization, you are responsible for communicating the new password to them.`} </div> )} <Alert className="mb-4" type="warning"> {c('Info') .t`Do NOT forget this password. If you forget it, you will not be able to manage your organization.`} <br /> {c('Info').t`Save your password somewhere safe.`} </Alert> <InputFieldTwo id="organizationPassword" as={PasswordInputTwo} label={c('Label').t`New organization password`} placeholder={c('Placeholder').t`Password`} value={newPassword} onValue={setNewPassword} error={validator([passwordLengthValidator(newPassword)])} autoComplete="new-password" autoFocus /> <InputFieldTwo id="confirmPassword" as={PasswordInputTwo} label={c('Label').t`Confirm organization password`} placeholder={c('Placeholder').t`Confirm`} value={confirmPassword} onValue={setConfirmPassword} error={validator([ passwordLengthValidator(newPassword), confirmPasswordValidator(newPassword, confirmPassword), ])} autoComplete="new-password" /> </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={loading}> {c('Action').t`Close`} </Button> <Button loading={loading} type="submit" color="norm"> {c('Action').t`Save`} </Button> </ModalFooter> </Modal> </> ); }; export default ChangeOrganizationPasswordModal;
6,641
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/OrganizationNameModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { updateOrganizationName } from '@proton/shared/lib/api/organization'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { Organization } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import { Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, useFormErrors, } from '../../components'; import { useApi, useEventManager } from '../../hooks'; interface Props extends ModalProps { organization: Organization; } const OrganizationNameModal = ({ onClose, organization, ...rest }: Props) => { const api = useApi(); const { call } = useEventManager(); const [loading, withLoading] = useLoading(); const { validator, onFormSubmit } = useFormErrors(); const [name, setName] = useState(organization.Name); const handleSubmit = async () => { await api(updateOrganizationName(name)); await call(); onClose?.(); }; const handleClose = loading ? noop : onClose; const header = organization.RequiresKey ? c('Title').t`Change organization name` : c('familyOffer_2023:Title').t`Change family name`; const label = organization.RequiresKey ? c('Title').t`Organization name` : c('familyOffer_2023:Title').t`Family name`; return ( <Modal as={Form} onSubmit={() => { if (!onFormSubmit()) { return; } void withLoading(handleSubmit()); }} onClose={handleClose} {...rest} > <ModalHeader title={header} /> <ModalContent> <InputFieldTwo id="organization-name" label={label} placeholder={c('Placeholder').t`Choose a name`} error={validator([requiredValidator(name)])} autoFocus disableChange={loading} value={name} onValue={(value: string) => setName(value)} /> </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={loading}> {c('Action').t`Cancel`} </Button> <Button loading={loading} type="submit" color="norm"> {c('Action').t`Save`} </Button> </ModalFooter> </Modal> ); }; export default OrganizationNameModal;
6,642
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/OrganizationPasswordSection.tsx
import { MutableRefObject, useEffect } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Organization } from '@proton/shared/lib/interfaces'; import { getHasOtherAdmins, getNonPrivateMembers, getOrganizationKeyInfo, } from '@proton/shared/lib/organization/helper'; import { Alert, Block, Loader, Table, TableBody, TableHeader, TableRow } from '../../components'; import { useMembers, useModals, useNotifications, useOrganizationKey, useUser } from '../../hooks'; import { SettingsParagraph, SettingsSection } from '../account'; import ChangeOrganizationKeysModal from './ChangeOrganizationKeysModal'; import ChangeOrganizationPasswordModal from './ChangeOrganizationPasswordModal'; import ReactivateOrganizationKeysModal from './ReactivateOrganizationKeysModal'; import { getActivationText } from './helper'; import useDisplayOrganizationKey from './useDisplayOrganizationKey'; interface Props { organization?: Organization; onceRef: MutableRefObject<boolean>; } const OrganizationPasswordSection = ({ organization, onceRef }: Props) => { const [user] = useUser(); const [organizationKey, loadingOrganizationKey] = useOrganizationKey(organization); const organizationKeyInfo = getOrganizationKeyInfo(organization, organizationKey); const displayOrganizationKey = useDisplayOrganizationKey(organizationKey); const [members, loadingMembers] = useMembers(); const { createModal } = useModals(); const { createNotification } = useNotifications(); const hasOtherAdmins = members ? getHasOtherAdmins(members) : false; const publicMembers = members ? getNonPrivateMembers(members) : []; const tableHeaders = [c('Header').t`Organization key fingerprint`, c('Header').t`Key type`]; const handleChangeOrganizationKeys = (mode?: 'reset') => { if (!organizationKey) { throw new Error('Organization key not loaded'); } if (publicMembers.length > 0 && !organizationKey.privateKey) { return createNotification({ text: c('Error').t`You must privatize all users before generating new organization keys`, type: 'error', }); } createModal( <ChangeOrganizationKeysModal mode={mode} hasOtherAdmins={hasOtherAdmins} organizationKey={organizationKey} publicMembers={publicMembers} /> ); }; const handleResetOrganizationKeys = () => { handleChangeOrganizationKeys('reset'); }; const handleReactivateOrganizationKeys = () => { createModal(<ReactivateOrganizationKeysModal mode="reactivate" onResetKeys={handleResetOrganizationKeys} />); }; const handleActivateOrganizationKeys = () => { createModal(<ReactivateOrganizationKeysModal mode="activate" onResetKeys={handleResetOrganizationKeys} />); }; const handleChangeOrganizationPassword = () => { if (!organizationKey?.privateKey) { return createNotification({ text: c('Error').t`Organization key is not decrypted`, type: 'error' }); } createModal( <ChangeOrganizationPasswordModal hasOtherAdmins={hasOtherAdmins} organizationKey={organizationKey.privateKey} /> ); }; const loading = !organization || loadingMembers || loadingOrganizationKey; useEffect(() => { if (onceRef.current || loading || !organizationKey || !user.isAdmin || !organization?.HasKeys) { return; } const organizationKeyInfo = getOrganizationKeyInfo(organization, organizationKey); if (organizationKeyInfo.userNeedsToActivateKey) { handleActivateOrganizationKeys(); onceRef.current = true; } else if (organizationKeyInfo.userNeedsToReactivateKey) { handleReactivateOrganizationKeys(); onceRef.current = true; } }, [organization, organizationKey, user, loadingMembers]); if (loading) { return <Loader />; } // Organization is not setup. if (!organization?.HasKeys) { return <Alert className="mb-4" type="warning">{c('Info').t`Multi-user support not enabled.`}</Alert>; } return ( <SettingsSection> <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/organization-key')}> {c('Info') .t`Your organization's emails are protected with end-to-end encryption using the organization key. This fingerprint can be used to verify that all administrators in your account have the same key.`} </SettingsParagraph> <Block> {organizationKey?.privateKey && ( <> <Button color="norm" onClick={handleChangeOrganizationPassword} className="mr-4"> {c('Action').t`Change password`} </Button> <Button onClick={() => handleChangeOrganizationKeys()}> {c('Action').t`Change organization keys`} </Button> </> )} {organizationKeyInfo.userNeedsToReactivateKey && ( <> <Alert className="mb-4" type="error"> {c('Error') .t`You have lost access to your organization keys. Without restoration you will not be able to create new users, add addresses to existing users, or access non-private user accounts.`} </Alert> <Button onClick={handleResetOrganizationKeys} className="mr-4"> {c('Action').t`Reset organization keys`} </Button> <Button color="norm" onClick={handleReactivateOrganizationKeys} className="mr-4"> {c('Action').t`Restore administrator privileges`} </Button> </> )} {organizationKeyInfo.userNeedsToActivateKey && ( <> <Alert className="mb-4" type="error"> {getActivationText()} </Alert> <Button color="norm" onClick={handleActivateOrganizationKeys} className="mr-4"> {c('Action').t`Activate organization key`} </Button> <Button onClick={handleResetOrganizationKeys} className="mr-4"> {c('Action').t`Reset organization keys`} </Button> </> )} </Block> {displayOrganizationKey.fingerprint && ( <Table responsive="cards"> <TableHeader cells={tableHeaders} /> <TableBody colSpan={2}> <TableRow labels={tableHeaders} cells={[ <code key={1} className="max-w-full block text-ellipsis"> {displayOrganizationKey.fingerprint} </code>, displayOrganizationKey.algorithm, ]} /> </TableBody> </Table> )} </SettingsSection> ); }; export default OrganizationPasswordSection;
6,643
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/OrganizationSection.tsx
import { c } from 'ttag'; import { Button, ButtonLike } from '@proton/atoms'; import { createPreAuthKTVerifier } from '@proton/components/containers'; import useKTActivation from '@proton/components/containers/keyTransparency/useKTActivation'; import useLoading from '@proton/hooks/useLoading'; import { queryAvailableDomains } from '@proton/shared/lib/api/domains'; import { unlockPasswordChanges } from '@proton/shared/lib/api/user'; import innerMutatePassword from '@proton/shared/lib/authentication/mutate'; import { APPS, APP_NAMES, BRAND_NAME, DRIVE_APP_NAME, MAIL_APP_NAME, SHARED_UPSELL_PATHS, UPSELL_COMPONENT, } from '@proton/shared/lib/constants'; import { hasFamily } from '@proton/shared/lib/helpers/subscription'; import { getUpsellRefFromApp } from '@proton/shared/lib/helpers/upsell'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Audience, Organization } from '@proton/shared/lib/interfaces'; import { handleSetupAddressKeys } from '@proton/shared/lib/keys'; import { Credentials } from '@proton/shared/lib/srp'; import { Field, Label, Loader, PrimaryButton, Row, SettingsLink, useAppLink } from '../../components'; import { useApi, useAuthentication, useConfig, useGetAddresses, useModals, useNotifications, useSubscription, useUser, } from '../../hooks'; import { SettingsParagraph, SettingsSectionWide, UpgradeBanner } from '../account'; import AuthModal from '../password/AuthModal'; import OrganizationNameModal from './OrganizationNameModal'; import SetupOrganizationModal from './SetupOrganizationModal'; interface Props { app: APP_NAMES; organization?: Organization; onSetupOrganization?: () => void; } const OrganizationSection = ({ app, organization, onSetupOrganization }: Props) => { const { APP_NAME } = useConfig(); const { createModal } = useModals(); const [user] = useUser(); const getAddresses = useGetAddresses(); const api = useApi(); const [subscription] = useSubscription(); const appLink = useAppLink(); const [loading, withLoading] = useLoading(); const ktActivation = useKTActivation(); const authentication = useAuthentication(); const { createNotification } = useNotifications(); const isPartOfFamily = hasFamily(subscription); if (!organization || !user || !subscription) { return <Loader />; } // Upsell if (organization.MaxMembers === 1) { return ( <SettingsSectionWide> <SettingsParagraph> {c('new_plans: info') .t`${BRAND_NAME} lets you create email addresses and manage accounts for sub-users. Ideal for families and organizations.`} </SettingsParagraph> <UpgradeBanner free={user.isFree} audience={Audience.B2B} upsellPath={getUpsellRefFromApp({ app: APP_NAME, feature: SHARED_UPSELL_PATHS.MULTI_USER, component: UPSELL_COMPONENT.BANNER, fromApp: app, })} >{c('new_plans: upgrade') .t`Included with multiple users ${BRAND_NAME} for Business plans.`}</UpgradeBanner> </SettingsSectionWide> ); } if (organization.RequiresDomain && organization.UsedDomains === 0) { return ( <> <SettingsParagraph> {c('Info') .t`Create email addresses for other people, manage ${MAIL_APP_NAME} for a business, school, or group. Get started by adding your organization name and custom domain (e.g. @yourcompany.com). `} </SettingsParagraph> <ButtonLike color="norm" as={SettingsLink} path="/domain-names" app={APPS.PROTONMAIL}> {c('Action').t`Add domain`} </ButtonLike> </> ); } if (!organization.RequiresKey && !organization.Name) { const buttonCTA = hasFamily(subscription) ? c('familyOffer_2023:Action').t`Set up family group` : c('Action').t`Enable multi-user support`; return ( <> <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl( isPartOfFamily ? '/get-started-proton-family' : '/proton-for-business' )} > {c('familyOffer_2023:Info') .t`Create and manage family members and assign them storage space shared between ${DRIVE_APP_NAME} and ${MAIL_APP_NAME}.`} </SettingsParagraph> <PrimaryButton onClick={async () => { if (organization?.MaxMembers === 1) { return createNotification({ type: 'error', text: c('Error') .t`Please upgrade to a business plan with more than 1 user to get multi-user support`, }); } await new Promise((resolve, reject) => { createModal( <AuthModal onCancel={reject} onSuccess={resolve} config={unlockPasswordChanges()} /> ); }); onSetupOrganization?.(); createModal(<SetupOrganizationModal />); }} > {buttonCTA} </PrimaryButton> </> ); } if (organization.RequiresKey && !organization.HasKeys) { return ( <> <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/proton-for-business')}> {c('Info').t`Create and manage sub-accounts and assign them email addresses on your custom domain.`} </SettingsParagraph> <PrimaryButton loading={loading} onClick={async () => { if (organization?.MaxMembers === 1) { return createNotification({ type: 'error', text: c('Error') .t`Please upgrade to a business plan with more than 1 user to get multi-user support`, }); } const run = async () => { const { credentials } = await new Promise<{ credentials: Credentials; }>((resolve, reject) => { createModal( <AuthModal onCancel={reject} onSuccess={resolve} config={unlockPasswordChanges()} /> ); }); // VPN username only users might arrive here through the VPN business plan in protonvpn.com if (user.isPrivate && !user.Keys.length) { const [addresses, domains] = await Promise.all([ getAddresses(), api<{ Domains: string[]; }>(queryAvailableDomains('signup')).then(({ Domains }) => Domains), ]); const preAuthKTVerifier = createPreAuthKTVerifier(ktActivation, api); const passphrase = await handleSetupAddressKeys({ addresses, api, username: user.Name, password: credentials.password, domains, preAuthKTVerify: preAuthKTVerifier.preAuthKTVerify, }); await innerMutatePassword({ api, authentication, keyPassword: passphrase, User: user, }); await preAuthKTVerifier.preAuthKTCommit(user.ID); } onSetupOrganization?.(); createModal(<SetupOrganizationModal />); }; withLoading(run()); }} >{c('Action').t`Enable multi-user support`}</PrimaryButton> </> ); } const organizationName = organization.Name; const inputLabel = isPartOfFamily ? c('familyOffer_2023:Label').t`Family name` : c('Label').t`Organization name`; return ( <> <SettingsParagraph> {c('Info').t`The name will be visible to your users while they are signed in.`} </SettingsParagraph> <Row> <Label htmlFor="organization-name-edit-button">{inputLabel}</Label> <Field className="pt-2"> <div className="text-bold text-ellipsis">{organizationName}</div> </Field> <div className="ml-0 md:ml-4"> <Button id="organization-name-edit-button" color="norm" onClick={() => createModal(<OrganizationNameModal organization={organization} />)} >{c('Action').t`Edit`}</Button> </div> </Row> {isPartOfFamily && ( <Row> <Button onClick={() => appLink('/mail/users-addresses', APPS.PROTONACCOUNT)}>{c( 'familyOffer_2023:Action' ).t`Invite member to your family`}</Button> </Row> )} </> ); }; export default OrganizationSection;
6,644
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/OrganizationSpamFiltersSection.tsx
import { c } from 'ttag'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { SettingsParagraph, SettingsSectionWide } from '../account'; import Spams from '../filters/spams/Spams'; const OrganizationSpamFiltersSection = () => ( <SettingsSectionWide> <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/filter-lists-organization')}> {c('FilterSettings') .t`Take control over what lands in your organization members' inboxes by creating the following lists:`} <ul className="mt-2"> <li> <strong>{c('FilterSettings').t`Spam:`}</strong>{' '} {c('FilterSettings').t`To prevent junk mail from clogging up inboxes`} </li> <li> <strong>{c('FilterSettings').t`Block:`}</strong>{' '} {c('FilterSettings') .t`To stop phishing or suspicious emails from entering your organization's email system`} </li> <li> <strong>{c('FilterSettings').t`Allow:`}</strong>{' '} {c('FilterSettings').t`To ensure critical messages don't end up in spam and getting missed`} </li> </ul> {c('FilterSettings') .t`These lists apply to all accounts in your organization. Members can create their own individual filters, but won't be able to override addresses or domains you blocked.`} </SettingsParagraph> <Spams isOrganization /> </SettingsSectionWide> ); export default OrganizationSpamFiltersSection;
6,645
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/OrganizationTwoFAEnforcementSection.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Alert, Info, useApi } from '@proton/components'; import { queryEnforceTwoFA, queryRemoveTwoFA } from '@proton/shared/lib/api/organization'; import { APPS, ORGANIZATION_TWOFA_SETTING } from '@proton/shared/lib/constants'; import { hasTwoFARequiredForAdminOnly, hasTwoFARequiredForAll } from '@proton/shared/lib/helpers/organization'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Organization } from '@proton/shared/lib/interfaces'; import { Label, Loader, Row, Toggle } from '../../components'; import { useConfig, useNotifications } from '../../hooks'; import { SettingsParagraph } from '../account'; interface Props { organization?: Organization; } const OrganizationTwoFAEnforcementSection = ({ organization }: Props) => { const api = useApi(); const { APP_NAME } = useConfig(); const [isTwoFARequiredForAdminOnlyChecked, setIsTwoFARequiredForAdminOnlyChecked] = useState( hasTwoFARequiredForAdminOnly(organization) ); const [isTwoFARequiredForAllChecked, setIsTwoFARequiredForAllChecked] = useState( hasTwoFARequiredForAll(organization) ); const { createNotification } = useNotifications(); if (!organization) { return <Loader />; } // Organization is not setup. if (!organization?.HasKeys) { return <Alert className="mb-1" type="warning">{c('Info').t`Multi-user support not enabled.`}</Alert>; } const handleEnforceTwoFA = async (require: number) => { await api(queryEnforceTwoFA(require)); if (require === ORGANIZATION_TWOFA_SETTING.REQUIRED_ADMIN_ONLY) { setIsTwoFARequiredForAdminOnlyChecked(true); setIsTwoFARequiredForAllChecked(false); createNotification({ text: c('Notification').t`Two-factor authentication has been enforced for administrators`, }); return; } setIsTwoFARequiredForAdminOnlyChecked(true); setIsTwoFARequiredForAllChecked(true); createNotification({ text: c('Notification').t`Two-factor authentication has been enforced for all members`, }); }; const handleRemoveTwoFA = async () => { await api(queryRemoveTwoFA()); setIsTwoFARequiredForAdminOnlyChecked(false); setIsTwoFARequiredForAllChecked(false); createNotification({ text: c('Notification').t`Two-factor authentication is not required anymore`, }); }; return ( <> <SettingsParagraph> {c('Info') .t`We recommend notifying the organization members and asking them to set up 2FA for their accounts before enforcing the use of 2FA.`} </SettingsParagraph> <Row> <Label> <span className="mr-0.5">{c('Label').t`Require 2FA for administrators`}</span> <span className="hidden md:inline"> <Info url={ APP_NAME === APPS.PROTONVPN_SETTINGS ? 'https://protonvpn.com/support/require-2fa-organization' : getKnowledgeBaseUrl('/two-factor-authentication-2fa') } /> </span> </Label> <div className="flex flex-align-items-center"> <Toggle id="two-fa-admin" className="mr-0.5 pt-0.5" checked={isTwoFARequiredForAdminOnlyChecked || isTwoFARequiredForAllChecked} disabled={isTwoFARequiredForAllChecked} onChange={() => !isTwoFARequiredForAdminOnlyChecked ? handleEnforceTwoFA(ORGANIZATION_TWOFA_SETTING.REQUIRED_ADMIN_ONLY) : handleRemoveTwoFA() } /> </div> </Row> <Row> <Label> <span className="mr-0.5">{c('Label').t`Require 2FA for everyone`}</span> <span className="hidden md:inline"> <Info url={ APP_NAME === APPS.PROTONVPN_SETTINGS ? 'https://protonvpn.com/support/require-2fa-organization' : getKnowledgeBaseUrl('/two-factor-authentication-2fa') } /> </span> </Label> <div className="flex flex-align-items-center"> <Toggle id="two-fa-member" className="mr-0.5 pt-0.5" checked={isTwoFARequiredForAllChecked} onChange={() => !isTwoFARequiredForAllChecked ? handleEnforceTwoFA(ORGANIZATION_TWOFA_SETTING.REQUIRED_ALL) : handleRemoveTwoFA() } /> </div> </Row> </> ); }; export default OrganizationTwoFAEnforcementSection;
6,646
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/OrganizationTwoFAHeader.tsx
import { c, msgid } from 'ttag'; import { Card } from '@proton/atoms'; import { Alert, useMembers } from '@proton/components'; import { Organization } from '@proton/shared/lib/interfaces'; import { Loader } from '../../components'; interface Props { organization?: Organization; } const OrganizationTwoFAHeader = ({ organization }: Props) => { const [members, loadingMembers] = useMembers(); if (!organization || loadingMembers) { return <Loader />; } // Organization is not setup. if (!organization?.HasKeys) { return <Alert className="mb-1" type="warning">{c('Info').t`Multi-user support not enabled.`}</Alert>; } const twoFAMembers = members.filter((member) => member['2faStatus'] !== 0) || []; // translator: the variables here are numbers, e.g. "2/4 of your organization members use two-factor authentication." const cardContent = c('Loading info').ngettext( msgid`${twoFAMembers.length}/${members.length} of your organization member use two-factor authentication.`, `${twoFAMembers.length}/${members.length} of your organization members use two-factor authentication.`, members.length ); return ( <Card rounded background bordered={false} className="max-w-custom" style={{ '--max-w-custom': '43em' }}> {cardContent} </Card> ); }; export default OrganizationTwoFAHeader;
6,647
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/OrganizationTwoFARemindersSection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Alert, Info, useConfig, useMembers, useModals } from '@proton/components'; import { APPS } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Organization } from '@proton/shared/lib/interfaces'; import { Label, Loader, Row } from '../../components'; import { SettingsParagraph } from '../account'; import SendEmailReminderTwoFAModal from './SendEmailReminderTwoFAModal'; interface Props { organization?: Organization; } const OrganizationTwoFARemindersSection = ({ organization }: Props) => { const { APP_NAME } = useConfig(); const { createModal } = useModals(); const [members, loadingMembers] = useMembers(); if (!organization || loadingMembers) { return <Loader />; } // Organization is not setup. if (!organization?.HasKeys) { return <Alert className="mb-1" type="warning">{c('Info').t`Multi-user support not enabled.`}</Alert>; } const noTwoFAMembers = members.filter((member) => (member.State === undefined || member.State === 1) && member['2faStatus'] === 0) || []; return ( <> <SettingsParagraph learnMoreUrl={ APP_NAME === APPS.PROTONVPN_SETTINGS ? 'https://protonvpn.com/support/require-2fa-organization' : getKnowledgeBaseUrl('/two-factor-authentication-organization') } > {c('Info').t`Send emails to encourage your members to protect their accounts with 2FA.`} </SettingsParagraph> <Row className="mt-1"> <Label> <span className="mr-0.5">{c('Label').t`Email`}</span> <span className="hidden md:inline"> <Info title={c('Tooltip') .t`Members who do not use 2FA will get an email asking them to enable it as soon as possible.`} /> </span> </Label> <div className="flex flex-align-items-center"> <Button id="send-email-reminder-button" onClick={() => createModal(<SendEmailReminderTwoFAModal members={noTwoFAMembers} />)} disabled={noTwoFAMembers.length === 0} >{c('Action').t`Send email reminder`}</Button> </div> </Row> </> ); }; export default OrganizationTwoFARemindersSection;
6,648
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/ReactivateOrganizationKeysModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { CryptoProxy, PrivateKeyReference } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { activateOrganizationKey, getOrganizationBackupKeys } from '@proton/shared/lib/api/organization'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { decryptPrivateKeyWithSalt } from '@proton/shared/lib/keys'; import { OrganizationModel } from '@proton/shared/lib/models'; import noop from '@proton/utils/noop'; import { Alert, Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, PasswordInputTwo, useFormErrors, } from '../../components'; import { useApi, useAuthentication, useCache, useEventManager, useNotifications } from '../../hooks'; interface Props extends ModalProps { mode: 'reactivate' | 'activate'; onResetKeys?: () => void; } const ReactivateOrganizationKeysModal = ({ onResetKeys, mode, onClose, ...rest }: Props) => { const cache = useCache(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const authentication = useAuthentication(); const api = useApi(); const { validator, onFormSubmit } = useFormErrors(); const [loading, withLoading] = useLoading(); const [backupPassword, setBackupPassword] = useState(''); const [error, setError] = useState(''); const { title, message, warning, success } = (() => { if (mode === 'activate') { return { title: c('Title').t`Activate organization key`, message: c('Info') .t`You must activate your organization private key with the backup organization key password provided to you by your organization administrator.`, warning: c('Info') .t`Without activation you will not be able to create new users, add addresses to existing users, or access non-private user accounts.`, success: c('Info').t`Organization keys activated`, }; } if (mode === 'reactivate') { const learnMore = ( <Href key={1} href={getKnowledgeBaseUrl('/restore-administrator')}> {c('Link').t`Learn more`} </Href> ); return { title: c('Title').t`Restore administrator privileges`, message: c('Info') .jt`Enter the Organization Password to restore administrator privileges. ${learnMore}`, warning: c('Info') .t`If another administrator changed this password, you will need to ask them for the new Organization Password.`, success: c('Info').t`Organization keys restored`, }; } throw new Error('Invalid mode'); })(); const handleSubmit = async () => { try { setError(''); const { PrivateKey, KeySalt } = await api(getOrganizationBackupKeys()); let decryptedPrivateKey: PrivateKeyReference; try { decryptedPrivateKey = await decryptPrivateKeyWithSalt({ PrivateKey, password: backupPassword, keySalt: KeySalt, }); } catch (e) { throw new Error(c('Error').t`Incorrect password`); } const armoredPrivateKey = await CryptoProxy.exportPrivateKey({ privateKey: decryptedPrivateKey, passphrase: authentication.getPassword(), }); await api(activateOrganizationKey(armoredPrivateKey)); await call(); // Warning: The organization model is deleted because there is no event manager notification for when the // organization key gets reactivated. Thus the organization is deleted from the cache which would trigger // the organizationKeys hook to re-run. cache.delete(OrganizationModel.key); createNotification({ text: success }); onClose?.(); } catch (e: any) { setError(e.message); } }; const handleClose = loading ? noop : onClose; return ( <Modal as={Form} onSubmit={() => { if (!onFormSubmit()) { return; } void withLoading(handleSubmit()); }} onClose={handleClose} {...rest} > <ModalHeader title={title} /> <ModalContent> <div className="mb-4">{message}</div> <Alert className="mb-4" type="warning"> {warning} </Alert> <InputFieldTwo id="organizationPassword" as={PasswordInputTwo} label={c('Label').t`Organization password`} placeholder={c('Placeholder').t`Password`} value={backupPassword} onValue={(value: string) => { setError(''); setBackupPassword(value); }} error={validator([requiredValidator(backupPassword), error])} autoComplete="off" autoFocus /> </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={loading}> {c('Action').t`Close`} </Button> <div> {onResetKeys && ( <Button className="mr-4" onClick={() => { onClose?.(); onResetKeys(); }} >{c('Action').t`Reset keys`}</Button> )} <Button loading={loading} type="submit" color="norm"> {c('Action').t`Save`} </Button> </div> </ModalFooter> </Modal> ); }; export default ReactivateOrganizationKeysModal;
6,649
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/RestoreAdministratorPrivileges.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { getHasOtherAdmins, getNonPrivateMembers, getOrganizationKeyInfo, } from '@proton/shared/lib/organization/helper'; import { Alert, Block, useModalState } from '../../components'; import { useMembers, useNotifications, useOrganization, useOrganizationKey } from '../../hooks'; import ChangeOrganizationKeysModal from './ChangeOrganizationKeysModal'; import ReactivateOrganizationKeysModal from './ReactivateOrganizationKeysModal'; import { getActivationText } from './helper'; const UserNeedsToReactivate = ({ onRestorePrivilegesClick }: { onRestorePrivilegesClick: () => void }) => { return ( <Block> <Alert className="mb-4" type="error"> <div> {c('Restore administrator panel') .t`Due to a password change, your organization administrator privileges have been restricted. The following actions are no longer permitted:`} </div> <ul className="mb-0"> <li>{c('Restore administrator panel').t`Creating or accessing non-private users`}</li> <li>{c('Restore administrator panel').t`Changing organization password`}</li> <li>{c('Restore administrator panel').t`Changing organization keys`}</li> </ul> </Alert> <Button color="norm" className="mr-4" onClick={onRestorePrivilegesClick}> {c('Action').t`Restore administrator privileges`} </Button> <Href href={getKnowledgeBaseUrl('/proton-for-business')} className="inline-block"> {c('Link').t`Learn more`} </Href> </Block> ); }; const UserNeedsToActivate = ({ onActiveOrganizationKeyClick }: { onActiveOrganizationKeyClick: () => void }) => { return ( <Block> <Alert className="mb-4" type="error"> {getActivationText()} </Alert> <Button color="norm" onClick={onActiveOrganizationKeyClick}> {c('Action').t`Activate organization key`} </Button> </Block> ); }; const RestoreAdministratorPrivileges = () => { const [members, loadingMembers] = useMembers(); const { createNotification } = useNotifications(); const [organization, loadingOrganization] = useOrganization(); const [organizationKey, loadingOrganizationKey] = useOrganizationKey(organization); const [ reactivateOrganizationKeysModalProps, setReactivateOrganizationKeysModalOpen, renderReactivateOrganizationKeysModal, ] = useModalState(); const [ activateOrganizationKeysModalProps, setActivateOrganizationKeysModalOpen, renderActivateOrganizationKeysModal, ] = useModalState(); const [changeOrganizationKeysModalProps, setChangeOrganizationKeysModalOpen, renderChangeOrganizationKeysModal] = useModalState(); const organizationKeyInfo = getOrganizationKeyInfo(organization, organizationKey); const hasOtherAdmins = members ? getHasOtherAdmins(members) : false; const publicMembers = members ? getNonPrivateMembers(members) : []; const handleResetOrganizationKeys = () => { if (!organizationKey) { throw new Error('Organization key not loaded'); } if (publicMembers.length > 0 && !organizationKey.privateKey) { return createNotification({ text: c('Error').t`You must privatize all users before generating new organization keys`, type: 'error', }); } setChangeOrganizationKeysModalOpen(true); }; if (!organizationKey || loadingOrganization || loadingOrganizationKey || !organization?.HasKeys || loadingMembers) { return null; } return ( <> {renderActivateOrganizationKeysModal && ( <ReactivateOrganizationKeysModal mode="activate" onResetKeys={handleResetOrganizationKeys} {...activateOrganizationKeysModalProps} /> )} {renderReactivateOrganizationKeysModal && ( <ReactivateOrganizationKeysModal mode="reactivate" onResetKeys={handleResetOrganizationKeys} {...reactivateOrganizationKeysModalProps} /> )} {renderChangeOrganizationKeysModal && ( <ChangeOrganizationKeysModal mode="reset" hasOtherAdmins={hasOtherAdmins} organizationKey={organizationKey} publicMembers={publicMembers} {...changeOrganizationKeysModalProps} /> )} {(() => { if (organizationKeyInfo.userNeedsToReactivateKey) { return ( <UserNeedsToReactivate onRestorePrivilegesClick={() => setReactivateOrganizationKeysModalOpen(true)} /> ); } if (organizationKeyInfo.userNeedsToActivateKey) { return ( <UserNeedsToActivate onActiveOrganizationKeyClick={() => setActivateOrganizationKeysModalOpen(true)} /> ); } })()} </> ); }; export default RestoreAdministratorPrivileges;
6,650
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/SendEmailReminderTwoFAModal.tsx
import { c } from 'ttag'; import { Avatar, Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { sendEmailReminderTwoFA } from '@proton/shared/lib/api/organization'; import { MEMBER_ROLE } from '@proton/shared/lib/constants'; import { getInitials } from '@proton/shared/lib/helpers/string'; import { Member } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import { Badge, Form, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, useFormErrors, } from '../../components'; import { useApi, useEventManager, useMemberAddresses, useNotifications } from '../../hooks'; interface Props extends ModalProps { members: Member[]; } const SendEmailReminderTwoFAModal = ({ onClose, members, ...rest }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const { onFormSubmit } = useFormErrors(); const [loading, withLoading] = useLoading(); const [memberAddressesMap] = useMemberAddresses(members, true); const handleSubmit = async () => { await api(sendEmailReminderTwoFA()); await call(); createNotification({ text: c('Notification').t`Reminder has been sent` }); onClose?.(); }; const handleClose = loading ? noop : onClose; return ( <Modal as={Form} onSubmit={() => { if (!onFormSubmit()) { return; } void withLoading(handleSubmit()); }} onClose={handleClose} {...rest} > <ModalHeader title={c('Title').t`Send email reminders?`} /> <ModalContent> <p>{c('Info') .t`The following members will receive an email prompting them to enable two-factor authentication as soon as possible.`}</p> <ul className="unstyled"> {members .filter(function (member) { const memberAddresses = memberAddressesMap?.[member.ID] || []; return memberAddresses.length > 0; }) .map((member) => { const memberAddresses = memberAddressesMap?.[member.ID] || []; return ( <li className="py-2 flex flex-nowrap flex-align-items-center border-bottom" title={member.Name} > <Avatar className="mr-2 flex-item-noshrink">{getInitials(member.Name)}</Avatar> <div className="flex-items-fluid"> <div className="text-ellipsis max-100" title={member.Name}> {member.Name} </div> <div className="max-w-full flex flex-"> <span className="flex-item-fluid mr-2 text-ellipsis"> {memberAddresses[0].Email} </span> {member.Role === MEMBER_ROLE.ORGANIZATION_ADMIN && ( <span className="flex-item-noshrink"> <Badge type="light">{c('Admin').t`admin`}</Badge> </span> )} </div> </div> </li> ); })} </ul> </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={loading}> {c('Action').t`Cancel`} </Button> <Button loading={loading} type="submit" color="norm" disabled={loading}> {c('Action').t`Send reminder`} </Button> </ModalFooter> </Modal> ); }; export default SendEmailReminderTwoFAModal;
6,651
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/SetupOrganizationModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { updateQuota, updateVPN } from '@proton/shared/lib/api/members'; import { updateOrganizationKeysLegacy, updateOrganizationKeysV2, updateOrganizationName, } from '@proton/shared/lib/api/organization'; import { ENCRYPTION_CONFIGS, ENCRYPTION_TYPES, GIGA, VPN_CONNECTIONS } from '@proton/shared/lib/constants'; import { confirmPasswordValidator, getMinPasswordLengthMessage, passwordLengthValidator, requiredValidator, } from '@proton/shared/lib/helpers/formValidators'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { getHasVpnB2BPlan } from '@proton/shared/lib/helpers/subscription'; import { generateOrganizationKeys, getHasMigratedAddressKeys } from '@proton/shared/lib/keys'; import clamp from '@proton/utils/clamp'; import noop from '@proton/utils/noop'; import { Alert, Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, PasswordInputTwo, useFormErrors, useSettingsLink, } from '../../components'; import { useAddresses, useApi, useAuthentication, useEventManager, useMembers, useNotifications, useOrganization, useSubscription, useUser, } from '../../hooks'; import MemberStorageSelector, { getStorageRange, getTotalStorage } from '../members/MemberStorageSelector'; enum STEPS { NAME, PASSWORD, STORAGE, } const SetupOrganizationModal = ({ onClose, ...rest }: ModalProps) => { const api = useApi(); const authentication = useAuthentication(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const goToSettings = useSettingsLink(); const [addresses] = useAddresses(); const [members = [], loadingMembers] = useMembers(); const [loading, withLoading] = useLoading(); const [organization] = useOrganization(); const [step, setStep] = useState<STEPS>(STEPS.NAME); const storageSizeUnit = GIGA; const [{ hasPaidVpn }] = useUser(); const [subscription] = useSubscription(); const hasVpnB2BPlan = getHasVpnB2BPlan(subscription); const selfMember = members.find(({ Self }) => !!Self); const storageRange = getStorageRange(selfMember, organization); const [model, setModel] = useState({ name: '', password: '', confirm: '', storage: -1, }); const { validator, onFormSubmit, reset } = useFormErrors(); const handleChange = (key: keyof typeof model) => { return (value: any) => setModel({ ...model, [key]: value }); }; const selfMemberID = selfMember?.ID; const minStorage = organization.RequiresKey ? 5 : 500; // Storage can be undefined in the beginning because org is undefined. So we keep it floating until it's set. const storageValue = model.storage === -1 ? clamp(minStorage * GIGA, storageRange.min, storageRange.max) : model.storage; const finalizeOrganizationCreation = async () => { await call(); createNotification({ text: c('Success').t`Organization activated` }); onClose?.(); goToSettings('/users-addresses'); }; const setStepStorage = async () => { if (hasVpnB2BPlan) { // If user setting up organization for VPN B2B plan then the storage step must be skipped. await finalizeOrganizationCreation(); } else { setStep(STEPS.STORAGE); } }; const { title, onSubmit, section } = (() => { if (step === STEPS.NAME) { const title = organization.RequiresKey ? c('Title').t`Set organization name` : c('familyOffer_2023:Title').t`Set family name`; const label = organization.RequiresKey ? c('Label').t`Organization name` : c('familyOffer_2023:Label').t`Family name`; return { title, section: ( <InputFieldTwo id="organization-name" label={label} placeholder={c('Placeholder').t`Choose a name`} error={validator([requiredValidator(model.name)])} autoFocus disableChange={loading} value={model.name} onValue={handleChange('name')} /> ), async onSubmit() { if (!selfMemberID) { throw new Error('Missing member id'); } // NOTE: By default the admin gets allocated all of the VPN connections. Here we artificially set the admin to the default value // So that other users can get connections allocated. await (hasPaidVpn && api(updateVPN(selfMemberID, VPN_CONNECTIONS))); await api(updateOrganizationName(model.name)); if (organization.RequiresKey) { setStep(STEPS.PASSWORD); } else { await setStepStorage(); } }, }; } if (step === STEPS.PASSWORD) { return { title: c('Title').t`Set organization password`, section: ( <> <div className="mb-4"> {c('Info') .t`Your organization password can be shared with other users you wish to give administrative privileges. It is also an emergency recovery code to gain access to your organization in case you lose access to your account. Please save this password and keep it safe.`} </div> <Alert className="mb-4" type="warning"> {c('Info') .t`Do NOT forget this password. If you forget it, you will not be able to sign in or decrypt your messages.`} <br /> {c('Info') .t`Save your password somewhere safe. Click on icon to confirm that you have typed your password correctly.`} </Alert> <InputFieldTwo autoFocus id="orgPassword" as={PasswordInputTwo} label={c('Label').t`Organization password`} placeholder={c('Placeholder').t`Password`} value={model.password} onValue={handleChange('password')} assistiveText={getMinPasswordLengthMessage()} error={validator([passwordLengthValidator(model.password)])} autoComplete="new-password" /> <InputFieldTwo id="confirmPassword" as={PasswordInputTwo} label={c('Label').t`Confirm password`} placeholder={c('Placeholder').t`Confirm`} value={model.confirm} onValue={handleChange('confirm')} error={validator([ passwordLengthValidator(model.confirm), confirmPasswordValidator(model.confirm, model.password), ])} autoComplete="new-password" /> </> ), async onSubmit() { const { privateKeyArmored, backupKeySalt, backupArmoredPrivateKey } = await generateOrganizationKeys({ keyPassword: authentication.getPassword(), backupPassword: model.password, encryptionConfig: ENCRYPTION_CONFIGS[ENCRYPTION_TYPES.CURVE25519], }); if (getHasMigratedAddressKeys(addresses)) { await api( updateOrganizationKeysV2({ PrivateKey: privateKeyArmored, BackupPrivateKey: backupArmoredPrivateKey, BackupKeySalt: backupKeySalt, Members: [], }) ); } else { await api( updateOrganizationKeysLegacy({ PrivateKey: privateKeyArmored, BackupPrivateKey: backupArmoredPrivateKey, BackupKeySalt: backupKeySalt, Tokens: [], }) ); } await setStepStorage(); }, }; } if (step === STEPS.STORAGE) { const formattedStorage = humanSize(storageValue); return { title: c('Title').t`Allocate storage`, section: ( <> <div className="mb-7"> {c('familyOffer_2023:Info') .t`By default we assign ${formattedStorage} of storage to the administrator account. You can manage the assigned storage to be distributed among additional users later on.`} </div> <MemberStorageSelector orgInitialization value={storageValue} sizeUnit={storageSizeUnit} totalStorage={getTotalStorage(selfMember, organization)} range={storageRange} onChange={handleChange('storage')} /> </> ), async onSubmit() { if (!selfMemberID) { throw new Error('Missing member id'); } await api(updateQuota(selfMemberID, storageValue)); await finalizeOrganizationCreation(); }, }; } throw new Error('Unknown step'); })(); const handleClose = loading ? noop : onClose; const handleBack = () => { if (organization.RequiresKey && step) { setStep(step - 1); return; } // Going back when the organization don't requires a key should take user back to the name step if (!organization.RequiresKey && step === STEPS.STORAGE) { setStep(STEPS.NAME); return; } setStep(step - 1); }; return ( <Modal as={Form} onSubmit={() => { if (!onFormSubmit()) { return; } void withLoading(onSubmit()).then(reset); }} onClose={handleClose} size="medium" {...rest} > <ModalHeader title={title} /> <ModalContent>{section}</ModalContent> <ModalFooter> {step ? ( <Button onClick={handleBack} disabled={loading}> {c('Action').t`Back`} </Button> ) : ( <Button onClick={handleClose} disabled={loading}> {c('Action').t`Close`} </Button> )} <Button disabled={loadingMembers} loading={loading} type="submit" color="norm"> {c('Action').t`Submit`} </Button> </ModalFooter> </Modal> ); }; export default SetupOrganizationModal;
6,652
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/helper.ts
import { c } from 'ttag'; export const getActivationText = () => { return c('Error') .t`You must activate your organization keys. Without activation you will not be able to create or access non-private users.`; };
6,653
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/index.ts
export { default as OrganizationSection } from './OrganizationSection'; export { default as OrganizationPasswordSection } from './OrganizationPasswordSection'; export { default as OrganizationSpamFiltersSection } from './OrganizationSpamFiltersSection'; export { default as OrganizationTwoFAHeader } from './OrganizationTwoFAHeader'; export { default as OrganizationTwoFAEnforcementSection } from './OrganizationTwoFAEnforcementSection'; export { default as OrganizationTwoFARemindersSection } from './OrganizationTwoFARemindersSection';
6,654
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/organization/useDisplayOrganizationKey.ts
import { useEffect, useMemo, useState } from 'react'; import { CryptoProxy, PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; import { CachedOrganizationKey } from '@proton/shared/lib/interfaces'; import { getFormattedAlgorithmName } from '@proton/shared/lib/keys'; const useDisplayOrganizationKey = (organizationKey?: CachedOrganizationKey) => { const [parsedKey, setParsedKey] = useState<PublicKeyReference | PrivateKeyReference>(); useEffect(() => { void (async () => { if (!organizationKey) { setParsedKey(undefined); return; } if (organizationKey.privateKey) { setParsedKey(organizationKey.privateKey); return; } if (organizationKey.Key.PrivateKey) { // We import the key as PublicKey since importing it as PrivateKey requires knowing the passphrase to decrypt it. const key = await CryptoProxy.importPublicKey({ armoredKey: organizationKey.Key.PrivateKey }).catch( () => undefined ); setParsedKey(key); return; } setParsedKey(undefined); })(); }, [organizationKey]); return useMemo(() => { const algorithmInfo = parsedKey?.getAlgorithmInfo() ?? { algorithm: '' }; const fingerprint = parsedKey?.getFingerprint() ?? ''; const isDecrypted = parsedKey?.isPrivate() ?? false; return { algorithm: getFormattedAlgorithmName(algorithmInfo), fingerprint, isDecrypted, }; }, [parsedKey]); }; export default useDisplayOrganizationKey;
6,655
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/otherMailPreferences/OtherMailPreferencesSection.tsx
import { FeatureCode, useFeature } from '../..'; import { SenderImages } from './SenderImages'; import { UnreadFaviconCounter } from './UnreadFaviconCounter'; export const OtherMailPreferencesSection = () => { const isUnreadFaviconEnabled = !!useFeature(FeatureCode.UnreadFavicon).feature?.Value; return ( <div className="mt-8"> <SenderImages /> {isUnreadFaviconEnabled && <UnreadFaviconCounter />} </div> ); };
6,656
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/otherMailPreferences/SenderImages.tsx
import { c } from 'ttag'; import { Info } from '../../components'; import { SettingsLayout, SettingsLayoutLeft, SettingsLayoutRight } from '../account'; import SenderImagesToggle from './SenderImagesToggle'; export const SenderImages = () => { return ( <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="senderImagesToggle"> <span className="text-semibold mr-2">{c('Label').t`Show sender images`}</span> <Info title={c('Tooltip') .t`Show each sender's image in the message list. The sender's initials will be shown if a photo is not available.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <SenderImagesToggle className="mr-4" id="senderImagesToggle" /> </SettingsLayoutRight> </SettingsLayout> ); };
6,657
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/otherMailPreferences/SenderImagesToggle.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateHideSenderImages } from '@proton/shared/lib/api/mailSettings'; import { Toggle } from '../../components'; import { useApi, useEventManager, useMailSettings, useNotifications, useToggle } from '../../hooks'; interface Props { id?: string; className?: string; } const SenderImagesToggle = ({ id, className }: Props) => { const [mailSettings] = useMailSettings(); const { state, toggle } = useToggle(!mailSettings?.HideSenderImages); const { call } = useEventManager(); const { createNotification } = useNotifications(); const api = useApi(); const [loading, withLoading] = useLoading(); const handleChange = async (checked: boolean) => { await api(updateHideSenderImages(+!checked)); await call(); toggle(); createNotification({ text: c('Success').t`Preference saved` }); }; return ( <Toggle id={id} className={className} checked={state} onChange={({ target }) => withLoading(handleChange(target.checked))} loading={loading} /> ); }; export default SenderImagesToggle;
6,658
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/otherMailPreferences/UnreadFaviconCounter.tsx
import { c } from 'ttag'; import { Info } from '../../components'; import { SettingsLayout, SettingsLayoutLeft, SettingsLayoutRight } from '../account'; import { UnreadFaviconCounterToggle } from './UnreadFaviconCounterToggle'; export const UnreadFaviconCounter = () => { return ( <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="unreadFaviconCounterToggle"> <span className="text-semibold mr-2">{c('Label').t`Show unread count in Favicon`}</span> <Info title={c('Tooltip').t`See number of unread messages in the tab icon`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <UnreadFaviconCounterToggle className="mr-4" id="unreadFaviconCounterToggle" /> </SettingsLayoutRight> </SettingsLayout> ); };
6,659
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/otherMailPreferences/UnreadFaviconCounterToggle.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateDisplayUnreadFavicon } from '@proton/shared/lib/api/mailSettings'; import { Toggle } from '../../components'; import { useApi, useEventManager, useMailSettings, useNotifications, useToggle } from '../../hooks'; interface Props { id?: string; className?: string; } export const UnreadFaviconCounterToggle = ({ id, className }: Props) => { const [mailSettings] = useMailSettings(); const { call } = useEventManager(); const api = useApi(); const { state, toggle } = useToggle(!!mailSettings?.UnreadFavicon); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const handleChange = async (checked: boolean) => { await api(updateDisplayUnreadFavicon(+checked)); await call(); toggle(); createNotification({ text: c('Success').t`Preference saved` }); }; return ( <Toggle id={id} className={className} checked={state} onChange={({ target }) => withLoading(handleChange(target.checked))} loading={loading} /> ); };
6,660
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/otherMailPreferences/index.ts
export * from './OtherMailPreferencesSection';
6,661
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/overview/IndexSection.tsx
import clsx from '@proton/utils/clsx'; import { Icon } from '../../components'; import { SectionConfig } from '../layout'; import Sections from './Sections'; const IndexSection = ({ pages, limit = 4 }: { pages: SectionConfig[]; limit?: number }) => { return ( <div className="overview-grid"> {pages.map(({ icon, text, to, subsections = [], available }) => { return ( <section key={to} className={clsx([ 'overview-grid-item border bg-norm shadow-norm p-6', subsections.length > limit && 'overview-grid-item--tall', ])} > <h2 className="h6 mb-4 flex flex-align-items-center flex-nowrap"> <Icon name={icon} className="mr-2 flex-item-noshrink" /> <strong className="text-ellipsis" title={text}> {text} </strong> </h2> <Sections to={to} subsections={subsections} text={text} available={available} /> </section> ); })} </div> ); }; export default IndexSection;
6,662
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/overview/LinkItem.tsx
import { Link } from 'react-router-dom'; import { c } from 'ttag'; import { Icon, Tooltip } from '../../components'; interface Props { to: string; text?: string; available?: boolean; } const LinkItem = ({ to, text, available }: Props) => { return ( <Link to={to}> <span className="mr-2">{text}</span> {available ? null : ( <Tooltip title={c('Tag').t`Premium feature`}> <Icon name="star-filled" className="color-warning" /> </Tooltip> )} </Link> ); }; export default LinkItem;
6,663
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/overview/OverviewLayout.tsx
import { ReactNode, useEffect, useRef } from 'react'; import { c } from 'ttag'; import { ButtonLike } from '@proton/atoms'; import { hasMailPlus } from '@proton/shared/lib/helpers/subscription'; import { SettingsLink } from '../../components'; import { useOrganization, useSubscription, useUser, useUserSettings } from '../../hooks'; import { SettingsPageTitle } from '../account'; import { SectionConfig } from '../layout'; import IndexSection from './IndexSection'; import SummarySection from './SummarySection'; interface Props { title: string; pages: SectionConfig[]; children?: ReactNode; limit?: number; } const OverviewLayout = ({ title, pages, children, limit }: Props) => { const mainAreaRef = useRef<HTMLDivElement>(null); const [user] = useUser(); const [userSettings] = useUserSettings(); const [organization] = useOrganization(); const [subscription] = useSubscription(); const { hasPaidMail } = user; useEffect(() => { if (mainAreaRef.current) { mainAreaRef.current.scrollTop = 0; } }, []); return ( <div className="lg:flex flex-item-fluid lg:h-full flex-nowrap"> <div ref={mainAreaRef} className="relative flex-nowrap flex-item-fluid bg-weak lg:h-full scroll-if-needed"> <SettingsPageTitle>{title}</SettingsPageTitle> <div className="container-section-sticky pt-0"> <div className="flex on-mobile-flex-column pb-8"> <div className="flex-item-fluid"> {children ? ( <section className="overview-grid-item overview-grid-item--full border bg-norm shadow-norm p-8 mb-6"> {children} </section> ) : null} <IndexSection pages={pages} limit={limit} /> </div> </div> </div> </div> <aside className="context-bar lg:h-full scroll-if-needed p-6"> <SummarySection user={user} userSettings={userSettings} subscription={subscription} organization={organization} /> {subscription && hasMailPlus(subscription) ? ( <div className="bg-primary rounded text-center p-4 mt-8 relative"> <p className="mt-0 mb-4"> {c('Info') .t`Upgrade to a paid plan with multi-user support to add more users to your organization.`} </p> <div> <ButtonLike as={SettingsLink} className="increase-click-surface color-inherit" color="weak" shape="outline" path="/upgrade" > {c('Action').t`Upgrade`} </ButtonLike> </div> </div> ) : null} {hasPaidMail ? null : ( <div className="bg-primary rounded text-center p-4 mt-8 relative"> <p className="mt-0 mb-4"> {c('Info') .t`Upgrade to a paid plan to unlock premium features and increase your storage space.`} </p> <div> <ButtonLike as={SettingsLink} className="increase-click-surface color-inherit" color="weak" shape="outline" path="/upgrade" > {c('Action').t`Upgrade`} </ButtonLike> </div> </div> )} </aside> </div> ); }; export default OverviewLayout;
6,664
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/overview/Sections.tsx
import { SubSectionConfig } from '../layout'; import LinkItem from './LinkItem'; interface Props { to: string; text: string; subsections?: SubSectionConfig[]; available?: boolean; } const Sections = ({ to, subsections = [], text, available }: Props) => { return ( <ul className="unstyled mt-2"> {subsections.length ? ( subsections .filter(({ hide }) => !hide) .map(({ text, id, available }) => { return ( <li key={id} className="my-2"> <LinkItem to={`${to}#${id}`} text={text} available={available} /> </li> ); }) ) : ( <li> <LinkItem to={to} text={text} available={available} /> </li> )} </ul> ); }; export default Sections;
6,665
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/overview/SummarySection.tsx
import { c, msgid } from 'ttag'; import { APPS, CALENDAR_APP_NAME, MAIL_APP_NAME, PLANS, PLAN_SERVICES, VPN_APP_NAME, } from '@proton/shared/lib/constants'; import { getInitials } from '@proton/shared/lib/helpers/string'; import { getPlan } from '@proton/shared/lib/helpers/subscription'; import { getClosestLocaleCode } from '@proton/shared/lib/i18n/helper'; import { Organization, Plan, Subscription, UserModel, UserSettings } from '@proton/shared/lib/interfaces'; import { Icon, Loader, SettingsLink } from '../../components'; import { useConfig } from '../../hooks'; interface Props { user: UserModel; userSettings: UserSettings; organization?: Partial<Organization>; subscription?: Subscription; } const SummarySection = ({ user, userSettings, organization, subscription }: Props) => { const { APP_NAME, LOCALES = {} } = useConfig(); const { Email, DisplayName, Name, canPay, isAdmin } = user; const { UsedMembers = 0, UsedDomains = 0, MaxMembers = 0, MaxDomains = 0 } = organization || {}; const initials = getInitials(DisplayName || Name || Email || ''); const vpnPlan = subscription ? getPlan(subscription, PLAN_SERVICES.VPN) : undefined; const mailPlan = subscription ? getPlan(subscription, PLAN_SERVICES.MAIL) : undefined; const getPlanTitle = (plan: Plan | undefined, service: string) => { if (!plan) { return `${service} Free`; } if (plan.Name === PLANS.VISIONARY) { // For visionary plan, Title equals "Visionary" return `${service} Visionary`; } if (plan.Title) { return plan.Title; } }; const closestLocale = getClosestLocaleCode(userSettings?.Locale, LOCALES); const languageText = LOCALES[closestLocale]; return ( <div className="border bg-norm shadow-norm p-6"> <div className="mb-8 text-center"> <span className="user-initials rounded text-semibold p-1 mb-2 inline-flex bg-primary"> <span className="dropdown-logout-text m-auto">{initials}</span> </span> <h3 className="mb-2 lh-rg text-ellipsis" title={DisplayName || Name}> {DisplayName || Name} </h3> {organization?.Name ? ( <p className="mt-0 mb-2 text-ellipsis" title={organization.Name}> {organization.Name} </p> ) : null} <p className="my-0 text-ellipsis" title={Email}> {Email} </p> </div> {canPay ? ( <div className="mb-4"> <strong className="block mb-2">{c('Title').t`Plans`}</strong> {!subscription ? ( <Loader /> ) : ( <ul className="unstyled my-0"> <li className="flex flex-nowrap flex-align-items-center"> <Icon name="brand-proton-vpn" className="mr-2 flex-item-noshrink" /> <span className="flex-item-fluid">{getPlanTitle(vpnPlan, VPN_APP_NAME)}</span> </li> <li className="flex flex-nowrap flex-align-items-center"> <Icon name="brand-proton-mail" className="mr-2 flex-item-noshrink" /> <span className="flex-item-fluid">{getPlanTitle(mailPlan, MAIL_APP_NAME)}</span> </li> </ul> )} </div> ) : null} {languageText ? ( <div className="mb-4"> <strong className="block mb-2">{c('Title').t`Default language`}</strong> <ul className="unstyled my-0"> <li className="flex flex-nowrap flex-align-items-center"> <Icon name="globe" className="mr-2 flex-item-noshrink" /> <span className="flex-item-fluid">{languageText}</span> </li> </ul> </div> ) : null} {isAdmin ? ( <div className="mb-4"> <strong className="block mb-2">{c('Title').t`Your organization`}</strong> {!organization ? ( <Loader /> ) : ( <ul className="unstyled my-0"> <li> {c('Organization attribute').ngettext( msgid`${UsedMembers}/${MaxMembers} active user`, `${UsedMembers}/${MaxMembers} active users`, MaxMembers )} </li> <li> {c('Organization attribute').ngettext( msgid`${UsedDomains}/${MaxDomains} custom domain`, `${UsedDomains}/${MaxDomains} custom domains`, MaxDomains )} </li> </ul> )} </div> ) : null} {APP_NAME === APPS.PROTONACCOUNT ? ( <div className="mb-4"> <strong className="block mb-2">{c('Title').t`Application settings`}</strong> <ul className="unstyled my-0"> <li className="flex flex-nowrap flex-align-items-center"> <Icon name="brand-proton-mail" className="mr-2 flex-item-noshrink" /> <SettingsLink path="/general" app={APPS.PROTONMAIL}> {c('Link').t`${MAIL_APP_NAME} settings`} </SettingsLink> </li> <li className="flex flex-nowrap flex-align-items-center"> <Icon name="brand-proton-calendar" className="mr-2 flex-item-noshrink" /> <SettingsLink path="/general" app={APPS.PROTONCALENDAR}> {c('Link').t`${CALENDAR_APP_NAME} settings`} </SettingsLink> </li> </ul> </div> ) : null} {APP_NAME === APPS.PROTONACCOUNT ? null : ( <div className="mb-4"> <SettingsLink path="/dashboard">{c('Link').t`Manage account`}</SettingsLink> </div> )} </div> ); }; export default SummarySection;
6,666
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/overview/index.ts
export { default as IndexSection } from './IndexSection'; export { default as SummarySection } from './SummarySection'; export { default as OverviewLayout } from './OverviewLayout';
6,667
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/password/AuthModal.tsx
import { MutableRefObject, useEffect, useRef, useState } from 'react'; import { flushSync } from 'react-dom'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { PASSWORD_WRONG_ERROR, getInfo } from '@proton/shared/lib/api/auth'; import { getApiError } from '@proton/shared/lib/api/helpers/apiErrorHelper'; import { Fido2Data, InfoAuthedResponse } from '@proton/shared/lib/authentication/interface'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { captureMessage } from '@proton/shared/lib/helpers/sentry'; import { Unwrap } from '@proton/shared/lib/interfaces'; import { Credentials, SrpConfig, srpAuth } from '@proton/shared/lib/srp'; import { getAuthentication } from '@proton/shared/lib/webauthn/get'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import { Form, InlineLinkButton, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, PasswordInputTwo, Tabs, useFormErrors, } from '../../components'; import { useApi, useConfig, useErrorHandler, useUser, useUserSettings } from '../../hooks'; import { useIsSessionRecoveryInitiationAvailable } from '../../hooks/useSessionRecovery'; import AuthSecurityKeyContent from '../account/fido/AuthSecurityKeyContent'; import TotpInputs from '../account/totp/TotpInputs'; import { getAuthTypes } from './getAuthTypes'; const FORM_ID = 'auth-form'; enum Step { Password, TWO_FA, } const TOTPForm = ({ onSubmit, loading, hasBeenAutoSubmitted, defaultType, }: { onSubmit: (value: string) => void; loading?: boolean; hasBeenAutoSubmitted: MutableRefObject<boolean>; defaultType: 'totp' | 'recovery-code'; }) => { const { validator, onFormSubmit, reset } = useFormErrors(); const [code, setCode] = useState(''); const [type, setType] = useState(defaultType); const safeCode = code.replaceAll(/\s+/g, ''); const requiredError = requiredValidator(safeCode); useEffect(() => { if (type !== 'totp' || loading || requiredError || hasBeenAutoSubmitted.current) { return; } // Auto-submit the form once the user has entered the TOTP if (safeCode.length === 6) { // Do it just one time hasBeenAutoSubmitted.current = true; onSubmit(safeCode); } }, [safeCode]); return ( <Form id={FORM_ID} onSubmit={(event) => { if (!onFormSubmit(event.currentTarget) || loading) { return; } onSubmit(safeCode); }} > <TotpInputs type={type} code={code} error={validator([requiredError])} loading={loading} setCode={setCode} /> <div className="mt-4"> <InlineLinkButton type="button" onClick={() => { reset(); setCode(''); setType(type === 'totp' ? 'recovery-code' : 'totp'); }} > {type === 'totp' ? c('Action').t`Use recovery code` : c('Action').t`Use authentication code`} </InlineLinkButton> </div> </Form> ); }; const PasswordForm = ({ defaultPassword, onSubmit, loading, isSignedInAsAdmin, }: { isSignedInAsAdmin: boolean; defaultPassword: string; onSubmit: (password: string) => void; loading: boolean; }) => { const { validator, onFormSubmit } = useFormErrors(); const [password, setPassword] = useState(defaultPassword); return ( <Form id={FORM_ID} onSubmit={(event) => { if (!onFormSubmit(event.currentTarget) || loading) { return; } onSubmit(password); }} > {isSignedInAsAdmin && ( <div className="mb-4">{c('Info').t`Enter your own password (as organization admin).`}</div> )} <InputFieldTwo autoFocus autoComplete="current-password" id="password" as={PasswordInputTwo} value={password} disableChange={loading} onValue={setPassword} error={validator([requiredValidator(password)])} label={isSignedInAsAdmin ? c('Label').t`Your password (admin)` : c('Label').t`Password`} placeholder={c('Placeholder').t`Password`} /> </Form> ); }; type TwoFactorData = { type: 'code'; payload: string } | { type: 'fido2'; payload: Promise<Fido2Data> }; const getTwoFaCredentials = async ( twoFa: TwoFactorData | undefined ): Promise<{ totp: string } | { fido2: Fido2Data } | undefined> => { if (twoFa?.type === 'code') { return { totp: twoFa.payload, } as const; } if (twoFa?.type === 'fido2') { return { fido2: await twoFa.payload, } as const; } }; interface Props extends Omit<ModalProps<'div'>, 'as' | 'onSubmit' | 'size' | 'onSuccess' | 'onError'> { config: SrpConfig; onSuccess?: (data: { credentials: Credentials; response: Response }) => Promise<void> | void; onCancel: (() => void) | undefined; onError?: (error: any) => void; prioritised2FAItem?: 'fido2' | 'totp'; onSessionRecovery?: () => void; } const AuthModal = ({ config, onSuccess, onError, onClose, onCancel, prioritised2FAItem = 'fido2', onSessionRecovery, ...rest }: Props) => { const { APP_NAME } = useConfig(); const [infoResult, setInfoResult] = useState<InfoAuthedResponse>(); const api = useApi(); const [user] = useUser(); const [userSettings] = useUserSettings(); const [step, setStep] = useState(Step.Password); const [submitting, withSubmitting] = useLoading(); const hasBeenAutoSubmitted = useRef(false); const errorHandler = useErrorHandler(); const [fidoError, setFidoError] = useState(false); const isSessionRecoveryInitiationAvailable = useIsSessionRecoveryInitiationAvailable(); const [password, setPassword] = useState(''); const [rerender, setRerender] = useState(0); const [tabIndex, setTabIndex] = useState(0); const cancelClose = () => { onCancel?.(); onClose?.(); }; const refresh = async () => { const infoResult = await api<InfoAuthedResponse>(getInfo()); setInfoResult(infoResult); }; const isLoadingAuth = !infoResult; const authTypes = getAuthTypes(infoResult, userSettings, APP_NAME); useEffect(() => { refresh().catch(cancelClose); }, []); const handleSubmit = async ({ password, twoFa }: { password: string; twoFa: TwoFactorData | undefined }) => { if (submitting || isLoadingAuth) { return; } let twoFaCredentials: Unwrap<ReturnType<typeof getTwoFaCredentials>>; try { setFidoError(false); twoFaCredentials = await getTwoFaCredentials(twoFa); } catch (error) { if (twoFa?.type === 'fido2') { setFidoError(true); captureMessage('Security key auth', { level: 'error', extra: { error } }); // Purposefully logging the error for somewhat easier debugging console.error(error); } return; } try { const credentials = { password, ...twoFaCredentials, }; const response = await srpAuth({ api, info: infoResult, credentials, config: { ...config, silence: true, }, }); // We want to just keep the modal open until the consumer's promise is finished. Not interested in errors. await onSuccess?.({ credentials, response })?.catch(noop); onClose?.(); } catch (error: any) { errorHandler(error); const { code } = getApiError(error); if (code !== PASSWORD_WRONG_ERROR) { onError?.(error); cancelClose(); return; } await refresh().catch(cancelClose); flushSync(() => { setFidoError(false); setPassword(''); setStep(Step.Password); // Rerender the password form to trigger autofocus and form validation reset setRerender((old) => ++old); }); } }; const loading = submitting || isLoadingAuth; // Don't allow to close this modal if it's loading as it could leave other consumers in an undefined state const handleClose = loading ? noop : cancelClose; const fido2 = infoResult?.['2FA']?.FIDO2; return ( <Modal {...rest} size="small" onClose={handleClose}> <ModalHeader title={step === Step.TWO_FA ? c('Title').t`Sign in with 2FA` : c('Title').t`Enter your password`} /> <ModalContent> {step === Step.Password && ( <> <PasswordForm key={`${rerender}`} isSignedInAsAdmin={user?.isSubUser} defaultPassword={password} onSubmit={(password) => { if (isLoadingAuth) { return; } if (authTypes.twoFactor) { setPassword(password); setStep(Step.TWO_FA); return; } return withSubmitting(handleSubmit({ password, twoFa: undefined })); }} loading={submitting} /> {onSessionRecovery && isSessionRecoveryInitiationAvailable && ( <Button shape="underline" color="norm" onClick={onSessionRecovery}> {c('Action').t`Don't know your password?`} </Button> )} </> )} {(() => { if (step !== Step.TWO_FA) { return null; } const fido2Tab = authTypes.fido2 && fido2 && { title: c('fido2: Label').t`Security key`, content: ( <Form id={FORM_ID} onSubmit={() => { withSubmitting( handleSubmit({ password, twoFa: { type: 'fido2', payload: getAuthentication(fido2.AuthenticationOptions), }, }) ).catch(noop); }} > <AuthSecurityKeyContent error={fidoError} /> </Form> ), }; const totpTab = authTypes.totp && { title: c('Label').t`Authenticator app`, content: ( <TOTPForm defaultType="totp" hasBeenAutoSubmitted={hasBeenAutoSubmitted} loading={submitting} onSubmit={(payload) => withSubmitting( handleSubmit({ password, twoFa: { type: 'code', payload }, }) ) } /> ), }; const tabs = (() => { if (prioritised2FAItem === 'totp') { return [totpTab, fido2Tab]; } return [fido2Tab, totpTab]; })().filter(isTruthy); return ( <Tabs fullWidth value={tabIndex} onChange={(index) => { setTabIndex(index); setFidoError(false); }} tabs={tabs} /> ); })()} </ModalContent> <ModalFooter> {step === Step.TWO_FA ? ( <Button onClick={() => { setFidoError(false); setStep(Step.Password); }} >{c('Action').t`Back`}</Button> ) : ( <Button onClick={handleClose}>{c('Action').t`Cancel`}</Button> )} <Button color="norm" type="submit" form={FORM_ID} loading={submitting} disabled={isLoadingAuth}> {step === Step.Password && authTypes.twoFactor ? c('Action').t`Continue` : c('Action').t`Authenticate`} </Button> </ModalFooter> </Modal> ); }; export default AuthModal;
6,668
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/password/getAuthTypes.ts
import { InfoAuthedResponse } from '@proton/shared/lib/authentication/interface'; import { APP_NAMES } from '@proton/shared/lib/constants'; import { UserSettings } from '@proton/shared/lib/interfaces'; import { getHasFIDO2Enabled, getHasTOTPEnabled } from '@proton/shared/lib/settings/twoFactor'; import { getHasFIDO2Support } from '@proton/shared/lib/webauthn/helper'; export const getAuthTypes = (info: InfoAuthedResponse | undefined, userSettings: UserSettings, app: APP_NAMES) => { const Enabled = info?.['2FA']?.Enabled || userSettings?.['2FA']?.Enabled || 0; const hasTOTPEnabled = getHasTOTPEnabled(Enabled); const hasFido2Enabled = getHasFIDO2Support(app, location.hostname) && getHasFIDO2Enabled(Enabled); return { totp: hasTOTPEnabled, fido2: hasFido2Enabled, twoFactor: hasFido2Enabled || hasTOTPEnabled }; };
6,669
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/password/index.ts
export { default as AuthModal } from './AuthModal';
6,670
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/PaymentMethodActions.spec.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import { Autopay, PAYMENT_METHOD_TYPES, SavedPaymentMethod } from '@proton/components/payments/core'; import { deletePaymentMethod, orderPaymentMethods } from '@proton/shared/lib/api/payments'; import { DropdownActions } from '../../components'; import { useApi, useEventManager, useModals, useNotifications } from '../../hooks'; import PaymentMethodActions from './PaymentMethodActions'; jest.mock('../../hooks/useNotifications', () => jest.fn().mockReturnValue({ createNotification: jest.fn(), }) ); jest.mock('../../hooks/useModals', () => jest.fn().mockReturnValue({ createModal: jest.fn(), }) ); jest.mock('../../hooks/useEventManager', () => jest.fn().mockReturnValue({ call: jest.fn(), }) ); jest.mock('../../hooks/useApi', () => jest.fn().mockReturnValue(jest.fn())); jest.mock('../../components/dropdown/DropdownActions', () => jest.fn().mockImplementation(({ list }) => list.map(({ text }: any) => <span>{text}</span>)) ); jest.mock('../payments/EditCardModal', () => jest.fn().mockImplementation(() => <span>Edit Card Modal</span>)); jest.mock('../../components/modal/Confirm', () => jest.fn().mockImplementation(({ onConfirm }) => ( <button onClick={onConfirm} data-testid="confirm-deletion"> ConfirmModal </button> )) ); describe('PaymentMethodActions', () => { it('should show only delete button if paypal is the first method', () => { const method: SavedPaymentMethod = { Order: 1, ID: 'id-123', Type: PAYMENT_METHOD_TYPES.PAYPAL, Details: { BillingAgreementID: 'agreement-123', PayerID: 'payer-123', Payer: 'payer-123', }, }; const { container } = render(<PaymentMethodActions method={method} methods={[method]} index={0} />); expect(container).not.toHaveTextContent('Edit'); expect(container).not.toHaveTextContent('Mark as default'); expect(container).toHaveTextContent('Delete'); }); it('should show "delete" and "mark as default" button if paypal is not the first', () => { const method: SavedPaymentMethod = { Order: 1, ID: 'id-123', Type: PAYMENT_METHOD_TYPES.PAYPAL, Details: { BillingAgreementID: 'agreement-123', PayerID: 'payer-123', Payer: 'payer-123', }, }; const { container } = render(<PaymentMethodActions method={method} methods={[method]} index={1} />); expect(container).not.toHaveTextContent('Edit'); expect(container).toHaveTextContent('Mark as default'); expect(container).toHaveTextContent('Delete'); }); it('should show Edit, Default and Delete buttons for non-first card', () => { const method: SavedPaymentMethod = { Order: 1, ID: 'id-123', Type: PAYMENT_METHOD_TYPES.CARD, Details: { Name: 'John Smith', ExpMonth: '01', ExpYear: '2038', ZIP: '12345', Country: 'US', Last4: '4444', Brand: 'Mastercard', }, Autopay: Autopay.ENABLE, }; const { container } = render(<PaymentMethodActions method={method} methods={[method]} index={1} />); expect(container).toHaveTextContent('Edit'); expect(container).toHaveTextContent('Mark as default'); expect(container).toHaveTextContent('Delete'); }); it('should show Edit and Delete buttons for first card', () => { const method: SavedPaymentMethod = { Order: 1, ID: 'id-123', Type: PAYMENT_METHOD_TYPES.CARD, Details: { Name: 'John Smith', ExpMonth: '01', ExpYear: '2038', ZIP: '12345', Country: 'US', Last4: '4444', Brand: 'Mastercard', }, Autopay: Autopay.ENABLE, }; const { container } = render(<PaymentMethodActions method={method} methods={[method]} index={0} />); expect(container).toHaveTextContent('Edit'); expect(container).not.toHaveTextContent('Mark as default'); expect(container).toHaveTextContent('Delete'); }); describe('action handlers', () => { beforeEach(() => { const DropdownActionsMock: jest.Mock = DropdownActions as any; DropdownActionsMock.mockReset().mockImplementation(({ list }: { list: any[] }) => list.map(({ text, onClick }, actionIndex) => ( <button onClick={onClick} data-testid={`actionIndex-${actionIndex}`}> {text} </button> )) ); }); it('should open EditCardModal on Edit', async () => { const method: SavedPaymentMethod = { Order: 1, ID: 'id-123', Type: PAYMENT_METHOD_TYPES.CARD, Details: { Name: 'John Smith', ExpMonth: '01', ExpYear: '2038', ZIP: '12345', Country: 'US', Last4: '4444', Brand: 'Mastercard', }, Autopay: Autopay.ENABLE, }; const { createModal } = useModals(); (createModal as jest.Mock).mockReset(); const { findByTestId } = render(<PaymentMethodActions method={method} methods={[method]} index={1} />); fireEvent.click(await findByTestId('actionIndex-0')); expect(createModal).toHaveBeenCalled(); }); it('should make an API call on Mark as Default', async () => { const method0: SavedPaymentMethod = { Order: 0, ID: 'id-000', Type: PAYMENT_METHOD_TYPES.CARD, Details: { Name: 'John Smith', ExpMonth: '01', ExpYear: '2055', ZIP: '12345', Country: 'US', Last4: '4242', Brand: 'Visa', }, Autopay: Autopay.ENABLE, }; const method1: SavedPaymentMethod = { Order: 1, ID: 'id-123', Type: PAYMENT_METHOD_TYPES.CARD, Details: { Name: 'John Smith', ExpMonth: '01', ExpYear: '2038', ZIP: '12345', Country: 'US', Last4: '4444', Brand: 'Mastercard', }, Autopay: Autopay.ENABLE, }; const api = useApi(); (api as jest.Mock).mockReset(); const { call } = useEventManager(); (call as jest.Mock).mockReset(); const { createNotification } = useNotifications(); (createNotification as jest.Mock).mockReset(); const { findByTestId } = render( <PaymentMethodActions method={method1} methods={[method0, method1]} index={1} /> ); fireEvent.click(await findByTestId('actionIndex-1')); await waitFor(async () => { expect(api).toHaveBeenCalledWith(orderPaymentMethods(['id-123', 'id-000'])); // a request to change the order of the payment methods }); await waitFor(async () => { expect(call).toHaveBeenCalled(); }); await waitFor(async () => { expect(createNotification).toHaveBeenCalled(); }); }); it('should open ConfirmModal on Delete', async () => { const method: SavedPaymentMethod = { Order: 1, ID: 'id-123', Type: PAYMENT_METHOD_TYPES.CARD, Details: { Name: 'John Smith', ExpMonth: '01', ExpYear: '2038', ZIP: '12345', Country: 'US', Last4: '4444', Brand: 'Mastercard', }, Autopay: Autopay.ENABLE, }; const { createModal } = useModals(); (createModal as jest.Mock).mockReset(); const api = useApi(); (api as jest.Mock).mockReset(); const { call } = useEventManager(); (call as jest.Mock).mockReset(); const { createNotification } = useNotifications(); (createNotification as jest.Mock).mockReset(); const { findByTestId } = render(<PaymentMethodActions method={method} methods={[method]} index={1} />); fireEvent.click(await findByTestId('actionIndex-2')); expect(createModal).toHaveBeenCalled(); const onDelete = (createModal as jest.Mock).mock.lastCall[0].props.onConfirm; await onDelete(); await waitFor(async () => { expect(api).toHaveBeenCalledWith(deletePaymentMethod('id-123')); }); await waitFor(async () => { expect(call).toHaveBeenCalled(); }); await waitFor(async () => { expect(createNotification).toHaveBeenCalled(); }); }); }); });
6,671
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/PaymentMethodActions.tsx
import { c } from 'ttag'; import { deletePaymentMethod, orderPaymentMethods } from '@proton/shared/lib/api/payments'; import { Alert } from '../../components/alert'; import { ErrorButton } from '../../components/button'; import DropdownActions, { DropdownActionProps } from '../../components/dropdown/DropdownActions'; import { ConfirmModal } from '../../components/modal'; import { useApi, useEventManager, useModals, useNotifications } from '../../hooks'; import { CardModel, PAYMENT_METHOD_TYPES, PaymentMethodCardDetails, SavedPaymentMethod, isExpired, } from '../../payments/core'; import EditCardModal from '../payments/EditCardModal'; const toCardModel = ({ Details }: PaymentMethodCardDetails): CardModel => { return { month: `${Details.ExpMonth}`, // ExpMonth is a number number: '', year: `${Details.ExpYear}`.slice(-2), // ExpYear is a number cvc: '', zip: Details.ZIP, country: Details.Country, }; }; export interface Props { index: number; method: SavedPaymentMethod; methods: SavedPaymentMethod[]; } const PaymentMethodActions = ({ method, methods, index }: Props) => { const { createNotification } = useNotifications(); const { createModal } = useModals(); const api = useApi(); const { call } = useEventManager(); const deleteMethod = async () => { await api(deletePaymentMethod(method.ID)); await call(); createNotification({ text: c('Success').t`Payment method deleted` }); }; const markAsDefault = async () => { const IDs = methods.map(({ ID }) => ID); IDs.splice(index, 1); IDs.unshift(method.ID); await api(orderPaymentMethods(IDs)); await call(); createNotification({ text: c('Success').t`Payment method updated` }); }; const dropdownActions: DropdownActionProps[] = []; if (method.Type === PAYMENT_METHOD_TYPES.CARD) { const card: CardModel = toCardModel(method); dropdownActions.push({ text: c('Action').t`Edit`, onClick: () => createModal(<EditCardModal card={card} renewState={method.Autopay} paymentMethodId={method.ID} />), 'data-testid': 'Edit', }); } if (index > 0 && !isExpired(method.Details)) { dropdownActions.push({ text: c('Action').t`Mark as default`, onClick: markAsDefault, }); } dropdownActions.push({ text: c('Action').t`Delete`, actionType: 'delete', 'data-testid': 'Delete', onClick: () => { createModal( <ConfirmModal onConfirm={deleteMethod} title={c('Confirmation title').t`Delete payment method`} confirm={<ErrorButton type="submit">{c('Action').t`Delete`}</ErrorButton>} > <Alert className="mb-4" data-testid="valid-payment-alert">{c('Info when deleting payment method') .t`To avoid any service interruption due to unpaid invoices, please make sure that you have at least 1 valid payment method saved at any point in time.`}</Alert> <Alert className="mb-4" type="error" data-testid="confirmation-alert">{c( 'Confirmation message to delete payment method' ).t`Are you sure you want to delete this payment method?`}</Alert> </ConfirmModal> ); }, }); return <DropdownActions size="small" list={dropdownActions} />; }; export default PaymentMethodActions;
6,672
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/PaymentMethodDetails.scss
@import '~@proton/styles/scss/lib'; .card-numbers { font-size: rem(40); }
6,673
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/PaymentMethodDetails.tsx
import { useRef } from 'react'; import { c } from 'ttag'; import { getBankSvg } from '@proton/components/payments/client-extensions/credit-card-type'; import { PAYMENT_METHOD_TYPES, PayPalDetails, SavedCardDetails, isPaypalDetails, isSavedCardDetails, } from '@proton/components/payments/core'; import { Bordered } from '../../components'; import useSvgGraphicsBbox from '../../hooks/useSvgGraphicsBbox'; import './PaymentMethodDetails.scss'; const getCreditCardTypeByBrand = (brand: string): string => { const CREDIT_CARD_TYPES: { [brand: string]: string; } = { 'American Express': 'american-express', 'Diners Club': 'diners-club', Discover: 'discover', JCB: 'jcb', Maestro: 'maestro', MasterCard: 'mastercard', UnionPay: 'unionpay', Visa: 'visa', }; return CREDIT_CARD_TYPES[brand] ?? ''; }; const PaymentMethodDetailsCard = ({ details }: { details: SavedCardDetails }) => { const { Last4, Name, ExpMonth, ExpYear, Brand = '' } = details; const cardNumberText = `•••• •••• •••• ${Last4}`; const textRef = useRef<SVGTextElement>(null); const textBbox = useSvgGraphicsBbox(textRef, [cardNumberText]); const textWidth = Math.floor(textBbox.width); const bankIcon = getBankSvg(getCreditCardTypeByBrand(Brand)); return ( <Bordered className="bg-weak rounded inline-flex flex-column w-full p-7" data-testid="existing-credit-card"> {bankIcon ? <img width="70" src={bankIcon} alt={Brand} className="mb-4" /> : null} <span className="block mb-4 opacity-40">{c('Label').t`Card number`}</span> <div className="ratio-container-5-1 text-center"> <svg xmlns="http://www.w3.org/2000/svg" className="inner-ratio-container fill-currentcolor" viewBox={`0 0 ${textWidth} 50`} xmlSpace="preserve" > <text x="0px" y="40px" className="card-numbers text-strong text-monospace" ref={textRef}> {cardNumberText} </text> </svg> </div> <div className="flex flex-nowrap max-w-full"> <div className="flex-item-fluid"> {!!Name && ( <> <span className="block mb-2 opacity-40">{c('Label').t`Card holder`}</span> <span className="text-xl my-0 inline-block text-ellipsis max-w-full">{Name}</span> </> )} </div> <div className="text-right flex-item-noshrink pl-4"> <span className="block mb-2 opacity-40">{c('Label').t`Expires`}</span> <span className="text-xl my-0"> {ExpMonth}/{ExpYear} </span> </div> </div> </Bordered> ); }; const PaymentMethodDetailsPaypal = ({ details }: { details: PayPalDetails }) => { const { Payer } = details; const bankIcon = getBankSvg('paypal'); return ( <Bordered className="p-7 rounded" data-testid="existing-paypal"> <div> <img width="70" src={bankIcon} alt="PayPal" className="mb-4" /> </div> <div className="flex flex-wrap flex-align-items-center"> <label className="flex-item-noshrink mr-4" htmlFor="paypal-payer">{c('Label').t`Payer`}</label> <code id="paypal-payer" className="block text-xl mb-0 mb-4 text-ellipsis" title={Payer}> {Payer} </code> </div> </Bordered> ); }; interface Props { type: PAYMENT_METHOD_TYPES.CARD | PAYMENT_METHOD_TYPES.PAYPAL; details: SavedCardDetails | PayPalDetails; } const PaymentMethodDetails = ({ type, details }: Props) => { if (type === PAYMENT_METHOD_TYPES.CARD) { if (!isSavedCardDetails(details)) { return null; } return <PaymentMethodDetailsCard details={details} />; } if (type === PAYMENT_METHOD_TYPES.PAYPAL) { if (!isPaypalDetails(details)) { return null; } return <PaymentMethodDetailsPaypal details={details} />; } return null; }; export default PaymentMethodDetails;
6,674
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/PaymentMethodSelector.tsx
import clsx from '@proton/utils/clsx'; import { DropdownSizeUnit, Icon, Option, Radio, SelectTwo } from '../../components'; import { DropdownSize } from '../../components/dropdown/utils'; import { PaymentMethodType } from '../../payments/core'; import { PaymentMethodData } from './interface'; interface Props { options: PaymentMethodData[]; method?: PaymentMethodType; onChange: (value: PaymentMethodType) => void; lastUsedMethod?: PaymentMethodData; forceDropdown?: boolean; narrow?: boolean; } const PaymentMethodSelector = ({ method, lastUsedMethod, options, onChange, forceDropdown, narrow }: Props) => { if (options.length <= 2 && !forceDropdown) { return ( <> {options.map(({ text, value, disabled, icon }) => { return ( <label htmlFor={value} key={value} className={clsx([ 'py-2 flex flex-nowrap flex-align-items-center', lastUsedMethod?.value === value && 'border-bottom', ])} > <Radio disabled={disabled} className="mr-2" id={value} name="value" checked={value === method} onChange={() => onChange(value)} /> {icon && <Icon className="mr-2" name={icon} />} <span className="text-cut">{text}</span> </label> ); })} </> ); } const size: DropdownSize | undefined = narrow ? { width: DropdownSizeUnit.Dynamic, } : undefined; return ( <SelectTwo id="select-method" value={method} onChange={({ value }) => onChange(value)} className={clsx(narrow && 'w-auto')} size={size} data-testid="payment-method-selector" > {options.flatMap((option) => { const child = ( <Option key={option.value} value={option.value} title={option.text}> <span className="inline-flex max-w-full flex-nowrap flex-items-align-center flex-justify-start"> {option.icon && <Icon className="mr-2 my-auto flex-item-noshrink" name={option.icon} />} <span className="text-ellipsis">{option.text}</span> </span> </Option> ); if (lastUsedMethod?.value === option.value) { return [ child, <div className="py-2 block" key={`${option.value}-separator`}> <hr className="my-0" /> </div>, ]; } return child; })} </SelectTwo> ); }; export default PaymentMethodSelector;
6,675
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/PaymentMethodState.tsx
import { c } from 'ttag'; import { PAYMENT_METHOD_TYPES, SavedPaymentMethod, isExpired } from '@proton/components/payments/core'; import { Badge } from '../../components'; interface Props { method: SavedPaymentMethod; index?: number; } const PaymentMethodState = ({ method, index }: Props) => { if (method.Type === PAYMENT_METHOD_TYPES.CARD && isExpired(method.Details)) { return ( <Badge type="error" data-testid="expired">{`${c('Label on payment method').t`Expired`} ${ method.Details.ExpMonth }/${method.Details.ExpYear}`}</Badge> ); } if (!index) { return <Badge type="primary" data-testid="default-badge">{c('Label on payment method').t`Default`}</Badge>; } return null; }; export default PaymentMethodState;
6,676
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/PaymentMethodsSection.spec.tsx
import { render } from '@testing-library/react'; import { PAYMENT_METHOD_TYPES } from '@proton/components/payments/core'; import { FREE_SUBSCRIPTION } from '@proton/shared/lib/constants'; import { Loader, MozillaInfoPanel, PaymentMethodsSection, PaymentMethodsTable, useModals, usePaymentMethods, useSubscription, useTypedSubscription, } from '../..'; jest.mock('../../hooks/useConfig', () => () => ({ APP_NAME: 'proton-vpn-settings', })); jest.mock('../../hooks/usePaymentMethods'); jest.mock('../../hooks/useSubscription'); jest.mock('../../hooks/useModals'); jest.mock('../../components/loader/Loader'); jest.mock('../account/MozillaInfoPanel'); jest.mock('./PaymentMethodsTable'); describe('PaymentMethodsSection', () => { beforeEach(() => { jest.resetAllMocks(); jest.mocked(usePaymentMethods).mockReturnValue([[], false, undefined as any]); jest.mocked(useSubscription).mockReturnValue([{} as any, false, undefined as any]); jest.mocked(useTypedSubscription).mockReturnValue([FREE_SUBSCRIPTION, false]); jest.mocked(useModals).mockReturnValue({ createModal: jest.fn(), } as any); jest.mocked(Loader).mockImplementation(() => <>Loader</>); jest.mocked(MozillaInfoPanel).mockImplementation(() => <>MozillaInfoPanel</>); jest.mocked(PaymentMethodsTable).mockImplementation(() => <>PaymentMethodsTable</>); }); it('should render <Loading> if payment methods are loading', () => { const usePaymentMethodsMock = jest.mocked(usePaymentMethods); usePaymentMethodsMock.mockReturnValue([[], true, undefined as any]); const { container } = render(<PaymentMethodsSection />); expect(container).toHaveTextContent('Loader'); }); it('should render <Loading> if subscriptions are loading', () => { jest.mocked(useTypedSubscription).mockReturnValue([undefined, true]); const { container } = render(<PaymentMethodsSection />); expect(container).toHaveTextContent('Loader'); }); it('should render <MozillaInfoPanel> if subscription is managed by mozilla', () => { jest.mocked(useTypedSubscription).mockReturnValue([{ isManagedByMozilla: true } as any, false]); const { container } = render(<PaymentMethodsSection />); expect(container).toHaveTextContent('MozillaInfoPanel'); }); it('should render the main contanet otherwise', () => { const { container } = render(<PaymentMethodsSection />); expect(container).toHaveTextContent('PaymentMethodsTable'); }); it('should show the paypal button only if there is not paypal payment yet', () => { const { container } = render(<PaymentMethodsSection />); expect(container).toHaveTextContent('Add PayPal'); }); it('should NOT show the paypal button only if there is already paypal payment', () => { jest.mocked(usePaymentMethods).mockReturnValue([ [ { Order: 1, ID: 'id123', Type: PAYMENT_METHOD_TYPES.PAYPAL, Details: { BillingAgreementID: 'BillingAgreementID123', PayerID: 'PayerID123', Payer: 'Arthur Morgan', }, }, ], false, undefined as any, ]); const { container } = render(<PaymentMethodsSection />); expect(container).not.toHaveTextContent('Add PayPal'); }); });
6,677
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/PaymentMethodsSection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { PAYMENT_METHOD_TYPES } from '@proton/components/payments/core'; import { APPS } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Icon, Loader, useModalState } from '../../components'; import { useConfig, useMozillaCheck, usePaymentMethods } from '../../hooks'; import { SettingsParagraph, SettingsSection } from '../account'; import MozillaInfoPanel from '../account/MozillaInfoPanel'; import EditCardModal from '../payments/EditCardModal'; import PayPalModal from '../payments/PayPalModal'; import PaymentMethodsTable from './PaymentMethodsTable'; const PaymentMethodsSection = () => { const { APP_NAME } = useConfig(); const [paymentMethods = [], loadingPaymentMethods] = usePaymentMethods(); const [isManagedByMozilla, loadingCheck] = useMozillaCheck(); const [creditCardModalProps, setCreditCardModalOpen, renderCreditCardModal] = useModalState(); const [paypalModalProps, setPaypalModalOpen, renderPaypalModal] = useModalState(); if (loadingPaymentMethods || loadingCheck) { return <Loader />; } if (isManagedByMozilla) { return <MozillaInfoPanel />; } const learnMoreUrl = APP_NAME === APPS.PROTONVPN_SETTINGS ? 'https://protonvpn.com/support/payment-options/' : getKnowledgeBaseUrl('/payment-options'); const hasPayPal = paymentMethods.some((method) => method.Type === PAYMENT_METHOD_TYPES.PAYPAL); return ( <SettingsSection> <SettingsParagraph learnMoreUrl={learnMoreUrl}> {c('Info for payment methods') .t`You can add a payment method to have your subscription renewed automatically. Other payment methods are also available.`} </SettingsParagraph> <div className="mb-4"> <Button shape="outline" className="mr-4" onClick={() => setCreditCardModalOpen(true)}> <Icon name="credit-card" className="mr-2" /> <span>{c('Action').t`Add credit / debit card`}</span> </Button> {!hasPayPal && ( <Button shape="outline" onClick={() => setPaypalModalOpen(true)}> <Icon name="brand-paypal" className="mr-2" /> <span>{c('Action').t`Add PayPal`}</span> </Button> )} </div> <PaymentMethodsTable loading={false} methods={paymentMethods} /> {renderCreditCardModal && <EditCardModal {...creditCardModalProps} />} {renderPaypalModal && <PayPalModal {...paypalModalProps} />} </SettingsSection> ); }; export default PaymentMethodsSection;
6,678
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/PaymentMethodsTable.spec.tsx
import { render } from '@testing-library/react'; import { Autopay, PAYMENT_METHOD_TYPES, PayPalDetails, SavedCardDetails, SavedPaymentMethod, } from '@proton/components/payments/core'; import TableBody from '../../components/table/TableBody'; import TableRow from '../../components/table/TableRow'; import PaymentMethodsTable from './PaymentMethodsTable'; jest.mock('../../components/table/TableRow', () => jest.fn()); jest.mock('../../components/table/TableBody'); jest.mock('./PaymentMethodActions', () => jest.fn().mockReturnValue(null)); describe('PaymentMethodsTable', () => { it('should render message that user has no payment methods', () => { const { container } = render(<PaymentMethodsTable loading={false} methods={[]} />); expect(container).toHaveTextContent('You have no saved payment methods.'); }); it('should render <TableBody> with loading flag', () => { const TableBodyMock: jest.Mock = TableBody as any; TableBodyMock.mockReset(); TableBodyMock.mockReturnValue(<span>Table Body</span>); const { container } = render(<PaymentMethodsTable loading={true} methods={[]} />); expect(TableBodyMock).toHaveBeenCalled(); expect(TableBodyMock.mock.calls[0][0].loading).toEqual(true); expect(container).not.toHaveTextContent('You have no saved payment methods.'); expect(container).toHaveTextContent('Table Body'); }); it('should render Card method', () => { const Details: SavedCardDetails = { Name: 'John Smith', ExpMonth: '01', ExpYear: '2034', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }; const cardPaymentMethod: SavedPaymentMethod = { Type: PAYMENT_METHOD_TYPES.CARD, Details, Order: 1, ID: 'id123', Autopay: Autopay.ENABLE, }; const TableBodyMock: jest.Mock = TableBody as any; TableBodyMock.mockReset(); TableBodyMock.mockImplementation(({ children }) => children); const TableRowMock: jest.Mock = TableRow as any; TableRowMock.mockReset(); TableRowMock.mockImplementation(({ cells }) => ( <> <span>Table Row</span> <div>{cells}</div> </> )); const { container } = render(<PaymentMethodsTable methods={[cardPaymentMethod]} loading={false} />); expect(container).toHaveTextContent(Details.Brand); expect(container).toHaveTextContent(Details.Last4); }); it('should render Paypal method', () => { const Details: PayPalDetails & { Payer: string } = { BillingAgreementID: 'agreement-id-123', PayerID: 'payer-id-123', Payer: 'John Smith', }; const paypalMethod: SavedPaymentMethod = { Type: PAYMENT_METHOD_TYPES.PAYPAL, Details, Order: 1, ID: 'id123', }; const TableBodyMock: jest.Mock = TableBody as any; TableBodyMock.mockReset(); TableBodyMock.mockImplementation(({ children }) => children); const TableRowMock: jest.Mock = TableRow as any; TableRowMock.mockReset(); TableRowMock.mockImplementation(({ cells }) => ( <> <span>Table Row</span> <div>{cells}</div> </> )); const { container } = render(<PaymentMethodsTable methods={[paypalMethod]} loading={false} />); expect(container).toHaveTextContent('PayPal'); expect(container).toHaveTextContent('John Smith'); }); it('should display multiple payment methods', () => { const Details1: SavedCardDetails = { Name: 'John Smith', ExpMonth: '01', ExpYear: '2034', ZIP: '12345', Country: 'US', Last4: '1234', Brand: 'Visa', }; const cardPaymentMethod1: SavedPaymentMethod = { Type: PAYMENT_METHOD_TYPES.CARD, Details: Details1, Order: 1, ID: 'id-visa', Autopay: Autopay.ENABLE, }; const Details2: SavedCardDetails = { Name: 'John Smith', ExpMonth: '01', ExpYear: '2038', ZIP: '12345', Country: 'US', Last4: '4444', Brand: 'Mastercard', }; const cardPaymentMethod2: SavedPaymentMethod = { Type: PAYMENT_METHOD_TYPES.CARD, Details: Details2, Order: 2, ID: 'id-mastercard', Autopay: Autopay.ENABLE, }; const paypalMethod: SavedPaymentMethod = { Type: PAYMENT_METHOD_TYPES.PAYPAL, Details: { BillingAgreementID: 'agreement-id-123', PayerID: 'payer-id-123', Payer: 'John Smith PayPal', } as any, Order: 0, ID: 'id-paypal', }; const TableBodyMock: jest.Mock = TableBody as any; TableBodyMock.mockReset(); TableBodyMock.mockImplementation(({ children }) => children); const TableRowMock: jest.Mock = TableRow as any; TableRowMock.mockReset(); TableRowMock.mockImplementation(({ cells }) => ( <> <span>Table Row</span> <div>{cells}</div> </> )); const { container } = render( <PaymentMethodsTable methods={[cardPaymentMethod1, cardPaymentMethod2, paypalMethod]} loading={false} /> ); expect(container).toHaveTextContent('John Smith PayPal'); expect(container).toHaveTextContent('Visa'); expect(container).toHaveTextContent('Mastercard'); // sorted by Order expect(TableBodyMock.mock.calls[0][0].children.map((it: any) => it.key)).toEqual([ 'id-paypal', 'id-visa', 'id-mastercard', ]); }); });
6,679
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/PaymentMethodsTable.tsx
import { c } from 'ttag'; import { isPaypalDetails, isSavedCardDetails } from '@proton/components/payments/core'; import { SavedPaymentMethod } from '@proton/components/payments/core'; import orderBy from '@proton/utils/orderBy'; import { Table, TableBody, TableHeader, TableRow } from '../../components'; import PaymentMethodActions from './PaymentMethodActions'; import PaymentMethodState from './PaymentMethodState'; export interface Props { methods: SavedPaymentMethod[]; loading: boolean; } const MethodCell = ({ method }: { method: SavedPaymentMethod }) => { if (isPaypalDetails(method.Details)) { return ( <> <span className="mr-2 align-middle" data-testid="payment-method"> PayPal </span> <span className="block lg:inline-block align-middle text-ellipsis max-w-full" data-testid="payer" title={method.Details.Payer} > {method.Details.Payer} </span> </> ); } if (isSavedCardDetails(method.Details)) { return ( <span data-testid="card-details"> {method.Details.Brand} (•••• {method.Details.Last4}) </span> ); } return null; }; const PaymentMethodsTable = ({ methods, loading }: Props) => { if (!loading && !methods.length) { return <p data-testid="no-payments">{c('Info').t`You have no saved payment methods.`}</p>; } const orderedMethods = orderBy(methods, 'Order'); return ( <Table hasActions responsive="cards"> <TableHeader cells={[ c('Title for payment methods table').t`Method`, c('Title for payment methods table').t`Status`, c('Title for payment methods table').t`Actions`, ]} /> <TableBody loading={loading} colSpan={5}> {orderedMethods.map((method, index) => { return ( <TableRow key={method.ID} cells={[ <MethodCell method={method} />, <PaymentMethodState key={method.ID} method={method} index={index} />, <PaymentMethodActions key={method.ID} index={index} methods={orderedMethods} method={method} />, ]} /> ); })} </TableBody> </Table> ); }; export default PaymentMethodsTable;
6,680
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/index.ts
export { default as PaymentMethodState } from './PaymentMethodState'; export { default as PaymentMethodActions } from './PaymentMethodActions'; export { default as PaymentMethodDetails } from './PaymentMethodDetails'; export { default as PaymentMethodsTable } from './PaymentMethodsTable'; export { default as PaymentMethodsSection } from './PaymentMethodsSection'; export { default as PaymentMethodSelector } from './PaymentMethodSelector';
6,681
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/paymentMethods/interface.ts
import { PaymentMethodType } from '@proton/components/payments/core'; import { IconName } from '../../components/icon'; export interface PaymentMethodData { icon?: IconName; value: PaymentMethodType; text: string; disabled?: boolean; } export type PaymentMethodFlows = | 'invoice' | 'signup' | 'signup-pass' | 'signup-vpn' | 'human-verification' | 'credit' | 'donation' | 'subscription';
6,682
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/Alert3ds.tsx
import { c } from 'ttag'; import americanExpressSafekeySvg from '@proton/styles/assets/img/bank-icons/amex-safekey-colored.svg'; import discoverProtectBuySvg from '@proton/styles/assets/img/bank-icons/discover-protectbuy-colored.svg'; import mastercardSecurecodeSvg from '@proton/styles/assets/img/bank-icons/mastercard-securecode-colored.svg'; import verifiedByVisaSvg from '@proton/styles/assets/img/bank-icons/visa-secure-colored.svg'; const Alert3ds = () => { return ( <div className="my-6 color-weak text-center"> <div className="mb-2 text-sm" data-testid="3ds-info"> {c('Info').t`We use 3-D Secure to protect your payments`} </div> <div className="flex flex-nowrap flex-align-items-center flex-justify-center"> <img alt={c('Info').t`Visa Secure logo`} className="mr-4" style={{ maxHeight: '44px' }} src={verifiedByVisaSvg} /> <img alt={c('Info').t`Mastercard SecureCode logo`} className="mr-4" style={{ maxHeight: '44px' }} src={mastercardSecurecodeSvg} /> <img alt={c('Info').t`Discover ProtectBuy logo`} className="mr-4" style={{ maxHeight: '44px' }} src={discoverProtectBuySvg} /> <img alt={c('Info').t`American Express SafeKey logo`} className="mr-4" style={{ maxHeight: '44px' }} src={americanExpressSafekeySvg} /> </div> </div> ); }; export default Alert3ds;
6,683
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/AmountButton.tsx
import { Button, ButtonProps } from '@proton/atoms'; import { Currency } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { Price } from '../../components'; interface Props extends Omit<ButtonProps, 'onSelect' | 'onClick'> { value?: number; amount?: number; currency?: Currency; onSelect: (value: number) => void; } const AmountButton = ({ value = 0, amount = 0, currency, onSelect, className = '', ...rest }: Props) => { return ( <Button aria-pressed={value === amount} className={clsx(['field', className, value === amount && 'is-active'])} onClick={() => onSelect(value)} {...rest} > <Price currency={currency}>{value}</Price> </Button> ); }; export default AmountButton;
6,684
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/AmountRow.tsx
import { c } from 'ttag'; import { PAYMENT_METHOD_TYPES, PlainPaymentMethodType } from '@proton/components/payments/core'; import { Currency } from '@proton/shared/lib/interfaces'; import { Field, Row } from '../../components'; import PaymentSelector from './PaymentSelector'; interface Props { paymentMethodType?: PlainPaymentMethodType; amount: number; onChangeAmount: (value: number) => void; currency?: Currency; onChangeCurrency: (currency: Currency) => void; } const AmountRow = ({ paymentMethodType, amount, onChangeAmount, currency, onChangeCurrency }: Props) => { if (paymentMethodType === PAYMENT_METHOD_TYPES.CASH) { return null; } return ( <Row> <span className="label" id="id_desc_amount">{c('Label').t`Amount`}</span> <Field> <PaymentSelector amount={amount} onChangeAmount={onChangeAmount} currency={currency} onChangeCurrency={onChangeCurrency} /> </Field> </Row> ); }; export default AmountRow;
6,685
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/Bitcoin.test.tsx
import { render, waitFor } from '@testing-library/react'; import { createToken, getTokenStatus } from '@proton/shared/lib/api/payments'; import { Api, Currency } from '@proton/shared/lib/interfaces'; import { addApiMock, apiMock, flushPromises } from '@proton/testing'; import { PAYMENT_METHOD_TYPES, PAYMENT_TOKEN_STATUS } from '../../payments/core'; import Bitcoin from './Bitcoin'; import useBitcoin, { BITCOIN_POLLING_INTERVAL, OnBitcoinAwaitingPayment, OnBitcoinTokenValidated } from './useBitcoin'; const onTokenValidated = jest.fn(); const onAwaitingPayment = jest.fn(); type InnerProps = { onTokenValidated: OnBitcoinTokenValidated; onAwaitingPayment: OnBitcoinAwaitingPayment; api: Api; amount: number; currency: Currency; processingToken: boolean; }; const BitcoinTestComponent = (props: InnerProps) => { const bitcoinHook = useBitcoin({ api: props.api, Amount: props.amount, Currency: props.currency, onTokenValidated: props.onTokenValidated, onAwaitingPayment: props.onAwaitingPayment, enablePolling: true, }); return <Bitcoin {...props} {...bitcoinHook} />; }; beforeAll(() => { jest.useFakeTimers(); }); afterAll(() => { jest.useRealTimers(); }); const createTokenUrl = createToken({} as any).url; const defaultTokenResponse = { Token: 'token-123', Data: { CoinAddress: 'address-123', CoinAmount: '0.00135', }, }; beforeEach(() => { jest.clearAllMocks(); addApiMock(createTokenUrl, () => defaultTokenResponse); }); it('should render', async () => { const { container } = render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); await waitFor(() => { expect(container).not.toBeEmptyDOMElement(); }); expect(container).toHaveTextContent('address-123'); expect(container).toHaveTextContent('0.00135'); }); it('should render for signup-pass', async () => { const { container } = render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); await waitFor(() => { expect(container).not.toBeEmptyDOMElement(); }); expect(container).toHaveTextContent('address-123'); expect(container).toHaveTextContent('0.00135'); }); it('should show loading during the initial fetching', async () => { const { queryByTestId } = render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); expect(queryByTestId('circle-loader')).toBeInTheDocument(); }); it('should check the token every 10 seconds', async () => { addApiMock(getTokenStatus('token-123').url, () => { return { Status: PAYMENT_TOKEN_STATUS.STATUS_PENDING }; }); render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); addApiMock(getTokenStatus('token-123').url, function second() { return { Status: PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE }; }); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(onTokenValidated).toHaveBeenCalledTimes(1); expect(onTokenValidated).toHaveBeenLastCalledWith({ Payment: { Type: PAYMENT_METHOD_TYPES.TOKEN, Details: { Token: 'token-123', }, }, cryptoAddress: 'address-123', cryptoAmount: '0.00135', }); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(onTokenValidated).toHaveBeenCalledTimes(1); // check that it's called only once }); it('should render Try again button in case of error', async () => { addApiMock(createTokenUrl, () => { return Promise.reject('error'); }); const { queryByTestId, container } = render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); await waitFor(() => { expect(queryByTestId('bitcoin-try-again')).toBeInTheDocument(); }); addApiMock(createTokenUrl, () => defaultTokenResponse); queryByTestId('bitcoin-try-again')?.click(); await waitFor(() => { expect(container).toHaveTextContent('address-123'); }); await waitFor(() => { expect(container).toHaveTextContent('0.00135'); }); }); it('should render warning if the amount is too low', async () => { const { container } = render( <BitcoinTestComponent api={apiMock} amount={100} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); await waitFor(() => { expect(container).toHaveTextContent('Amount below minimum'); }); }); it('should render warning if the amount is too high', async () => { const { container } = render( <BitcoinTestComponent api={apiMock} amount={4000100} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); await waitFor(() => { expect(container).toHaveTextContent('Amount above maximum'); }); }); it('should call awaitingPayment callback when the token is created', async () => { const onAwaitingPayment = jest.fn(); render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); expect(onAwaitingPayment).toHaveBeenLastCalledWith(false); await waitFor(() => { expect(onAwaitingPayment).toHaveBeenLastCalledWith(true); }); }); it('should call awaitingPayment callback when the token is validated', async () => { const onAwaitingPayment = jest.fn(); render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(onAwaitingPayment).toHaveBeenLastCalledWith(false); }); it('should call awaitingPayment callback when amount or currency is changed', async () => { const onAwaitingPayment = jest.fn(); const { rerender } = render( <BitcoinTestComponent api={apiMock} amount={1000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); rerender( <BitcoinTestComponent api={apiMock} amount={2000} currency="USD" onTokenValidated={onTokenValidated} onAwaitingPayment={onAwaitingPayment} processingToken={false} /> ); jest.advanceTimersByTime(BITCOIN_POLLING_INTERVAL); await flushPromises(); expect(onAwaitingPayment).toHaveBeenLastCalledWith(false); });
6,686
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/Bitcoin.tsx
import { ReactNode, useEffect } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { MAX_BITCOIN_AMOUNT, MIN_BITCOIN_AMOUNT } from '@proton/shared/lib/constants'; import { Alert, Bordered, Loader, Price } from '../../components'; import BitcoinDetails from './BitcoinDetails'; import BitcoinQRCode, { OwnProps as BitcoinQRCodeProps } from './BitcoinQRCode'; import useBitcoin from './useBitcoin'; export type Props = ReturnType<typeof useBitcoin> & { processingToken?: boolean; }; const Bitcoin = ({ amount, currency, processingToken, paymentValidated, model, loading, error, request }: Props) => { useEffect(() => { void request(); }, [amount, currency]); if (amount < MIN_BITCOIN_AMOUNT) { const i18n = (amount: ReactNode) => c('Info').jt`Amount below minimum (${amount}).`; return ( <Alert className="mb-4" type="warning"> {i18n( <Price key="price" currency={currency}> {MIN_BITCOIN_AMOUNT} </Price> )} </Alert> ); } if (amount > MAX_BITCOIN_AMOUNT) { const i18n = (amount: ReactNode) => c('Info').jt`Amount above maximum (${amount}).`; return ( <Alert className="mb-4" type="warning"> {i18n( <Price key="price" currency={currency}> {MAX_BITCOIN_AMOUNT} </Price> )} </Alert> ); } if (loading) { return <Loader />; } if (error || !model.amountBitcoin || !model.address) { return ( <> <Alert className="mb-4" type="error">{c('Error').t`Error connecting to the Bitcoin API.`}</Alert> <Button onClick={request} data-testid="bitcoin-try-again">{c('Action').t`Try again`}</Button> </> ); } const qrCodeStatus: BitcoinQRCodeProps['status'] = (() => { if (processingToken) { return 'pending'; } if (paymentValidated) { return 'confirmed'; } return 'initial'; })(); const btcAmountBold = ( <span className="text-bold" key="btc-info-amount"> {model.amountBitcoin} BTC </span> ); return ( <Bordered className="p-6 rounded" data-testid="bitcoin-payment-data"> <div> <span> {c('Info').jt`To complete your payment, please send ${btcAmountBold} to the address below.`} </span> <div className="my-6 flex flex-justify-center"> <BitcoinQRCode className="flex flex-align-items-center flex-column" amount={model.amountBitcoin} address={model.address} status={qrCodeStatus} /> </div> </div> <BitcoinDetails amount={model.amountBitcoin} address={model.address} /> </Bordered> ); }; export default Bitcoin;
6,687
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/BitcoinDetails.tsx
import { HTMLAttributes } from 'react'; import { c } from 'ttag'; import clsx from '@proton/utils/clsx'; import { Copy } from '../../components'; export interface Props { amount: number; address: string; } const BitcoinDetailsLine = ({ label, value, fieldClassName: className, ...rest }: { label: string; value: string; fieldClassName?: string; } & HTMLAttributes<HTMLElement>) => { return ( <> <div className="text-rg text-semibold mb-1">{label}</div> <div className={clsx( 'rounded bg-weak py-1 px-3 flex flex-justify-space-between flex-align-items-center', className )} > <span {...rest}>{value}</span> <Copy value={`${value}`} shape="ghost" size="small" /> </div> </> ); }; const BitcoinDetails = ({ amount, address }: Props) => { return ( <div> {amount ? ( <BitcoinDetailsLine label={c('Label').t`BTC amount`} value={`${amount}`} fieldClassName="mb-4" /> ) : null} <BitcoinDetailsLine label={c('Label').t`BTC address`} value={address} data-testid="btc-address" /> </div> ); }; export default BitcoinDetails;
6,688
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/BitcoinInfoMessage.tsx
import { HTMLAttributes } from 'react'; import { c } from 'ttag'; import { Href } from '@proton/atoms/Href'; import { APPS } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { useConfig } from '../../hooks'; type Props = HTMLAttributes<HTMLDivElement>; const BitcoinInfoMessage = ({ ...rest }: Props) => { const { APP_NAME } = useConfig(); return ( <div className="mb-6" {...rest} data-testid="bitcoin-info-message"> <p className="mb-0"> {c('Info') .t`Submit a deposit using the following address or scan the QR code. Your deposit will be reflected in your account after confirmation.`} </p> <Href href={ APP_NAME === APPS.PROTONVPN_SETTINGS ? 'https://protonvpn.com/support/vpn-bitcoin-payments/' : getKnowledgeBaseUrl('/pay-with-bitcoin') } >{c('Link').t`How to pay with Bitcoin?`}</Href> </div> ); }; export default BitcoinInfoMessage;
6,689
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/BitcoinQRCode.scss
.blurred { filter: blur(7px); opacity: 0.5; }
6,690
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/BitcoinQRCode.tsx
import { ComponentProps } from 'react'; import { CircleLoader } from '@proton/atoms'; import clsx from '@proton/utils/clsx'; import { Icon, QRCode } from '../../components'; import './BitcoinQRCode.scss'; export interface OwnProps { amount: number; address: string; status: 'initial' | 'pending' | 'confirmed'; } const BitcoinQRCode = ({ amount, address, status, className, ...rest }: OwnProps & Omit<ComponentProps<typeof QRCode>, 'value'>) => { const url = `bitcoin:${address}?amount=${amount}`; const blurred = status === 'pending' || status === 'confirmed' ? 'blurred' : null; return ( <div className="border rounded relative p-6"> <QRCode value={url} className={clsx(className, blurred)} {...rest} /> {status === 'pending' && <CircleLoader size="medium" className="absolute-center" />} {status === 'confirmed' && ( <Icon name="checkmark-circle" size={36} className="absolute-center color-success" /> )} </div> ); }; export default BitcoinQRCode;
6,691
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/Cash.tsx
import { c } from 'ttag'; import { APPS } from '@proton/shared/lib/constants'; import envelopSvg from '@proton/styles/assets/img/illustrations/welcome-pane.svg'; import { Bordered } from '../../components'; import { useConfig } from '../../hooks'; const Cash = () => { const { APP_NAME } = useConfig(); const email = ( <b key="email-contact"> {APP_NAME === APPS.PROTONVPN_SETTINGS ? 'contact@protonvpn.com' : 'contact@proton.me'} </b> ); return ( <Bordered className="bg-weak rounded"> <div className="mb-4">{c('Info for cash payment method') .jt`Please contact us at ${email} for instructions on how to pay us with cash.`}</div> <div className="text-center"> <img src={envelopSvg} alt="" /> </div> </Bordered> ); }; export default Cash;
6,692
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/Checkout.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { Currency } from '@proton/shared/lib/interfaces'; import { Icon } from '../../components'; import CurrencySelector from './CurrencySelector'; interface Props { currency: Currency; onChangeCurrency: (newCurrency: Currency) => void; loading?: boolean; children: ReactNode; hasGuarantee?: boolean; hasPayments?: boolean; description?: ReactNode; renewNotice: ReactNode; hiddenRenewNotice?: ReactNode; } const Checkout = ({ currency, onChangeCurrency, loading, children, hasGuarantee, hasPayments = true, description, renewNotice, hiddenRenewNotice, }: Props) => { return ( <div className="p-6"> <div className="flex flex-nowrap mb-5"> <h2 className="h3 text-bold mt-1 mb-0 text-cut flex-item-fluid">{c('Title').t`Summary`}</h2> <span className="flex-item-noshrink" data-testid="checkoutCurrencyDropdown"> <CurrencySelector currency={currency} onSelect={onChangeCurrency} className="" mode="select-two" disabled={loading} /> </span> </div> <div className={loading ? 'opacity-50 no-pointer-events-children' : ''}>{children}</div> <div className="text-sm lh-standard"> {hasPayments && !hiddenRenewNotice && renewNotice && ( <div className="flex flex-nowrap color-weak"> <span className="flex-item-noshrink mr-2"> <Icon name="info-circle" size={16} /> </span> <span className="flex-item-fluid">{renewNotice}</span> </div> )} {hasPayments ? ( <div className="flex flex-nowrap color-weak my-2"> <span className="flex-item-noshrink mr-2"> <Icon name="shield" /> </span> <span className="flex-item-fluid">{c('Info') .t`Payments are protected with TLS encryption and Swiss privacy laws.`}</span> </div> ) : ( <div className="flex flex-nowrap mb-2"> <b className="flex-item-fluid">{c('new_plans: info') .t`Applicable credits, proration, and coupons are applied in the next step`}</b> </div> )} {hasGuarantee && ( <div className="flex flex-nowrap color-weak"> <span className="flex-item-noshrink mr-2"> <Icon name="clock" /> </span> <span className="flex-item-fluid">{c('Info').t`30-day money-back guarantee.`}</span> </div> )} </div> {description} {hiddenRenewNotice && hasPayments && ( <div className="mt-4"> <hr /> <div className="text-sm lh-standard">{hiddenRenewNotice}</div> </div> )} </div> ); }; export default Checkout;
6,693
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CredisModal.scss
@import '~@proton/styles/scss/lib'; .credits-modal .field-container.payment-right { inline-size: 70%; } @include media('<=small') { .credits-modal .label.payment-left, .credits-modal .field-container.payment-right { inline-size: 100%; } }
6,694
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CreditCard.scss
@import '~@proton/styles/scss/lib'; .card-information { .exp, .cvv { flex: initial; } .exp { .input-element { // ems should scale accordingly on mobile. max-inline-size: 5.5em; } } .cvv { .input-element { // ems should scale accordingly on mobile. max-inline-size: 3em; } } .input-adornment { margin-inline: 0; .input-element { border-radius: 0; } } } // for larger version .field-two--bigger { .exp:not(.exp--small), .cvv:not(.cvv--small) { .input-element { padding-block: rem(6); } } } .country-select { .input-adornment { color: var(--text-norm); margin-inline: 0; .input-element { border-radius: 0; padding-inline-start: rem(12) !important; } // we want the country dropdown to take exactly half of the width &:first-child { flex: 0 0 50%; } &:last-child { border: none !important; } } } .error-container { color: var(--signal-danger); min-block-size: rem(20); } .card-number--small, .exp--small, .cvv--small { &.error { z-index: $layer-upper; } &:focus-within { // we want the focus frame to be displayed over error frame z-index: $layer-upper + 1; } } .card-number--small { &#{&} { border-radius: var(--border-radius-md) var(--border-radius-md) 0 0; margin-block-end: -1px; } } .exp--small { &#{&} { border-radius: 0 0 0 var(--border-radius-md); } } .cvv--small { &#{&} { border-radius: 0 0 var(--border-radius-md) 0; margin-inline-start: -1px; } }
6,695
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CreditCard.test.tsx
import { render } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { useCard } from '@proton/components/payments/react-extensions'; import { apiMock } from '@proton/testing'; import CreditCard, { Props } from './CreditCard'; beforeEach(() => { jest.clearAllMocks(); }); const TestComponent = (rest?: Partial<Props>) => { const cardHook = useCard( { amountAndCurrency: { Amount: 0, Currency: 'USD', }, }, { api: apiMock, verifyPayment: jest.fn(), } ); return ( <CreditCard card={cardHook.card} errors={cardHook.errors} fieldsStatus={cardHook.fieldsStatus} onChange={cardHook.setCardProperty} {...rest} /> ); }; it('should render', () => { const { container } = render(<TestComponent />); expect(container).not.toBeEmptyDOMElement(); }); it('should be not narrow by default', () => { const { queryByTestId } = render(<TestComponent />); expect(queryByTestId('credit-card-form-container')).toHaveClass('field-two-container'); expect(queryByTestId('credit-card-form-container')).not.toHaveClass('credit-card-form--narrow'); }); it('should render narrow', () => { const { queryByTestId } = render(<TestComponent forceNarrow />); expect(queryByTestId('credit-card-form-container')).toHaveClass('field-two-container'); expect(queryByTestId('credit-card-form-container')).toHaveClass('credit-card-form--narrow'); }); it('should not accept invalid CVC input', async () => { const { queryByTestId } = render(<TestComponent />); const cvcInput = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(cvcInput, 'abc'); expect(cvcInput.value).toBe(''); }); describe('autoadvancer', () => { it('should move the cursor to the expiration date when credit card number is entered', async () => { const { queryByTestId } = render(<TestComponent />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; await userEvent.type(ccNumber, '4242424242424242'); const expInput = queryByTestId('exp') as HTMLInputElement; expect(expInput).toHaveFocus(); }); it('should move the cursor to the cvc when expiration date is entered', async () => { const { queryByTestId } = render(<TestComponent />); const expInput = queryByTestId('exp') as HTMLInputElement; await userEvent.type(expInput, '1232'); const cvcInput = queryByTestId('cvc') as HTMLInputElement; expect(cvcInput).toHaveFocus(); }); it('should move the cursor to the zip when cvc is entered', async () => { const { queryByTestId } = render(<TestComponent />); const cvcInput = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(cvcInput, '123'); const zipInput = queryByTestId('postalCode') as HTMLInputElement; expect(zipInput).toHaveFocus(); }); it('narrow - should move the cursor to the expiration date when credit card number is entered', async () => { const { queryByTestId } = render(<TestComponent forceNarrow />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; await userEvent.type(ccNumber, '4242424242424242'); const expInput = queryByTestId('exp') as HTMLInputElement; expect(expInput).toHaveFocus(); }); it('narrow should move the cursor to the cvc when expiration date is entered', async () => { const { queryByTestId } = render(<TestComponent forceNarrow />); const expInput = queryByTestId('exp') as HTMLInputElement; await userEvent.type(expInput, '1232'); const cvcInput = queryByTestId('cvc') as HTMLInputElement; expect(cvcInput).toHaveFocus(); }); it('narrow should move the cursor to the zip when cvc is entered', async () => { const { queryByTestId } = render(<TestComponent forceNarrow />); const cvcInput = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(cvcInput, '123'); const zipInput = queryByTestId('postalCode') as HTMLInputElement; expect(zipInput).toHaveFocus(); }); it('should not move cursor the second time, if user decides to edit the field', async () => { const { queryByTestId } = render(<TestComponent />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; await userEvent.type(ccNumber, '4242424242424242'); expect(ccNumber.value).toBe('4242 4242 4242 4242'); // formatted const expInput = queryByTestId('exp') as HTMLInputElement; expect(expInput).toHaveFocus(); await userEvent.click(ccNumber); await userEvent.type(ccNumber, '4242424242424242'); expect(ccNumber).toHaveFocus(); }); it('should not move the cursor if the credit card number is invalid', async () => { const { queryByTestId } = render(<TestComponent />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; await userEvent.type(ccNumber, '4000000000000000'); expect(ccNumber.value).toBe('4000 0000 0000 0000'); // formatted expect(ccNumber).toHaveFocus(); }); it('should not move the cursor if the expiration date is invalid', async () => { const { queryByTestId } = render(<TestComponent />); const expInput = queryByTestId('exp') as HTMLInputElement; await userEvent.type(expInput, '1211'); expect(expInput.value).toBe('12/11'); expect(expInput).toHaveFocus(); }); it('should not move the cursor if the cvc is invalid', async () => { const { queryByTestId } = render(<TestComponent />); const cvcInput = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(cvcInput, '12'); expect(cvcInput).toHaveFocus(); }); it('should move the cursor when user enter correct AmEx card number', async () => { const { queryByTestId } = render(<TestComponent />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; const num = '374245455400126'; expect(num.length).toBe(15); // not 16 as for Visa await userEvent.type(ccNumber, num); expect(ccNumber.value).toBe('3742 454554 00126'); // formatted const expInput = queryByTestId('exp') as HTMLInputElement; expect(expInput).toHaveFocus(); }); it('should move the cursor to ZIP when user enter correct AmEx card number and 4-digit security code', async () => { const { queryByTestId } = render(<TestComponent />); const ccNumber = queryByTestId('ccnumber') as HTMLInputElement; const num = '374245455400126'; expect(num.length).toBe(15); // not 16 as for Visa await userEvent.type(ccNumber, num); const expInput = queryByTestId('exp') as HTMLInputElement; expect(expInput).toHaveFocus(); await userEvent.type(expInput, '1232'); const cvcInput = queryByTestId('cvc') as HTMLInputElement; expect(cvcInput).toHaveFocus(); await userEvent.type(cvcInput, '1234'); const zipInput = queryByTestId('postalCode') as HTMLInputElement; expect(zipInput).toHaveFocus(); expect(cvcInput.value).toBe('1234'); }); });
6,696
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CreditCard.tsx
import { ChangeEvent, useEffect, useMemo, useRef, useState } from 'react'; import valid from 'card-validator'; import { c } from 'ttag'; import { Input } from '@proton/atoms'; import { SelectChangeEvent } from '@proton/components/components/selectTwo/select'; import { requestAnimationFrameRateLimiter, default as useElementRect } from '@proton/components/hooks/useElementRect'; import { formatCreditCardNumber, isValidNumber } from '@proton/components/payments/client-extensions/credit-card-type'; import { CardFieldStatus } from '@proton/components/payments/react-extensions/useCard'; import { rootFontSize } from '@proton/shared/lib/helpers/dom'; import { isNumber } from '@proton/shared/lib/helpers/validators'; import clsx from '@proton/utils/clsx'; import { Icon, Label, Option, SelectTwo } from '../../components'; import { DEFAULT_SEPARATOR, getFullList } from '../../helpers/countries'; import { CardModel } from '../../payments/core'; import './CreditCard.scss'; const isPotentiallyCVV = (value: string, maxLength: number) => valid.cvv(value, maxLength).isPotentiallyValid; const isValidMonth = (m: string) => !m || (isNumber(m) && m.length <= 2); const isValidYear = (y: string) => !y || (isNumber(y) && y.length <= 4); const handleExpOnChange = (newValue: string, prevMonth: string, prevYear: string) => { const [newMonth = '', newYear = ''] = newValue.split('/'); if (newValue.includes('/')) { return { month: isValidMonth(newMonth) ? newMonth : prevMonth, year: isValidYear(newYear) ? newYear : prevYear, }; } if (newMonth.length > 2) { // User removes the '/' return; } if (prevMonth.length === 2) { // User removes the '/' and year is empty const [first = ''] = newMonth; return { year: '', month: isValidMonth(first) ? first : prevMonth, }; } const [first = '', second = ''] = newMonth; return { year: '', month: isValidMonth(`${first}${second}`) ? `${first}${second}` : prevMonth, }; }; const WarningIcon = ({ className }: { className?: string }) => { return ( <Icon name="exclamation-circle-filled" className={clsx('flex-item-noshrink color-danger', className)} size={18} /> ); }; export interface Props { onChange: (key: keyof CardModel, value: string) => void; loading?: boolean; card: CardModel; errors: Partial<CardModel>; fieldsStatus: CardFieldStatus; bigger?: boolean; forceNarrow?: boolean; } /** * The hook will focus the next field if the current field is filled and the condition is true. * The codition typically should be true when the current field is valid. */ const useAdvancer = ( currentElementRef: React.RefObject<HTMLInputElement>, nextElementRef: React.RefObject<HTMLInputElement>, currentFieldState: string, condition: boolean ) => { const [advanced, setAdvanced] = useState(false); useEffect(() => { const currentElementFocused = document.activeElement === currentElementRef.current; if (condition && currentElementFocused && nextElementRef.current && !advanced) { nextElementRef.current.focus(); setAdvanced(true); } }, [currentFieldState, condition]); }; const CreditCard = ({ card, errors, onChange, loading = false, fieldsStatus, bigger = false, forceNarrow = false, }: Props) => { const narrowNumberRef = useRef<HTMLInputElement>(null); const narrowExpRef = useRef<HTMLInputElement>(null); const narrowCvcRef = useRef<HTMLInputElement>(null); const wideNumberRef = useRef<HTMLInputElement>(null); const wideExpRef = useRef<HTMLInputElement>(null); const wideCvcRef = useRef<HTMLInputElement>(null); const zipRef = useRef<HTMLInputElement>(null); useAdvancer(narrowNumberRef, narrowExpRef, card.number, fieldsStatus?.number ?? false); useAdvancer(narrowExpRef, narrowCvcRef, card.month, fieldsStatus?.month ?? false); useAdvancer(narrowCvcRef, zipRef, card.cvc, fieldsStatus?.cvc ?? false); useAdvancer(wideNumberRef, wideExpRef, card.number, fieldsStatus?.number ?? false); useAdvancer(wideExpRef, wideCvcRef, card.month, fieldsStatus?.month ?? false); useAdvancer(wideCvcRef, zipRef, card.cvc, fieldsStatus?.cvc ?? false); const formContainer = useRef<HTMLDivElement>(null); const formRect = useElementRect(formContainer, requestAnimationFrameRateLimiter); const countries = useMemo(() => getFullList(), []); const maxCvvLength = 4; const handleChange = (key: keyof CardModel) => ({ target }: ChangeEvent<HTMLInputElement> | ChangeEvent<HTMLSelectElement>) => { const newValue = target.value; // todo: if the new design is widely adopted or at least stabilized by several weeks in prod, // then make this logic as part of credit card validation overall, i.e. apply it to getErrors() in useCard() hook const isInvalid = key === 'cvc' && !isPotentiallyCVV(newValue, maxCvvLength); if (isInvalid) { return; } onChange(key, newValue); }; // translator: this is the pattern for bank card expiration MM/YY, where MM stands for Month Month and YY Year Year. Please keep the slash in the middle. const patternExpiration = c('Info').t`MM/YY`; // translator: this is a ZIP code used for american credit cards const zipCode = c('Label, credit card').t`ZIP code`; const title = card.country === 'US' ? zipCode : c('Label').t`Postal code`; const commonNumberProps = { id: 'ccnumber', 'data-testid': 'ccnumber', disableChange: loading, autoComplete: 'cc-number', name: 'cardnumber', maxLength: 23, }; const commonExpProps = { id: 'exp', disableChange: loading, placeholder: patternExpiration, 'data-testid': 'exp', autoComplete: 'cc-exp', maxLength: 5, }; const commonCvcProps = { autoComplete: 'cc-csc', id: 'cvc', name: 'cvc', 'data-testid': 'cvc', value: card.cvc, onChange: handleChange('cvc'), disableChange: loading, maxLength: maxCvvLength, }; const { valueWithGaps, bankIcon, niceType, codeName } = formatCreditCardNumber(card.number); const { month, year } = card; // 25 x 16 = we want eq 400px width to trigger the adaptation being zoom-friendly const narrowWidth = rootFontSize() * 25; const isNarrow = forceNarrow || (formRect ? formRect.width < narrowWidth : false); let error = null; if (errors.number) { error = ( <span data-testid="error-ccnumber" id="error-ccnumber"> {errors.number} </span> ); } else if (errors.month) { error = ( <span data-testid="error-exp" id="error-exp"> {errors.month} </span> ); } else if (errors.cvc) { error = ( <span data-testid="error-cvc" id="error-cvc"> {errors.cvc} </span> ); } let creditCardForm; if (isNarrow) { const cardNumberSuffix = (() => { if (errors.number) { return <WarningIcon />; } if (card.number && bankIcon) { return <img src={bankIcon} title={niceType} alt={niceType} width="24" />; } return <Icon name="credit-card" size={16} className="mr-1" />; })(); creditCardForm = ( <> <Label htmlFor={commonNumberProps.id} className="field-two-label field-two-label-container flex pt-3" >{c('Label').t`Card details`}</Label> <span id="id_desc_card_number" className="sr-only">{c('Label').t`Card number`}</span> <Input className="card-number--small" inputClassName="px-3" placeholder={c('Label').t`Card number`} aria-describedby="id_desc_card_number error-ccnumber" value={valueWithGaps} error={errors.number} onChange={({ target }) => { const val = target.value.replace(/\s/g, ''); if (isValidNumber(val)) { onChange('number', val); } }} suffix={cardNumberSuffix} ref={narrowNumberRef} {...commonNumberProps} /> <div className="flex"> <Label htmlFor={commonExpProps.id} className="sr-only">{c('Label') .t`Expiration (${patternExpiration})`}</Label> <Input inputClassName="px-3" className="exp exp--small" aria-describedby="error-exp" value={`${month}${month.length === 2 || year.length ? '/' : ''}${year}`} error={errors.month} onChange={({ target }) => { const change = handleExpOnChange(target.value, month, year); if (change) { onChange('month', change.month); onChange('year', change.year); } }} ref={narrowExpRef} suffix={errors.month ? <WarningIcon /> : null} {...commonExpProps} /> <Label htmlFor={commonCvcProps.id} className="sr-only">{c('Label') .t`Security code (${codeName})`}</Label> <Input placeholder={codeName} inputClassName="px-3" className="cvv cvv--small" aria-describedby="error-cvc" ref={narrowCvcRef} error={errors.cvc} suffix={errors.cvc ? <WarningIcon /> : null} {...commonCvcProps} /> </div> </> ); } else { creditCardForm = ( <> <Label htmlFor={commonNumberProps.id} className="field-two-label field-two-label-container flex pt-3" >{c('Label').t`Card details`}</Label> <span id="id_desc_card_number" className="sr-only">{c('Label').t`Card number`}</span> <Input className="card-information" inputClassName="card-number" placeholder={c('Label').t`Card number`} value={valueWithGaps} error={error} aria-describedby="id_desc_card_number error-ccnumber" onChange={({ target }) => { const val = target.value.replace(/\s/g, ''); if (isValidNumber(val)) { onChange('number', val); } }} ref={wideNumberRef} prefix={ <div className="ml-3 mr-1"> {card.number && bankIcon ? ( <img src={bankIcon} title={niceType} alt={niceType} width="32" /> ) : ( <Icon name="credit-card-detailed" size={32} /> )} </div> } suffix={ <div className="flex mx-0"> <Label htmlFor={commonExpProps.id} className="sr-only">{c('Label') .t`Expiration (${patternExpiration})`}</Label> <Input unstyled inputClassName="mr-3 py-0.5 px-3 border-left border-right" className="exp" aria-describedby="error-exp" value={`${month}${month.length === 2 || year.length ? '/' : ''}${year}`} onChange={({ target }) => { const change = handleExpOnChange(target.value, month, year); if (change) { onChange('month', change.month); onChange('year', change.year); } }} ref={wideExpRef} {...commonExpProps} /> <Label htmlFor={commonCvcProps.id} className="sr-only">{c('Label') .t`Security code (${codeName})`}</Label> <Input unstyled placeholder={codeName} aria-describedby="error-cvc" inputClassName="p-0" className="cvv" ref={wideCvcRef} {...commonCvcProps} /> </div> } {...commonNumberProps} /> </> ); } return ( <div ref={formContainer} data-testid="credit-card-form-container" className={clsx([ 'field-two-container', bigger && 'field-two--bigger', isNarrow && 'credit-card-form--narrow', ])} > {creditCardForm} <div className="error-container mt-1 text-semibold text-sm flex gap-2"> {error && ( <div className="flex"> <WarningIcon className="mr-1" /> {error} </div> )} </div> <Label htmlFor="postalcode" className="field-two-label field-two-label-container flex pt-1">{c('Label') .t`Billing address`}</Label> <Input placeholder={title} className="country-select flex-justify-space-between divide-x" inputClassName="ml-1" prefixClassName="flex-item-fluid" ref={zipRef} prefix={ <SelectTwo className="mx-3" unstyled onChange={ loading ? undefined : ({ value }: SelectChangeEvent<string>) => { if (value === DEFAULT_SEPARATOR.value) { return; } onChange('country', value); } } data-testid="country" id="country" value={card.country} > {countries.map(({ key, value, label, disabled }) => { return ( <Option key={key} value={value} title={label} disabled={disabled} data-testid={`country-${value}`} > {value === DEFAULT_SEPARATOR.value ? <hr className="m-0" /> : label} </Option> ); })} </SelectTwo> } data-testid="postalCode" minLength={3} maxLength={9} autoComplete="postal-code" id="postalcode" aria-describedby="id_desc_postal" value={card.zip} onChange={handleChange('zip')} disableChange={loading} title={title} error={errors.zip} suffix={errors.zip ? <WarningIcon className="mr-2" /> : null} /> <span className="sr-only" id="id_desc_postal"> {title} </span> <div className="error-container mt-1 mb-3 text-semibold text-sm flex"> {errors.zip && ( <> <WarningIcon className="mr-1" /> <span data-testid="error-postalCode">{errors.zip}</span> </> )} </div> </div> ); }; export default CreditCard;
6,697
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CreditsModal.test.tsx
import { fireEvent, render, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { PAYMENT_TOKEN_STATUS } from '@proton/components/payments/core'; import { buyCredit, createToken } from '@proton/shared/lib/api/payments'; import { wait } from '@proton/shared/lib/helpers/promise'; import { addApiMock, applyHOCs, mockEventManager, mockPaymentMethods, mockPaymentStatus, withApi, withAuthentication, withCache, withConfig, withDeprecatedModals, withEventManager, withNotifications, } from '@proton/testing'; // eslint-disable-next-line @typescript-eslint/no-unused-vars import PaymentMethodSelector from '../paymentMethods/PaymentMethodSelector'; import CreditsModal from './CreditsModal'; jest.mock('@proton/components/components/portal/Portal'); const createTokenMock = jest.fn((request) => { const type = request?.data?.Payment?.Type ?? ''; let Token: string; if (type === 'paypal') { Token = 'paypal-payment-token-123'; } else if (type === 'paypal-credit') { Token = 'paypal-credit-payment-token-123'; } else { Token = 'payment-token-123'; } return { Token, Status: PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE, }; }); const buyCreditUrl = buyCredit({} as any).url; const buyCreditMock = jest.fn().mockResolvedValue({}); beforeEach(() => { jest.clearAllMocks(); // That's an unresolved issue of jsdom https://github.com/jsdom/jsdom/issues/918 (window as any).SVGElement.prototype.getBBox = jest.fn().mockReturnValue({ width: 0 }); addApiMock(createToken({} as any).url, createTokenMock); addApiMock(buyCreditUrl, buyCreditMock); mockPaymentStatus(); mockPaymentMethods().noSaved(); }); const ContextCreditsModal = applyHOCs( withConfig(), withNotifications(), withEventManager(), withApi(), withCache(), withDeprecatedModals(), withAuthentication() )(CreditsModal); it('should render', () => { const { container } = render(<ContextCreditsModal open={true} />); expect(container).not.toBeEmptyDOMElement(); }); it('should display the credit card form by default', async () => { const { findByTestId } = render(<ContextCreditsModal open={true} />); const ccnumber = await findByTestId('ccnumber'); expect(ccnumber).toBeTruthy(); }); it('should display the payment method selector', async () => { const { queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => { /** * That's essentially internals of {@link PaymentMethodSelector} **/ expect(queryByTestId('payment-method-selector')).toBeTruthy(); }); }); function selectMethod(container: HTMLElement, value: string) { const dropdownButton = container.querySelector('#select-method') as HTMLButtonElement; if (dropdownButton) { fireEvent.click(dropdownButton); const button = container.querySelector(`button[title="${value}"]`) as HTMLButtonElement; fireEvent.click(button); return; } const input = container.querySelector(`#${value}`) as HTMLInputElement; input.click(); } it('should select the payment method when user clicks it', async () => { const { container, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); // secondary check expect(queryByTestId('payment-method-selector')).toHaveTextContent('PayPal'); // check that the credit card form is not displayed expect(queryByTestId('ccnumber')).toBeFalsy(); expect(queryByTestId('paypal-view')).toBeTruthy(); expect(queryByTestId('paypal-button')).toBeTruthy(); // switching back to credit card selectMethod(container, 'New credit/debit card'); expect(queryByTestId('ccnumber')).toBeTruthy(); expect(queryByTestId('paypal-button')).toBeFalsy(); expect(queryByTestId('top-up-button')).toBeTruthy(); }); it('should display the credit card form initially', async () => { const { queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => { expect(queryByTestId('ccnumber')).toBeTruthy(); }); }); it('should remember credit card details when switching back and forth', async () => { const { container, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => {}); const ccnumber = queryByTestId('ccnumber') as HTMLInputElement; const exp = queryByTestId('exp') as HTMLInputElement; const cvc = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(ccnumber, '4242424242424242'); await userEvent.type(exp, '1232'); await userEvent.type(cvc, '123'); // switching to paypal selectMethod(container, 'PayPal'); expect(queryByTestId('paypal-view')).toBeTruthy(); // switching back to credit card selectMethod(container, 'New credit/debit card'); expect((queryByTestId('ccnumber') as HTMLInputElement).value).toBe('4242 4242 4242 4242'); expect((queryByTestId('exp') as HTMLInputElement).value).toBe('12/32'); expect((queryByTestId('cvc') as HTMLInputElement).value).toBe('123'); }); it('should display validation errors after user submits credit card', async () => { const { container, findByTestId, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => {}); const ccnumber = queryByTestId('ccnumber') as HTMLInputElement; const exp = queryByTestId('exp') as HTMLInputElement; const cvc = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(ccnumber, '1234567812345678'); await userEvent.type(exp, '1212'); await userEvent.type(cvc, '123'); const cardError = 'Invalid card number'; const zipError = 'Invalid postal code'; expect(container).not.toHaveTextContent(cardError); expect(container).not.toHaveTextContent(zipError); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); expect(container).toHaveTextContent(cardError); expect(container).toHaveTextContent(zipError); }); it('should display invalid expiration date error', async () => { const { container, findByTestId, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => {}); const ccnumber = queryByTestId('ccnumber') as HTMLInputElement; const exp = queryByTestId('exp') as HTMLInputElement; const cvc = queryByTestId('cvc') as HTMLInputElement; await userEvent.type(ccnumber, '4242424242424242'); await userEvent.type(exp, '1212'); await userEvent.type(cvc, '123'); const expError = 'Invalid expiration date'; expect(container).not.toHaveTextContent(expError); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); expect(container).toHaveTextContent(expError); }); it('should create payment token and then buy credits with it', async () => { const onClose = jest.fn(); const { findByTestId, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => {}); const ccnumber = queryByTestId('ccnumber') as HTMLInputElement; const exp = queryByTestId('exp') as HTMLInputElement; const cvc = queryByTestId('cvc') as HTMLInputElement; const postalCode = queryByTestId('postalCode') as HTMLInputElement; await userEvent.type(ccnumber, '4242424242424242'); await userEvent.type(exp, '1232'); await userEvent.type(cvc, '123'); await userEvent.type(postalCode, '11111'); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'payment-token-123', }), }), Amount: 5000, Currency: 'EUR', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should create payment token and then buy credits with it - custom amount', async () => { const onClose = jest.fn(); const { findByTestId, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => {}); const otherAmountInput = queryByTestId('other-amount') as HTMLInputElement; await userEvent.type(otherAmountInput, '123'); const ccnumber = queryByTestId('ccnumber') as HTMLInputElement; const exp = queryByTestId('exp') as HTMLInputElement; const cvc = queryByTestId('cvc') as HTMLInputElement; const postalCode = queryByTestId('postalCode') as HTMLInputElement; await userEvent.type(ccnumber, '4242424242424242'); await userEvent.type(exp, '1232'); await userEvent.type(cvc, '123'); await userEvent.type(postalCode, '11111'); await wait(500); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'payment-token-123', }), }), Amount: 12300, Currency: 'EUR', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should create payment token for paypal and then buy credits with it', async () => { const onClose = jest.fn(); const { container, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); const paypalButton = queryByTestId('paypal-button') as HTMLButtonElement; fireEvent.click(paypalButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'paypal-payment-token-123', }), }), Amount: 5000, Currency: 'EUR', type: 'paypal', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should create payment token for paypal and then buy credits with it - custom amount', async () => { const onClose = jest.fn(); const { container, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); const otherAmountInput = queryByTestId('other-amount') as HTMLInputElement; await userEvent.type(otherAmountInput, '123'); await wait(1000); const paypalButton = queryByTestId('paypal-button') as HTMLButtonElement; fireEvent.click(paypalButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'paypal-payment-token-123', }), }), Amount: 12300, Currency: 'EUR', type: 'paypal', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should disable paypal button while the amount is debouncing', async () => { const onClose = jest.fn(); const { container, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); const otherAmountInput = queryByTestId('other-amount') as HTMLInputElement; await userEvent.type(otherAmountInput, '123'); expect(queryByTestId('paypal-button')).toBeDisabled(); expect(queryByTestId('paypal-credit-button')).toBeDisabled(); await wait(1000); expect(queryByTestId('paypal-button')).not.toBeDisabled(); expect(queryByTestId('paypal-credit-button')).not.toBeDisabled(); }); it('should disable paypal button if the amount is too high', async () => { const onClose = jest.fn(); const { container, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); const otherAmountInput = queryByTestId('other-amount') as HTMLInputElement; await userEvent.type(otherAmountInput, '40001'); await wait(1000); expect(queryByTestId('paypal-button')).toBeDisabled(); expect(queryByTestId('paypal-credit-button')).toBeDisabled(); await userEvent.clear(otherAmountInput); await userEvent.type(otherAmountInput, '40000'); await wait(1000); expect(queryByTestId('paypal-button')).not.toBeDisabled(); expect(queryByTestId('paypal-credit-button')).not.toBeDisabled(); }); it('should create payment token for paypal-credit and then buy credits with it', async () => { const onClose = jest.fn(); const { container, queryByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'PayPal'); }); const paypalCreditButton = queryByTestId('paypal-credit-button') as HTMLButtonElement; fireEvent.click(paypalCreditButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'paypal-credit-payment-token-123', }), }), Amount: 5000, Currency: 'EUR', type: 'paypal-credit', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); const paypalPayerId = 'AAAAAAAAAAAAA'; const paypalShort = `PayPal - ${paypalPayerId}`; it('should display the saved credit cards', async () => { mockPaymentMethods().noSaved().withCard({ Last4: '4242', Brand: 'Visa', ExpMonth: '01', ExpYear: '2025', Name: 'John Smith', Country: 'US', ZIP: '11111', }); const { container, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => { expect(container.querySelector('#select-method')).toBeTruthy(); }); await waitFor(() => { expect(queryByTestId('existing-credit-card')).toBeTruthy(); }); expect(container).toHaveTextContent('Visa ending in 4242'); expect(container).toHaveTextContent('•••• •••• •••• 4242'); expect(container).toHaveTextContent('John Smith'); expect(container).toHaveTextContent('01/2025'); }); it('should display the saved paypal account', async () => { mockPaymentMethods().noSaved().withPaypal({ BillingAgreementID: 'B-22222222222222222', PayerID: paypalPayerId, Payer: '', }); const { container, queryByTestId } = render(<ContextCreditsModal open={true} />); await waitFor(() => { expect(container.querySelector('#select-method')).toBeTruthy(); selectMethod(container, paypalShort); }); expect(queryByTestId('existing-paypal')).toBeTruthy(); expect(container).toHaveTextContent('PayPal - AAAAAAAAAAAAA'); }); it('should create payment token for saved card and then buy credits with it', async () => { mockPaymentMethods().noSaved().withCard({ Last4: '4242', Brand: 'Visa', ExpMonth: '01', ExpYear: '2025', Name: 'John Smith', Country: 'US', ZIP: '11111', }); const onClose = jest.fn(); const { container, findByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, 'Visa ending in 4242'); }); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ Token: 'payment-token-123', }), }), Amount: 5000, Currency: 'EUR', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); }); it('should create payment token for saved paypal and then buy credits with it', async () => { mockPaymentMethods().noSaved().withPaypal({ BillingAgreementID: 'B-22222222222222222', PayerID: paypalPayerId, Payer: '', }); const onClose = jest.fn(); const { container, findByTestId } = render(<ContextCreditsModal open={true} onClose={onClose} />); await waitFor(() => { selectMethod(container, paypalShort); }); const topUpButton = await findByTestId('top-up-button'); fireEvent.click(topUpButton); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalled(); }); await waitFor(() => { expect(buyCreditMock).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ Payment: expect.objectContaining({ Type: 'token', Details: expect.objectContaining({ // The saved paypal method isn't handled by paypal hook. // It's handled by the same hook as the saved credit card. // That's why the mocked token isn't taken from the paypal mock this time. Token: 'payment-token-123', }), }), Amount: 5000, Currency: 'EUR', }), method: 'post', url: buyCreditUrl, }) ); }); await waitFor(() => { expect(mockEventManager.call).toHaveBeenCalled(); }); await waitFor(() => { expect(onClose).toHaveBeenCalled(); }); });
6,698
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/payments/CreditsModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { usePaymentFacade } from '@proton/components/payments/client-extensions'; import { AmountAndCurrency, PAYMENT_METHOD_TYPES, TokenPaymentMethod } from '@proton/components/payments/core'; import { PaymentProcessorHook } from '@proton/components/payments/react-extensions/interface'; import { useLoading } from '@proton/hooks'; import { buyCredit } from '@proton/shared/lib/api/payments'; import { APPS, DEFAULT_CREDITS_AMOUNT, DEFAULT_CURRENCY, MAX_BITCOIN_AMOUNT, MIN_BITCOIN_AMOUNT, MIN_CREDIT_AMOUNT, } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { captureMessage } from '@proton/shared/lib/helpers/sentry'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Currency } from '@proton/shared/lib/interfaces'; import { getSentryError } from '@proton/shared/lib/keys'; import { Form, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, useDebounceInput, } from '../../components'; import { useApi, useConfig, useEventManager, useNotifications } from '../../hooks'; import AmountRow from './AmountRow'; import PaymentInfo from './PaymentInfo'; import PaymentWrapper from './PaymentWrapper'; import StyledPayPalButton from './StyledPayPalButton'; const getCurrenciesI18N = () => ({ EUR: c('Monetary unit').t`Euro`, CHF: c('Monetary unit').t`Swiss franc`, USD: c('Monetary unit').t`Dollar`, }); const CreditsModal = (props: ModalProps) => { const { APP_NAME } = useConfig(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const [currency, setCurrency] = useState<Currency>(DEFAULT_CURRENCY); const [amount, setAmount] = useState(DEFAULT_CREDITS_AMOUNT); const debouncedAmount = useDebounceInput(amount); const amountLoading = debouncedAmount !== amount; const i18n = getCurrenciesI18N(); const i18nCurrency = i18n[currency]; const api = useApi(); const paymentFacade = usePaymentFacade({ amount: debouncedAmount, currency, onChargeable: (operations) => { return withLoading(async () => { await operations.buyCredit(); await call(); props.onClose?.(); createNotification({ text: c('Success').t`Credits added` }); }); }, flow: 'credit', }); const [bitcoinValidated, setBitcoinValidated] = useState(false); const [awaitingBitcoinPayment, setAwaitingBitcoinPayment] = useState(false); const exitSuccess = async () => { props.onClose?.(); createNotification({ text: c('Success').t`Credits added` }); }; const handleChargeableToken = async (tokenPaymentMethod: TokenPaymentMethod) => { const amountAndCurrency: AmountAndCurrency = { Amount: debouncedAmount, Currency: currency }; await api(buyCredit({ ...tokenPaymentMethod, ...amountAndCurrency })); await call(); }; const method = paymentFacade.selectedMethodValue; const submit = (() => { const bitcoinAmountInRange = debouncedAmount >= MIN_BITCOIN_AMOUNT && debouncedAmount <= MAX_BITCOIN_AMOUNT; if (debouncedAmount < MIN_CREDIT_AMOUNT || (method === PAYMENT_METHOD_TYPES.BITCOIN && !bitcoinAmountInRange)) { return null; } if (paymentFacade.methods.isNewPaypal) { return ( <StyledPayPalButton type="submit" paypal={paymentFacade.paypal} amount={debouncedAmount} currency={paymentFacade.currency} loading={loading} disabled={amountLoading} data-testid="paypal-button" /> ); } const topUpText = c('Action').t`Top up`; if (method === PAYMENT_METHOD_TYPES.BITCOIN) { return ( <PrimaryButton loading={!bitcoinValidated && awaitingBitcoinPayment} disabled={true} data-testid="top-up-button" > {awaitingBitcoinPayment ? c('Info').t`Awaiting transaction` : topUpText} </PrimaryButton> ); } return ( <PrimaryButton loading={loading} disabled={paymentFacade.methods.loading || !paymentFacade.userCanTriggerSelected || amountLoading} type="submit" data-testid="top-up-button" > {topUpText} </PrimaryButton> ); })(); const process = async (processor?: PaymentProcessorHook) => withLoading(async () => { if (!processor) { return; } try { await processor.processPaymentToken(); } catch (e) { const error = getSentryError(e); if (error) { const context = { app: APP_NAME, currency, amount, debouncedAmount, processorType: paymentFacade.selectedProcessor?.meta.type, paymentMethod: paymentFacade.selectedMethodType, paymentMethodValue: paymentFacade.selectedMethodValue, }; captureMessage('Payments: failed to handle credits', { level: 'error', extra: { error, context }, }); } } }); return ( <ModalTwo className="credits-modal" size="large" as={Form} onSubmit={() => process(paymentFacade.selectedProcessor)} {...props} > <ModalTwoHeader title={c('Title').t`Add credits`} /> <ModalTwoContent> <PaymentInfo paymentMethodType={paymentFacade.selectedMethodType} /> <div className="mb-4"> <div> {c('Info') .jt`Top up your account with credits that you can use to subscribe to a new plan or renew your current plan. You get one credit for every ${i18nCurrency} spent.`} </div> <Href href={ APP_NAME === APPS.PROTONVPN_SETTINGS ? 'https://protonvpn.com/support/vpn-credit-proration/' : getKnowledgeBaseUrl('/credit-proration-coupons') } > {c('Link').t`Learn more`} </Href> </div> <AmountRow paymentMethodType={paymentFacade.selectedMethodType} amount={amount} onChangeAmount={setAmount} currency={currency} onChangeCurrency={setCurrency} /> <PaymentWrapper {...paymentFacade} onPaypalCreditClick={() => process(paymentFacade.paypalCredit)} noMaxWidth onBitcoinTokenValidated={async (data) => { setBitcoinValidated(true); await handleChargeableToken(data); void wait(2000).then(() => exitSuccess()); }} onAwaitingBitcoinPayment={setAwaitingBitcoinPayment} triggersDisabled={amountLoading} /> </ModalTwoContent> <ModalTwoFooter> <Button onClick={props.onClose}>{c('Action').t`Close`}</Button> {submit} </ModalTwoFooter> </ModalTwo> ); }; export default CreditsModal;
6,699