The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
chore(billing): drop the creditBalanceMicro and hasReachedCurrentPeriodCap columns (#24969)
Félix Malfait53e284caa5f7
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787906740818-drop-billing-customer-credit-balance-micro.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787906740818-drop-billing-customer-credit-balance-micro.tsnew file mode 100644index 00000000000..9cb1e2925da--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787906740818-drop-billing-customer-credit-balance-micro.ts@@ -0,0 +1,34 @@+import { QueryRunner } from 'typeorm';++import { isCoreTablePresent } from 'src/database/commands/upgrade-version-command/2-38/utils/is-core-table-present.util';+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';++// Second phase of the move to the billingCreditGrant ledger: the column was+// kept as a mirror of the ledger so a rollback to a pre-2.31 release stayed a+// deploy. The 2.31 backfill runs earlier in the sequence than this drop, so+// balances are in the ledger by the time the column goes.+@RegisteredInstanceCommand('2.38.0', 1787906740818)+export class DropBillingCustomerCreditBalanceMicroFastInstanceCommand+ implements FastInstanceCommand+{+ public async up(queryRunner: QueryRunner): Promise<void> {+ if (!(await isCoreTablePresent(queryRunner, 'billingCustomer'))) {+ return;+ }++ await queryRunner.query(+ `ALTER TABLE "core"."billingCustomer" DROP COLUMN IF EXISTS "creditBalanceMicro"`,+ );+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ if (!(await isCoreTablePresent(queryRunner, 'billingCustomer'))) {+ return;+ }++ await queryRunner.query(+ `ALTER TABLE "core"."billingCustomer" ADD COLUMN IF NOT EXISTS "creditBalanceMicro" bigint NOT NULL DEFAULT 0`,+ );+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787906740819-drop-has-reached-current-period-cap.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787906740819-drop-has-reached-current-period-cap.tsnew file mode 100644index 00000000000..f81940175c3--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787906740819-drop-has-reached-current-period-cap.ts@@ -0,0 +1,33 @@+import { QueryRunner } from 'typeorm';++import { isCoreTablePresent } from 'src/database/commands/upgrade-version-command/2-38/utils/is-core-table-present.util';+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';++// The GraphQL field of the same name is derived from the live credit balance in+// BillingSubscriptionItemResolver; the column has been neither read nor written+// since 2.32 and was only kept so a rollback to 2.31 still ran.+@RegisteredInstanceCommand('2.38.0', 1787906740819)+export class DropHasReachedCurrentPeriodCapFastInstanceCommand+ implements FastInstanceCommand+{+ public async up(queryRunner: QueryRunner): Promise<void> {+ if (!(await isCoreTablePresent(queryRunner, 'billingSubscriptionItem'))) {+ return;+ }++ await queryRunner.query(+ `ALTER TABLE "core"."billingSubscriptionItem" DROP COLUMN IF EXISTS "hasReachedCurrentPeriodCap"`,+ );+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ if (!(await isCoreTablePresent(queryRunner, 'billingSubscriptionItem'))) {+ return;+ }++ await queryRunner.query(+ `ALTER TABLE "core"."billingSubscriptionItem" ADD COLUMN IF NOT EXISTS "hasReachedCurrentPeriodCap" boolean NOT NULL DEFAULT false`,+ );+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/utils/is-core-table-present.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/utils/is-core-table-present.util.tsnew file mode 100644index 00000000000..31d660941ce--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/utils/is-core-table-present.util.ts@@ -0,0 +1,15 @@+import { type QueryRunner } from 'typeorm';++// An instance without billing never grew the billing tables, and+// DROP COLUMN IF EXISTS still fails when the table itself is missing.+export const isCoreTablePresent = async (+ queryRunner: QueryRunner,+ tableName: string,+): Promise<boolean> => {+ const rows = await queryRunner.query(+ `SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = $1`,+ [tableName],+ );++ return rows.length > 0;+};diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.tsindex bc17c45e6f9..432c673ecf7 100644--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts@@ -161,6 +161,8 @@ import { AddLabelToApplicationVariableFastInstanceCommand } from 'src/database/cimport { AddUsageLimitFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-36/2-36-instance-command-fast-1787821567133-add-usage-limit';import { MakeUserEmailCaseInsensitiveFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-37/2-37-instance-command-fast-1787836741000-make-user-email-case-insensitive';import { BackfillMissingPageLayoutWidgetPositionsSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-37/2-37-instance-command-slow-1787838153752-backfill-missing-page-layout-widget-positions';+import { DropBillingCustomerCreditBalanceMicroFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787906740818-drop-billing-customer-credit-balance-micro';+import { DropHasReachedCurrentPeriodCapFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787906740819-drop-has-reached-current-period-cap';export const INSTANCE_COMMANDS = [AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,@@ -324,4 +326,6 @@ export const INSTANCE_COMMANDS = [AddUsageLimitFastInstanceCommand,MakeUserEmailCaseInsensitiveFastInstanceCommand,BackfillMissingPageLayoutWidgetPositionsSlowInstanceCommand,+ DropBillingCustomerCreditBalanceMicroFastInstanceCommand,+ DropHasReachedCurrentPeriodCapFastInstanceCommand,];diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.tsindex 20109995ebf..76016ed5eab 100644--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts@@ -202,9 +202,7 @@ export class AdminPanelBillingService {const stripeCustomerId =customer?.stripeCustomerId ?? subscription?.stripeCustomerId ?? null;const creditBalance = toDisplayCredits(- await this.billingCreditGrantService.getSpendableCreditsMicro(- workspaceId,- ),+ await this.billingCreditGrantService.getActiveCreditsMicro(workspaceId),);if (!subscription) {diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-customer.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-customer.service.tsindex 69768c70c12..5e59353b1e1 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-customer.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-customer.service.ts@@ -13,7 +13,6 @@ import {} from 'src/engine/core-modules/billing/billing.exception';import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';import { BillingWebhookEvent } from 'src/engine/core-modules/billing/enums/billing-webhook-events.enum';-import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/services/stripe-customer.service';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';@@ -29,7 +28,6 @@ export class BillingWebhookCustomerService {@InjectRepository(BillingCustomerEntity)private readonly billingCustomerRepositoryUnscoped: Repository<BillingCustomerEntity>,private readonly stripeCustomerService: StripeCustomerService,- private readonly billingCreditService: BillingCreditService,) {}async processStripeEvent(@@ -71,11 +69,6 @@ export class BillingWebhookCustomerService {skipUpdateIfNoValuesChanged: true,},);-- // Credits granted before this row existed, an onboarding reward at signup- // above all, mirrored onto nothing. This is the earliest point the row is- // known to exist, so put the ledger balance on it here.- await this.billingCreditService.reconcileMirroredBalance(workspaceId);}private async processPaymentMethodAttachedEvent(diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.tsindex 0413ba1a10b..ed6f6f525ef 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts@@ -24,7 +24,6 @@ import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/eimport { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';import { BillingWebhookEvent } from 'src/engine/core-modules/billing/enums/billing-webhook-events.enum';-import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/services/stripe-customer.service';import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';@@ -66,7 +65,6 @@ export class BillingWebhookSubscriptionService {private readonly workspaceService: WorkspaceService,private readonly stripeSubscriptionScheduleService: StripeSubscriptionScheduleService,private readonly billingUsageCacheService: BillingUsageCacheService,- private readonly billingCreditService: BillingCreditService,private readonly workspaceCacheService: WorkspaceCacheService,) {}@@ -116,10 +114,6 @@ export class BillingWebhookSubscriptionService {},);- // Credits can be granted before this row exists, and those writes mirrored- // onto nothing. The row is here now, so put the ledger balance on it.- await this.billingCreditService.reconcileMirroredBalance(workspaceId);-const liveCustomerSubscriptions =await this.stripeSubscriptionScheduleService.listCustomerNotEndedSubscriptionsWithSchedule(String(data.object.customer),diff --git a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-customer.entity.ts b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-customer.entity.tsindex 8523fa08faa..169c7170736 100644--- a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-customer.entity.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-customer.entity.ts@@ -15,7 +15,6 @@ import {import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';import { BillingEntitlementEntity } from 'src/engine/core-modules/billing/entities/billing-entitlement.entity';import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';-import { bigintColumnTransformer } from 'src/engine/core-modules/billing/utils/bigint-column-transformer.util';import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity';@Entity({ name: 'billingCustomer', schema: 'core' })@@ -45,14 +44,6 @@ export class BillingCustomerEntity extends WorkspaceRelatedEntity {@Column({ nullable: true, type: 'boolean' })hasPaymentMethod: boolean | null;- @Column({- type: 'bigint',- nullable: false,- default: 0,- transformer: bigintColumnTransformer,- })- creditBalanceMicro: number;-@OneToMany(() => BillingSubscriptionEntity,(billingSubscription) => billingSubscription.billingCustomer,diff --git a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription-item.entity.ts b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription-item.entity.tsindex 53dede8117e..ad0cf99a87d 100644--- a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription-item.entity.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription-item.entity.ts@@ -73,10 +73,4 @@ export class BillingSubscriptionItemEntity {@Column({ nullable: true, type: 'numeric' })quantity: number | null;-- // No longer read or written: the GraphQL field of the same name is derived- // from the live credit balance in BillingSubscriptionItemResolver. Kept so a- // deploy rollback still runs; drop in a follow-up migration.- @Column({ type: 'boolean', default: false })- hasReachedCurrentPeriodCap: boolean;}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.tsindex 66851d73e07..49dcca298c1 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts@@ -11,15 +11,10 @@ import {BillingExceptionCode,} from 'src/engine/core-modules/billing/billing.exception';import { BillingCreditGrantEntity } from 'src/engine/core-modules/billing/entities/billing-credit-grant.entity';-import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';-import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';+import { type BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';-// Shared with the backfill instance command so the two are safe in either-// order: whichever runs first claims the key, the other is a no-op.-const LEGACY_BALANCE_IDEMPOTENCY_KEY_PREFIX = 'backfill-credit-balance:';-export type CreateBillingCreditGrantParams = {workspaceId: string;amountMicro: number;@@ -69,8 +64,6 @@ export class BillingCreditGrantService {constructor(@InjectWorkspaceScopedRepository(BillingCreditGrantEntity)private readonly billingCreditGrantRepository: WorkspaceScopedRepository<BillingCreditGrantEntity>,- @InjectWorkspaceScopedRepository(BillingCustomerEntity)- private readonly billingCustomerRepository: WorkspaceScopedRepository<BillingCustomerEntity>,) {}// Returns null when idempotencyKey has already been used, so callers can tell@@ -162,52 +155,6 @@ export class BillingCreditGrantService {return total;}- // Moves a not-yet-backfilled balance into the ledger before anything writes- // to it. Without this the first grant recomputes the mirror column from a- // ledger that does not hold the legacy balance yet, erasing it.- // Remove along with creditBalanceMicro.- async materializeLegacyBalance({- workspaceId,- effectiveAt,- expiresAt,- }: {- workspaceId: string;- effectiveAt: Date;- expiresAt: Date;- }): Promise<void> {- if (await this.hasAnyGrant(workspaceId)) {- return;- }-- const legacyBalanceMicro = await this.getMirroredBalanceMicro(workspaceId);-- if (legacyBalanceMicro <= 0) {- return;- }-- await this.createGrant({- workspaceId,- amountMicro: legacyBalanceMicro,- type: BillingCreditGrantType.ROLLOVER,- effectiveAt,- expiresAt,- reason: 'Backfilled from billingCustomer.creditBalanceMicro',- idempotencyKey: `${LEGACY_BALANCE_IDEMPOTENCY_KEY_PREFIX}${workspaceId}`,- });- }-- // What a workspace can actually spend, which is the ledger except in the- // window between this release deploying and its backfill running: until a- // workspace has any grant at all, its balance still only exists in the- // mirror column. Remove along with creditBalanceMicro.- async getSpendableCreditsMicro(workspaceId: string): Promise<number> {- if (await this.hasAnyGrant(workspaceId)) {- return this.getActiveCreditsMicro(workspaceId);- }-- return this.getMirroredBalanceMicro(workspaceId);- }-// Grants that were spendable at any point during the given period.async findGrantsLiveDuringPeriod({workspaceId,@@ -333,20 +280,4 @@ export class BillingCreditGrantService {return grant ?? null;}-- // Whether the ledger has taken over from billingCustomer.creditBalanceMicro- // for this workspace. Public so the mirror write can refuse to overwrite a- // balance the backfill has not reached yet.- async hasAnyGrant(workspaceId: string): Promise<boolean> {- return this.billingCreditGrantRepository.exists(workspaceId, { where: {} });- }-- private async getMirroredBalanceMicro(workspaceId: string): Promise<number> {- const billingCustomer = await this.billingCustomerRepository.findOne(- workspaceId,- { select: { creditBalanceMicro: true }, where: {} },- );-- return billingCustomer?.creditBalanceMicro ?? 0;- }}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.tsindex 092ca7614d6..d8e3b5f7c85 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts@@ -88,12 +88,6 @@ export class BillingCreditRolloverService {nextAllowanceMicro,usageMicro,}: ProcessRolloverParams & { usageMicro: number }): Promise<void> {- await this.billingCreditGrantService.materializeLegacyBalance({- workspaceId,- effectiveAt: closingPeriodStart,- expiresAt: closingPeriodEnd,- });-const closingGrants =await this.billingCreditGrantService.findGrantsLiveDuringPeriod({workspaceId,diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.tsindex b574db2334f..82c1319dfc6 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts@@ -5,7 +5,6 @@ import { Injectable, Logger } from '@nestjs/common';import { addDays } from 'date-fns';import { isDefined } from 'twenty-shared/utils';-import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';import { type BillingCreditGrantEntity } from 'src/engine/core-modules/billing/entities/billing-credit-grant.entity';import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';import { type BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';@@ -16,8 +15,6 @@ import { BillingService } from 'src/engine/core-modules/billing/services/billingimport { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';-import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';-import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';// Used when a workspace has no subscription yet, which happens for rewards@@ -48,8 +45,6 @@ export class BillingCreditService {private readonly billingUsageCacheService: BillingUsageCacheService,private readonly cacheLockService: CacheLockService,private readonly workspaceCacheService: WorkspaceCacheService,- @InjectWorkspaceScopedRepository(BillingCustomerEntity)- private readonly billingCustomerRepository: WorkspaceScopedRepository<BillingCustomerEntity>,) {}async grantCredits(@@ -92,12 +87,6 @@ export class BillingCreditService {subscription,);- await this.billingCreditGrantService.materializeLegacyBalance({- workspaceId,- effectiveAt,- expiresAt,- });-const grant = await this.billingCreditGrantService.createGrant({...params,effectiveAt,@@ -215,51 +204,12 @@ export class BillingCreditService {return grant;}- // The mirror column only exists once a workspace has a billingCustomer row,- // so a grant written before that (an onboarding reward at signup) mirrors- // onto nothing. Called when the row appears, so rolling this release back- // does not lose those credits. Remove along with creditBalanceMicro.- async reconcileMirroredBalance(workspaceId: string): Promise<void> {- if (!this.billingService.isBillingEnabled()) {- return;- }-- await this.cacheLockService.withLock(- () => this.syncMirrorBalance(workspaceId),- buildBillingCreditStateLockKey(workspaceId),- );- }-- private async syncMirrorBalance(workspaceId: string): Promise<number> {- const activeCreditsMicro =- await this.billingCreditGrantService.getActiveCreditsMicro(workspaceId);-- // Until the backfill reaches a workspace the column is still the only copy- // of its balance, and an empty ledger sums to zero. Callers materialize the- // legacy balance before writing, but the guard belongs here too rather than- // resting on an ordering contract between services.- if (- activeCreditsMicro === 0 &&- !(await this.billingCreditGrantService.hasAnyGrant(workspaceId))- ) {- return 0;- }-- await this.billingCustomerRepository.update(- workspaceId,- {},- { creditBalanceMicro: activeCreditsMicro },- );-- return activeCreditsMicro;- }-// Keeps everything that reads a credit balance consistent with the ledger:- // the mirror column, the Redis counter that gates usage, and the cached- // subscription the front reads. Public so a caller writing several grants at- // once pays for this once; such a caller must hold- // buildBillingCreditStateLockKey for its own ledger writes and this refresh- // together, which is why this does not take the lock itself.+ // the Redis counter that gates usage and the cached subscription the front+ // reads. Public so a caller writing several grants at once pays for this+ // once; such a caller must hold buildBillingCreditStateLockKey for its own+ // ledger writes and this refresh together, which is why this does not take+ // the lock itself.async refreshWorkspaceCreditState({workspaceId,availableDeltaMicro,@@ -277,8 +227,6 @@ export class BillingCreditService {// Saves a re-read for a caller that already has it in hand.subscription?: BillingSubscriptionEntity;}): Promise<void> {- await this.syncMirrorBalance(workspaceId);-const subscription =knownSubscription ??(await this.billingSubscriptionService.getCurrentBillingSubscription({diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.tsindex c5a93543858..0d337a35d63 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts@@ -147,7 +147,7 @@ export class BillingUsageService {): Promise<BillingResourceCreditUsageDTO> {const [usedCredits, rolloverCredits] = await Promise.all([this.getCurrentPeriodCreditsUsed(workspaceId, periodStart),- this.billingCreditGrantService.getSpendableCreditsMicro(workspaceId),+ this.billingCreditGrantService.getActiveCreditsMicro(workspaceId),]);const grantedCredits =@@ -196,7 +196,7 @@ export class BillingUsageService {const resourceUsageCap = this.getResourceUsageCap(subscription);const [creditBalance, usage] = await Promise.all([- this.billingCreditGrantService.getSpendableCreditsMicro(workspaceId),+ this.billingCreditGrantService.getActiveCreditsMicro(workspaceId),this.getCurrentPeriodCreditsUsed(subscription.workspaceId,subscription.currentPeriodStart,diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.tsindex 10765294cc9..2563291aeba 100644--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts@@ -4,7 +4,6 @@ import { addMonths, startOfMonth } from 'date-fns';import request from 'supertest';import {getBillingUsageCacheService,- getMirroredCreditBalance,getSeededBillingWorkspaceId,listCreditGrants,resetBillingCreditState,@@ -109,9 +108,6 @@ describe('Admin credit grant and revoke (integration)', () => {reason: 'Outage on the 3rd',revokedAt: null,});- expect(await getMirroredCreditBalance(workspaceId)).toBe(- 2 * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,- );});it('adds the granted amount to a warm usage counter', async () => {@@ -167,7 +163,6 @@ describe('Admin credit grant and revoke (integration)', () => {const grants = await listCreditGrants(workspaceId);expect(grants[0].revokedAt).not.toBeNull();- expect(await getMirroredCreditBalance(workspaceId)).toBe(0);expect(await cache.getAvailableCredits(workspaceId, PERIOD_START)).toBe(500_000,);@@ -227,8 +222,5 @@ describe('Admin credit grant and revoke (integration)', () => {first.body.data.grantWorkspaceCredits.id,);expect(await listCreditGrants(workspaceId)).toHaveLength(1);- expect(await getMirroredCreditBalance(workspaceId)).toBe(- 25 * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,- );});});diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.tsindex a8bb2f2c1ae..d24058f3f90 100644--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts@@ -3,7 +3,6 @@ import request from 'supertest';import { createMockStripeInvoiceFinalizedData } from 'test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util';import {getBillingUsageCacheService,- getMirroredCreditBalance,getSeededBillingWorkspaceId,insertCreditGrant,listCreditGrants,@@ -19,8 +18,8 @@ import { type BillingUsageService } from 'src/engine/core-modules/billing/servicconst client = request(`http://localhost:${APP_PORT}`);// Whole calendar months, anchored so the period the transition opens is the-// one running right now. The mirror column and the ledger both filter on now(),-// so periods fixed in the past would read as expired and assert nothing.+// one running right now. The ledger filters on now(), so periods fixed in the+// past would read as expired and assert nothing.const PERIOD_BOUNDARY = startOfMonth(new Date());const CLOSING_PERIOD_START = subMonths(PERIOD_BOUNDARY, 1);const CLOSING_PERIOD_END = PERIOD_BOUNDARY;@@ -175,14 +174,6 @@ describe('Billing credit rollover (integration)', () => {).toBe(ALLOWANCE_MICRO);});- it('mirrors the resulting balance onto the billing customer', async () => {- usageSpy.mockResolvedValue(300_000);-- await postInvoiceFinalized().expect(200);-- expect(await getMirroredCreditBalance(workspaceId)).toBe(700_000);- });-// A redelivery must not hand out the credits a second time.it('is idempotent when Stripe redelivers the same invoice', async () => {usageSpy.mockResolvedValue(300_000);@@ -197,7 +188,6 @@ describe('Billing credit rollover (integration)', () => {expect(afterSecond.reduce((total, grant) => total + grant.amountMicro, 0),).toBe(afterFirst.reduce((total, grant) => total + grant.amountMicro, 0));- expect(await getMirroredCreditBalance(workspaceId)).toBe(700_000);});// Returning normally would answer 200 and Stripe would never redeliver, so@@ -208,7 +198,6 @@ describe('Billing credit rollover (integration)', () => {await postInvoiceFinalized().expect(500);expect(await listCreditGrants(workspaceId)).toHaveLength(0);- expect(await getMirroredCreditBalance(workspaceId)).toBe(0);});it('adds the carried balance to a warm usage counter', async () => {diff --git a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.tsindex 5fa1a912b1a..cd26c9cd5a2 100644--- a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts+++ b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts@@ -166,17 +166,6 @@ export const listCreditGrants = async ([workspaceId],);-export const getMirroredCreditBalance = async (- workspaceId: string,-): Promise<number> => {- const [row] = await query<{ creditBalanceMicro: string }>(- `SELECT "creditBalanceMicro" FROM core."billingCustomer" WHERE "workspaceId" = $1`,- [workspaceId],- );-- return Number(row?.creditBalanceMicro ?? 0);-};-export const resetBillingCreditState = async (workspaceId: string,): Promise<void> => {@@ -184,10 +173,6 @@ export const resetBillingCreditState = async (`DELETE FROM core."billingCreditGrant" WHERE "workspaceId" = $1`,[workspaceId],);- await query(- `UPDATE core."billingCustomer" SET "creditBalanceMicro" = 0 WHERE "workspaceId" = $1`,- [workspaceId],- );const cache = getBillingUsageCacheService();await cache.flushAvailableCredits(workspaceId);