Skip to content

The open alternative to Salesforce, designed for AI.

Add in-product Update Payment Method modal and retry unpaid invoices after SetupIntent (#25430)

Félix Malfaita1ad1bf297a3
diff --git a/packages/twenty-front/src/modules/information-banner/components/InformationBannerWrapper.tsx b/packages/twenty-front/src/modules/information-banner/components/InformationBannerWrapper.tsx
index 0417930ef44..ac7fe9104ef 100644
--- a/packages/twenty-front/src/modules/information-banner/components/InformationBannerWrapper.tsx
+++ b/packages/twenty-front/src/modules/information-banner/components/InformationBannerWrapper.tsx
@@ -13,6 +13,7 @@ import { InformationBannerReconnectAccountInsufficientPermissions } from '@/info
import { usePermissionFlagMap } from '@/settings/roles/hooks/usePermissionFlagMap';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { useIsWorkspaceActivationStatusEqualsTo } from '@/workspace/hooks/useIsWorkspaceActivationStatusEqualsTo';
+import { isSubscriptionPaymentOverdue } from '@/settings/billing/utils/isSubscriptionPaymentOverdue';
import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';
import { hasReachedCurrentBillingPeriodCapSelector } from '@/workspace/states/hasReachedCurrentBillingPeriodCapSelector';
@@ -49,8 +50,7 @@ export const InformationBannerWrapper = () => {
isWorkspaceSuspended && !isDefined(subscriptionStatus);
const displayFailPaymentInfoBanner =
- subscriptionStatus === SubscriptionStatus.PastDue ||
- subscriptionStatus === SubscriptionStatus.Unpaid;
+ isSubscriptionPaymentOverdue(subscriptionStatus);
const displayEndTrialPeriodBanner =
hasReachedCurrentBillingPeriodCap &&
diff --git a/packages/twenty-front/src/modules/information-banner/components/billing/InformationBannerBillingSubscriptionPaused.tsx b/packages/twenty-front/src/modules/information-banner/components/billing/InformationBannerBillingSubscriptionPaused.tsx
index 88048a9c438..d3b2a1c5f78 100644
--- a/packages/twenty-front/src/modules/information-banner/components/billing/InformationBannerBillingSubscriptionPaused.tsx
+++ b/packages/twenty-front/src/modules/information-banner/components/billing/InformationBannerBillingSubscriptionPaused.tsx
@@ -14,18 +14,18 @@ import {
export const InformationBannerBillingSubscriptionPaused = () => {
const { redirect } = useRedirect();
+ const { [PermissionFlagType.BILLING]: hasPermissionToUpdateBillingDetails } =
+ usePermissionFlagMap();
+
const { data, loading, error } = useQuery(BillingPortalSessionDocument, {
variables: {
returnUrlPath: getSettingsPath(SettingsPath.Billing),
},
+ skip: !hasPermissionToUpdateBillingDetails,
});
useSnackBarOnQueryError(error);
- const {
- [PermissionFlagType.WORKSPACE]: hasPermissionToUpdateBillingDetails,
- } = usePermissionFlagMap();
-
const openBillingPortal = () => {
if (isDefined(data) && isDefined(data.billingPortalSession.url)) {
redirect(data.billingPortalSession.url);
diff --git a/packages/twenty-front/src/modules/information-banner/components/billing/InformationBannerFailPaymentInfo.tsx b/packages/twenty-front/src/modules/information-banner/components/billing/InformationBannerFailPaymentInfo.tsx
index d9d9efea76b..4105ea38b04 100644
--- a/packages/twenty-front/src/modules/information-banner/components/billing/InformationBannerFailPaymentInfo.tsx
+++ b/packages/twenty-front/src/modules/information-banner/components/billing/InformationBannerFailPaymentInfo.tsx
@@ -1,49 +1,57 @@
-import { useRedirect } from '@/domain-manager/hooks/useRedirect';
import { InformationBanner } from '@/information-banner/components/InformationBanner';
-import { usePermissionFlagMap } from '@/settings/roles/hooks/usePermissionFlagMap';
+import { UpdatePaymentMethodModal } from '@/settings/billing/components/UpdatePaymentMethodModal';
+import { usePaymentMethodFlow } from '@/settings/billing/hooks/usePaymentMethodFlow';
import { t } from '@lingui/core/macro';
-import { SettingsPath } from 'twenty-shared/types';
-import { getSettingsPath, isDefined } from 'twenty-shared/utils';
-import { useQuery } from '@apollo/client/react';
-import {
- PermissionFlagType,
- BillingPortalSessionDocument,
-} from '~/generated-metadata/graphql';
+
+const FAILED_PAYMENT_UPDATE_PAYMENT_MODAL_ID =
+ 'failed-payment-update-payment-modal';
export const InformationBannerFailPaymentInfo = () => {
- const { redirect } = useRedirect();
+ const {
+ hasPermissionToManageBilling: hasPermissionToUpdateBillingDetails,
+ shouldAddPaymentMethodInProduct,
+ openPaymentMethodFlow,
+ isPaymentMethodFlowDisabled,
+ } = usePaymentMethodFlow(FAILED_PAYMENT_UPDATE_PAYMENT_MODAL_ID);
- const { data, loading } = useQuery(BillingPortalSessionDocument, {
- variables: {
- returnUrlPath: getSettingsPath(SettingsPath.Billing),
- },
- });
+ const getMessage = () => {
+ if (!hasPermissionToUpdateBillingDetails) {
+ return t`There is a billing issue. Please contact your admin.`;
+ }
- const {
- [PermissionFlagType.WORKSPACE]: hasPermissionToUpdateBillingDetails,
- } = usePermissionFlagMap();
+ if (shouldAddPaymentMethodInProduct) {
+ return t`A payment method is needed to keep your workspace active.`;
+ }
+
+ return t`Last payment failed. Please update your billing details.`;
+ };
- const openBillingPortal = () => {
- if (isDefined(data) && isDefined(data.billingPortalSession.url)) {
- redirect(data.billingPortalSession.url);
+ const getButtonTitle = () => {
+ if (!hasPermissionToUpdateBillingDetails) {
+ return undefined;
}
+
+ return shouldAddPaymentMethodInProduct
+ ? t`Add payment method`
+ : t`Update payment`;
};
return (
- <InformationBanner
- componentInstanceId="information-banner-fail-payment-info"
- color="danger"
- variant="secondary"
- message={
- hasPermissionToUpdateBillingDetails
- ? t`Last payment failed. Please update your billing details.`
- : t`Last payment failed. Please contact your admin.`
- }
- buttonTitle={
- hasPermissionToUpdateBillingDetails ? t`Update payment` : undefined
- }
- buttonOnClick={() => openBillingPortal()}
- isButtonDisabled={loading || !isDefined(data)}
- />
+ <>
+ <InformationBanner
+ componentInstanceId="information-banner-fail-payment-info"
+ color="danger"
+ variant="secondary"
+ message={getMessage()}
+ buttonTitle={getButtonTitle()}
+ buttonOnClick={openPaymentMethodFlow}
+ isButtonDisabled={isPaymentMethodFlowDisabled}
+ />
+ {shouldAddPaymentMethodInProduct && (
+ <UpdatePaymentMethodModal
+ modalInstanceId={FAILED_PAYMENT_UPDATE_PAYMENT_MODAL_ID}
+ />
+ )}
+ </>
);
};
diff --git a/packages/twenty-front/src/modules/settings/billing/components/AddPaymentMethodForm.tsx b/packages/twenty-front/src/modules/settings/billing/components/AddPaymentMethodForm.tsx
index 9f5b1acaebc..c57a6b9644e 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/AddPaymentMethodForm.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/AddPaymentMethodForm.tsx
@@ -25,6 +25,7 @@ import { CreateBillingPaymentMethodSetupIntentDocument } from '~/generated-metad
type AddPaymentMethodFormContentProps = {
finalRedirectPath?: string;
onPaymentMethodAdded: () => Promise<void>;
+ shouldStartSubscriptionAfterPaymentMethod?: boolean;
};
type AddPaymentMethodFormProps = AddPaymentMethodFormContentProps;
@@ -39,6 +40,7 @@ const StyledFormContainer = styled.div`
const AddPaymentMethodFormContent = ({
finalRedirectPath,
onPaymentMethodAdded,
+ shouldStartSubscriptionAfterPaymentMethod = true,
}: AddPaymentMethodFormContentProps) => {
const stripe = useStripe();
const elements = useElements();
@@ -59,10 +61,12 @@ const AddPaymentMethodFormContent = ({
finalRedirectPath ?? `${location.pathname}${location.search}`;
const returnUrl = new URL(basePath, window.location.origin);
- returnUrl.searchParams.set(
- START_SUBSCRIPTION_AFTER_PAYMENT_METHOD_QUERY_PARAM,
- 'true',
- );
+ if (shouldStartSubscriptionAfterPaymentMethod) {
+ returnUrl.searchParams.set(
+ START_SUBSCRIPTION_AFTER_PAYMENT_METHOD_QUERY_PARAM,
+ 'true',
+ );
+ }
return returnUrl.toString();
};
@@ -156,6 +160,7 @@ const AddPaymentMethodFormContent = ({
export const AddPaymentMethodForm = ({
finalRedirectPath,
onPaymentMethodAdded,
+ shouldStartSubscriptionAfterPaymentMethod,
}: AddPaymentMethodFormProps) => {
const stripePromise = useStripePromise();
const appearance = useStripeAppearance();
@@ -179,6 +184,9 @@ export const AddPaymentMethodForm = ({
<AddPaymentMethodFormContent
finalRedirectPath={finalRedirectPath}
onPaymentMethodAdded={onPaymentMethodAdded}
+ shouldStartSubscriptionAfterPaymentMethod={
+ shouldStartSubscriptionAfterPaymentMethod
+ }
/>
</Elements>
);
diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingContent.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingContent.tsx
index 80efac73fa9..15e27e99183 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingContent.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingContent.tsx
@@ -4,19 +4,23 @@ import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { SettingsBillingCreditsSection } from '@/settings/billing/components/SettingsBillingCreditsSection';
import { SettingsBillingSubscriptionInfo } from '@/settings/billing/components/SettingsBillingSubscriptionInfo';
import { SettingsBillingTrialNoPaymentMethodBanner } from '@/settings/billing/components/SettingsBillingTrialNoPaymentMethodBanner';
-import { useBillingPortalSession } from '@/settings/billing/hooks/useBillingPortalSession';
+import { UpdatePaymentMethodModal } from '@/settings/billing/components/UpdatePaymentMethodModal';
import { useGetResourceCreditUsage } from '@/settings/billing/hooks/useGetResourceCreditUsage';
+import { usePaymentMethodFlow } from '@/settings/billing/hooks/usePaymentMethodFlow';
import { billingHasPaymentMethodSelector } from '@/settings/billing/states/billingHasPaymentMethodSelector';
import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';
-import { SettingsPath } from 'twenty-shared/types';
-import { getSettingsPath, isDefined } from 'twenty-shared/utils';
+import { isDefined } from 'twenty-shared/utils';
import { IconCircleX, IconCreditCard } from 'twenty-ui/icon';
import { H2Title } from 'twenty-ui/typography';
import { Button } from 'twenty-ui/input';
import { Section } from 'twenty-ui/layout';
import { SubscriptionStatus } from '~/generated-metadata/graphql';
+
+const SETTINGS_BILLING_UPDATE_PAYMENT_MODAL_ID =
+ 'settings-billing-update-payment-modal';
+
export const SettingsBillingContent = () => {
const { t } = useLingui();
@@ -30,6 +34,14 @@ export const SettingsBillingContent = () => {
billingHasPaymentMethodSelector,
);
+ const {
+ shouldAddPaymentMethodInProduct,
+ openPaymentMethodFlow,
+ isPaymentMethodFlowDisabled,
+ isBillingPortalSessionDisabled,
+ openBillingPortal,
+ } = usePaymentMethodFlow(SETTINGS_BILLING_UPDATE_PAYMENT_MODAL_ID);
+
const { isGetResourceCreditUsageQueryLoaded: isUsageQueryLoaded } =
useGetResourceCreditUsage();
@@ -46,9 +58,6 @@ export const SettingsBillingContent = () => {
const canCancelCurrentSubscription =
hasNotCanceledCurrentSubscription && !hasScheduledCancellation;
- const { isBillingPortalSessionDisabled, openBillingPortal } =
- useBillingPortalSession(getSettingsPath(SettingsPath.Billing));
-
return (
<SettingsPageContainer>
{displayTrialNoPaymentMethodCard && currentBillingSubscription && (
@@ -62,8 +71,10 @@ export const SettingsBillingContent = () => {
<SettingsBillingSubscriptionInfo
currentWorkspace={currentWorkspace}
currentBillingSubscription={currentBillingSubscription}
- onUpdatePayment={openBillingPortal}
- isUpdatePaymentDisabled={isBillingPortalSessionDisabled}
+ onManageBilling={openBillingPortal}
+ isManageBillingDisabled={isBillingPortalSessionDisabled}
+ onUpdatePayment={openPaymentMethodFlow}
+ isUpdatePaymentDisabled={isPaymentMethodFlowDisabled}
/>
)}
{hasNotCanceledCurrentSubscription &&
@@ -72,8 +83,10 @@ export const SettingsBillingContent = () => {
isUsageQueryLoaded && (
<SettingsBillingCreditsSection
currentBillingSubscription={currentBillingSubscription}
- onUpdatePayment={openBillingPortal}
- isUpdatePaymentDisabled={isBillingPortalSessionDisabled}
+ onManageBilling={openBillingPortal}
+ isManageBillingDisabled={isBillingPortalSessionDisabled}
+ onUpdatePayment={openPaymentMethodFlow}
+ isUpdatePaymentDisabled={isPaymentMethodFlowDisabled}
/>
)}
<Section>
@@ -105,6 +118,11 @@ export const SettingsBillingContent = () => {
/>
</Section>
)}
+ {shouldAddPaymentMethodInProduct && (
+ <UpdatePaymentMethodModal
+ modalInstanceId={SETTINGS_BILLING_UPDATE_PAYMENT_MODAL_ID}
+ />
+ )}
</SettingsPageContainer>
);
};
diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx
index aecec380ba8..11d1287e2a9 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx
@@ -14,6 +14,7 @@ import { useSplitPhaseItemsInPrices } from '@/settings/billing/hooks/useSplitPha
import { usePermissionFlagMap } from '@/settings/roles/hooks/usePermissionFlagMap';
import { getDocumentationUrl } from '@/support/utils/getDocumentationUrl';
import { useModal } from '@/ui/layout/modal/hooks/useModal';
+import { isSubscriptionPaymentOverdue } from '@/settings/billing/utils/isSubscriptionPaymentOverdue';
import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
@@ -118,12 +119,16 @@ const StyledCreditUsageFooterActions = styled.div`
export const SettingsBillingCreditsSection = ({
currentBillingSubscription,
+ onManageBilling,
+ isManageBillingDisabled,
onUpdatePayment,
isUpdatePaymentDisabled,
}: {
currentBillingSubscription: NonNullable<
CurrentWorkspace['currentBillingSubscription']
>;
+ onManageBilling: () => void;
+ isManageBillingDisabled: boolean;
onUpdatePayment: () => void;
isUpdatePaymentDisabled: boolean;
}) => {
@@ -149,9 +154,7 @@ export const SettingsBillingCreditsSection = ({
const { getIntervalLabel } = useBillingWording();
const isTrialing = subscriptionStatus === SubscriptionStatus.Trialing;
- const shouldUpdatePayment =
- subscriptionStatus === SubscriptionStatus.PastDue ||
- subscriptionStatus === SubscriptionStatus.Unpaid;
+ const shouldUpdatePayment = isSubscriptionPaymentOverdue(subscriptionStatus);
const { [PermissionFlagType.WORKSPACE]: hasPermissionToEndTrialPeriod } =
usePermissionFlagMap();
@@ -242,8 +245,8 @@ export const SettingsBillingCreditsSection = ({
shouldRedirectToManageBilling={isCancellationScheduled}
shouldRedirectToUpdatePayment={shouldUpdatePayment}
canEndTrialPeriod={hasPermissionToEndTrialPeriod}
- onManageBilling={onUpdatePayment}
- isManageBillingDisabled={isUpdatePaymentDisabled}
+ onManageBilling={onManageBilling}
+ isManageBillingDisabled={isManageBillingDisabled}
onUpdatePayment={onUpdatePayment}
isUpdatePaymentDisabled={isUpdatePaymentDisabled}
canCancelCreditPackSwitch={canCancelCreditPackSwitch}
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 18d1f7134fe..df644bbbf62 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingSubscriptionInfo.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingSubscriptionInfo.tsx
@@ -22,6 +22,7 @@ import { usePermissionFlagMap } from '@/settings/roles/hooks/usePermissionFlagMa
import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
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 { CombinedGraphQLErrors } from '@apollo/client/errors';
import { useMutation } from '@apollo/client/react';
@@ -46,6 +47,8 @@ import { beautifyExactDate } from '~/utils/date-utils';
export const SettingsBillingSubscriptionInfo = ({
currentWorkspace,
currentBillingSubscription,
+ onManageBilling,
+ isManageBillingDisabled,
onUpdatePayment,
isUpdatePaymentDisabled,
}: {
@@ -53,6 +56,8 @@ export const SettingsBillingSubscriptionInfo = ({
currentBillingSubscription: NonNullable<
CurrentWorkspace['currentBillingSubscription']
>;
+ onManageBilling: () => void;
+ isManageBillingDisabled: boolean;
onUpdatePayment: () => void;
isUpdatePaymentDisabled: boolean;
}) => {
@@ -119,9 +124,7 @@ export const SettingsBillingSubscriptionInfo = ({
);
const isTrialPeriod = subscriptionStatus === SubscriptionStatus.Trialing;
- const shouldUpdatePayment =
- subscriptionStatus === SubscriptionStatus.PastDue ||
- subscriptionStatus === SubscriptionStatus.Unpaid;
+ const shouldUpdatePayment = isSubscriptionPaymentOverdue(subscriptionStatus);
const scheduledCancellationDate = currentBillingSubscription.cancelAt;
const isCancellationScheduled =
@@ -493,6 +496,7 @@ export const SettingsBillingSubscriptionInfo = ({
isEndTrialPeriodLoading || isAnyActionLoading
}
isSubscriptionActionDisabled={isSubscriptionActionDisabled}
+ isManageBillingDisabled={isManageBillingDisabled}
isUpdatePaymentDisabled={isUpdatePaymentDisabled}
onCancelIntervalSwitch={() =>
openModal(BILLING_MODAL_IDS.cancelSwitchBillingInterval)
@@ -501,6 +505,7 @@ export const SettingsBillingSubscriptionInfo = ({
openModal(BILLING_MODAL_IDS.cancelSwitchBillingPlan)
}
onEndTrialPeriod={() => openModal(BILLING_MODAL_IDS.endTrialPeriod)}
+ onManageBilling={onManageBilling}
onUpdatePayment={onUpdatePayment}
shouldUpdatePayment={shouldUpdatePayment}
/>
diff --git a/packages/twenty-front/src/modules/settings/billing/components/UpdatePaymentMethodModal.tsx b/packages/twenty-front/src/modules/settings/billing/components/UpdatePaymentMethodModal.tsx
new file mode 100644
index 00000000000..778f2f4db21
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/components/UpdatePaymentMethodModal.tsx
@@ -0,0 +1,101 @@
+import { AddPaymentMethodForm } from '@/settings/billing/components/AddPaymentMethodForm';
+import { useMarkBillingPaymentMethodAsAdded } from '@/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded';
+import { useWaitForPaymentRecovery } from '@/settings/billing/hooks/useWaitForPaymentRecovery';
+import { isSubscriptionPaymentOverdue } from '@/settings/billing/utils/isSubscriptionPaymentOverdue';
+import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
+import { ModalStatefulWrapper } from '@/ui/layout/modal/components/ModalStatefulWrapper';
+import { useModal } from '@/ui/layout/modal/hooks/useModal';
+import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { Button } from 'twenty-ui/input';
+import { Section, SectionAlignment, SectionFontColor } from 'twenty-ui/layout';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+import { H1Title, H1TitleFontColor } from 'twenty-ui/typography';
+
+type UpdatePaymentMethodModalProps = {
+ modalInstanceId: string;
+};
+
+const StyledCenteredTitle = styled.div`
+ text-align: center;
+`;
+
+const StyledSectionContainer = styled.div`
+ margin-bottom: ${themeCssVariables.spacing[6]};
+`;
+
+const StyledCancelButtonContainer = styled.div`
+ margin-top: ${themeCssVariables.spacing[4]};
+`;
+
+export const UpdatePaymentMethodModal = ({
+ modalInstanceId,
+}: UpdatePaymentMethodModalProps) => {
+ const { t } = useLingui();
+ const { closeModal } = useModal();
+ const { enqueueSuccessSnackBar, enqueueInfoSnackBar } = useSnackBar();
+ const subscriptionStatus = useSubscriptionStatus();
+ const { markBillingPaymentMethodAsAdded } =
+ useMarkBillingPaymentMethodAsAdded();
+ const { waitForPaymentRecovery } = useWaitForPaymentRecovery();
+
+ const handlePaymentMethodAdded = async () => {
+ closeModal(modalInstanceId);
+ markBillingPaymentMethodAsAdded();
+
+ if (!isSubscriptionPaymentOverdue(subscriptionStatus)) {
+ enqueueSuccessSnackBar({ message: t`Payment method added.` });
+
+ return;
+ }
+
+ enqueueInfoSnackBar({
+ message: t`Payment method added. Retrying your payment...`,
+ });
+
+ await waitForPaymentRecovery();
+ };
+
+ return (
+ <ModalStatefulWrapper
+ modalInstanceId={modalInstanceId}
+ isClosable
+ size="medium"
+ padding="large"
+ overlay="dark"
+ dataGloballyPreventClickOutside
+ renderInDocumentBody
+ smallBorderRadius
+ autoHeight
+ >
+ <StyledCenteredTitle>
+ <H1Title
+ title={t`Update your payment method`}
+ fontColor={H1TitleFontColor.Primary}
+ />
+ </StyledCenteredTitle>
+ <StyledSectionContainer>
+ <Section
+ alignment={SectionAlignment.Center}
+ fontColor={SectionFontColor.Primary}
+ >
+ {t`Add a card below to update your billing details and retry your payment.`}
+ </Section>
+ </StyledSectionContainer>
+ <AddPaymentMethodForm
+ onPaymentMethodAdded={handlePaymentMethodAdded}
+ shouldStartSubscriptionAfterPaymentMethod={false}
+ />
+ <StyledCancelButtonContainer>
+ <Button
+ onClick={() => closeModal(modalInstanceId)}
+ variant="secondary"
+ title={t`Cancel`}
+ fullWidth
+ justify="center"
+ />
+ </StyledCancelButtonContainer>
+ </ModalStatefulWrapper>
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoCardHeaderActions.tsx b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoCardHeaderActions.tsx
index 9addcfa1994..15d589a5cf1 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoCardHeaderActions.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingSubscriptionInfoCardHeaderActions.tsx
@@ -18,10 +18,12 @@ export type SettingsBillingSubscriptionInfoCardHeaderActionsProps = {
isCancellationScheduled: boolean;
isEndTrialPeriodDisabled: boolean;
isSubscriptionActionDisabled: boolean;
+ isManageBillingDisabled: boolean;
isUpdatePaymentDisabled: boolean;
onCancelIntervalSwitch: () => void;
onCancelPlanSwitch: () => void;
onEndTrialPeriod: () => void;
+ onManageBilling: () => void;
onUpdatePayment: () => void;
shouldUpdatePayment: boolean;
};
@@ -35,10 +37,12 @@ export const SettingsBillingSubscriptionInfoCardHeaderActions = ({
isCancellationScheduled,
isEndTrialPeriodDisabled,
isSubscriptionActionDisabled,
+ isManageBillingDisabled,
isUpdatePaymentDisabled,
onCancelIntervalSwitch,
onCancelPlanSwitch,
onEndTrialPeriod,
+ onManageBilling,
onUpdatePayment,
shouldUpdatePayment,
}: SettingsBillingSubscriptionInfoCardHeaderActionsProps) => {
@@ -52,8 +56,8 @@ export const SettingsBillingSubscriptionInfoCardHeaderActions = ({
variant="primary"
accent="blue"
size="small"
- onClick={onUpdatePayment}
- disabled={isUpdatePaymentDisabled}
+ onClick={onManageBilling}
+ disabled={isManageBillingDisabled}
/>
);
}
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/PaymentRecoveryPollingIntervalMs.ts b/packages/twenty-front/src/modules/settings/billing/constants/PaymentRecoveryPollingIntervalMs.ts
new file mode 100644
index 00000000000..5cf89b4e55f
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/constants/PaymentRecoveryPollingIntervalMs.ts
@@ -0,0 +1 @@
+export const PAYMENT_RECOVERY_POLLING_INTERVAL_MS = 3000;
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/PaymentRecoveryPollingMaxAttempts.ts b/packages/twenty-front/src/modules/settings/billing/constants/PaymentRecoveryPollingMaxAttempts.ts
new file mode 100644
index 00000000000..a2f0ae7d83c
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/constants/PaymentRecoveryPollingMaxAttempts.ts
@@ -0,0 +1 @@
+export const PAYMENT_RECOVERY_POLLING_MAX_ATTEMPTS = 10;
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/__tests__/useMarkBillingPaymentMethodAsAdded.test.tsx b/packages/twenty-front/src/modules/settings/billing/hooks/__tests__/useMarkBillingPaymentMethodAsAdded.test.tsx
new file mode 100644
index 00000000000..d3b7cd44a6f
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/__tests__/useMarkBillingPaymentMethodAsAdded.test.tsx
@@ -0,0 +1,59 @@
+import { act, renderHook } from '@testing-library/react';
+import { Provider as JotaiProvider } from 'jotai';
+import { type ReactNode } from 'react';
+
+import {
+ type CurrentWorkspace,
+ currentWorkspaceState,
+} from '@/auth/states/currentWorkspaceState';
+import { useMarkBillingPaymentMethodAsAdded } from '@/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded';
+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';
+
+const Wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
+);
+
+const renderMarkBillingPaymentMethodAsAdded = () =>
+ renderHook(() => useMarkBillingPaymentMethodAsAdded(), { wrapper: Wrapper });
+
+describe('useMarkBillingPaymentMethodAsAdded', () => {
+ it('should mark the billing customer of the current workspace as having a payment method', () => {
+ jotaiStore.set(currentWorkspaceState.atom, {
+ id: '1',
+ billingCustomer: {
+ id: '20202020-1c25-4d02-bf25-6aeccf7ea419',
+ hasPaymentMethod: false,
+ },
+ } as CurrentWorkspace);
+
+ const { result } = renderMarkBillingPaymentMethodAsAdded();
+
+ act(() => {
+ result.current.markBillingPaymentMethodAsAdded();
+ });
+
+ expect(
+ jotaiStore.get(currentWorkspaceState.atom)?.billingCustomer
+ ?.hasPaymentMethod,
+ ).toBe(true);
+ });
+
+ it('should leave the current workspace untouched when it has no billing customer', () => {
+ const workspaceWithoutBillingCustomer = {
+ id: '1',
+ billingCustomer: null,
+ } as CurrentWorkspace;
+
+ jotaiStore.set(currentWorkspaceState.atom, workspaceWithoutBillingCustomer);
+
+ const { result } = renderMarkBillingPaymentMethodAsAdded();
+
+ act(() => {
+ result.current.markBillingPaymentMethodAsAdded();
+ });
+
+ expect(jotaiStore.get(currentWorkspaceState.atom)).toEqual(
+ workspaceWithoutBillingCustomer,
+ );
+ });
+});
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 aa0712503d8..c79c517164e 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useBillingPlanActions.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useBillingPlanActions.ts
@@ -7,6 +7,7 @@ import { type SettingsBillingPlanAction } from '@/settings/billing/types/setting
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';
@@ -42,9 +43,7 @@ export const useBillingPlanActions = ({
const hasPermissionToManageBilling =
permissionMap[PermissionFlagType.BILLING] ?? false;
- const shouldUpdatePayment =
- subscriptionStatus === SubscriptionStatus.PastDue ||
- subscriptionStatus === SubscriptionStatus.Unpaid;
+ const shouldUpdatePayment = isSubscriptionPaymentOverdue(subscriptionStatus);
const isSubscriptionCanceled =
currentBillingSubscription?.status === SubscriptionStatus.Canceled ||
subscriptionStatus === SubscriptionStatus.Canceled;
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded.ts
new file mode 100644
index 00000000000..317f0595d7c
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded.ts
@@ -0,0 +1,26 @@
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
+import { isDefined } from 'twenty-shared/utils';
+
+export const useMarkBillingPaymentMethodAsAdded = () => {
+ const setCurrentWorkspace = useSetAtomState(currentWorkspaceState);
+
+ // Stripe confirms the setup intent before the payment method webhook lands,
+ // so the workspace billing state has to be updated client-side
+ const markBillingPaymentMethodAsAdded = () => {
+ setCurrentWorkspace((previousWorkspace) =>
+ isDefined(previousWorkspace) &&
+ isDefined(previousWorkspace.billingCustomer)
+ ? {
+ ...previousWorkspace,
+ billingCustomer: {
+ ...previousWorkspace.billingCustomer,
+ hasPaymentMethod: true,
+ },
+ }
+ : previousWorkspace,
+ );
+ };
+
+ return { markBillingPaymentMethodAsAdded };
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/usePaymentMethodFlow.ts b/packages/twenty-front/src/modules/settings/billing/hooks/usePaymentMethodFlow.ts
new file mode 100644
index 00000000000..79efeb5dbf2
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/usePaymentMethodFlow.ts
@@ -0,0 +1,48 @@
+import { useBillingPortalSession } from '@/settings/billing/hooks/useBillingPortalSession';
+import { billingHasPaymentMethodSelector } from '@/settings/billing/states/billingHasPaymentMethodSelector';
+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 { SettingsPath } from 'twenty-shared/types';
+import { getSettingsPath } from 'twenty-shared/utils';
+import { PermissionFlagType } from '~/generated-metadata/graphql';
+
+export const usePaymentMethodFlow = (modalInstanceId: string) => {
+ const { openModal } = useModal();
+
+ const billingHasPaymentMethod = useAtomStateValue(
+ billingHasPaymentMethodSelector,
+ );
+
+ const { [PermissionFlagType.BILLING]: hasPermissionToManageBilling } =
+ usePermissionFlagMap();
+
+ const { isBillingPortalSessionDisabled, openBillingPortal } =
+ useBillingPortalSession(getSettingsPath(SettingsPath.Billing));
+
+ // Adding the first payment method is the only flow the in-product form can
+ // handle, everything else needs the billing portal
+ const shouldAddPaymentMethodInProduct =
+ hasPermissionToManageBilling && billingHasPaymentMethod === false;
+
+ const openPaymentMethodFlow = () => {
+ if (shouldAddPaymentMethodInProduct) {
+ openModal(modalInstanceId);
+ return;
+ }
+
+ openBillingPortal();
+ };
+
+ const isPaymentMethodFlowDisabled =
+ !shouldAddPaymentMethodInProduct && isBillingPortalSessionDisabled;
+
+ return {
+ hasPermissionToManageBilling,
+ shouldAddPaymentMethodInProduct,
+ openPaymentMethodFlow,
+ isPaymentMethodFlowDisabled,
+ isBillingPortalSessionDisabled,
+ openBillingPortal,
+ };
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useWaitForPaymentRecovery.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useWaitForPaymentRecovery.ts
new file mode 100644
index 00000000000..8fe3029dc60
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useWaitForPaymentRecovery.ts
@@ -0,0 +1,79 @@
+import { PAYMENT_RECOVERY_POLLING_INTERVAL_MS } from '@/settings/billing/constants/PaymentRecoveryPollingIntervalMs';
+import { PAYMENT_RECOVERY_POLLING_MAX_ATTEMPTS } from '@/settings/billing/constants/PaymentRecoveryPollingMaxAttempts';
+import { useApplyCurrentWorkspaceBillingUpdate } from '@/settings/billing/hooks/useApplyCurrentWorkspaceBillingUpdate';
+import { useMarkBillingPaymentMethodAsAdded } from '@/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded';
+import { waitForSubscriptionRecovery } from '@/settings/billing/utils/waitForSubscriptionRecovery';
+import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
+import { useLoadCurrentUser } from '@/users/hooks/useLoadCurrentUser';
+import { useApolloClient } from '@apollo/client/react';
+import { t } from '@lingui/core/macro';
+import { SettingsPath } from 'twenty-shared/types';
+import { getSettingsPath } from 'twenty-shared/utils';
+import { GetCurrentUserDocument } from '~/generated-metadata/graphql';
+import { logError } from '~/utils/logError';
+import { sleep } from '~/utils/sleep';
+
+export const useWaitForPaymentRecovery = () => {
+ const client = useApolloClient();
+ const { loadCurrentUser } = useLoadCurrentUser();
+ const { applyCurrentWorkspaceBillingUpdate } =
+ useApplyCurrentWorkspaceBillingUpdate();
+ const { markBillingPaymentMethodAsAdded } =
+ useMarkBillingPaymentMethodAsAdded();
+ const { enqueueSuccessSnackBar, enqueueWarningSnackBar } = useSnackBar();
+
+ const fetchWorkspaceBilling = async () => {
+ const { data } = await client.query({
+ query: GetCurrentUserDocument,
+ fetchPolicy: 'network-only',
+ });
+
+ return data?.currentUser.currentWorkspace;
+ };
+
+ // The retry itself runs server-side from the setup_intent.succeeded webhook
+ // and only reaches the persisted subscription through the invoice and
+ // subscription webhooks, so its outcome can only be observed by polling
+ const waitForPaymentRecovery = async () => {
+ const recovery = await waitForSubscriptionRecovery({
+ fetchWorkspaceBilling,
+ getSubscriptionStatus: (workspaceBilling) =>
+ workspaceBilling?.currentBillingSubscription?.status,
+ waitBeforeAttempt: () => sleep(PAYMENT_RECOVERY_POLLING_INTERVAL_MS),
+ maxAttempts: PAYMENT_RECOVERY_POLLING_MAX_ATTEMPTS,
+ });
+
+ if (recovery.outcome !== 'recovered') {
+ enqueueWarningSnackBar({
+ message: t`Your card was saved, but the payment still needs attention.`,
+ options: {
+ buttonLabel: t`Go to billing`,
+ buttonTo: getSettingsPath(SettingsPath.Billing),
+ },
+ });
+
+ return;
+ }
+
+ try {
+ await loadCurrentUser();
+ } catch {
+ const hasAppliedBillingUpdate = applyCurrentWorkspaceBillingUpdate(
+ recovery.workspaceBilling,
+ );
+
+ if (!hasAppliedBillingUpdate) {
+ logError(
+ 'Payment recovered but the workspace billing state could not be refreshed',
+ );
+ }
+ }
+
+ // The payment method webhook can still be in flight
+ markBillingPaymentMethodAsAdded();
+
+ enqueueSuccessSnackBar({ message: t`Payment successful.` });
+ };
+
+ return { waitForPaymentRecovery };
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/waitForSubscriptionRecovery.test.ts b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/waitForSubscriptionRecovery.test.ts
new file mode 100644
index 00000000000..ac8803eac7d
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/waitForSubscriptionRecovery.test.ts
@@ -0,0 +1,97 @@
+import { waitForSubscriptionRecovery } from '@/settings/billing/utils/waitForSubscriptionRecovery';
+import { SubscriptionStatus } from '~/generated-metadata/graphql';
+
+type WorkspaceBilling = { status: SubscriptionStatus | undefined };
+
+type FetchStep = SubscriptionStatus | undefined | Error;
+
+const runRecovery = async (steps: FetchStep[], maxAttempts = 3) => {
+ let fetchCount = 0;
+ let waitCount = 0;
+
+ const result = await waitForSubscriptionRecovery({
+ fetchWorkspaceBilling: async (): Promise<WorkspaceBilling> => {
+ // The last step repeats so a bounded run can be exercised with one status
+ const step = steps[Math.min(fetchCount, steps.length - 1)];
+
+ fetchCount++;
+
+ if (step instanceof Error) {
+ throw step;
+ }
+
+ return { status: step };
+ },
+ getSubscriptionStatus: (workspaceBilling) => workspaceBilling.status,
+ waitBeforeAttempt: async () => {
+ waitCount++;
+ },
+ maxAttempts,
+ });
+
+ return { result, fetchCount, waitCount };
+};
+
+describe('waitForSubscriptionRecovery', () => {
+ it('should keep polling while the payment is overdue and hand back the recovered billing', async () => {
+ const { result, fetchCount, waitCount } = await runRecovery([
+ SubscriptionStatus.PastDue,
+ SubscriptionStatus.Unpaid,
+ SubscriptionStatus.Active,
+ ]);
+
+ expect(result).toEqual({
+ outcome: 'recovered',
+ workspaceBilling: { status: SubscriptionStatus.Active },
+ });
+ expect(fetchCount).toBe(3);
+ expect(waitCount).toBe(3);
+ });
+
+ it('should wait before the first attempt so the webhook gets a chance to land', async () => {
+ const { waitCount } = await runRecovery([SubscriptionStatus.Active]);
+
+ expect(waitCount).toBe(1);
+ });
+
+ it('should skip a failed fetch and keep polling', async () => {
+ const { result, fetchCount } = await runRecovery([
+ new Error('Network error'),
+ SubscriptionStatus.Active,
+ ]);
+
+ expect(result.outcome).toBe('recovered');
+ expect(fetchCount).toBe(2);
+ });
+
+ it('should time out when the payment is still overdue after the last attempt', async () => {
+ const { result, fetchCount } = await runRecovery(
+ [SubscriptionStatus.PastDue],
+ 4,
+ );
+
+ expect(result).toEqual({ outcome: 'timedOut' });
+ expect(fetchCount).toBe(4);
+ });
+
+ it('should stop at the first status that can no longer recover', async () => {
+ const { result, fetchCount } = await runRecovery([
+ SubscriptionStatus.PastDue,
+ SubscriptionStatus.Canceled,
+ SubscriptionStatus.Active,
+ ]);
+
+ expect(result).toEqual({ outcome: 'unrecoverable' });
+ expect(fetchCount).toBe(2);
+ });
+
+ it('should keep polling while the subscription status is unknown', async () => {
+ const { result, fetchCount } = await runRecovery([
+ undefined,
+ SubscriptionStatus.Active,
+ ]);
+
+ expect(result.outcome).toBe('recovered');
+ expect(fetchCount).toBe(2);
+ });
+});
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/isSubscriptionPaymentOverdue.ts b/packages/twenty-front/src/modules/settings/billing/utils/isSubscriptionPaymentOverdue.ts
new file mode 100644
index 00000000000..8ceebd2ebab
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/isSubscriptionPaymentOverdue.ts
@@ -0,0 +1,7 @@
+import { SubscriptionStatus } from '~/generated-metadata/graphql';
+
+export const isSubscriptionPaymentOverdue = (
+ subscriptionStatus: SubscriptionStatus | undefined,
+) =>
+ subscriptionStatus === SubscriptionStatus.PastDue ||
+ subscriptionStatus === SubscriptionStatus.Unpaid;
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/waitForSubscriptionRecovery.ts b/packages/twenty-front/src/modules/settings/billing/utils/waitForSubscriptionRecovery.ts
new file mode 100644
index 00000000000..ac5c6bd6200
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/waitForSubscriptionRecovery.ts
@@ -0,0 +1,52 @@
+import { isSubscriptionPaymentOverdue } from '@/settings/billing/utils/isSubscriptionPaymentOverdue';
+import { isDefined } from 'twenty-shared/utils';
+import { SubscriptionStatus } from '~/generated-metadata/graphql';
+
+export type SubscriptionRecoveryResult<TWorkspaceBilling> =
+ | { outcome: 'recovered'; workspaceBilling: TWorkspaceBilling }
+ | { outcome: 'unrecoverable' }
+ | { outcome: 'timedOut' };
+
+export const waitForSubscriptionRecovery = async <TWorkspaceBilling>({
+ fetchWorkspaceBilling,
+ getSubscriptionStatus,
+ waitBeforeAttempt,
+ maxAttempts,
+}: {
+ fetchWorkspaceBilling: () => Promise<TWorkspaceBilling>;
+ getSubscriptionStatus: (
+ workspaceBilling: TWorkspaceBilling,
+ ) => SubscriptionStatus | undefined;
+ waitBeforeAttempt: () => Promise<unknown>;
+ maxAttempts: number;
+}): Promise<SubscriptionRecoveryResult<TWorkspaceBilling>> => {
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
+ await waitBeforeAttempt();
+
+ let workspaceBilling: TWorkspaceBilling;
+
+ try {
+ workspaceBilling = await fetchWorkspaceBilling();
+ } catch {
+ // A transient fetch failure says nothing about the payment itself
+ continue;
+ }
+
+ const subscriptionStatus = getSubscriptionStatus(workspaceBilling);
+
+ if (subscriptionStatus === SubscriptionStatus.Active) {
+ return { outcome: 'recovered', workspaceBilling };
+ }
+
+ // Only a definite status that cannot recover ends the wait early, no
+ // status at all is not a verdict on the payment
+ if (
+ isDefined(subscriptionStatus) &&
+ !isSubscriptionPaymentOverdue(subscriptionStatus)
+ ) {
+ return { outcome: 'unrecoverable' };
+ }
+ }
+
+ return { outcome: 'timedOut' };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
index 928fd22f777..7f346e8cc2a 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-portal.workspace-service.ts
@@ -203,8 +203,10 @@ export class BillingPortalWorkspaceService {
);
}
- const setupIntent =
- await this.stripeCustomerService.createSetupIntent(stripeCustomerId);
+ const setupIntent = await this.stripeCustomerService.createSetupIntent({
+ stripeCustomerId,
+ workspaceId: workspace.id,
+ });
assertIsDefinedOrThrow(
setupIntent.client_secret,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
index 7ff21482786..35377887c22 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
@@ -201,14 +201,70 @@ export class BillingSubscriptionService {
}
async handleUnpaidInvoices(data: Stripe.SetupIntentSucceededEvent.Data) {
- const billingSubscription = await this.getCurrentBillingSubscriptionOrThrow(
- { stripeCustomerId: data.object.customer as string },
- );
+ const stripeCustomerId =
+ typeof data.object.customer === 'string'
+ ? data.object.customer
+ : data.object.customer?.id;
+
+ // The Stripe account receives every setup intent, including ones that are
+ // not tied to a workspace subscription. Those can never be recovered, and
+ // failing would only have Stripe redeliver them
+ if (!isDefined(stripeCustomerId)) {
+ this.logger.warn(
+ `Ignoring successful setup intent ${data.object.id} without customer`,
+ );
+
+ return { handleUnpaidInvoiceStripeSubscriptionId: undefined };
+ }
+
+ const billingSubscription = await this.getCurrentBillingSubscription({
+ stripeCustomerId,
+ });
+
+ if (!isDefined(billingSubscription)) {
+ this.logger.warn(
+ `Ignoring successful setup intent ${data.object.id}, customer ${stripeCustomerId} has no current subscription`,
+ );
+
+ return { handleUnpaidInvoiceStripeSubscriptionId: undefined };
+ }
+
+ const stripePaymentMethodId =
+ typeof data.object.payment_method === 'string'
+ ? data.object.payment_method
+ : data.object.payment_method?.id;
- if (billingSubscription.status === SubscriptionStatus.Unpaid) {
- await this.stripeSubscriptionService.collectLastInvoice(
+ if (!isDefined(stripePaymentMethodId)) {
+ this.logger.warn(
+ `Ignoring successful setup intent ${data.object.id} without payment method`,
+ );
+
+ return { handleUnpaidInvoiceStripeSubscriptionId: undefined };
+ }
+
+ await this.stripeCustomerService.setDefaultPaymentMethod({
+ stripeCustomerId: billingSubscription.stripeCustomerId,
+ stripePaymentMethodId,
+ });
+
+ const stripeSubscription =
+ await this.stripeSubscriptionService.updateSubscription(
billingSubscription.stripeSubscriptionId,
+ { default_payment_method: stripePaymentMethodId },
);
+
+ // The persisted status can lag behind Stripe when this event lands before
+ // the subscription update one, so the live status decides whether an
+ // overdue invoice has to be retried
+ if (
+ [SubscriptionStatus.PastDue, SubscriptionStatus.Unpaid].includes(
+ getSubscriptionStatus(stripeSubscription.status),
+ )
+ ) {
+ await this.stripeSubscriptionService.payOpenInvoices({
+ stripeSubscriptionId: billingSubscription.stripeSubscriptionId,
+ stripePaymentMethodId,
+ });
}
return {
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/__tests__/stripe-subscription.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/__tests__/stripe-subscription.service.spec.ts
new file mode 100644
index 00000000000..2f44af4c514
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/__tests__/stripe-subscription.service.spec.ts
@@ -0,0 +1,129 @@
+/* @license Enterprise */
+
+import { Test, type TestingModule } from '@nestjs/testing';
+
+import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';
+import { StripeSDKService } from 'src/engine/core-modules/billing/stripe/stripe-sdk/services/stripe-sdk.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+
+class StripeCardError extends Error {}
+
+describe('StripeSubscriptionService', () => {
+ let service: StripeSubscriptionService;
+
+ const stripe = {
+ errors: { StripeCardError },
+ invoices: {
+ list: jest.fn(),
+ pay: jest.fn(),
+ retrieve: jest.fn(),
+ },
+ };
+
+ const givenOpenInvoices = (invoiceIds: string[]) =>
+ stripe.invoices.list.mockReturnValue({
+ async *[Symbol.asyncIterator]() {
+ for (const invoiceId of invoiceIds) {
+ yield { id: invoiceId, status: 'open' };
+ }
+ },
+ });
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+ stripe.invoices.pay.mockResolvedValue({});
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ StripeSubscriptionService,
+ {
+ provide: TwentyConfigService,
+ useValue: {
+ get: (key: string) =>
+ key === 'IS_BILLING_ENABLED' ? true : 'stripe-api-key',
+ },
+ },
+ { provide: StripeSDKService, useValue: { getStripe: () => stripe } },
+ ],
+ }).compile();
+
+ service = module.get(StripeSubscriptionService);
+ });
+
+ describe('payOpenInvoices', () => {
+ it('should pay every open auto-charged invoice, oldest first, with the new payment method', async () => {
+ givenOpenInvoices(['in_newer', 'in_older']);
+
+ await service.payOpenInvoices({
+ stripeSubscriptionId: 'sub_1',
+ stripePaymentMethodId: 'pm_1',
+ });
+
+ expect(stripe.invoices.list).toHaveBeenCalledWith({
+ subscription: 'sub_1',
+ status: 'open',
+ collection_method: 'charge_automatically',
+ limit: 100,
+ });
+ expect(stripe.invoices.pay.mock.calls).toEqual([
+ ['in_older', { payment_method: 'pm_1' }],
+ ['in_newer', { payment_method: 'pm_1' }],
+ ]);
+ });
+
+ it('should keep paying the remaining invoices when the card is declined', async () => {
+ givenOpenInvoices(['in_newer', 'in_older']);
+ stripe.invoices.pay.mockRejectedValueOnce(
+ new StripeCardError('Your card was declined.'),
+ );
+
+ await expect(
+ service.payOpenInvoices({
+ stripeSubscriptionId: 'sub_1',
+ stripePaymentMethodId: 'pm_1',
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(stripe.invoices.pay).toHaveBeenCalledTimes(2);
+ });
+
+ it('should move on when the invoice was settled in the meantime', async () => {
+ givenOpenInvoices(['in_newer', 'in_older']);
+ stripe.invoices.pay.mockRejectedValueOnce(
+ new Error('This invoice is already paid.'),
+ );
+ stripe.invoices.retrieve.mockResolvedValue({
+ id: 'in_older',
+ status: 'paid',
+ });
+
+ await expect(
+ service.payOpenInvoices({
+ stripeSubscriptionId: 'sub_1',
+ stripePaymentMethodId: 'pm_1',
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(stripe.invoices.retrieve).toHaveBeenCalledWith('in_older');
+ expect(stripe.invoices.pay).toHaveBeenCalledTimes(2);
+ });
+
+ it('should propagate a failure that leaves the invoice open', async () => {
+ givenOpenInvoices(['in_1']);
+ const stripeError = new Error('Stripe is unavailable');
+
+ stripe.invoices.pay.mockRejectedValueOnce(stripeError);
+ stripe.invoices.retrieve.mockResolvedValue({
+ id: 'in_1',
+ status: 'open',
+ });
+
+ await expect(
+ service.payOpenInvoices({
+ stripeSubscriptionId: 'sub_1',
+ stripePaymentMethodId: 'pm_1',
+ }),
+ ).rejects.toBe(stripeError);
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts
index 4c6bf9368cc..15c610c7228 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-customer.service.ts
@@ -45,13 +45,18 @@ export class StripeCustomerService {
return paymentMethods.length > 0;
}
- async createSetupIntent(
- stripeCustomerId: string,
- ): Promise<Stripe.SetupIntent> {
+ async createSetupIntent({
+ stripeCustomerId,
+ workspaceId,
+ }: {
+ stripeCustomerId: string;
+ workspaceId: string;
+ }): Promise<Stripe.SetupIntent> {
return await this.stripe.setupIntents.create({
customer: stripeCustomerId,
usage: 'off_session',
automatic_payment_methods: { enabled: true },
+ metadata: { workspaceId },
});
}
@@ -81,6 +86,18 @@ export class StripeCustomerService {
});
}
+ async setDefaultPaymentMethod({
+ stripeCustomerId,
+ stripePaymentMethodId,
+ }: {
+ stripeCustomerId: string;
+ stripePaymentMethodId: string;
+ }): Promise<void> {
+ await this.stripe.customers.update(stripeCustomerId, {
+ invoice_settings: { default_payment_method: stripePaymentMethodId },
+ });
+ }
+
async createStripeCustomer(
userEmail: string,
workspaceId: string,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription.service.ts
index 5f5a9729bf6..bd6c0261677 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-subscription.service.ts
@@ -37,23 +37,52 @@ export class StripeSubscriptionService {
return subscription.data[0]?.customer ?? undefined;
}
- async collectLastInvoice(stripeSubscriptionId: string) {
- const subscription = await this.stripe.subscriptions.retrieve(
- stripeSubscriptionId,
- { expand: ['latest_invoice'] },
- );
- const latestInvoice = subscription.latest_invoice;
-
- if (
- !(
- latestInvoice &&
- typeof latestInvoice !== 'string' &&
- latestInvoice.status === 'draft'
- )
- ) {
- return;
+ async payOpenInvoices({
+ stripeSubscriptionId,
+ stripePaymentMethodId,
+ }: {
+ stripeSubscriptionId: string;
+ stripePaymentMethodId: string;
+ }) {
+ const openInvoices: Stripe.Invoice[] = [];
+
+ for await (const invoice of this.stripe.invoices.list({
+ subscription: stripeSubscriptionId,
+ status: 'open',
+ collection_method: 'charge_automatically',
+ limit: 100,
+ })) {
+ openInvoices.push(invoice);
+ }
+
+ // Stripe lists the most recent invoices first, settle the oldest overdue period first
+ for (const invoice of openInvoices.reverse()) {
+ try {
+ await this.stripe.invoices.pay(invoice.id, {
+ payment_method: stripePaymentMethodId,
+ });
+ } catch (error) {
+ // A decline is final for this webhook, Stripe dunning retries the invoice
+ // on its own schedule
+ if (error instanceof this.stripe.errors.StripeCardError) {
+ this.logger.error(
+ `Card declined for invoice ${invoice.id} of subscription ${stripeSubscriptionId}: ${error.message}`,
+ );
+
+ continue;
+ }
+
+ // Stripe dunning or a concurrent webhook can have settled the invoice
+ // in the meantime, only a still open one is worth a webhook retry
+ const refreshedInvoice = await this.stripe.invoices.retrieve(
+ invoice.id,
+ );
+
+ if (refreshedInvoice.status === 'open') {
+ throw error;
+ }
+ }
}
- await this.stripe.invoices.pay(latestInvoice.id);
}
async updateSubscription(