The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(billing): clarify subscription, credits, and add-credits sections (#22126)
Félix Malfait179ab2f066cf
diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsxindex 9f65f706ca4..48edb2c756e 100644--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx@@ -18,7 +18,7 @@ import { getSettingsPath } from 'twenty-shared/utils';import { IconChartBar, IconExternalLink } from 'twenty-ui/icon';import { HorizontalSeparator, Section } from 'twenty-ui/layout';import { H2Title } from 'twenty-ui/typography';-import { ProgressBar } from 'twenty-ui/feedback';+import { Info, ProgressBar } from 'twenty-ui/feedback';import { Button } from 'twenty-ui/input';import { UndecoratedLink } from 'twenty-ui/navigation';import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';@@ -58,6 +58,14 @@ export const SettingsBillingCreditsSection = ({const intervalLabel = getIntervalLabel(isMonthlyPlan);+ const usedCreditsDisplay = formatNumber(usedCredits, { decimals: 2 });+ const totalGrantedCreditsDisplay = formatNumber(totalGrantedCredits, {+ decimals: 2,+ });+ const grantedCreditsDisplay = formatNumber(grantedCredits, { decimals: 2 });+ const rolloverCreditsDisplay = formatNumber(rolloverCredits, { decimals: 2 });+ const rolloverCapDisplay = formatNumber(grantedCredits * 2, { decimals: 2 });+const resourceCreditPrices = getResourceCreditPricesByInterval(currentBillingSubscription.interval,);@@ -72,7 +80,7 @@ export const SettingsBillingCreditsSection = ({<SubscriptionInfoContainer><SettingsBillingLabelValueItemlabel={t`Credits Used`}- value={`${formatNumber(usedCredits, { abbreviate: true, decimals: 2 })}/${formatNumber(totalGrantedCredits, { abbreviate: true, decimals: 2 })}`}+ value={t`${usedCreditsDisplay} / ${totalGrantedCreditsDisplay} available`}/><ProgressBarvalue={progressBarValue}@@ -87,32 +95,19 @@ export const SettingsBillingCreditsSection = ({<><HorizontalSeparator noMargin color={theme.background.tertiary} /><SettingsBillingLabelValueItem- label={t`Base Credits`}- value={formatNumber(grantedCredits, {- abbreviate: true,- decimals: 2,- })}+ label={t`This ${intervalLabel}'s credits`}+ value={grantedCreditsDisplay}/>{rolloverCredits > 0 && (<SettingsBillingLabelValueItem- label={t`Rollover Credits`}- value={formatNumber(rolloverCredits, {- abbreviate: true,- decimals: 2,- })}- tooltipText={t`Unused credits from the previous period. Expired at the end of the period.`}- tooltipId="rollover-credits-info"- />- )}- {rolloverCredits > 0 && (- <SettingsBillingLabelValueItem- label={t`Total Available`}- value={formatNumber(totalGrantedCredits, {- abbreviate: true,- decimals: 2,- })}+ label={t`Rolled over`}+ value={`+${rolloverCreditsDisplay}`}/>)}+ <Info+ accent="blue"+ text={t`Unused credits roll over, up to 2× your plan's credits (max ${rolloverCapDisplay}).`}+ /></>)}</SubscriptionInfoContainer>diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingSubscriptionInfo.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingSubscriptionInfo.tsxindex c62164fd3ca..3da45a7d15f 100644--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingSubscriptionInfo.tsx+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingSubscriptionInfo.tsx@@ -11,6 +11,7 @@ import {import { useNumberFormat } from '@/localization/hooks/useNumberFormat';import { PlansTags } from '@/settings/billing/components/internal/PlansTags';+import { useBillingSubscriptionCost } from '@/settings/billing/hooks/useBillingSubscriptionCost';import { useBillingWording } from '@/settings/billing/hooks/useBillingWording';import { useCurrentBillingFlags } from '@/settings/billing/hooks/useCurrentBillingFlags';import { useCurrentPlan } from '@/settings/billing/hooks/useCurrentPlan';@@ -40,16 +41,16 @@ import {IconCalendarRepeat,IconCircleX,IconCoins,+ IconSum,IconTag,IconUsers,} from 'twenty-ui/icon';-import { H2Title } from 'twenty-ui/typography';+import { H2Title, Label } from 'twenty-ui/typography';import { Button } from 'twenty-ui/input';-import { Section } from 'twenty-ui/layout';+import { HorizontalSeparator, Section } from 'twenty-ui/layout';import { themeCssVariables } from 'twenty-ui/theme-constants';import {BillingPlanKey,- BillingProductKey,CancelSwitchBillingIntervalDocument,CancelSwitchBillingPlanDocument,CancelSwitchResourceCreditPriceDocument,@@ -89,6 +90,12 @@ const StyledSwitchButtonContainer = styled.div`margin-top: ${themeCssVariables.spacing[4]};`;+const StyledTotalGroup = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[1]};+`;+export const SettingsBillingSubscriptionInfo = ({currentWorkspace,currentBillingSubscription,@@ -132,7 +139,9 @@ export const SettingsBillingSubscriptionInfo = ({const nextCreditsByPeriod = nextResourceCreditPrice?.creditAmount ?? null;const {+ getIntervalLabel,getIntervalLabelAsAdjectiveCapitalize,+ getYearlyDiscountPercent,confirmationModalSwitchToProMessage,confirmationModalSwitchToOrganizationMessage,confirmationModalSwitchToMonthlyMessage,@@ -173,11 +182,54 @@ export const SettingsBillingSubscriptionInfo = ({const { [PermissionFlagType.WORKSPACE]: hasPermissionToEndTrialPeriod } =usePermissionFlagMap();- const seats = currentBillingSubscription.billingSubscriptionItems?.find(- (item) =>- item.billingProduct.metadata.productKey ===- BillingProductKey.BASE_PRODUCT,- )?.quantity as number | undefined;+ const {+ seats,+ perSeatAmountCents,+ seatsSubtotalCents,+ creditsSubtotalCents,+ totalCents,+ } = useBillingSubscriptionCost();++ const formatCentsToDisplay = (cents: number | null | undefined) =>+ isDefined(cents) ? formatNumber(cents / 100, { decimals: 2 }) : undefined;++ const perSeatUnit = isMonthlyPlan ? t`mo` : t`yr`;+ const totalIntervalWord = getIntervalLabel(isMonthlyPlan);+ const creditsIntervalAdjective =+ getIntervalLabelAsAdjectiveCapitalize(isMonthlyPlan);++ const perSeatPriceDisplay = formatCentsToDisplay(perSeatAmountCents);++ const seatsInlinePrice =+ isDefined(seats) && isDefined(perSeatPriceDisplay)+ ? t`${seats} × $${perSeatPriceDisplay} / seat / ${perSeatUnit}`+ : undefined;++ const totalDisplay = formatCentsToDisplay(totalCents);+ const seatsSubtotalDisplay = formatCentsToDisplay(seatsSubtotalCents);+ const creditsSubtotalDisplay = formatCentsToDisplay(creditsSubtotalCents);++ const totalRenewDate = isDefined(currentBillingSubscription.currentPeriodEnd)+ ? getBeautifiedRenewDate()+ : undefined;++ const totalBreakdownText =+ isDefined(seatsSubtotalDisplay) && isDefined(creditsSubtotalDisplay)+ ? t`$${seatsSubtotalDisplay} seats + $${creditsSubtotalDisplay} credits`+ : undefined;+ const totalNextChargeText = isDefined(totalRenewDate)+ ? t`next charge ${totalRenewDate}`+ : undefined;+ const totalHelperText = isDefined(totalBreakdownText)+ ? [totalBreakdownText, totalNextChargeText].filter(isDefined).join(' · ')+ : undefined;++ const yearlyDiscountPercent = getYearlyDiscountPercent();++ const switchToYearlyTitle =+ yearlyDiscountPercent > 0+ ? t`Switch to Yearly · save ${yearlyDiscountPercent}%`+ : t`Switch to Yearly`;// Loading states to avoid race conditions on actionsconst [isSwitchingInterval, setIsSwitchingInterval] = useState(false);@@ -410,29 +462,39 @@ export const SettingsBillingSubscriptionInfo = ({<SubscriptionInfoRowContainerlabel={t`Seats`}Icon={IconUsers}- currentValue={seats}+ currentValue={seatsInlinePrice ?? seats}nextValue={nextBillingSeats}/><SubscriptionInfoRowContainer- label={t`Credits by period`}+ label={t`${creditsIntervalAdjective} credits`}Icon={IconCoins}currentValue={isDefined(currentCreditsByPeriod)- ? formatNumber(currentCreditsByPeriod, {- abbreviate: true,- decimals: 2,- })+ ? formatNumber(currentCreditsByPeriod, { decimals: 2 }): undefined}nextValue={isDefined(nextCreditsByPeriod)- ? formatNumber(nextCreditsByPeriod, {- abbreviate: true,- decimals: 2,- })+ ? formatNumber(nextCreditsByPeriod, { decimals: 2 }): undefined}/>+ {isDefined(totalCents) && (+ <>+ <HorizontalSeparator+ noMargin+ color={themeCssVariables.background.tertiary}+ />+ <StyledTotalGroup>+ <SubscriptionInfoRowContainer+ label={t`Total per ${totalIntervalWord}`}+ Icon={IconSum}+ currentValue={`$${totalDisplay}`}+ />+ {isDefined(totalHelperText) && <Label>{totalHelperText}</Label>}+ </StyledTotalGroup>+ </>+ )}</SubscriptionInfoContainer><StyledSwitchButtonContainer>{isTrialPeriod && hasPermissionToEndTrialPeriod && (@@ -457,7 +519,7 @@ export const SettingsBillingSubscriptionInfo = ({(!nextInterval || currentInterval === nextInterval) && (<ButtonIcon={IconArrowUp}- title={t`Switch to Yearly`}+ title={switchToYearlyTitle}variant="secondary"onClick={() =>openModal(SWITCH_BILLING_INTERVAL_TO_YEARLY_MODAL_ID)diff --git a/packages/twenty-front/src/modules/settings/billing/components/internal/ResourceCreditPriceSelector.tsx b/packages/twenty-front/src/modules/settings/billing/components/internal/ResourceCreditPriceSelector.tsxindex ff97ca91d32..52accf9648f 100644--- a/packages/twenty-front/src/modules/settings/billing/components/internal/ResourceCreditPriceSelector.tsx+++ b/packages/twenty-front/src/modules/settings/billing/components/internal/ResourceCreditPriceSelector.tsx@@ -1,5 +1,7 @@import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { useNumberFormat } from '@/localization/hooks/useNumberFormat';+import { SettingsBillingLabelValueItem } from '@/settings/billing/components/internal/SettingsBillingLabelValueItem';+import { useBillingSubscriptionCost } from '@/settings/billing/hooks/useBillingSubscriptionCost';import { useBillingWording } from '@/settings/billing/hooks/useBillingWording';import { useCurrentResourceCredit } from '@/settings/billing/hooks/useCurrentResourceCredit';import { useGetResourceCreditUsage } from '@/settings/billing/hooks/useGetResourceCreditUsage';@@ -37,6 +39,13 @@ const StyledButtonContainer = styled.div`flex: 0 0 auto;`;+const StyledSummary = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[2]};+ margin-top: ${themeCssVariables.spacing[2]};+`;+export const ResourceCreditPriceSelector = ({resourceCreditPrices,isTrialing = false,@@ -46,6 +55,7 @@ export const ResourceCreditPriceSelector = ({}) => {const { currentResourceCreditBillingPrice } = useCurrentResourceCredit();const { formatNumber } = useNumberFormat();+ const { getTotalCentsWithCreditsAmountCents } = useBillingSubscriptionCost();const [currentWorkspace, setCurrentWorkspace] = useAtomState(currentWorkspaceState,@@ -120,10 +130,29 @@ export const ResourceCreditPriceSelector = ({openModal(confirmModalId);};- const recurringInterval = getIntervalLabel(+ const isMonthly =currentResourceCreditPrice?.recurringInterval ===- SubscriptionInterval.Month,- );+ SubscriptionInterval.Month;+ const intervalAdjective = getIntervalLabel(isMonthly, true);++ const effectiveResourceCreditPrice =+ selectedPrice ?? currentResourceCreditPrice;+ const effectiveCreditUnitAmount = effectiveResourceCreditPrice?.unitAmount;+ const effectiveCreditAmount = effectiveResourceCreditPrice?.creditAmount;++ const newTotalCents = isDefined(effectiveCreditUnitAmount)+ ? getTotalCentsWithCreditsAmountCents(effectiveCreditUnitAmount)+ : undefined;+ const newRolloverCap = isDefined(effectiveCreditAmount)+ ? effectiveCreditAmount * 2+ : undefined;++ const newTotalDisplay = isDefined(newTotalCents)+ ? formatNumber(newTotalCents / 100, { decimals: 2 })+ : undefined;+ const newRolloverCapDisplay = isDefined(newRolloverCap)+ ? formatNumber(newRolloverCap, { decimals: 2 })+ : undefined;const handleConfirmClick = async () => {if (!selectedPrice) return;@@ -163,8 +192,8 @@ export const ResourceCreditPriceSelector = ({return (<><H2Title- title={t`Resource credits`}- description={t`Number of new credits allocated every ${recurringInterval}`}+ title={t`Add ${intervalAdjective} credits`}+ description={t`Stacks on top of your plan's base credits and adjusts your ${intervalAdjective} bill.`}/><StyledRow><StyledSelectContainer>@@ -195,6 +224,22 @@ export const ResourceCreditPriceSelector = ({</StyledButtonContainer>)}</StyledRow>+ {!isTrialing &&+ isChanged &&+ isDefined(newTotalDisplay) &&+ isDefined(newRolloverCapDisplay) && (+ <StyledSummary>+ <SettingsBillingLabelValueItem+ label={t`New ${intervalAdjective} total`}+ value={`$${newTotalDisplay}`}+ isValueInPrimaryColor+ />+ <SettingsBillingLabelValueItem+ label={t`New rollover cap`}+ value={t`${newRolloverCapDisplay} credits`}+ />+ </StyledSummary>+ )}<ConfirmationModalmodalInstanceId={confirmModalId}title={isUpgrade() ? t`Confirm upgrade` : t`Confirm downgrade`}diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingSubscriptionCost.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingSubscriptionCost.tsnew file mode 100644index 00000000000..302edbec59a--- /dev/null+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingSubscriptionCost.ts@@ -0,0 +1,60 @@+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';+import { useBaseLicensedPriceByPlanKeyAndInterval } from '@/settings/billing/hooks/useBaseLicensedPriceByPlanKeyAndInterval';+import { useCurrentPlan } from '@/settings/billing/hooks/useCurrentPlan';+import { useCurrentResourceCredit } from '@/settings/billing/hooks/useCurrentResourceCredit';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { isDefined } from 'twenty-shared/utils';+import { BillingProductKey } from '~/generated-metadata/graphql';++// Centralizes the monthly/yearly bill breakdown so the subscription card and+// the add-credits selector compute the same numbers from a single source.+export const useBillingSubscriptionCost = () => {+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);+ const subscription = currentWorkspace?.currentBillingSubscription;++ const { currentPlan } = useCurrentPlan();+ const { getBaseLicensedPriceByPlanKeyAndInterval } =+ useBaseLicensedPriceByPlanKeyAndInterval();+ const { currentResourceCreditBillingPrice } = useCurrentResourceCredit();++ const interval = subscription?.interval;++ const seats = subscription?.billingSubscriptionItems?.find(+ (item) =>+ item.billingProduct.metadata.productKey ===+ BillingProductKey.BASE_PRODUCT,+ )?.quantity;++ // Per-seat amount is expressed at the subscription interval (full yearly+ // amount for yearly subscriptions), so subtotals match the actual charge.+ const perSeatAmountCents = isDefined(interval)+ ? getBaseLicensedPriceByPlanKeyAndInterval(currentPlan.planKey, interval)+ .unitAmount+ : undefined;++ const seatsSubtotalCents =+ isDefined(seats) && isDefined(perSeatAmountCents)+ ? seats * perSeatAmountCents+ : undefined;++ const creditsSubtotalCents = currentResourceCreditBillingPrice?.unitAmount;++ const totalCents =+ isDefined(seatsSubtotalCents) && isDefined(creditsSubtotalCents)+ ? seatsSubtotalCents + creditsSubtotalCents+ : undefined;++ const getTotalCentsWithCreditsAmountCents = (creditsAmountCents: number) =>+ isDefined(seatsSubtotalCents)+ ? seatsSubtotalCents + creditsAmountCents+ : undefined;++ return {+ seats,+ perSeatAmountCents,+ seatsSubtotalCents,+ creditsSubtotalCents,+ totalCents,+ getTotalCentsWithCreditsAmountCents,+ };+};diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingWording.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingWording.tsindex e0613007503..e5bf17a7f7f 100644--- a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingWording.ts+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingWording.ts@@ -4,7 +4,11 @@ import {SubscriptionInterval,SubscriptionStatus,} from '~/generated-metadata/graphql';-import { assertIsDefinedOrThrow, capitalize } from 'twenty-shared/utils';+import {+ assertIsDefinedOrThrow,+ capitalize,+ isDefined,+} from 'twenty-shared/utils';import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';import { useLingui } from '@lingui/react/macro';@@ -70,6 +74,11 @@ export const useBillingWording = () => {currentBillingSubscription.metadata['plan'] as BillingPlanKey]?.[SubscriptionInterval.Month];+ const getYearlyDiscountPercent = () =>+ isDefined(monthlyPrice) && isDefined(yearlyPrice) && monthlyPrice > 0+ ? Math.round((1 - yearlyPrice / monthlyPrice) * 100)+ : 0;+const getCurrentIntervalLabel = () =>getIntervalLabelAsAdjectiveCapitalize(currentBillingSubscription.interval === SubscriptionInterval.Month,@@ -138,6 +147,7 @@ export const useBillingWording = () => {getBeautifiedRenewDate,getIntervalLabel,getIntervalLabelAsAdjectiveCapitalize,+ getYearlyDiscountPercent,confirmationModalSwitchToYearlyMessage,confirmationModalSwitchToMonthlyMessage,confirmationModalSwitchToOrganizationMessage,