Skip to content

The open alternative to Salesforce, designed for AI.

fix(billing) - update billing plan CTAs from the plan and interval grid (#26129)

Etienne5b280ccbdf26
diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingSubscriptionInfo.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingSubscriptionInfo.tsx
index 5e4cb65ca1e..6ec6088b76c 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingSubscriptionInfo.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingSubscriptionInfo.tsx
@@ -5,8 +5,10 @@ import { SettingsBillingSubscriptionInfoCard } from '@/settings/billing/componen
import { SettingsBillingSubscriptionInfoCardHeaderActions } from '@/settings/billing/components/internal/SettingsBillingSubscriptionInfoCardHeaderActions';
import { SettingsBillingSubscriptionInfoModals } from '@/settings/billing/components/internal/SettingsBillingSubscriptionInfoModals';
import { BILLING_MODAL_IDS } from '@/settings/billing/constants/BillingModalIds';
+import { useApplyBillingSubscriptionChange } from '@/settings/billing/hooks/useApplyBillingSubscriptionChange';
import { useApplyCurrentWorkspaceBillingUpdate } from '@/settings/billing/hooks/useApplyCurrentWorkspaceBillingUpdate';
import { useBillingSubscriptionCost } from '@/settings/billing/hooks/useBillingSubscriptionCost';
+import { useBillingSubscriptionChangeWording } from '@/settings/billing/hooks/useBillingSubscriptionChangeWording';
import { useBillingWording } from '@/settings/billing/hooks/useBillingWording';
import { useCurrentBillingFlags } from '@/settings/billing/hooks/useCurrentBillingFlags';
import { useCurrentPlan } from '@/settings/billing/hooks/useCurrentPlan';
@@ -14,6 +16,7 @@ import { useCurrentResourceCredit } from '@/settings/billing/hooks/useCurrentRes
import { useEndSubscriptionTrialPeriod } from '@/settings/billing/hooks/useEndSubscriptionTrialPeriod';
import { useGetResourceCreditUsage } from '@/settings/billing/hooks/useGetResourceCreditUsage';
import { useNextBillingPhase } from '@/settings/billing/hooks/useNextBillingPhase';
+import { useNextInterval } from '@/settings/billing/hooks/useNextInterval';
import { useNextPlan } from '@/settings/billing/hooks/useNextPlan';
import { useSplitPhaseItemsInPrices } from '@/settings/billing/hooks/useSplitPhaseItemsInPrices';
import { billingHasPaymentMethodSelector } from '@/settings/billing/states/billingHasPaymentMethodSelector';
@@ -32,13 +35,10 @@ import { Section } from 'twenty-ui/primitives/layout';
import { H2Title } from 'twenty-ui/primitives/typography';
import {
BillingPlanKey,
- CancelSwitchBillingIntervalDocument,
- CancelSwitchBillingPlanDocument,
CancelSwitchResourceCreditPriceDocument,
PermissionFlagType,
SubscriptionInterval,
SubscriptionStatus,
- SwitchSubscriptionIntervalDocument,
} from '~/generated-metadata/graphql';
import { beautifyExactDate } from '~/utils/date-utils';
@@ -81,8 +81,7 @@ export const SettingsBillingSubscriptionInfo = ({
const { nextBillingPhase } = useNextBillingPhase();
const { nextPlan } = useNextPlan();
- const nextInterval =
- splitedPhaseItemsInPrices?.nextBasePrice?.recurringInterval;
+ const { nextInterval } = useNextInterval();
const nextResourceCreditPrice =
splitedPhaseItemsInPrices.nextResourceCreditPrice;
const subscriptionStatus = useSubscriptionStatus();
@@ -95,25 +94,16 @@ export const SettingsBillingSubscriptionInfo = ({
const nextCreditsByPeriod = nextResourceCreditPrice?.creditAmount ?? null;
const {
- getIntervalLabelAsAdjectiveCapitalize,
- confirmationModalSwitchToMonthlyMessage,
- confirmationModalSwitchToYearlyMessage,
- confirmationModalCancelPlanSwitchingMessage,
- confirmationModalCancelIntervalSwitchingMessage,
getBeautifiedRenewDate,
+ getBillingPlanLabel,
+ getIntervalLabelAsAdjectiveCapitalize,
} = useBillingWording();
-
- const [switchSubscriptionIntervalMutation] = useMutation(
- SwitchSubscriptionIntervalDocument,
- );
-
- const [cancelSwitchBillingInterval] = useMutation(
- CancelSwitchBillingIntervalDocument,
- );
-
- const [cancelSwitchBillingPlan] = useMutation(
- CancelSwitchBillingPlanDocument,
- );
+ const { getBillingSubscriptionChangeWording } =
+ useBillingSubscriptionChangeWording();
+ const {
+ applyBillingSubscriptionChange,
+ isApplyingBillingSubscriptionChange,
+ } = useApplyBillingSubscriptionChange();
const [cancelSwitchResourceCreditPrice] = useMutation(
CancelSwitchResourceCreditPriceDocument,
@@ -268,7 +258,7 @@ export const SettingsBillingSubscriptionInfo = ({
const totalIntervalSubtitle = isDefined(totalDisplay)
? currentInterval === SubscriptionInterval.Month
? t`/month`
- : t`/month billed yearly`
+ : t`/month billed annually`
: undefined;
const scheduledChangeStartDate = isDefined(nextBillingPhase?.start_date)
? beautifyExactDate(nextBillingPhase.start_date * 1000)
@@ -299,10 +289,7 @@ export const SettingsBillingSubscriptionInfo = ({
{
Icon: IconTag,
label: t`Plan`,
- value:
- nextPlan.planKey === BillingPlanKey.PRO
- ? t`Pro`
- : t`Organization`,
+ value: getBillingPlanLabel(nextPlan.planKey),
},
]
: []),
@@ -330,17 +317,11 @@ export const SettingsBillingSubscriptionInfo = ({
]
: []),
];
- const [isSwitchingInterval, setIsSwitchingInterval] = useState(false);
- const [isCancellingPlanSwitch, setIsCancellingPlanSwitch] = useState(false);
- const [isCancellingIntervalSwitch, setIsCancellingIntervalSwitch] =
- useState(false);
const [isCancellingMeteredSwitch, setIsCancellingMeteredSwitch] =
useState(false);
const isAnyActionLoading =
- isSwitchingInterval ||
- isCancellingPlanSwitch ||
- isCancellingIntervalSwitch ||
+ isApplyingBillingSubscriptionChange ||
isCancellingMeteredSwitch ||
isEndTrialPeriodLoading;
@@ -386,72 +367,6 @@ export const SettingsBillingSubscriptionInfo = ({
}
};
- const switchInterval = async () => {
- await runBillingAction({
- action: async () => {
- const { data } = await switchSubscriptionIntervalMutation();
-
- if (
- isDefined(data?.switchSubscriptionInterval.currentBillingSubscription)
- ) {
- applyBillingUpdate(data.switchSubscriptionInterval);
- }
- },
- getErrorMessage: () => t`Error while switching subscription.`,
- getSuccessMessage: () => {
- const isCurrentMonth =
- currentBillingSubscription.interval === SubscriptionInterval.Month;
-
- if (isCurrentMonth) {
- return t`Subscription has been switched to Yearly.`;
- }
-
- return isTrialPeriod
- ? t`Subscription has been switched to Monthly.`
- : t`Subscription will be switched to Monthly the ${getBeautifiedRenewDate()}.`;
- },
- isLoading: isSwitchingInterval,
- setIsLoading: setIsSwitchingInterval,
- });
- };
-
- const cancelPlanSwitching = async () => {
- await runBillingAction({
- action: async () => {
- const { data } = await cancelSwitchBillingPlan();
-
- if (
- isDefined(data?.cancelSwitchBillingPlan.currentBillingSubscription)
- ) {
- applyBillingUpdate(data.cancelSwitchBillingPlan);
- }
- },
- getErrorMessage: () => t`Error while cancelling plan switching.`,
- getSuccessMessage: () => t`Plan switching has been cancelled.`,
- isLoading: isCancellingPlanSwitch,
- setIsLoading: setIsCancellingPlanSwitch,
- });
- };
-
- const cancelIntervalSwitching = async () => {
- await runBillingAction({
- action: async () => {
- const { data } = await cancelSwitchBillingInterval();
- if (
- isDefined(
- data?.cancelSwitchBillingInterval.currentBillingSubscription,
- )
- ) {
- applyBillingUpdate(data.cancelSwitchBillingInterval);
- }
- },
- getErrorMessage: () => t`Error while cancelling interval switching.`,
- getSuccessMessage: () => t`Interval switching has been cancelled.`,
- isLoading: isCancellingIntervalSwitch,
- setIsLoading: setIsCancellingIntervalSwitch,
- });
- };
-
const cancelResourceCreditSwitching = async () => {
await runBillingAction({
action: async () => {
@@ -530,22 +445,45 @@ export const SettingsBillingSubscriptionInfo = ({
/>
<SettingsBillingSubscriptionInfoModals
billingHasPaymentMethod={billingHasPaymentMethod}
- cancelIntervalSwitchingSubtitle={confirmationModalCancelIntervalSwitchingMessage()}
- cancelPlanSwitchingSubtitle={confirmationModalCancelPlanSwitchingMessage()}
- isCancellingIntervalSwitch={isCancellingIntervalSwitch}
+ cancelIntervalSwitchingWording={getBillingSubscriptionChangeWording({
+ change: { type: 'CANCEL_INTERVAL_SWITCH' },
+ })}
+ cancelPlanSwitchingWording={getBillingSubscriptionChangeWording({
+ change: { type: 'CANCEL_PLAN_SWITCH' },
+ })}
+ isApplyingSubscriptionChange={isApplyingBillingSubscriptionChange}
isCancellingMeteredSwitch={isCancellingMeteredSwitch}
- isCancellingPlanSwitch={isCancellingPlanSwitch}
isEndTrialPeriodLoading={isEndTrialPeriodLoading}
- isSwitchingInterval={isSwitchingInterval}
- onCancelIntervalSwitching={cancelIntervalSwitching}
- onCancelPlanSwitching={cancelPlanSwitching}
+ onCancelIntervalSwitching={() =>
+ applyBillingSubscriptionChange({ type: 'CANCEL_INTERVAL_SWITCH' })
+ }
+ onCancelPlanSwitching={() =>
+ applyBillingSubscriptionChange({ type: 'CANCEL_PLAN_SWITCH' })
+ }
onCancelResourceCreditSwitching={cancelResourceCreditSwitching}
onEndTrialPeriod={endTrialPeriod}
onPaymentMethodAdded={startSubscriptionAfterPaymentMethodAdded}
- onSwitchInterval={switchInterval}
+ onSwitchInterval={() =>
+ applyBillingSubscriptionChange({
+ type: 'SWITCH_INTERVAL',
+ targetInterval: isMonthlyPlan
+ ? SubscriptionInterval.Year
+ : SubscriptionInterval.Month,
+ })
+ }
startSubscriptionSubtitle={startSubscriptionSubtitle}
- switchToMonthlySubtitle={confirmationModalSwitchToMonthlyMessage()}
- switchToYearlySubtitle={confirmationModalSwitchToYearlyMessage()}
+ switchToMonthlyWording={getBillingSubscriptionChangeWording({
+ change: {
+ type: 'SWITCH_INTERVAL',
+ targetInterval: SubscriptionInterval.Month,
+ },
+ })}
+ switchToYearlyWording={getBillingSubscriptionChangeWording({
+ change: {
+ type: 'SWITCH_INTERVAL',
+ targetInterval: SubscriptionInterval.Year,
+ },
+ })}
/>
</Section>
);
diff --git a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlanComparisonTable.tsx b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlanComparisonTable.tsx
index c82d4c603da..411363a98ad 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlanComparisonTable.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlanComparisonTable.tsx
@@ -180,7 +180,7 @@ export const SettingsBillingPlanComparisonTable = ({
<StyledComparisonTitle>{t`Compare plans`}</StyledComparisonTitle>
<StyledPlanSubtitle>
{billingInterval === SubscriptionInterval.Year
- ? t`Save 25% when billed yearly`
+ ? t`Save 25% when billed annually`
: t`Billed monthly`}
</StyledPlanSubtitle>
</StyledHeaderText>
diff --git a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlansWithSubscription.tsx b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlansWithSubscription.tsx
index daa22981c6b..33609783e0c 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlansWithSubscription.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingPlansWithSubscription.tsx
@@ -1,15 +1,20 @@
import { SettingsBillingPlanComparisonTable } from '@/settings/billing/components/internal/SettingsBillingPlanComparisonTable';
import { BILLING_MODAL_IDS } from '@/settings/billing/constants/BillingModalIds';
+import { useApplyBillingSubscriptionChange } from '@/settings/billing/hooks/useApplyBillingSubscriptionChange';
import { useBillingPlanActions } from '@/settings/billing/hooks/useBillingPlanActions';
-import { useBillingWording } from '@/settings/billing/hooks/useBillingWording';
+import { useBillingSubscriptionChangeWording } from '@/settings/billing/hooks/useBillingSubscriptionChangeWording';
+import { type BillingSubscriptionChange } from '@/settings/billing/types/billingSubscriptionChange.type';
import {
type SettingsBillingPlanInterval,
type SettingsBillingPlanPrices,
} from '@/settings/billing/types/settingsBillingPlanComparison.type';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { ConfirmationModal } from '@/ui/layout/modal/components/ConfirmationModal';
+import { useModal } from '@/ui/layout/modal/hooks/useModal';
import { useLingui } from '@lingui/react/macro';
-import { BillingPlanKey } from '~/generated-metadata/graphql';
+import { useState } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { type BillingPlanKey } from '~/generated-metadata/graphql';
type SettingsBillingPlansWithSubscriptionProps = {
billingInterval: SettingsBillingPlanInterval;
@@ -27,12 +32,31 @@ export const SettingsBillingPlansWithSubscription = ({
planPrices,
}: SettingsBillingPlansWithSubscriptionProps) => {
const { t } = useLingui();
+ const { openModal } = useModal();
+ const [pendingChange, setPendingChange] =
+ useState<BillingSubscriptionChange | null>(null);
const {
- confirmationModalSwitchToOrganizationMessage,
- confirmationModalSwitchToProMessage,
- } = useBillingWording();
- const { isSwitchingPlan, planActions, switchBillingPlan } =
- useBillingPlanActions({ currentPlanKey });
+ applyBillingSubscriptionChange,
+ isApplyingBillingSubscriptionChange,
+ } = useApplyBillingSubscriptionChange();
+ const { getBillingSubscriptionChangeWording } =
+ useBillingSubscriptionChangeWording();
+ const { planActions } = useBillingPlanActions({
+ billingInterval,
+ currentPlanKey,
+ isApplyingBillingSubscriptionChange,
+ onBillingSubscriptionChangeRequested: (change) => {
+ setPendingChange(change);
+ openModal(BILLING_MODAL_IDS.confirmSubscriptionChange);
+ },
+ });
+
+ const pendingChangeWording = isDefined(pendingChange)
+ ? getBillingSubscriptionChangeWording({
+ change: pendingChange,
+ selectedInterval: billingInterval,
+ })
+ : undefined;
return (
<SettingsPageContainer overflow="visible">
@@ -42,24 +66,17 @@ export const SettingsBillingPlansWithSubscription = ({
planActions={planActions}
planPrices={planPrices}
/>
- <ConfirmationModal
- modalInstanceId={BILLING_MODAL_IDS.switchBillingPlanToEnterprise}
- title={t`Change to Organization Plan?`}
- subtitle={confirmationModalSwitchToOrganizationMessage()}
- onConfirmClick={() => switchBillingPlan(BillingPlanKey.ENTERPRISE)}
- confirmButtonText={t`Confirm`}
- confirmButtonColor="accent"
- loading={isSwitchingPlan}
- />
- <ConfirmationModal
- modalInstanceId={BILLING_MODAL_IDS.switchBillingPlanToPro}
- title={t`Change to Pro Plan?`}
- subtitle={confirmationModalSwitchToProMessage()}
- onConfirmClick={() => switchBillingPlan(BillingPlanKey.PRO)}
- confirmButtonText={t`Confirm`}
- confirmButtonColor="accent"
- loading={isSwitchingPlan}
- />
+ {isDefined(pendingChange) && isDefined(pendingChangeWording) && (
+ <ConfirmationModal
+ modalInstanceId={BILLING_MODAL_IDS.confirmSubscriptionChange}
+ title={pendingChangeWording.title}
+ subtitle={pendingChangeWording.subtitle}
+ onConfirmClick={() => applyBillingSubscriptionChange(pendingChange)}
+ confirmButtonText={t`Confirm`}
+ confirmButtonColor="accent"
+ loading={isApplyingBillingSubscriptionChange}
+ />
+ )}
</SettingsPageContainer>
);
};
diff --git a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoCard.tsx b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoCard.tsx
index a66aa1fa18e..1541fddff0f 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoCard.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoCard.tsx
@@ -264,11 +264,11 @@ export const SettingsBillingSubscriptionInfoCard = ({
</StyledBillingIntervalSeparator>
<SettingsTextLink
variant="secondary"
- title={t`Switch to yearly`}
+ title={t`Switch to annual`}
onClick={onSwitchToYearly}
disabled={isSubscriptionActionDisabled}
>
- {t`Switch to yearly`}
+ {t`Switch to annual`}
</SettingsTextLink>
</>
)}
diff --git a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoModals.tsx b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoModals.tsx
index 050ae35e2f8..5097911bfc0 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoModals.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoModals.tsx
@@ -1,17 +1,16 @@
import { AddCreditCardModal } from '@/settings/billing/components/AddCreditCardModal';
import { BILLING_MODAL_IDS } from '@/settings/billing/constants/BillingModalIds';
+import { type BillingSubscriptionChangeWording } from '@/settings/billing/types/billingSubscriptionChangeWording.type';
import { ConfirmationModal } from '@/ui/layout/modal/components/ConfirmationModal';
import { useLingui } from '@lingui/react/macro';
type SettingsBillingSubscriptionInfoModalsProps = {
billingHasPaymentMethod: boolean | null | undefined;
- cancelIntervalSwitchingSubtitle: string;
- cancelPlanSwitchingSubtitle: string;
- isCancellingIntervalSwitch: boolean;
+ cancelIntervalSwitchingWording: BillingSubscriptionChangeWording;
+ cancelPlanSwitchingWording: BillingSubscriptionChangeWording;
+ isApplyingSubscriptionChange: boolean;
isCancellingMeteredSwitch: boolean;
- isCancellingPlanSwitch: boolean;
isEndTrialPeriodLoading: boolean;
- isSwitchingInterval: boolean;
onCancelIntervalSwitching: () => void;
onCancelPlanSwitching: () => void;
onCancelResourceCreditSwitching: () => void;
@@ -19,19 +18,17 @@ type SettingsBillingSubscriptionInfoModalsProps = {
onPaymentMethodAdded: () => Promise<void>;
onSwitchInterval: () => void;
startSubscriptionSubtitle: string;
- switchToMonthlySubtitle: string;
- switchToYearlySubtitle: string;
+ switchToMonthlyWording: BillingSubscriptionChangeWording;
+ switchToYearlyWording: BillingSubscriptionChangeWording;
};
export const SettingsBillingSubscriptionInfoModals = ({
billingHasPaymentMethod,
- cancelIntervalSwitchingSubtitle,
- cancelPlanSwitchingSubtitle,
- isCancellingIntervalSwitch,
+ cancelIntervalSwitchingWording,
+ cancelPlanSwitchingWording,
+ isApplyingSubscriptionChange,
isCancellingMeteredSwitch,
- isCancellingPlanSwitch,
isEndTrialPeriodLoading,
- isSwitchingInterval,
onCancelIntervalSwitching,
onCancelPlanSwitching,
onCancelResourceCreditSwitching,
@@ -39,8 +36,8 @@ export const SettingsBillingSubscriptionInfoModals = ({
onPaymentMethodAdded,
onSwitchInterval,
startSubscriptionSubtitle,
- switchToMonthlySubtitle,
- switchToYearlySubtitle,
+ switchToMonthlyWording,
+ switchToYearlyWording,
}: SettingsBillingSubscriptionInfoModalsProps) => {
const { t } = useLingui();
@@ -48,39 +45,39 @@ export const SettingsBillingSubscriptionInfoModals = ({
<>
<ConfirmationModal
modalInstanceId={BILLING_MODAL_IDS.switchBillingIntervalToYearly}
- title={t`Change to Yearly?`}
- subtitle={switchToYearlySubtitle}
+ title={switchToYearlyWording.title}
+ subtitle={switchToYearlyWording.subtitle}
onConfirmClick={onSwitchInterval}
confirmButtonText={t`Confirm`}
confirmButtonColor="accent"
- loading={isSwitchingInterval}
+ loading={isApplyingSubscriptionChange}
/>
<ConfirmationModal
modalInstanceId={BILLING_MODAL_IDS.switchBillingIntervalToMonthly}
- title={t`Change to Monthly?`}
- subtitle={switchToMonthlySubtitle}
+ title={switchToMonthlyWording.title}
+ subtitle={switchToMonthlyWording.subtitle}
onConfirmClick={onSwitchInterval}
confirmButtonText={t`Confirm`}
confirmButtonColor="accent"
- loading={isSwitchingInterval}
+ loading={isApplyingSubscriptionChange}
/>
<ConfirmationModal
modalInstanceId={BILLING_MODAL_IDS.cancelSwitchBillingInterval}
- title={t`Cancel interval switching?`}
- subtitle={cancelIntervalSwitchingSubtitle}
+ title={cancelIntervalSwitchingWording.title}
+ subtitle={cancelIntervalSwitchingWording.subtitle}
onConfirmClick={onCancelIntervalSwitching}
confirmButtonText={t`Confirm`}
confirmButtonColor="accent"
- loading={isCancellingIntervalSwitch}
+ loading={isApplyingSubscriptionChange}
/>
<ConfirmationModal
modalInstanceId={BILLING_MODAL_IDS.cancelSwitchBillingPlan}
- title={t`Cancel plan switching?`}
- subtitle={cancelPlanSwitchingSubtitle}
+ title={cancelPlanSwitchingWording.title}
+ subtitle={cancelPlanSwitchingWording.subtitle}
onConfirmClick={onCancelPlanSwitching}
confirmButtonText={t`Confirm`}
confirmButtonColor="accent"
- loading={isCancellingPlanSwitch}
+ loading={isApplyingSubscriptionChange}
/>
{billingHasPaymentMethod === false ? (
<AddCreditCardModal
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/BillingModalIds.ts b/packages/twenty-front/src/modules/settings/billing/constants/BillingModalIds.ts
index cc457508ee8..84276ac6caa 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/BillingModalIds.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/BillingModalIds.ts
@@ -2,6 +2,7 @@ export const BILLING_MODAL_IDS = {
cancelSwitchBillingInterval: 'cancel-switch-billing-interval-modal',
cancelSwitchBillingPlan: 'cancel-switch-billing-plan-modal',
cancelSwitchMeteredPrice: 'cancel-switch-metered-price-modal',
+ confirmSubscriptionChange: 'confirm-subscription-change-modal',
confirmResourceCreditPriceChange:
'resource-credit-price-change-confirmation-modal',
creditPackagePicker: 'resource-credit-package-picker-modal',
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useApplyBillingSubscriptionChange.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useApplyBillingSubscriptionChange.ts
new file mode 100644
index 00000000000..27372d44869
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useApplyBillingSubscriptionChange.ts
@@ -0,0 +1,158 @@
+import { useApplyCurrentWorkspaceBillingUpdate } from '@/settings/billing/hooks/useApplyCurrentWorkspaceBillingUpdate';
+import { assertUnreachable } from 'twenty-shared/utils';
+import { useBillingWording } from '@/settings/billing/hooks/useBillingWording';
+import { useGetResourceCreditUsage } from '@/settings/billing/hooks/useGetResourceCreditUsage';
+import { type BillingSubscriptionChange } from '@/settings/billing/types/billingSubscriptionChange.type';
+import { isBillingSubscriptionChangeImmediate } from '@/settings/billing/utils/isBillingSubscriptionChangeImmediate';
+import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+import { useMutation } from '@apollo/client/react';
+import { useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
+import { useToast } from 'twenty-ui/primitives/feedback';
+import {
+ CancelSwitchBillingIntervalDocument,
+ CancelSwitchBillingPlanDocument,
+ SubscriptionInterval,
+ SwitchBillingPlanDocument,
+ SwitchSubscriptionIntervalDocument,
+} from '~/generated-metadata/graphql';
+
+export const useApplyBillingSubscriptionChange = () => {
+ const { t } = useLingui();
+ const subscriptionStatus = useSubscriptionStatus();
+ const { enqueueToast } = useToast();
+ const { applyCurrentWorkspaceBillingUpdate } =
+ useApplyCurrentWorkspaceBillingUpdate();
+ const { refetchResourceCreditUsage } = useGetResourceCreditUsage();
+ const { getBeautifiedRenewDate, getBillingPlanLabel } = useBillingWording();
+
+ const [switchBillingPlanMutation] = useMutation(SwitchBillingPlanDocument);
+ const [switchSubscriptionIntervalMutation] = useMutation(
+ SwitchSubscriptionIntervalDocument,
+ );
+ const [cancelSwitchBillingPlanMutation] = useMutation(
+ CancelSwitchBillingPlanDocument,
+ );
+ const [cancelSwitchBillingIntervalMutation] = useMutation(
+ CancelSwitchBillingIntervalDocument,
+ );
+
+ const [
+ isApplyingBillingSubscriptionChange,
+ setIsApplyingBillingSubscriptionChange,
+ ] = useState(false);
+
+ const runBillingSubscriptionChangeMutation = async (
+ change: BillingSubscriptionChange,
+ ) => {
+ switch (change.type) {
+ case 'SWITCH_PLAN': {
+ const { data } = await switchBillingPlanMutation();
+
+ return data?.switchBillingPlan;
+ }
+ case 'SWITCH_INTERVAL': {
+ const { data } = await switchSubscriptionIntervalMutation();
+
+ return data?.switchSubscriptionInterval;
+ }
+ case 'CANCEL_PLAN_SWITCH': {
+ const { data } = await cancelSwitchBillingPlanMutation();
+
+ return data?.cancelSwitchBillingPlan;
+ }
+ case 'CANCEL_INTERVAL_SWITCH': {
+ const { data } = await cancelSwitchBillingIntervalMutation();
+
+ return data?.cancelSwitchBillingInterval;
+ }
+ default:
+ return assertUnreachable(change);
+ }
+ };
+
+ const getSuccessMessage = (change: BillingSubscriptionChange) => {
+ const isImmediate = isBillingSubscriptionChangeImmediate({
+ change,
+ subscriptionStatus,
+ });
+
+ switch (change.type) {
+ case 'SWITCH_PLAN': {
+ const planLabel = getBillingPlanLabel(change.targetPlanKey);
+
+ return isImmediate
+ ? t`Subscription has been switched to ${planLabel} Plan.`
+ : t`Subscription will be switched to ${planLabel} Plan the ${getBeautifiedRenewDate()}.`;
+ }
+ case 'SWITCH_INTERVAL': {
+ if (change.targetInterval === SubscriptionInterval.Year) {
+ return t`Subscription has been switched to annual billing.`;
+ }
+
+ return isImmediate
+ ? t`Subscription has been switched to monthly billing.`
+ : t`Subscription will be switched to monthly billing the ${getBeautifiedRenewDate()}.`;
+ }
+ case 'CANCEL_PLAN_SWITCH':
+ return t`Plan switching has been cancelled.`;
+ case 'CANCEL_INTERVAL_SWITCH':
+ return t`Interval switching has been cancelled.`;
+ default:
+ return assertUnreachable(change);
+ }
+ };
+
+ const getErrorMessage = (change: BillingSubscriptionChange) => {
+ switch (change.type) {
+ case 'CANCEL_PLAN_SWITCH':
+ return t`Error while cancelling plan switching.`;
+ case 'CANCEL_INTERVAL_SWITCH':
+ return t`Error while cancelling interval switching.`;
+ case 'SWITCH_PLAN':
+ case 'SWITCH_INTERVAL':
+ return t`Error while switching subscription.`;
+ default:
+ return assertUnreachable(change);
+ }
+ };
+
+ const applyBillingSubscriptionChange = async (
+ change: BillingSubscriptionChange,
+ ) => {
+ if (isApplyingBillingSubscriptionChange) {
+ return;
+ }
+
+ setIsApplyingBillingSubscriptionChange(true);
+
+ try {
+ const billingUpdate = await runBillingSubscriptionChangeMutation(change);
+ const isBillingUpdateApplied = applyCurrentWorkspaceBillingUpdate(
+ billingUpdate,
+ { onBillingUpdateApplied: refetchResourceCreditUsage },
+ );
+
+ if (!isBillingUpdateApplied) {
+ enqueueToast({ variant: 'error', children: getErrorMessage(change) });
+ return;
+ }
+
+ enqueueToast({ variant: 'success', children: getSuccessMessage(change) });
+ } catch (error) {
+ enqueueToast({ variant: 'error', children: getErrorMessage(change) });
+
+ if (!CombinedGraphQLErrors.is(error)) {
+ throw error;
+ }
+ } finally {
+ setIsApplyingBillingSubscriptionChange(false);
+ }
+ };
+
+ return {
+ applyBillingSubscriptionChange,
+ isApplyingBillingSubscriptionChange,
+ };
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingPlanActions.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingPlanActions.ts
index 3c03f556236..33d874950c5 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingPlanActions.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingPlanActions.ts
@@ -1,45 +1,64 @@
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
-import { BILLING_MODAL_IDS } from '@/settings/billing/constants/BillingModalIds';
import { useBillingPortalSession } from '@/settings/billing/hooks/useBillingPortalSession';
+import { useNextInterval } from '@/settings/billing/hooks/useNextInterval';
import { useNextPlan } from '@/settings/billing/hooks/useNextPlan';
-import { useSwitchBillingPlan } from '@/settings/billing/hooks/useSwitchBillingPlan';
+import { type BillingSubscriptionChange } from '@/settings/billing/types/billingSubscriptionChange.type';
import { type SettingsBillingPlanAction } from '@/settings/billing/types/settingsBillingPlanAction.type';
+import { type SettingsBillingPlanInterval } from '@/settings/billing/types/settingsBillingPlanComparison.type';
+import { getBillingPlanCell } from '@/settings/billing/utils/getBillingPlanCell';
+import { isBillingSubscriptionChangeUpgrade } from '@/settings/billing/utils/isBillingSubscriptionChangeUpgrade';
+import { isSubscriptionPaymentOverdue } from '@/settings/billing/utils/isSubscriptionPaymentOverdue';
import { usePermissionFlagMap } from '@/settings/roles/hooks/usePermissionFlagMap';
-import { useModal } from '@/ui/layout/modal/hooks/useModal';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
-import { isSubscriptionPaymentOverdue } from '@/settings/billing/utils/isSubscriptionPaymentOverdue';
import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';
import { useLingui } from '@lingui/react/macro';
import { SettingsPath } from 'twenty-shared/types';
-import { getSettingsPath, isDefined } from 'twenty-shared/utils';
-import { IconArrowDown, IconArrowUp, IconCheck } from 'twenty-ui/icon';
+import {
+ assertUnreachable,
+ getSettingsPath,
+ isDefined,
+} from 'twenty-shared/utils';
+import {
+ IconArrowDown,
+ IconArrowUp,
+ IconCheck,
+ IconCircleX,
+} from 'twenty-ui/icon';
import {
BillingPlanKey,
PermissionFlagType,
+ SubscriptionInterval,
SubscriptionStatus,
} from '~/generated-metadata/graphql';
type UseBillingPlanActionsParams = {
+ billingInterval: SettingsBillingPlanInterval;
currentPlanKey: BillingPlanKey;
+ isApplyingBillingSubscriptionChange: boolean;
+ onBillingSubscriptionChangeRequested: (
+ change: BillingSubscriptionChange,
+ ) => void;
};
export const useBillingPlanActions = ({
+ billingInterval,
currentPlanKey,
+ isApplyingBillingSubscriptionChange,
+ onBillingSubscriptionChangeRequested,
}: UseBillingPlanActionsParams) => {
const { t } = useLingui();
const currentWorkspace = useAtomStateValue(currentWorkspaceState);
const subscriptionStatus = useSubscriptionStatus();
- const { openModal } = useModal();
const { nextPlan } = useNextPlan();
+ const { nextInterval } = useNextInterval();
const permissionMap = usePermissionFlagMap();
- const { isSwitchingPlan, switchBillingPlan } = useSwitchBillingPlan();
-
const { isBillingPortalSessionDisabled, openBillingPortal } =
useBillingPortalSession(getSettingsPath(SettingsPath.BillingPlans));
const currentBillingSubscription =
currentWorkspace?.currentBillingSubscription;
+ const currentInterval = currentBillingSubscription?.interval;
const hasPermissionToManageBilling =
permissionMap[PermissionFlagType.BILLING] ?? false;
@@ -66,14 +85,77 @@ export const useBillingPlanActions = ({
variant: 'outline',
});
+ const getChangeTitle = (change: BillingSubscriptionChange) => {
+ switch (change.type) {
+ case 'SWITCH_PLAN':
+ return change.targetPlanKey === BillingPlanKey.ENTERPRISE
+ ? t`Upgrade to Organization`
+ : t`Switch to Pro`;
+ case 'SWITCH_INTERVAL':
+ return change.targetInterval === SubscriptionInterval.Year
+ ? t`Upgrade to annual`
+ : t`Switch to monthly`;
+ case 'CANCEL_PLAN_SWITCH':
+ return t`Cancel plan switching`;
+ case 'CANCEL_INTERVAL_SWITCH':
+ return t`Cancel interval switching`;
+ default:
+ return assertUnreachable(change);
+ }
+ };
+
+ const getChangeIcon = ({
+ change,
+ isUpgrade,
+ }: {
+ change: BillingSubscriptionChange;
+ isUpgrade: boolean;
+ }) => {
+ if (
+ change.type === 'CANCEL_PLAN_SWITCH' ||
+ change.type === 'CANCEL_INTERVAL_SWITCH'
+ ) {
+ return IconCircleX;
+ }
+
+ return isUpgrade ? IconArrowUp : IconArrowDown;
+ };
+
+ const createChangeAction = ({
+ change,
+ isUpgrade,
+ }: {
+ change: BillingSubscriptionChange;
+ isUpgrade: boolean;
+ }): SettingsBillingPlanAction => ({
+ color: isUpgrade ? 'accent' : 'neutral',
+ disabled: isApplyingBillingSubscriptionChange,
+ Icon: getChangeIcon({ change, isUpgrade }),
+ isLoading: isApplyingBillingSubscriptionChange,
+ onClick: () => onBillingSubscriptionChangeRequested(change),
+ title: getChangeTitle(change),
+ variant: isUpgrade ? 'solid' : 'outline',
+ });
+
const getPlanAction = (
planKey: BillingPlanKey,
): SettingsBillingPlanAction => {
- if (isSubscriptionCanceled) {
+ if (isSubscriptionCanceled || !isDefined(currentInterval)) {
return createBillingPortalAction(t`Manage billing`);
}
- if (currentPlanKey === planKey) {
+ const upcomingInterval = nextInterval ?? currentInterval;
+ const upcomingPlanKey = nextPlan?.planKey ?? currentPlanKey;
+ const cell = getBillingPlanCell({
+ currentInterval,
+ currentPlanKey,
+ interval: billingInterval,
+ planKey,
+ upcomingInterval,
+ upcomingPlanKey,
+ });
+
+ if (cell.kind === 'current') {
return {
disabled: true,
Icon: IconCheck,
@@ -82,7 +164,7 @@ export const useBillingPlanActions = ({
};
}
- if (nextPlan?.planKey === planKey) {
+ if (cell.kind === 'scheduled') {
return {
disabled: true,
title: t`Scheduled`,
@@ -106,30 +188,20 @@ export const useBillingPlanActions = ({
};
}
- const isSwitchingToOrganizationPlan = planKey === BillingPlanKey.ENTERPRISE;
-
- return {
- disabled: isSwitchingPlan,
- Icon: isSwitchingToOrganizationPlan ? IconArrowUp : IconArrowDown,
- isLoading: isSwitchingPlan,
- onClick: () =>
- openModal(
- isSwitchingToOrganizationPlan
- ? BILLING_MODAL_IDS.switchBillingPlanToEnterprise
- : BILLING_MODAL_IDS.switchBillingPlanToPro,
- ),
- title: isSwitchingToOrganizationPlan ? t`Upgrade` : t`Switch to Pro`,
- variant: isSwitchingToOrganizationPlan ? 'solid' : 'outline',
- color: isSwitchingToOrganizationPlan ? 'accent' : 'neutral',
- };
+ return createChangeAction({
+ change: cell.change,
+ isUpgrade: isBillingSubscriptionChangeUpgrade({
+ change: cell.change,
+ upcomingInterval,
+ upcomingPlanKey,
+ }),
+ });
};
return {
- isSwitchingPlan,
planActions: {
[BillingPlanKey.PRO]: getPlanAction(BillingPlanKey.PRO),
[BillingPlanKey.ENTERPRISE]: getPlanAction(BillingPlanKey.ENTERPRISE),
},
- switchBillingPlan,
};
};
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingSubscriptionChangeWording.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingSubscriptionChangeWording.ts
new file mode 100644
index 00000000000..27514624477
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingSubscriptionChangeWording.ts
@@ -0,0 +1,269 @@
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { useNumberFormat } from '@/localization/hooks/useNumberFormat';
+import { useBillingWording } from '@/settings/billing/hooks/useBillingWording';
+import { useCurrentPlan } from '@/settings/billing/hooks/useCurrentPlan';
+import { useFormatPrices } from '@/settings/billing/hooks/useFormatPrices';
+import { useNextInterval } from '@/settings/billing/hooks/useNextInterval';
+import { useNextPlan } from '@/settings/billing/hooks/useNextPlan';
+import { type BillingSubscriptionChange } from '@/settings/billing/types/billingSubscriptionChange.type';
+import { type BillingSubscriptionChangeWording } from '@/settings/billing/types/billingSubscriptionChangeWording.type';
+import { type SettingsBillingPlanInterval } from '@/settings/billing/types/settingsBillingPlanComparison.type';
+import { isBillingSubscriptionChangeImmediate } from '@/settings/billing/utils/isBillingSubscriptionChangeImmediate';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';
+import { useLingui } from '@lingui/react/macro';
+import {
+ assertIsDefinedOrThrow,
+ assertUnreachable,
+ isDefined,
+} from 'twenty-shared/utils';
+import {
+ BillingPlanKey,
+ SubscriptionInterval,
+ SubscriptionStatus,
+} from '~/generated-metadata/graphql';
+
+type ChargeTiming = 'CURRENT' | 'NOW' | 'AFTER_TRIAL' | 'SCHEDULED';
+
+export const useBillingSubscriptionChangeWording = () => {
+ const { t } = useLingui();
+ const { formatNumber } = useNumberFormat();
+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);
+
+ assertIsDefinedOrThrow(currentWorkspace?.currentBillingSubscription);
+
+ const currentInterval = currentWorkspace.currentBillingSubscription.interval;
+
+ assertIsDefinedOrThrow(currentInterval);
+
+ const { currentPlan } = useCurrentPlan();
+ const currentPlanKey = currentPlan.planKey;
+ const { nextPlan } = useNextPlan();
+ const { nextInterval } = useNextInterval();
+ const upcomingPlanKey = nextPlan?.planKey ?? currentPlanKey;
+ const upcomingInterval = nextInterval ?? currentInterval;
+ const isPlanSwitchScheduled = upcomingPlanKey !== currentPlanKey;
+ const isIntervalSwitchScheduled = upcomingInterval !== currentInterval;
+ const subscriptionStatus = useSubscriptionStatus();
+ const isTrialing = subscriptionStatus === SubscriptionStatus.Trialing;
+ const { formatPrices } = useFormatPrices();
+ const { getBeautifiedRenewDate, getBillingPlanLabel, getIntervalLabel } =
+ useBillingWording();
+
+ const getIntervalAdjective = (interval: SubscriptionInterval) =>
+ getIntervalLabel(interval === SubscriptionInterval.Month, true);
+
+ const getPriceLabel = ({
+ interval,
+ planKey,
+ }: {
+ interval: SubscriptionInterval;
+ planKey: BillingPlanKey;
+ }) => {
+ const price = formatNumber(formatPrices[planKey][interval]);
+
+ return interval === SubscriptionInterval.Year
+ ? t`$${price} per user per month, billed annually`
+ : t`$${price} per user per month`;
+ };
+
+ const getChargeSentence = ({
+ interval,
+ planKey,
+ timing,
+ }: {
+ interval: SubscriptionInterval;
+ planKey: BillingPlanKey;
+ timing: ChargeTiming;
+ }) => {
+ const priceLabel = getPriceLabel({ interval, planKey });
+
+ switch (timing) {
+ case 'CURRENT':
+ return t`You are charged ${priceLabel}.`;
+ case 'NOW':
+ return t`You will be charged ${priceLabel}.`;
+ case 'AFTER_TRIAL':
+ return t`When your trial ends, you will be charged ${priceLabel}.`;
+ case 'SCHEDULED':
+ return t`From ${getBeautifiedRenewDate()}, you will be charged ${priceLabel}.`;
+ default:
+ return assertUnreachable(timing);
+ }
+ };
+
+ const getChargeTiming = (change: BillingSubscriptionChange): ChargeTiming => {
+ if (isTrialing) {
+ return 'AFTER_TRIAL';
+ }
+
+ return isBillingSubscriptionChangeImmediate({ change, subscriptionStatus })
+ ? 'NOW'
+ : 'SCHEDULED';
+ };
+
+ const getSwitchPlanLeadSentence = (targetPlanKey: BillingPlanKey) => {
+ if (isTrialing) {
+ const planLabel = getBillingPlanLabel(targetPlanKey);
+
+ return t`Your plan switches to ${planLabel} immediately and your trial continues.`;
+ }
+
+ if (targetPlanKey === BillingPlanKey.ENTERPRISE) {
+ return t`Your plan switches to Organization immediately, with a prorated charge for the rest of your current billing period.`;
+ }
+
+ return t`Your plan switches to Pro on ${getBeautifiedRenewDate()}, at the end of your current billing period.`;
+ };
+
+ const getSwitchIntervalLeadSentence = (
+ targetInterval: SettingsBillingPlanInterval,
+ ) => {
+ if (isTrialing) {
+ const intervalAdjective = getIntervalAdjective(targetInterval);
+
+ return t`Your billing switches to ${intervalAdjective} immediately and your trial continues.`;
+ }
+
+ if (targetInterval === SubscriptionInterval.Year) {
+ return t`Your billing switches to annual immediately. A new annual period starts today and the unused part of your current period is credited.`;
+ }
+
+ return t`Your billing switches to monthly on ${getBeautifiedRenewDate()}, at the end of your current billing period.`;
+ };
+
+ const getStepNote = (selectedInterval: SettingsBillingPlanInterval) => {
+ const upcomingIntervalAdjective = getIntervalAdjective(upcomingInterval);
+ const selectedIntervalAdjective = getIntervalAdjective(selectedInterval);
+
+ return t`Billing stays ${upcomingIntervalAdjective}. To switch to ${selectedIntervalAdjective} billing, confirm this change first, then switch the billing interval as a second step.`;
+ };
+
+ const getSwitchPlanWording = ({
+ change,
+ selectedInterval,
+ }: {
+ change: Extract<BillingSubscriptionChange, { type: 'SWITCH_PLAN' }>;
+ selectedInterval: SettingsBillingPlanInterval | undefined;
+ }): BillingSubscriptionChangeWording => ({
+ title:
+ change.targetPlanKey === BillingPlanKey.ENTERPRISE
+ ? t`Upgrade to Organization?`
+ : t`Switch to Pro?`,
+ subtitle: [
+ getSwitchPlanLeadSentence(change.targetPlanKey),
+ getChargeSentence({
+ interval: upcomingInterval,
+ planKey: change.targetPlanKey,
+ timing: getChargeTiming(change),
+ }),
+ isDefined(selectedInterval) && selectedInterval !== upcomingInterval
+ ? getStepNote(selectedInterval)
+ : undefined,
+ ]
+ .filter(isDefined)
+ .join(' '),
+ });
+
+ const getSwitchIntervalWording = (
+ change: Extract<BillingSubscriptionChange, { type: 'SWITCH_INTERVAL' }>,
+ ): BillingSubscriptionChangeWording => ({
+ title:
+ change.targetInterval === SubscriptionInterval.Year
+ ? t`Upgrade to annual billing?`
+ : t`Switch to monthly billing?`,
+ subtitle: [
+ getSwitchIntervalLeadSentence(change.targetInterval),
+ getChargeSentence({
+ interval: change.targetInterval,
+ planKey: upcomingPlanKey,
+ timing: getChargeTiming(change),
+ }),
+ ].join(' '),
+ });
+
+ const getCancelPlanSwitchWording = (): BillingSubscriptionChangeWording => {
+ const upcomingPlanLabel = getBillingPlanLabel(upcomingPlanKey);
+ const currentPlanLabel = getBillingPlanLabel(currentPlanKey);
+ const upcomingIntervalAdjective = getIntervalAdjective(upcomingInterval);
+
+ return {
+ title: t`Cancel plan switching?`,
+ subtitle: [
+ t`This cancels the scheduled switch to ${upcomingPlanLabel} on ${getBeautifiedRenewDate()}.`,
+ t`You stay on the ${currentPlanLabel} plan.`,
+ ...(isIntervalSwitchScheduled
+ ? [
+ t`Your scheduled switch to ${upcomingIntervalAdjective} billing on ${getBeautifiedRenewDate()} is kept.`,
+ getChargeSentence({
+ interval: upcomingInterval,
+ planKey: currentPlanKey,
+ timing: 'SCHEDULED',
+ }),
+ ]
+ : [
+ getChargeSentence({
+ interval: currentInterval,
+ planKey: currentPlanKey,
+ timing: 'CURRENT',
+ }),
+ ]),
+ ].join(' '),
+ };
+ };
+
+ const getCancelIntervalSwitchWording =
+ (): BillingSubscriptionChangeWording => {
+ const upcomingIntervalAdjective = getIntervalAdjective(upcomingInterval);
+ const currentIntervalAdjective = getIntervalAdjective(currentInterval);
+ const currentPlanLabel = getBillingPlanLabel(currentPlanKey);
+ const upcomingPlanLabel = getBillingPlanLabel(upcomingPlanKey);
+
+ return {
+ title: t`Cancel interval switching?`,
+ subtitle: [
+ t`This cancels the scheduled switch to ${upcomingIntervalAdjective} billing on ${getBeautifiedRenewDate()}.`,
+ t`You keep ${currentIntervalAdjective} billing on the ${currentPlanLabel} plan.`,
+ ...(isPlanSwitchScheduled
+ ? [
+ t`Your scheduled switch to ${upcomingPlanLabel} on ${getBeautifiedRenewDate()} is kept.`,
+ getChargeSentence({
+ interval: currentInterval,
+ planKey: upcomingPlanKey,
+ timing: 'SCHEDULED',
+ }),
+ ]
+ : [
+ getChargeSentence({
+ interval: currentInterval,
+ planKey: currentPlanKey,
+ timing: 'CURRENT',
+ }),
+ ]),
+ ].join(' '),
+ };
+ };
+
+ const getBillingSubscriptionChangeWording = ({
+ change,
+ selectedInterval,
+ }: {
+ change: BillingSubscriptionChange;
+ selectedInterval?: SettingsBillingPlanInterval;
+ }): BillingSubscriptionChangeWording => {
+ switch (change.type) {
+ case 'SWITCH_PLAN':
+ return getSwitchPlanWording({ change, selectedInterval });
+ case 'SWITCH_INTERVAL':
+ return getSwitchIntervalWording(change);
+ case 'CANCEL_PLAN_SWITCH':
+ return getCancelPlanSwitchWording();
+ case 'CANCEL_INTERVAL_SWITCH':
+ return getCancelIntervalSwitchWording();
+ default:
+ return assertUnreachable(change);
+ }
+ };
+
+ return { getBillingSubscriptionChangeWording };
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingWording.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingWording.ts
index ad713e315e8..8292355ff93 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingWording.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingWording.ts
@@ -2,7 +2,6 @@ import { useFormatPrices } from '@/settings/billing/hooks/useFormatPrices';
import {
BillingPlanKey,
SubscriptionInterval,
- SubscriptionStatus,
} from '~/generated-metadata/graphql';
import {
assertIsDefinedOrThrow,
@@ -10,11 +9,8 @@ import {
isDefined,
} from 'twenty-shared/utils';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
-import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';
import { useLingui } from '@lingui/react/macro';
import { beautifyExactDate } from '~/utils/date-utils';
-import { useCurrentPlan } from '@/settings/billing/hooks/useCurrentPlan';
-import { useCurrentBillingFlags } from '@/settings/billing/hooks/useCurrentBillingFlags';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { getSubscriptionPlanKey } from '@/settings/billing/utils/getSubscriptionPlanKey';
@@ -32,12 +28,6 @@ export const useBillingWording = () => {
const { formatPrices } = useFormatPrices();
- const { currentPlan } = useCurrentPlan();
-
- const subscriptionStatus = useSubscriptionStatus();
-
- const { isYearlyPlan } = useCurrentBillingFlags();
-
const getIntervalLabel = (
isMonthly: boolean,
asAdjective: boolean = false,
@@ -45,7 +35,7 @@ export const useBillingWording = () => {
isMonthly && asAdjective
? t`monthly`
: asAdjective
- ? t`yearly`
+ ? t`annual`
: isMonthly
? t`month`
: t`year`;
@@ -61,6 +51,9 @@ export const useBillingWording = () => {
);
};
+ const getBillingPlanLabel = (planKey: BillingPlanKey) =>
+ planKey === BillingPlanKey.ENTERPRISE ? t`Organization` : t`Pro`;
+
const getIntervalLabelAsAdjectiveCapitalize = (isMonthlyPlan: boolean) => {
return capitalize(getIntervalLabel(isMonthlyPlan, true));
};
@@ -80,93 +73,11 @@ export const useBillingWording = () => {
? Math.round((1 - yearlyPrice / monthlyPrice) * 100)
: 0;
- const getCurrentIntervalLabel = () =>
- getIntervalLabelAsAdjectiveCapitalize(
- currentBillingSubscription.interval === SubscriptionInterval.Month,
- );
-
- const enterprisePrice =
- formatPrices[BillingPlanKey.ENTERPRISE]?.[
- currentBillingSubscription.interval as
- | SubscriptionInterval.Month
- | SubscriptionInterval.Year
- ];
-
- const proPrice =
- formatPrices[BillingPlanKey.PRO]?.[
- currentBillingSubscription.interval as
- | SubscriptionInterval.Month
- | SubscriptionInterval.Year
- ];
-
- const confirmationModalSwitchToYearlyMessage = () => {
- if (subscriptionStatus === SubscriptionStatus.Trialing) {
- return t`Your billing interval will switch to yearly immediately and your trial will continue. When it ends, you will be charged $${yearlyPrice} per user per year billed annually.`;
- }
-
- return t`You will be charged $${yearlyPrice} per user per year billed annually. A prorata with your current subscription will be applied.`;
- };
-
- const confirmationModalSwitchToMonthlyMessage = () => {
- if (subscriptionStatus === SubscriptionStatus.Trialing) {
- return t`Your billing interval will switch to monthly immediately and your trial will continue. When it ends, you will be charged $${monthlyPrice} per user per month billed monthly.`;
- }
-
- const beautifiedRenewDate = getBeautifiedRenewDate();
- return t`You will be charged $${monthlyPrice} per user per month billed monthly. The change will be applied the ${beautifiedRenewDate}.`;
- };
-
- const confirmationModalSwitchToOrganizationMessage = () => {
- if (subscriptionStatus === SubscriptionStatus.Trialing) {
- const suffix = isYearlyPlan ? t` billed annually` : '';
-
- return t`Your plan will switch to Organization immediately and your trial will continue. When it ends, you will be charged $${enterprisePrice} per user per month${suffix}.`;
- }
-
- const body = t`you will be charged $${enterprisePrice} per user per month`;
- const suffix = isYearlyPlan ? t` billed annually` : '';
- return capitalize(`${body}${suffix}.`);
- };
-
- const confirmationModalSwitchToProMessage = () => {
- if (subscriptionStatus === SubscriptionStatus.Trialing) {
- const suffix = isYearlyPlan ? t` billed annually` : '';
-
- return t`Your plan will switch to Pro immediately and your trial will continue. When it ends, you will be charged $${proPrice} per user per month${suffix}.`;
- }
-
- const beautifiedRenewDate = getBeautifiedRenewDate();
- const suffix1 = isYearlyPlan ? t` billed annually` : '';
- const suffix2 = t`. The change will be applied the ${beautifiedRenewDate}.`;
- const body = t`You will be charged $${proPrice} per user per month`;
- return `${body}${suffix1}${suffix2}`;
- };
-
- const confirmationModalCancelPlanSwitchingMessage = () => {
- const planKeyWord =
- currentPlan.planKey === BillingPlanKey.ENTERPRISE
- ? t`Organization`
- : t`Pro`;
-
- return t`This will cancel the scheduled plan change and keep your current plan (${planKeyWord}).`;
- };
-
- const confirmationModalCancelIntervalSwitchingMessage = () => {
- const currentIntervalLabel = getCurrentIntervalLabel();
-
- return t`This will cancel the scheduled interval change and keep your current billing interval (${currentIntervalLabel}).`;
- };
-
return {
getBeautifiedRenewDate,
+ getBillingPlanLabel,
getIntervalLabel,
getIntervalLabelAsAdjectiveCapitalize,
getYearlyDiscountPercent,
- confirmationModalSwitchToYearlyMessage,
- confirmationModalSwitchToMonthlyMessage,
- confirmationModalSwitchToOrganizationMessage,
- confirmationModalSwitchToProMessage,
- confirmationModalCancelPlanSwitchingMessage,
- confirmationModalCancelIntervalSwitchingMessage,
};
};
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useNextInterval.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useNextInterval.ts
new file mode 100644
index 00000000000..6884f4bb3ce
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useNextInterval.ts
@@ -0,0 +1,10 @@
+import { useSplitPhaseItemsInPrices } from '@/settings/billing/hooks/useSplitPhaseItemsInPrices';
+
+export const useNextInterval = () => {
+ const { splitedPhaseItemsInPrices } = useSplitPhaseItemsInPrices();
+
+ const nextInterval =
+ splitedPhaseItemsInPrices.nextBasePrice?.recurringInterval;
+
+ return { nextInterval };
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useSwitchBillingPlan.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useSwitchBillingPlan.ts
deleted file mode 100644
index 66713ecc4ed..00000000000
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useSwitchBillingPlan.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { useApplyCurrentWorkspaceBillingUpdate } from '@/settings/billing/hooks/useApplyCurrentWorkspaceBillingUpdate';
-import { useBillingWording } from '@/settings/billing/hooks/useBillingWording';
-import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';
-import { CombinedGraphQLErrors } from '@apollo/client/errors';
-import { useMutation } from '@apollo/client/react';
-import { useLingui } from '@lingui/react/macro';
-import { useState } from 'react';
-import { useToast } from 'twenty-ui/primitives/feedback';
-import {
- BillingPlanKey,
- SubscriptionStatus,
- SwitchBillingPlanDocument,
-} from '~/generated-metadata/graphql';
-
-export const useSwitchBillingPlan = () => {
- const { t } = useLingui();
- const subscriptionStatus = useSubscriptionStatus();
- const { enqueueToast } = useToast();
- const { applyCurrentWorkspaceBillingUpdate } =
- useApplyCurrentWorkspaceBillingUpdate();
- const { getBeautifiedRenewDate } = useBillingWording();
-
- const [switchBillingPlanMutation] = useMutation(SwitchBillingPlanDocument);
- const [isSwitchingPlan, setIsSwitchingPlan] = useState(false);
-
- const getTargetPlanLabel = (targetPlanKey: BillingPlanKey) =>
- targetPlanKey === BillingPlanKey.ENTERPRISE ? t`Organization` : t`Pro`;
-
- const getSuccessMessage = (targetPlanKey: BillingPlanKey) =>
- targetPlanKey === BillingPlanKey.ENTERPRISE ||
- subscriptionStatus === SubscriptionStatus.Trialing
- ? t`Subscription has been switched to ${getTargetPlanLabel(targetPlanKey)} Plan.`
- : t`Subscription will be switched to ${getTargetPlanLabel(targetPlanKey)} Plan the ${getBeautifiedRenewDate()}.`;
-
- const switchBillingPlan = async (targetPlanKey: BillingPlanKey) => {
- if (isSwitchingPlan) {
- return;
- }
-
- setIsSwitchingPlan(true);
-
- try {
- const { data } = await switchBillingPlanMutation();
- const isBillingUpdateApplied = applyCurrentWorkspaceBillingUpdate(
- data?.switchBillingPlan,
- );
-
- if (!isBillingUpdateApplied) {
- enqueueToast({
- variant: 'error',
- children: t`Error while switching subscription.`,
- });
- return;
- }
-
- enqueueToast({
- variant: 'success',
- children: getSuccessMessage(targetPlanKey),
- });
- } catch (error) {
- enqueueToast({
- variant: 'error',
- children: t`Error while switching subscription.`,
- });
-
- if (!CombinedGraphQLErrors.is(error)) {
- throw error;
- }
- } finally {
- setIsSwitchingPlan(false);
- }
- };
-
- return {
- isSwitchingPlan,
- switchBillingPlan,
- };
-};
diff --git a/packages/twenty-front/src/modules/settings/billing/types/billingSubscriptionChange.type.ts b/packages/twenty-front/src/modules/settings/billing/types/billingSubscriptionChange.type.ts
new file mode 100644
index 00000000000..5c3c49828ec
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/types/billingSubscriptionChange.type.ts
@@ -0,0 +1,8 @@
+import { type SettingsBillingPlanInterval } from '@/settings/billing/types/settingsBillingPlanComparison.type';
+import { type BillingPlanKey } from '~/generated-metadata/graphql';
+
+export type BillingSubscriptionChange =
+ | { type: 'SWITCH_PLAN'; targetPlanKey: BillingPlanKey }
+ | { type: 'SWITCH_INTERVAL'; targetInterval: SettingsBillingPlanInterval }
+ | { type: 'CANCEL_PLAN_SWITCH' }
+ | { type: 'CANCEL_INTERVAL_SWITCH' };
diff --git a/packages/twenty-front/src/modules/settings/billing/types/billingSubscriptionChangeWording.type.ts b/packages/twenty-front/src/modules/settings/billing/types/billingSubscriptionChangeWording.type.ts
new file mode 100644
index 00000000000..00c96b2b8bd
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/types/billingSubscriptionChangeWording.type.ts
@@ -0,0 +1,4 @@
+export type BillingSubscriptionChangeWording = {
+ subtitle: string;
+ title: string;
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/types/settingsBillingPlanCell.type.ts b/packages/twenty-front/src/modules/settings/billing/types/settingsBillingPlanCell.type.ts
new file mode 100644
index 00000000000..63d758cc16a
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/types/settingsBillingPlanCell.type.ts
@@ -0,0 +1,6 @@
+import { type BillingSubscriptionChange } from '@/settings/billing/types/billingSubscriptionChange.type';
+
+export type SettingsBillingPlanCell =
+ | { kind: 'current' }
+ | { kind: 'scheduled' }
+ | { kind: 'change'; change: BillingSubscriptionChange };
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/getBillingPlanCell.test.ts b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/getBillingPlanCell.test.ts
new file mode 100644
index 00000000000..1ee7f37170e
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/getBillingPlanCell.test.ts
@@ -0,0 +1,119 @@
+import { type SettingsBillingPlanCell } from '@/settings/billing/types/settingsBillingPlanCell.type';
+import { type SettingsBillingPlanInterval } from '@/settings/billing/types/settingsBillingPlanComparison.type';
+import { getBillingPlanCell } from '@/settings/billing/utils/getBillingPlanCell';
+import {
+ BillingPlanKey,
+ SubscriptionInterval,
+} from '~/generated-metadata/graphql';
+
+const { PRO, ENTERPRISE } = BillingPlanKey;
+const { Month, Year } = SubscriptionInterval;
+
+const current = { kind: 'current' } as const;
+const scheduled = { kind: 'scheduled' } as const;
+const switchPlan = (targetPlanKey: BillingPlanKey) =>
+ ({ kind: 'change', change: { type: 'SWITCH_PLAN', targetPlanKey } }) as const;
+const switchInterval = (targetInterval: SettingsBillingPlanInterval) =>
+ ({
+ kind: 'change',
+ change: { type: 'SWITCH_INTERVAL', targetInterval },
+ }) as const;
+const cancelPlanSwitch = {
+ kind: 'change',
+ change: { type: 'CANCEL_PLAN_SWITCH' },
+} as const;
+const cancelIntervalSwitch = {
+ kind: 'change',
+ change: { type: 'CANCEL_INTERVAL_SWITCH' },
+} as const;
+
+const getGrid = (subscription: {
+ currentPlanKey: BillingPlanKey;
+ currentInterval: SettingsBillingPlanInterval;
+ upcomingPlanKey: BillingPlanKey;
+ upcomingInterval: SettingsBillingPlanInterval;
+}) => {
+ const grid: Partial<
+ Record<BillingPlanKey, Record<SettingsBillingPlanInterval, unknown>>
+ > = {};
+
+ for (const planKey of [PRO, ENTERPRISE]) {
+ grid[planKey] = {
+ [Month]: getBillingPlanCell({
+ ...subscription,
+ planKey,
+ interval: Month,
+ }),
+ [Year]: getBillingPlanCell({ ...subscription, planKey, interval: Year }),
+ };
+ }
+
+ return grid as Record<
+ BillingPlanKey,
+ Record<SettingsBillingPlanInterval, SettingsBillingPlanCell>
+ >;
+};
+
+describe('getBillingPlanCell', () => {
+ it('offers a single-step switch from every other cell when nothing is scheduled', () => {
+ expect(
+ getGrid({
+ currentPlanKey: PRO,
+ currentInterval: Month,
+ upcomingPlanKey: PRO,
+ upcomingInterval: Month,
+ }),
+ ).toEqual({
+ [PRO]: { [Month]: current, [Year]: switchInterval(Year) },
+ [ENTERPRISE]: {
+ [Month]: switchPlan(ENTERPRISE),
+ [Year]: switchPlan(ENTERPRISE),
+ },
+ });
+ });
+
+ it('cancels a scheduled plan switch from the current plan column', () => {
+ expect(
+ getGrid({
+ currentPlanKey: PRO,
+ currentInterval: Month,
+ upcomingPlanKey: ENTERPRISE,
+ upcomingInterval: Month,
+ }),
+ ).toEqual({
+ [PRO]: { [Month]: current, [Year]: cancelPlanSwitch },
+ [ENTERPRISE]: { [Month]: scheduled, [Year]: switchInterval(Year) },
+ });
+ });
+
+ it('cancels a scheduled interval switch from the current interval column', () => {
+ expect(
+ getGrid({
+ currentPlanKey: PRO,
+ currentInterval: Year,
+ upcomingPlanKey: PRO,
+ upcomingInterval: Month,
+ }),
+ ).toEqual({
+ [PRO]: { [Month]: scheduled, [Year]: current },
+ [ENTERPRISE]: {
+ [Month]: switchPlan(ENTERPRISE),
+ [Year]: cancelIntervalSwitch,
+ },
+ });
+ });
+
+ it('cancels one dimension at a time when both switches are scheduled', () => {
+ expect(
+ getGrid({
+ currentPlanKey: ENTERPRISE,
+ currentInterval: Year,
+ upcomingPlanKey: PRO,
+ upcomingInterval: Month,
+ }),
+ ).toEqual({
+ [PRO]: { [Month]: scheduled, [Year]: cancelIntervalSwitch },
+ [ENTERPRISE]: { [Month]: cancelPlanSwitch, [Year]: current },
+ });
+ });
+});
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/isBillingSubscriptionChangeImmediate.test.ts b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/isBillingSubscriptionChangeImmediate.test.ts
new file mode 100644
index 00000000000..89c6d70919b
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/isBillingSubscriptionChangeImmediate.test.ts
@@ -0,0 +1,77 @@
+import { isBillingSubscriptionChangeImmediate } from '@/settings/billing/utils/isBillingSubscriptionChangeImmediate';
+import {
+ BillingPlanKey,
+ SubscriptionInterval,
+ SubscriptionStatus,
+} from '~/generated-metadata/graphql';
+
+describe('isBillingSubscriptionChangeImmediate', () => {
+ it('applies upgrades immediately and downgrades at period end', () => {
+ expect(
+ isBillingSubscriptionChangeImmediate({
+ change: {
+ type: 'SWITCH_PLAN',
+ targetPlanKey: BillingPlanKey.ENTERPRISE,
+ },
+ subscriptionStatus: SubscriptionStatus.Active,
+ }),
+ ).toBe(true);
+ expect(
+ isBillingSubscriptionChangeImmediate({
+ change: { type: 'SWITCH_PLAN', targetPlanKey: BillingPlanKey.PRO },
+ subscriptionStatus: SubscriptionStatus.Active,
+ }),
+ ).toBe(false);
+ expect(
+ isBillingSubscriptionChangeImmediate({
+ change: {
+ type: 'SWITCH_INTERVAL',
+ targetInterval: SubscriptionInterval.Year,
+ },
+ subscriptionStatus: SubscriptionStatus.Active,
+ }),
+ ).toBe(true);
+ expect(
+ isBillingSubscriptionChangeImmediate({
+ change: {
+ type: 'SWITCH_INTERVAL',
+ targetInterval: SubscriptionInterval.Month,
+ },
+ subscriptionStatus: SubscriptionStatus.Active,
+ }),
+ ).toBe(false);
+ });
+
+ it('applies every change immediately while trialing', () => {
+ expect(
+ isBillingSubscriptionChangeImmediate({
+ change: { type: 'SWITCH_PLAN', targetPlanKey: BillingPlanKey.PRO },
+ subscriptionStatus: SubscriptionStatus.Trialing,
+ }),
+ ).toBe(true);
+ expect(
+ isBillingSubscriptionChangeImmediate({
+ change: {
+ type: 'SWITCH_INTERVAL',
+ targetInterval: SubscriptionInterval.Month,
+ },
+ subscriptionStatus: SubscriptionStatus.Trialing,
+ }),
+ ).toBe(true);
+ });
+
+ it('applies cancellations immediately', () => {
+ expect(
+ isBillingSubscriptionChangeImmediate({
+ change: { type: 'CANCEL_PLAN_SWITCH' },
+ subscriptionStatus: SubscriptionStatus.Active,
+ }),
+ ).toBe(true);
+ expect(
+ isBillingSubscriptionChangeImmediate({
+ change: { type: 'CANCEL_INTERVAL_SWITCH' },
+ subscriptionStatus: SubscriptionStatus.Active,
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/isBillingSubscriptionChangeUpgrade.test.ts b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/isBillingSubscriptionChangeUpgrade.test.ts
new file mode 100644
index 00000000000..f10e2f4889d
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/isBillingSubscriptionChangeUpgrade.test.ts
@@ -0,0 +1,79 @@
+import { isBillingSubscriptionChangeUpgrade } from '@/settings/billing/utils/isBillingSubscriptionChangeUpgrade';
+import {
+ BillingPlanKey,
+ SubscriptionInterval,
+} from '~/generated-metadata/graphql';
+
+describe('isBillingSubscriptionChangeUpgrade', () => {
+ const proMonthlyUpcoming = {
+ upcomingPlanKey: BillingPlanKey.PRO,
+ upcomingInterval: SubscriptionInterval.Month,
+ };
+ const enterpriseYearlyUpcoming = {
+ upcomingPlanKey: BillingPlanKey.ENTERPRISE,
+ upcomingInterval: SubscriptionInterval.Year,
+ };
+
+ it('treats switching to Organization or to annual as upgrades', () => {
+ expect(
+ isBillingSubscriptionChangeUpgrade({
+ change: {
+ type: 'SWITCH_PLAN',
+ targetPlanKey: BillingPlanKey.ENTERPRISE,
+ },
+ ...proMonthlyUpcoming,
+ }),
+ ).toBe(true);
+ expect(
+ isBillingSubscriptionChangeUpgrade({
+ change: {
+ type: 'SWITCH_INTERVAL',
+ targetInterval: SubscriptionInterval.Year,
+ },
+ ...proMonthlyUpcoming,
+ }),
+ ).toBe(true);
+ expect(
+ isBillingSubscriptionChangeUpgrade({
+ change: { type: 'SWITCH_PLAN', targetPlanKey: BillingPlanKey.PRO },
+ ...enterpriseYearlyUpcoming,
+ }),
+ ).toBe(false);
+ expect(
+ isBillingSubscriptionChangeUpgrade({
+ change: {
+ type: 'SWITCH_INTERVAL',
+ targetInterval: SubscriptionInterval.Month,
+ },
+ ...enterpriseYearlyUpcoming,
+ }),
+ ).toBe(false);
+ });
+
+ it('treats cancelling a scheduled downgrade as an upgrade', () => {
+ expect(
+ isBillingSubscriptionChangeUpgrade({
+ change: { type: 'CANCEL_PLAN_SWITCH' },
+ ...proMonthlyUpcoming,
+ }),
+ ).toBe(true);
+ expect(
+ isBillingSubscriptionChangeUpgrade({
+ change: { type: 'CANCEL_INTERVAL_SWITCH' },
+ ...proMonthlyUpcoming,
+ }),
+ ).toBe(true);
+ expect(
+ isBillingSubscriptionChangeUpgrade({
+ change: { type: 'CANCEL_PLAN_SWITCH' },
+ ...enterpriseYearlyUpcoming,
+ }),
+ ).toBe(false);
+ expect(
+ isBillingSubscriptionChangeUpgrade({
+ change: { type: 'CANCEL_INTERVAL_SWITCH' },
+ ...enterpriseYearlyUpcoming,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/getBillingPlanCell.ts b/packages/twenty-front/src/modules/settings/billing/utils/getBillingPlanCell.ts
new file mode 100644
index 00000000000..9ac9c4af0c7
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/getBillingPlanCell.ts
@@ -0,0 +1,63 @@
+import { type SettingsBillingPlanCell } from '@/settings/billing/types/settingsBillingPlanCell.type';
+import { type SettingsBillingPlanInterval } from '@/settings/billing/types/settingsBillingPlanComparison.type';
+import { type BillingPlanKey } from '~/generated-metadata/graphql';
+
+type GetBillingPlanCellParams = {
+ currentInterval: SettingsBillingPlanInterval;
+ currentPlanKey: BillingPlanKey;
+ interval: SettingsBillingPlanInterval;
+ planKey: BillingPlanKey;
+ upcomingInterval: SettingsBillingPlanInterval;
+ upcomingPlanKey: BillingPlanKey;
+};
+
+export const getBillingPlanCell = ({
+ currentInterval,
+ currentPlanKey,
+ interval,
+ planKey,
+ upcomingInterval,
+ upcomingPlanKey,
+}: GetBillingPlanCellParams): SettingsBillingPlanCell => {
+ if (planKey === currentPlanKey && interval === currentInterval) {
+ return { kind: 'current' };
+ }
+
+ if (planKey === upcomingPlanKey && interval === upcomingInterval) {
+ return { kind: 'scheduled' };
+ }
+
+ const isPlanSwitchScheduled = upcomingPlanKey !== currentPlanKey;
+ const isIntervalSwitchScheduled = upcomingInterval !== currentInterval;
+
+ if (planKey === upcomingPlanKey) {
+ return {
+ kind: 'change',
+ change: isIntervalSwitchScheduled
+ ? { type: 'CANCEL_INTERVAL_SWITCH' }
+ : { type: 'SWITCH_INTERVAL', targetInterval: interval },
+ };
+ }
+
+ if (interval === upcomingInterval) {
+ return {
+ kind: 'change',
+ change: isPlanSwitchScheduled
+ ? { type: 'CANCEL_PLAN_SWITCH' }
+ : { type: 'SWITCH_PLAN', targetPlanKey: planKey },
+ };
+ }
+
+ if (isPlanSwitchScheduled) {
+ return { kind: 'change', change: { type: 'CANCEL_PLAN_SWITCH' } };
+ }
+
+ if (isIntervalSwitchScheduled) {
+ return { kind: 'change', change: { type: 'CANCEL_INTERVAL_SWITCH' } };
+ }
+
+ return {
+ kind: 'change',
+ change: { type: 'SWITCH_PLAN', targetPlanKey: planKey },
+ };
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/isBillingSubscriptionChangeImmediate.ts b/packages/twenty-front/src/modules/settings/billing/utils/isBillingSubscriptionChangeImmediate.ts
new file mode 100644
index 00000000000..5af6e409530
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/isBillingSubscriptionChangeImmediate.ts
@@ -0,0 +1,31 @@
+import { type BillingSubscriptionChange } from '@/settings/billing/types/billingSubscriptionChange.type';
+import { assertUnreachable } from 'twenty-shared/utils';
+import {
+ BillingPlanKey,
+ SubscriptionInterval,
+ SubscriptionStatus,
+} from '~/generated-metadata/graphql';
+
+export const isBillingSubscriptionChangeImmediate = ({
+ change,
+ subscriptionStatus,
+}: {
+ change: BillingSubscriptionChange;
+ subscriptionStatus: SubscriptionStatus | undefined;
+}) => {
+ if (subscriptionStatus === SubscriptionStatus.Trialing) {
+ return true;
+ }
+
+ switch (change.type) {
+ case 'SWITCH_PLAN':
+ return change.targetPlanKey === BillingPlanKey.ENTERPRISE;
+ case 'SWITCH_INTERVAL':
+ return change.targetInterval === SubscriptionInterval.Year;
+ case 'CANCEL_PLAN_SWITCH':
+ case 'CANCEL_INTERVAL_SWITCH':
+ return true;
+ default:
+ return assertUnreachable(change);
+ }
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/isBillingSubscriptionChangeUpgrade.ts b/packages/twenty-front/src/modules/settings/billing/utils/isBillingSubscriptionChangeUpgrade.ts
new file mode 100644
index 00000000000..15c28468247
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/isBillingSubscriptionChangeUpgrade.ts
@@ -0,0 +1,30 @@
+import { type BillingSubscriptionChange } from '@/settings/billing/types/billingSubscriptionChange.type';
+import { assertUnreachable } from 'twenty-shared/utils';
+import { type SettingsBillingPlanInterval } from '@/settings/billing/types/settingsBillingPlanComparison.type';
+import {
+ BillingPlanKey,
+ SubscriptionInterval,
+} from '~/generated-metadata/graphql';
+
+export const isBillingSubscriptionChangeUpgrade = ({
+ change,
+ upcomingInterval,
+ upcomingPlanKey,
+}: {
+ change: BillingSubscriptionChange;
+ upcomingInterval: SettingsBillingPlanInterval;
+ upcomingPlanKey: BillingPlanKey;
+}) => {
+ switch (change.type) {
+ case 'SWITCH_PLAN':
+ return change.targetPlanKey === BillingPlanKey.ENTERPRISE;
+ case 'SWITCH_INTERVAL':
+ return change.targetInterval === SubscriptionInterval.Year;
+ case 'CANCEL_PLAN_SWITCH':
+ return upcomingPlanKey === BillingPlanKey.PRO;
+ case 'CANCEL_INTERVAL_SWITCH':
+ return upcomingInterval === SubscriptionInterval.Month;
+ default:
+ return assertUnreachable(change);
+ }
+};