Skip to content

The open alternative to Salesforce, designed for AI.

fix(billing) - void unpaid upgrade invoices so a failed charge cannot be collected later (#24264)

Etienneea6e23bec7db
diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.exception.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.exception.ts
index 45108bc3b8d..faa13a5b609 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/billing.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.exception.ts
@@ -40,6 +40,8 @@ export enum BillingExceptionCode {
BILLING_CREDIT_GRANT_VALIDITY_INVALID = 'BILLING_CREDIT_GRANT_VALIDITY_INVALID',
BILLING_USAGE_UNAVAILABLE = 'BILLING_USAGE_UNAVAILABLE',
BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE = 'BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE',
+ BILLING_UPGRADE_INVOICE_PAYMENT_FAILED = 'BILLING_UPGRADE_INVOICE_PAYMENT_FAILED',
+ BILLING_UPGRADE_INVOICE_VOID_FAILED = 'BILLING_UPGRADE_INVOICE_VOID_FAILED',
}
const getBillingExceptionUserFriendlyMessage = (code: BillingExceptionCode) => {
@@ -108,6 +110,10 @@ const getBillingExceptionUserFriendlyMessage = (code: BillingExceptionCode) => {
return msg`Usage could not be read. Please try again later.`;
case BillingExceptionCode.BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE:
return msg`This kind of credit grant cannot be created by hand.`;
+ case BillingExceptionCode.BILLING_UPGRADE_INVOICE_PAYMENT_FAILED:
+ return msg`Your payment method was declined. Please update it and try again.`;
+ case BillingExceptionCode.BILLING_UPGRADE_INVOICE_VOID_FAILED:
+ return msg`An unexpected billing error occurred. Please contact support.`;
default:
assertUnreachable(code);
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-invoice.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-invoice.service.ts
index 710cf64cc21..466a9021995 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-invoice.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-invoice.service.ts
@@ -4,6 +4,10 @@ import { Injectable, Logger } from '@nestjs/common';
import type Stripe from 'stripe';
+import {
+ BillingException,
+ BillingExceptionCode,
+} from 'src/engine/core-modules/billing/billing.exception';
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';
@@ -54,25 +58,35 @@ export class StripeInvoiceService {
currency: string;
description: string;
}): Promise<void> {
- await this.stripe.invoiceItems.create({
- customer: stripeCustomerId,
- subscription: stripeSubscriptionId,
- amount: diffAmountInCents,
- currency,
- description,
- });
-
const invoice = await this.stripe.invoices.create({
customer: stripeCustomerId,
subscription: stripeSubscriptionId,
+ pending_invoice_items_behavior: 'exclude',
});
- const finalizedInvoice = await this.stripe.invoices.finalizeInvoice(
- invoice.id,
- {
- auto_advance: true,
- },
- );
+ let finalizedInvoice: Stripe.Invoice;
+
+ try {
+ await this.stripe.invoiceItems.create({
+ customer: stripeCustomerId,
+ subscription: stripeSubscriptionId,
+ invoice: invoice.id,
+ amount: diffAmountInCents,
+ currency,
+ description,
+ });
+
+ finalizedInvoice = await this.stripe.invoices.finalizeInvoice(
+ invoice.id,
+ {
+ auto_advance: false,
+ },
+ );
+ } catch (error) {
+ await this.deleteDraftUpgradeInvoice(invoice.id);
+
+ throw error;
+ }
if (finalizedInvoice.status === 'paid') {
return;
@@ -80,12 +94,68 @@ export class StripeInvoiceService {
try {
await this.stripe.invoices.pay(invoice.id);
- } catch (error) {
- const refreshedInvoice = await this.stripe.invoices.retrieve(invoice.id);
+ } catch (payError) {
+ await this.settleFailedUpgradeInvoiceOrThrow({
+ invoiceId: invoice.id,
+ payError,
+ });
+ }
+ }
+
+ private async settleFailedUpgradeInvoiceOrThrow({
+ invoiceId,
+ payError,
+ }: {
+ invoiceId: string;
+ payError: unknown;
+ }): Promise<void> {
+ const invoice = await this.stripe.invoices.retrieve(invoiceId);
- if (refreshedInvoice.status !== 'paid') {
- throw error;
+ if (invoice.status === 'paid') {
+ return;
+ }
+
+ const payErrorMessage = this.getErrorMessage(payError);
+
+ try {
+ await this.stripe.invoices.voidInvoice(invoiceId);
+ } catch (voidError) {
+ const refreshedInvoice = await this.stripe.invoices.retrieve(invoiceId);
+
+ if (refreshedInvoice.status === 'paid') {
+ return;
+ }
+
+ if (refreshedInvoice.status !== 'void') {
+ throw new BillingException(
+ `Failed to void upgrade invoice ${invoiceId} after payment failure (${payErrorMessage}): ${this.getErrorMessage(voidError)}`,
+ BillingExceptionCode.BILLING_UPGRADE_INVOICE_VOID_FAILED,
+ );
}
}
+
+ const isCardDecline =
+ payError instanceof this.stripe.errors.StripeCardError;
+
+ throw new BillingException(
+ `Failed to pay upgrade invoice ${invoiceId}: ${payErrorMessage}`,
+ isCardDecline
+ ? BillingExceptionCode.BILLING_UPGRADE_INVOICE_PAYMENT_FAILED
+ : BillingExceptionCode.BILLING_STRIPE_ERROR,
+ );
+ }
+
+ private async deleteDraftUpgradeInvoice(invoiceId: string): Promise<void> {
+ try {
+ await this.stripe.invoices.del(invoiceId);
+ } catch (deleteError) {
+ this.logger.error(
+ `Failed to delete draft upgrade invoice ${invoiceId}: ${this.getErrorMessage(deleteError)}`,
+ );
+ }
+ }
+
+ private getErrorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : 'unknown error';
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.ts
index 02c1a25eb87..71024bb96bf 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-exception-status-code.util.ts
@@ -31,6 +31,7 @@ export const getBillingExceptionStatusCode = (
case BillingExceptionCode.BILLING_SUBSCRIPTION_ALREADY_EXISTS:
return 400;
case BillingExceptionCode.BILLING_CREDITS_EXHAUSTED:
+ case BillingExceptionCode.BILLING_UPGRADE_INVOICE_PAYMENT_FAILED:
return 402;
case BillingExceptionCode.BILLING_CUSTOMER_EVENT_WORKSPACE_NOT_FOUND:
case BillingExceptionCode.BILLING_PRICE_NOT_FOUND:
@@ -46,6 +47,7 @@ export const getBillingExceptionStatusCode = (
case BillingExceptionCode.BILLING_TOO_MUCH_SUBSCRIPTIONS_FOUND:
case BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_CANCELED:
case BillingExceptionCode.BILLING_USAGE_UNAVAILABLE:
+ case BillingExceptionCode.BILLING_UPGRADE_INVOICE_VOID_FAILED:
return 500;
default: {
return assertUnreachable(exception.code);