Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions packages/features/ee/billing/credit-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -792,6 +792,54 @@ export class CreditService {
};
}

async moveCreditsFromTeamToUser({teamId , userId} : {teamId : number; userId : number}) {
return await prisma.$transaction(async (tx) => {
const teamCreditBalance = await CreditsRepository.findCreditBalance({teamId}, tx);

if(!teamCreditBalance || teamCreditBalance.additionalCredits <= 0) {
return ;
}

let userCreditBalance = await CreditsRepository.findCreditBalance({userId}, tx);

if(!userCreditBalance) {
userCreditBalance = await CreditsRepository.createCreditBalance(
{userId},
tx
);
}

const creditsToTransfer = teamCreditBalance.additionalCredits;
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Concurrent executions can double-transfer team credits because transfer amount is read before zeroing without lock/guard.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/features/ee/billing/credit-service.ts, line 812:

<comment>Concurrent executions can double-transfer team credits because transfer amount is read before zeroing without lock/guard.</comment>

<file context>
@@ -792,6 +792,54 @@ export class CreditService {
+        );
+      }
+
+      const creditsToTransfer = teamCreditBalance.additionalCredits;
+
+      logger.info("Moving credits from team to owner" , {
</file context>
Fix with Cubic


logger.info("Moving credits from team to owner" , {
teamId,
userId,
creditsToTransfer,
})

await CreditsRepository.updateCreditBalance (
{
teamId,
data : {additionalCredits : 0},
},
tx
);

await CreditsRepository.updateCreditBalance(
{
userId ,
data : {
additionalCredits : {
increment : creditsToTransfer,
},
},
},
tx
);
return { creditsTransferred : creditsToTransfer };
});
}

async moveCreditsFromTeamToOrg({ teamId, orgId }: { teamId: number; orgId: number }) {
return await prisma.$transaction(async (tx) => {
// Get team's credit balance
Expand Down
21 changes: 21 additions & 0 deletions packages/features/ee/billing/service/teams/TeamBillingService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import {
type TeamBillingInput,
TeamBillingPublishResponseStatus,
} from "./ITeamBillingService";
import { MembershipRole } from "@calcom/prisma/enums";
import { CreditService } from "../../credit-service"

const log = logger.getSubLogger({ prefix: ["TeamBilling"] });

Expand Down Expand Up @@ -133,6 +135,25 @@ export class TeamBillingService implements ITeamBillingService {
}
async downgrade() {
try {
const creditService = new CreditService();

const owner = await prisma.membership.findFirst({
where : {
teamId : this.team.id,
role : MembershipRole.OWNER
},
});

if(!owner) {
throw new Error(`No owner found for team ${this.team.id}`);
}

await creditService.moveCreditsFromTeamToUser({
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: downgrade() is non-atomic: failures in owner lookup/credit transfer can skip billing metadata cleanup, leaving stale subscription metadata after cancellation.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/features/ee/billing/service/teams/TeamBillingService.ts, line 151:

<comment>`downgrade()` is non-atomic: failures in owner lookup/credit transfer can skip billing metadata cleanup, leaving stale subscription metadata after cancellation.</comment>

<file context>
@@ -133,6 +135,25 @@ export class TeamBillingService implements ITeamBillingService {
+        throw new Error(`No owner found for team ${this.team.id}`);
+      }
+
+      await creditService.moveCreditsFromTeamToUser({
+        teamId : this.team.id,
+        userId : owner.userId,
</file context>
Fix with Cubic

teamId : this.team.id,
userId : owner.userId,
});


const { mergeMetadata } = getMetadataHelpers(teamPaymentMetadataSchema, this.team.metadata);
const metadata = mergeMetadata({
paymentId: undefined,
Expand Down
Loading