Skip to content

The open alternative to Salesforce, designed for AI.

feat(billing): replace the credit balance column with a credit grant ledger (#23973)

Félix Malfait0851387ea172
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index a91ba4bb0f9..b96fd120a6d 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -1466,6 +1466,11 @@ type BillingSubscriptionItem {
billingProduct: BillingProductDTO!
}
+type BillingCustomer {
+ id: UUID!
+ hasPaymentMethod: Boolean
+}
+
type BillingSubscription {
id: UUID!
status: SubscriptionStatus!
@@ -1488,11 +1493,6 @@ enum SubscriptionStatus {
Unpaid
}
-type BillingCustomer {
- id: UUID!
- hasPaymentMethod: Boolean
-}
-
type LogicFunctionExecutionResult {
"""Execution result in JSON format"""
data: JSON
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 92401db3771..629ac032590 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1148,6 +1148,12 @@ export interface BillingSubscriptionItem {
__typename: 'BillingSubscriptionItem'
}
+export interface BillingCustomer {
+ id: Scalars['UUID']
+ hasPaymentMethod?: Scalars['Boolean']
+ __typename: 'BillingCustomer'
+}
+
export interface BillingSubscription {
id: Scalars['UUID']
status: SubscriptionStatus
@@ -1162,12 +1168,6 @@ export interface BillingSubscription {
export type SubscriptionStatus = 'Active' | 'Canceled' | 'Incomplete' | 'IncompleteExpired' | 'PastDue' | 'Paused' | 'Trialing' | 'Unpaid'
-export interface BillingCustomer {
- id: Scalars['UUID']
- hasPaymentMethod?: Scalars['Boolean']
- __typename: 'BillingCustomer'
-}
-
export interface LogicFunctionExecutionResult {
/** Execution result in JSON format */
data?: Scalars['JSON']
@@ -4417,6 +4417,13 @@ export interface BillingSubscriptionItemGenqlSelection{
__scalar?: boolean | number
}
+export interface BillingCustomerGenqlSelection{
+ id?: boolean | number
+ hasPaymentMethod?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface BillingSubscriptionGenqlSelection{
id?: boolean | number
status?: boolean | number
@@ -4430,13 +4437,6 @@ export interface BillingSubscriptionGenqlSelection{
__scalar?: boolean | number
}
-export interface BillingCustomerGenqlSelection{
- id?: boolean | number
- hasPaymentMethod?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
export interface LogicFunctionExecutionResultGenqlSelection{
/** Execution result in JSON format */
data?: boolean | number
@@ -7733,14 +7733,6 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
- const BillingSubscription_possibleTypes: string[] = ['BillingSubscription']
- export const isBillingSubscription = (obj?: { __typename?: any } | null): obj is BillingSubscription => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isBillingSubscription"')
- return BillingSubscription_possibleTypes.includes(obj.__typename)
- }
-
-
-
const BillingCustomer_possibleTypes: string[] = ['BillingCustomer']
export const isBillingCustomer = (obj?: { __typename?: any } | null): obj is BillingCustomer => {
if (!obj?.__typename) throw new Error('__typename is missing in "isBillingCustomer"')
@@ -7749,6 +7741,14 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
+ const BillingSubscription_possibleTypes: string[] = ['BillingSubscription']
+ export const isBillingSubscription = (obj?: { __typename?: any } | null): obj is BillingSubscription => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isBillingSubscription"')
+ return BillingSubscription_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const LogicFunctionExecutionResult_possibleTypes: string[] = ['LogicFunctionExecutionResult']
export const isLogicFunctionExecutionResult = (obj?: { __typename?: any } | null): obj is LogicFunctionExecutionResult => {
if (!obj?.__typename) throw new Error('__typename is missing in "isLogicFunctionExecutionResult"')
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 531235be0d7..2e31ee458a2 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -48,7 +48,7 @@ export default {
130,
131,
133,
- 141,
+ 142,
144,
152,
155,
@@ -1653,16 +1653,16 @@ export default {
171
],
"billingSubscriptions": [
- 140
+ 141
],
"installedApplications": [
48
],
"currentBillingSubscription": [
- 140
+ 141
],
"billingCustomer": [
- 142
+ 140
],
"billingEntitlements": [
240
@@ -2877,12 +2877,23 @@ export default {
1
]
},
+ "BillingCustomer": {
+ "id": [
+ 4
+ ],
+ "hasPaymentMethod": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"BillingSubscription": {
"id": [
4
],
"status": [
- 141
+ 142
],
"interval": [
133
@@ -2907,17 +2918,6 @@ export default {
]
},
"SubscriptionStatus": {},
- "BillingCustomer": {
- "id": [
- 4
- ],
- "hasPaymentMethod": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
"LogicFunctionExecutionResult": {
"data": [
5
@@ -3228,7 +3228,7 @@ export default {
},
"BillingEndTrialPeriod": {
"status": [
- 141
+ 142
],
"hasPaymentMethod": [
3
@@ -3237,10 +3237,10 @@ export default {
1
],
"currentBillingSubscription": [
- 140
+ 141
],
"billingSubscriptions": [
- 140
+ 141
],
"__typename": [
1
@@ -3313,10 +3313,10 @@ export default {
},
"BillingUpdate": {
"currentBillingSubscription": [
- 140
+ 141
],
"billingSubscriptions": [
- 140
+ 141
],
"__typename": [
1
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index f256de0368a..cdbe7e5ba72 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -168,11 +168,25 @@ export type AdminPanelWorkerQueueHealth = {
export type AdminPanelWorkspaceBilling = {
__typename?: 'AdminPanelWorkspaceBilling';
creditBalance?: Maybe<Scalars['Float']['output']>;
+ creditGrants: Array<AdminPanelWorkspaceCreditGrant>;
stripeCustomerId?: Maybe<Scalars['String']['output']>;
subscription?: Maybe<AdminPanelWorkspaceSubscription>;
usage?: Maybe<AdminPanelWorkspaceUsage>;
};
+export type AdminPanelWorkspaceCreditGrant = {
+ __typename?: 'AdminPanelWorkspaceCreditGrant';
+ amount: Scalars['Float']['output'];
+ createdAt: Scalars['DateTime']['output'];
+ effectiveAt: Scalars['DateTime']['output'];
+ expiresAt: Scalars['DateTime']['output'];
+ id: Scalars['UUID']['output'];
+ isActive: Scalars['Boolean']['output'];
+ reason?: Maybe<Scalars['String']['output']>;
+ revokedAt?: Maybe<Scalars['DateTime']['output']>;
+ type: BillingCreditGrantType;
+};
+
export type AdminPanelWorkspaceSubscription = {
__typename?: 'AdminPanelWorkspaceSubscription';
cancelAt?: Maybe<Scalars['DateTime']['output']>;
@@ -293,6 +307,14 @@ export type ApplicationRegistrationVariableDto = {
value?: Maybe<Scalars['String']['output']>;
};
+/** The origin of a batch of credits granted to a workspace */
+export enum BillingCreditGrantType {
+ COMPENSATION = 'COMPENSATION',
+ ONBOARDING_REWARD = 'ONBOARDING_REWARD',
+ ROLLOVER = 'ROLLOVER',
+ SALES = 'SALES'
+}
+
export enum ConfigSource {
DATABASE = 'DATABASE',
DEFAULT = 'DEFAULT',
@@ -493,11 +515,13 @@ export type Mutation = {
createDatabaseConfigVariable: Scalars['Boolean']['output'];
deleteDatabaseConfigVariable: Scalars['Boolean']['output'];
deleteJobs: DeleteJobsResponse;
+ grantWorkspaceCredits: AdminPanelWorkspaceCreditGrant;
refreshUpgradeStatus: InstanceAndAllWorkspacesUpgradeStatus;
removeAiProvider: Scalars['Boolean']['output'];
removeModelFromProvider: Scalars['Boolean']['output'];
retryJobs: RetryJobsResponse;
revokeSigningKey: SigningKeyDto;
+ revokeWorkspaceCreditGrant: AdminPanelWorkspaceCreditGrant;
setAdminAiModelEnabled: Scalars['Boolean']['output'];
setAdminAiModelRecommended: Scalars['Boolean']['output'];
setAdminAiModelsEnabled: Scalars['Boolean']['output'];
@@ -542,6 +566,15 @@ export type MutationDeleteJobsArgs = {
};
+export type MutationGrantWorkspaceCreditsArgs = {
+ amount: Scalars['Float']['input'];
+ clientOperationId: Scalars['UUID']['input'];
+ reason?: InputMaybe<Scalars['String']['input']>;
+ type: BillingCreditGrantType;
+ workspaceId: Scalars['UUID']['input'];
+};
+
+
export type MutationRemoveAiProviderArgs = {
providerName: Scalars['String']['input'];
};
@@ -564,6 +597,12 @@ export type MutationRevokeSigningKeyArgs = {
};
+export type MutationRevokeWorkspaceCreditGrantArgs = {
+ creditGrantId: Scalars['UUID']['input'];
+ workspaceId: Scalars['UUID']['input'];
+};
+
+
export type MutationSetAdminAiModelEnabledArgs = {
enabled: Scalars['Boolean']['input'];
modelId: Scalars['String']['input'];
@@ -1240,6 +1279,25 @@ export type GetDatabaseConfigVariableQuery = { __typename?: 'Query', getDatabase
export type UserInfoFragmentFragment = { __typename?: 'UserInfo', id: string, email: string, firstName?: string | null, lastName?: string | null, createdAt: string };
+export type GrantWorkspaceCreditsMutationVariables = Exact<{
+ workspaceId: Scalars['UUID']['input'];
+ amount: Scalars['Float']['input'];
+ type: BillingCreditGrantType;
+ reason?: InputMaybe<Scalars['String']['input']>;
+ clientOperationId: Scalars['UUID']['input'];
+}>;
+
+
+export type GrantWorkspaceCreditsMutation = { __typename?: 'Mutation', grantWorkspaceCredits: { __typename?: 'AdminPanelWorkspaceCreditGrant', id: string, amount: number, type: BillingCreditGrantType, effectiveAt: string, expiresAt: string, revokedAt?: string | null, reason?: string | null, isActive: boolean, createdAt: string } };
+
+export type RevokeWorkspaceCreditGrantMutationVariables = Exact<{
+ workspaceId: Scalars['UUID']['input'];
+ creditGrantId: Scalars['UUID']['input'];
+}>;
+
+
+export type RevokeWorkspaceCreditGrantMutation = { __typename?: 'Mutation', revokeWorkspaceCreditGrant: { __typename?: 'AdminPanelWorkspaceCreditGrant', id: string, amount: number, type: BillingCreditGrantType, effectiveAt: string, expiresAt: string, revokedAt?: string | null, reason?: string | null, isActive: boolean, createdAt: string } };
+
export type UpdateServerAdminAccessMutationVariables = Exact<{
userId: Scalars['UUID']['input'];
canAccessFullAdminPanel?: InputMaybe<Scalars['Boolean']['input']>;
@@ -1330,7 +1388,7 @@ export type WorkspaceBillingAdminPanelQueryVariables = Exact<{
}>;
-export type WorkspaceBillingAdminPanelQuery = { __typename?: 'Query', workspaceBillingAdminPanel?: { __typename?: 'AdminPanelWorkspaceBilling', stripeCustomerId?: string | null, creditBalance?: number | null, usage?: { __typename?: 'AdminPanelWorkspaceUsage', periodStart: string, periodEnd: string, usedCredits: number, grantedCredits: number, rolloverCredits: number, totalGrantedCredits: number, remainingCredits: number } | null, subscription?: { __typename?: 'AdminPanelWorkspaceSubscription', stripeSubscriptionId: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, currency: string, planKey?: string | null, currentPeriodStart: string, currentPeriodEnd: string, trialStart?: string | null, trialEnd?: string | null, cancelAt?: string | null, canceledAt?: string | null, cancelAtPeriodEnd: boolean, items: Array<{ __typename?: 'AdminPanelWorkspaceSubscriptionItem', productName: string, productKey?: string | null, stripePriceId: string, quantity?: number | null, unitAmount?: number | null, includedCredits?: number | null }> } | null } | null };
+export type WorkspaceBillingAdminPanelQuery = { __typename?: 'Query', workspaceBillingAdminPanel?: { __typename?: 'AdminPanelWorkspaceBilling', stripeCustomerId?: string | null, creditBalance?: number | null, creditGrants: Array<{ __typename?: 'AdminPanelWorkspaceCreditGrant', id: string, amount: number, type: BillingCreditGrantType, effectiveAt: string, expiresAt: string, revokedAt?: string | null, reason?: string | null, isActive: boolean, createdAt: string }>, usage?: { __typename?: 'AdminPanelWorkspaceUsage', periodStart: string, periodEnd: string, usedCredits: number, grantedCredits: number, rolloverCredits: number, totalGrantedCredits: number, remainingCredits: number } | null, subscription?: { __typename?: 'AdminPanelWorkspaceSubscription', stripeSubscriptionId: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, currency: string, planKey?: string | null, currentPeriodStart: string, currentPeriodEnd: string, trialStart?: string | null, trialEnd?: string | null, cancelAt?: string | null, canceledAt?: string | null, cancelAtPeriodEnd: boolean, items: Array<{ __typename?: 'AdminPanelWorkspaceSubscriptionItem', productName: string, productKey?: string | null, stripePriceId: string, quantity?: number | null, unitAmount?: number | null, includedCredits?: number | null }> } | null } | null };
export type UserLookupAdminPanelQueryVariables = Exact<{
userIdentifier: Scalars['String']['input'];
@@ -1464,6 +1522,8 @@ export const DeleteDatabaseConfigVariableDocument = {"kind":"Document","definiti
export const UpdateDatabaseConfigVariableDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateDatabaseConfigVariable"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"key"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"value"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateDatabaseConfigVariable"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"key"},"value":{"kind":"Variable","name":{"kind":"Name","value":"key"}}},{"kind":"Argument","name":{"kind":"Name","value":"value"},"value":{"kind":"Variable","name":{"kind":"Name","value":"value"}}}]}]}}]} as unknown as DocumentNode<UpdateDatabaseConfigVariableMutation, UpdateDatabaseConfigVariableMutationVariables>;
export const GetConfigVariablesGroupedDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetConfigVariablesGrouped"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getConfigVariablesGrouped"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"groups"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"isHiddenOnLoad"}},{"kind":"Field","name":{"kind":"Name","value":"variables"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"value"}},{"kind":"Field","name":{"kind":"Name","value":"isSensitive"}},{"kind":"Field","name":{"kind":"Name","value":"isEnvOnly"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"options"}},{"kind":"Field","name":{"kind":"Name","value":"source"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GetConfigVariablesGroupedQuery, GetConfigVariablesGroupedQueryVariables>;
export const GetDatabaseConfigVariableDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetDatabaseConfigVariable"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"key"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getDatabaseConfigVariable"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"key"},"value":{"kind":"Variable","name":{"kind":"Name","value":"key"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"value"}},{"kind":"Field","name":{"kind":"Name","value":"isSensitive"}},{"kind":"Field","name":{"kind":"Name","value":"isEnvOnly"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"options"}},{"kind":"Field","name":{"kind":"Name","value":"source"}}]}}]}}]} as unknown as DocumentNode<GetDatabaseConfigVariableQuery, GetDatabaseConfigVariableQueryVariables>;
+export const GrantWorkspaceCreditsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GrantWorkspaceCredits"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"amount"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Float"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"type"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"BillingCreditGrantType"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"reason"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"clientOperationId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"grantWorkspaceCredits"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}},{"kind":"Argument","name":{"kind":"Name","value":"amount"},"value":{"kind":"Variable","name":{"kind":"Name","value":"amount"}}},{"kind":"Argument","name":{"kind":"Name","value":"type"},"value":{"kind":"Variable","name":{"kind":"Name","value":"type"}}},{"kind":"Argument","name":{"kind":"Name","value":"reason"},"value":{"kind":"Variable","name":{"kind":"Name","value":"reason"}}},{"kind":"Argument","name":{"kind":"Name","value":"clientOperationId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"clientOperationId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"amount"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveAt"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"revokedAt"}},{"kind":"Field","name":{"kind":"Name","value":"reason"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]} as unknown as DocumentNode<GrantWorkspaceCreditsMutation, GrantWorkspaceCreditsMutationVariables>;
+export const RevokeWorkspaceCreditGrantDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RevokeWorkspaceCreditGrant"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"creditGrantId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"revokeWorkspaceCreditGrant"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}},{"kind":"Argument","name":{"kind":"Name","value":"creditGrantId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"creditGrantId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"amount"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveAt"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"revokedAt"}},{"kind":"Field","name":{"kind":"Name","value":"reason"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]} as unknown as DocumentNode<RevokeWorkspaceCreditGrantMutation, RevokeWorkspaceCreditGrantMutationVariables>;
export const UpdateServerAdminAccessDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateServerAdminAccess"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"canImpersonate"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"otp"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateServerAdminAccess"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userId"}}},{"kind":"Argument","name":{"kind":"Name","value":"canAccessFullAdminPanel"},"value":{"kind":"Variable","name":{"kind":"Name","value":"canAccessFullAdminPanel"}}},{"kind":"Argument","name":{"kind":"Name","value":"canImpersonate"},"value":{"kind":"Variable","name":{"kind":"Name","value":"canImpersonate"}}},{"kind":"Argument","name":{"kind":"Name","value":"otp"},"value":{"kind":"Variable","name":{"kind":"Name","value":"otp"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},{"kind":"Field","name":{"kind":"Name","value":"canImpersonate"}}]}}]}}]} as unknown as DocumentNode<UpdateServerAdminAccessMutation, UpdateServerAdminAccessMutationVariables>;
export const UpdateWorkspaceFeatureFlagDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkspaceFeatureFlag"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"featureFlag"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"value"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkspaceFeatureFlag"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}},{"kind":"Argument","name":{"kind":"Name","value":"featureFlag"},"value":{"kind":"Variable","name":{"kind":"Name","value":"featureFlag"}}},{"kind":"Argument","name":{"kind":"Name","value":"value"},"value":{"kind":"Variable","name":{"kind":"Name","value":"value"}}}]}]}}]} as unknown as DocumentNode<UpdateWorkspaceFeatureFlagMutation, UpdateWorkspaceFeatureFlagMutationVariables>;
export const AdminPanelRecentUsersDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"AdminPanelRecentUsers"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"searchTerm"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"adminPanelRecentUsers"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"searchTerm"},"value":{"kind":"Variable","name":{"kind":"Name","value":"searchTerm"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceName"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceLogo"}}]}}]}}]} as unknown as DocumentNode<AdminPanelRecentUsersQuery, AdminPanelRecentUsersQueryVariables>;
@@ -1475,7 +1535,7 @@ export const GetAdminWorkspaceChatThreadsDocument = {"kind":"Document","definiti
export const GetServerAdminsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetServerAdmins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getServerAdmins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},{"kind":"Field","name":{"kind":"Name","value":"canImpersonate"}}]}}]}}]} as unknown as DocumentNode<GetServerAdminsQuery, GetServerAdminsQueryVariables>;
export const GetUpgradeStatusDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetUpgradeStatus"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceIds"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getUpgradeStatus"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceIds"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceIds"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"inferredVersion"}},{"kind":"Field","name":{"kind":"Name","value":"health"}},{"kind":"Field","name":{"kind":"Name","value":"latestCommand"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"executedByVersion"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]}}]} as unknown as DocumentNode<GetUpgradeStatusQuery, GetUpgradeStatusQueryVariables>;
export const GetVersionInfoDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetVersionInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"versionInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentVersion"}},{"kind":"Field","name":{"kind":"Name","value":"latestVersion"}}]}}]}}]} as unknown as DocumentNode<GetVersionInfoQuery, GetVersionInfoQueryVariables>;
-export const WorkspaceBillingAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceBillingAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceBillingAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripeCustomerId"}},{"kind":"Field","name":{"kind":"Name","value":"creditBalance"}},{"kind":"Field","name":{"kind":"Name","value":"usage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"usedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"grantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"rolloverCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalGrantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"remainingCredits"}}]}},{"kind":"Field","name":{"kind":"Name","value":"subscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripeSubscriptionId"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"currency"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodStart"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"trialStart"}},{"kind":"Field","name":{"kind":"Name","value":"trialEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"canceledAt"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAtPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productName"}},{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"includedCredits"}}]}}]}}]}}]}}]} as unknown as DocumentNode<WorkspaceBillingAdminPanelQuery, WorkspaceBillingAdminPanelQueryVariables>;
+export const WorkspaceBillingAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceBillingAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceBillingAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripeCustomerId"}},{"kind":"Field","name":{"kind":"Name","value":"creditBalance"}},{"kind":"Field","name":{"kind":"Name","value":"creditGrants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"amount"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveAt"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"revokedAt"}},{"kind":"Field","name":{"kind":"Name","value":"reason"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"usedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"grantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"rolloverCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalGrantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"remainingCredits"}}]}},{"kind":"Field","name":{"kind":"Name","value":"subscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripeSubscriptionId"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"currency"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodStart"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"trialStart"}},{"kind":"Field","name":{"kind":"Name","value":"trialEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"canceledAt"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAtPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productName"}},{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"includedCredits"}}]}}]}}]}}]}}]} as unknown as DocumentNode<WorkspaceBillingAdminPanelQuery, WorkspaceBillingAdminPanelQueryVariables>;
export const UserLookupAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UserLookupAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userLookupAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userIdentifier"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"UserInfoFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"totalUsers"}},{"kind":"Field","name":{"kind":"Name","value":"activationStatus"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customUrl"}},{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"users"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"featureFlags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"UserInfoFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"UserInfo"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]} as unknown as DocumentNode<UserLookupAdminPanelQuery, UserLookupAdminPanelQueryVariables>;
export const WorkspaceLookupAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceLookupAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceLookupAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"UserInfoFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"totalUsers"}},{"kind":"Field","name":{"kind":"Name","value":"activationStatus"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customUrl"}},{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"users"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"featureFlags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"UserInfoFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"UserInfo"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]} as unknown as DocumentNode<WorkspaceLookupAdminPanelQuery, WorkspaceLookupAdminPanelQueryVariables>;
export const DeleteJobsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteJobs"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"queueName"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"jobIds"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteJobs"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"queueName"},"value":{"kind":"Variable","name":{"kind":"Name","value":"queueName"}}},{"kind":"Argument","name":{"kind":"Name","value":"jobIds"},"value":{"kind":"Variable","name":{"kind":"Name","value":"jobIds"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deletedCount"}},{"kind":"Field","name":{"kind":"Name","value":"results"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"jobId"}},{"kind":"Field","name":{"kind":"Name","value":"success"}},{"kind":"Field","name":{"kind":"Name","value":"error"}}]}}]}}]}}]} as unknown as DocumentNode<DeleteJobsMutation, DeleteJobsMutationVariables>;
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceBillingContent.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceBillingContent.tsx
index 2a7fc64c3a7..0157e2a7bca 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceBillingContent.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceBillingContent.tsx
@@ -23,6 +23,9 @@ import { type ThemeColor } from 'twenty-ui/theme';
import { themeCssVariables } from 'twenty-ui/theme-constants';
import { useApolloAdminClient } from '@/settings/admin-panel/apollo/hooks/useApolloAdminClient';
+import { SettingsAdminWorkspaceCreditGrantModal } from '@/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal';
+import { SettingsAdminWorkspaceCreditGrantsTable } from '@/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantsTable';
+import { useModal } from '@/ui/layout/modal/hooks/useModal';
import { GET_WORKSPACE_BILLING_ADMIN_PANEL } from '@/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel';
import { SettingsTableCard } from '@/settings/components/SettingsTableCard';
import { PlansTags } from '@/settings/billing/components/internal/PlansTags';
@@ -40,6 +43,7 @@ const STRIPE_DASHBOARD_BASE_URL = 'https://dashboard.stripe.com';
const BASE_PRODUCT_KEY = 'BASE_PRODUCT';
const RESOURCE_CREDIT_KEY = 'RESOURCE_CREDIT';
const EM_DASH = '\u2014';
+const GRANT_CREDITS_MODAL_ID = 'settings-admin-grant-workspace-credits';
type SettingsAdminWorkspaceBillingContentProps = {
workspaceId: string;
@@ -138,6 +142,7 @@ export const SettingsAdminWorkspaceBillingContent = ({
}: SettingsAdminWorkspaceBillingContentProps) => {
const { t } = useLingui();
const { formatNumber } = useNumberFormat();
+ const { openModal } = useModal();
const apolloAdminClient = useApolloAdminClient();
const { data, loading } = useQuery<WorkspaceBillingAdminPanelQuery>(
@@ -172,7 +177,8 @@ export const SettingsAdminWorkspaceBillingContent = ({
);
}
- const { stripeCustomerId, creditBalance, subscription, usage } = billing;
+ const { stripeCustomerId, creditBalance, creditGrants, subscription, usage } =
+ billing;
const formatCredits = (credits: number): string =>
formatNumber(credits, { abbreviate: true, decimals: 2 });
@@ -421,6 +427,17 @@ export const SettingsAdminWorkspaceBillingContent = ({
/>
)}
</Section>
+
+ <SettingsAdminWorkspaceCreditGrantsTable
+ workspaceId={workspaceId}
+ creditGrants={creditGrants}
+ onGrantCreditsClick={() => openModal(GRANT_CREDITS_MODAL_ID)}
+ />
+
+ <SettingsAdminWorkspaceCreditGrantModal
+ modalInstanceId={GRANT_CREDITS_MODAL_ID}
+ workspaceId={workspaceId}
+ />
</StyledContainer>
);
};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal.tsx
new file mode 100644
index 00000000000..2c2c467f405
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal.tsx
@@ -0,0 +1,221 @@
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+import { useMutation } from '@apollo/client/react';
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
+import { v4 } from 'uuid';
+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';
+
+import { useApolloAdminClient } from '@/settings/admin-panel/apollo/hooks/useApolloAdminClient';
+import { CREDIT_GRANT_TYPE_LABELS } from '@/settings/admin-panel/constants/CreditGrantTypeLabels';
+import { GRANTABLE_CREDIT_GRANT_TYPES } from '@/settings/admin-panel/constants/GrantableCreditGrantTypes';
+import { GRANT_WORKSPACE_CREDITS } from '@/settings/admin-panel/graphql/mutations/grantWorkspaceCredits';
+import { GET_WORKSPACE_BILLING_ADMIN_PANEL } from '@/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel';
+import { Select } from '@/ui/input/components/Select';
+import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';
+import { ModalStatefulWrapper } from '@/ui/layout/modal/components/ModalStatefulWrapper';
+import { useModal } from '@/ui/layout/modal/hooks/useModal';
+import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
+import { BillingCreditGrantType } from '~/generated-admin/graphql';
+
+type SettingsAdminWorkspaceCreditGrantModalProps = {
+ modalInstanceId: string;
+ workspaceId: string;
+};
+
+const StyledCenteredTitle = styled.div`
+ text-align: center;
+`;
+
+const StyledSectionContainer = styled.div`
+ margin-bottom: ${themeCssVariables.spacing[6]};
+`;
+
+const StyledFields = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[4]};
+`;
+
+const StyledModalActions = styled.div`
+ display: flex;
+ gap: ${themeCssVariables.spacing[2]};
+ margin-top: ${themeCssVariables.spacing[6]};
+
+ > div {
+ flex: 1;
+ }
+`;
+
+export const SettingsAdminWorkspaceCreditGrantModal = ({
+ modalInstanceId,
+ workspaceId,
+}: SettingsAdminWorkspaceCreditGrantModalProps) => {
+ const { t } = useLingui();
+ const { closeModal } = useModal();
+ const { enqueueErrorSnackBar, enqueueSuccessSnackBar } = useSnackBar();
+ const apolloAdminClient = useApolloAdminClient();
+
+ const [amount, setAmount] = useState('');
+ const [type, setType] = useState<BillingCreditGrantType>(
+ BillingCreditGrantType.COMPENSATION,
+ );
+ const [reason, setReason] = useState('');
+ // Identifies one intended grant, so a RetryLink retry or a resubmit after a
+ // lost response is answered with the grant the first attempt wrote rather
+ // than crediting the workspace twice. Keyed on the submitted values, since
+ // editing the amount and resubmitting is a different intent that must not be
+ // answered with the earlier grant.
+ const [submittedGrant, setSubmittedGrant] = useState<{
+ payload: string;
+ clientOperationId: string;
+ } | null>(null);
+
+ const [grantWorkspaceCredits, { loading }] = useMutation(
+ GRANT_WORKSPACE_CREDITS,
+ {
+ client: apolloAdminClient,
+ refetchQueries: [GET_WORKSPACE_BILLING_ADMIN_PANEL],
+ },
+ );
+
+ const parsedAmount = Number(amount);
+ const isAmountValid = Number.isFinite(parsedAmount) && parsedAmount > 0;
+
+ // The modal is mounted for the whole page, so without this the next admin to
+ // open it starts from the last grant's amount and reason.
+ const handleClose = () => {
+ setAmount('');
+ setType(BillingCreditGrantType.COMPENSATION);
+ setReason('');
+ setSubmittedGrant(null);
+ closeModal(modalInstanceId);
+ };
+
+ const handleSubmit = async () => {
+ if (!isAmountValid) {
+ return;
+ }
+
+ const trimmedReason = reason.trim();
+ const payload = JSON.stringify([parsedAmount, type, trimmedReason]);
+
+ const clientOperationId =
+ submittedGrant?.payload === payload
+ ? submittedGrant.clientOperationId
+ : v4();
+
+ setSubmittedGrant({ payload, clientOperationId });
+
+ try {
+ await grantWorkspaceCredits({
+ variables: {
+ workspaceId,
+ amount: parsedAmount,
+ type,
+ reason: trimmedReason || null,
+ clientOperationId,
+ },
+ });
+
+ enqueueSuccessSnackBar({
+ message: t`Granted ${parsedAmount} credits to this workspace.`,
+ });
+ handleClose();
+ } catch (error) {
+ enqueueErrorSnackBar({
+ apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,
+ });
+ }
+ };
+
+ return (
+ <ModalStatefulWrapper
+ modalInstanceId={modalInstanceId}
+ onClose={handleClose}
+ isClosable
+ size="medium"
+ padding="large"
+ overlay="dark"
+ width="360px"
+ dataGloballyPreventClickOutside
+ renderInDocumentBody
+ smallBorderRadius
+ autoHeight
+ >
+ <StyledCenteredTitle>
+ <H1Title
+ title={t`Grant credits`}
+ fontColor={H1TitleFontColor.Primary}
+ />
+ </StyledCenteredTitle>
+ <StyledSectionContainer>
+ <Section
+ alignment={SectionAlignment.Center}
+ fontColor={SectionFontColor.Primary}
+ >
+ {t`Credits are added on top of the plan allowance and expire at the end of the current billing period. Unused granted credits carry over in full.`}
+ </Section>
+ </StyledSectionContainer>
+
+ <StyledFields>
+ <SettingsTextInput
+ instanceId={`${modalInstanceId}-amount`}
+ label={t`Amount`}
+ placeholder="200"
+ type="number"
+ min={0}
+ leftAdornment="$"
+ value={amount}
+ onChange={setAmount}
+ autoFocusOnMount
+ fullWidth
+ />
+
+ <Select
+ dropdownId={`${modalInstanceId}-type`}
+ label={t`Type`}
+ value={type}
+ options={GRANTABLE_CREDIT_GRANT_TYPES.map((grantType) => ({
+ value: grantType,
+ label: t(CREDIT_GRANT_TYPE_LABELS[grantType]),
+ }))}
+ onChange={setType}
+ fullWidth
+ />
+
+ <SettingsTextInput
+ instanceId={`${modalInstanceId}-reason`}
+ label={t`Reason`}
+ placeholder={t`Goodwill gesture after the March incident`}
+ value={reason}
+ onChange={setReason}
+ maxLength={500}
+ fullWidth
+ />
+ </StyledFields>
+
+ <StyledModalActions>
+ <Button
+ onClick={handleClose}
+ variant="secondary"
+ title={t`Cancel`}
+ fullWidth
+ justify="center"
+ />
+ <Button
+ onClick={handleSubmit}
+ variant="primary"
+ accent="blue"
+ title={t`Grant`}
+ disabled={!isAmountValid || loading}
+ fullWidth
+ justify="center"
+ />
+ </StyledModalActions>
+ </ModalStatefulWrapper>
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantRowDropdownMenu.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantRowDropdownMenu.tsx
new file mode 100644
index 00000000000..418f583957e
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantRowDropdownMenu.tsx
@@ -0,0 +1,48 @@
+import { t } from '@lingui/core/macro';
+import { IconDotsVertical, IconTrash } from 'twenty-ui/icon';
+import { LightIconButton } from 'twenty-ui/input';
+import { MenuItem } from 'twenty-ui/navigation';
+
+import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';
+import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';
+import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/DropdownMenuItemsContainer';
+import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
+
+type SettingsAdminWorkspaceCreditGrantRowDropdownMenuProps = {
+ creditGrantId: string;
+ onRevoke: () => void;
+};
+
+export const SettingsAdminWorkspaceCreditGrantRowDropdownMenu = ({
+ creditGrantId,
+ onRevoke,
+}: SettingsAdminWorkspaceCreditGrantRowDropdownMenuProps) => {
+ const dropdownId = `settings-admin-credit-grant-row-${creditGrantId}`;
+
+ const { closeDropdown } = useCloseDropdown();
+
+ return (
+ <Dropdown
+ dropdownId={dropdownId}
+ dropdownPlacement="right-start"
+ clickableComponent={
+ <LightIconButton Icon={IconDotsVertical} accent="tertiary" />
+ }
+ dropdownComponents={
+ <DropdownContent>
+ <DropdownMenuItemsContainer>
+ <MenuItem
+ accent="danger"
+ LeftIcon={IconTrash}
+ text={t`Revoke`}
+ onClick={() => {
+ onRevoke();
+ closeDropdown(dropdownId);
+ }}
+ />
+ </DropdownMenuItemsContainer>
+ </DropdownContent>
+ }
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantsTable.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantsTable.tsx
new file mode 100644
index 00000000000..efad1722b7c
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantsTable.tsx
@@ -0,0 +1,186 @@
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+import { useMutation } from '@apollo/client/react';
+import { type MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+import { useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { Tag } from 'twenty-ui/data-display';
+import { OverflowingTextWithTooltip } from 'twenty-ui/surfaces';
+import { type ThemeColor } from 'twenty-ui/theme';
+
+import { useApolloAdminClient } from '@/settings/admin-panel/apollo/hooks/useApolloAdminClient';
+import { SettingsAdminWorkspaceCreditGrantRowDropdownMenu } from '@/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantRowDropdownMenu';
+import { CREDIT_GRANT_TYPE_COLORS } from '@/settings/admin-panel/constants/CreditGrantTypeColors';
+import { CREDIT_GRANT_TYPE_LABELS } from '@/settings/admin-panel/constants/CreditGrantTypeLabels';
+import { REVOKE_WORKSPACE_CREDIT_GRANT } from '@/settings/admin-panel/graphql/mutations/revokeWorkspaceCreditGrant';
+import { GET_WORKSPACE_BILLING_ADMIN_PANEL } from '@/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel';
+import { SettingsTableListSection } from '@/settings/components/SettingsTableListSection';
+import { useNumberFormat } from '@/localization/hooks/useNumberFormat';
+import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
+import { ConfirmationModal } from '@/ui/layout/modal/components/ConfirmationModal';
+import { useModal } from '@/ui/layout/modal/hooks/useModal';
+import { beautifyExactDate } from '~/utils/date-utils';
+import { type WorkspaceBillingAdminPanelQuery } from '~/generated-admin/graphql';
+
+type CreditGrant = NonNullable<
+ WorkspaceBillingAdminPanelQuery['workspaceBillingAdminPanel']
+>['creditGrants'][number];
+
+type SettingsAdminWorkspaceCreditGrantsTableProps = {
+ workspaceId: string;
+ creditGrants: CreditGrant[];
+ onGrantCreditsClick: () => void;
+};
+
+// Every row is its own grid, so a fr track is sized by that row's own content
+// and a wide tag pushes the columns after it out of line with the rows above.
+// Fixed widths for all but the reason, which takes what is left because its
+// cell hides the overflow.
+const CREDIT_GRANTS_GRID_AUTO_COLUMNS = '88px 152px 96px 112px 1fr 36px';
+const REVOKE_CREDIT_GRANT_MODAL_ID = 'revoke-credit-grant-modal';
+const EM_DASH = '—';
+
+const getStatus = (
+ creditGrant: CreditGrant,
+): { label: MessageDescriptor; color: ThemeColor } => {
+ if (isDefined(creditGrant.revokedAt)) {
+ return { label: msg`Revoked`, color: 'red' };
+ }
+
+ if (creditGrant.isActive) {
+ return { label: msg`Active`, color: 'green' };
+ }
+
+ return { label: msg`Expired`, color: 'gray' };
+};
+
+export const SettingsAdminWorkspaceCreditGrantsTable = ({
+ workspaceId,
+ creditGrants,
+ onGrantCreditsClick,
+}: SettingsAdminWorkspaceCreditGrantsTableProps) => {
+ const { t } = useLingui();
+ const { formatNumber } = useNumberFormat();
+ const { enqueueErrorSnackBar, enqueueSuccessSnackBar } = useSnackBar();
+ const apolloAdminClient = useApolloAdminClient();
+ const { openModal } = useModal();
+
+ const [grantPendingRevocation, setGrantPendingRevocation] =
+ useState<CreditGrant | null>(null);
+ const [isRevoking, setIsRevoking] = useState(false);
+
+ const [revokeWorkspaceCreditGrant] = useMutation(
+ REVOKE_WORKSPACE_CREDIT_GRANT,
+ {
+ client: apolloAdminClient,
+ refetchQueries: [GET_WORKSPACE_BILLING_ADMIN_PANEL],
+ },
+ );
+
+ const formatCredits = (credits: number): string =>
+ formatNumber(credits, { decimals: 2 });
+
+ const handleRevokeClick = (creditGrant: CreditGrant) => {
+ setGrantPendingRevocation(creditGrant);
+ openModal(REVOKE_CREDIT_GRANT_MODAL_ID);
+ };
+
+ const handleRevoke = async (creditGrantId: string) => {
+ // The refetch that clears the row lands well after the mutation resolves,
+ // so without this the button stays live and a second click revokes an
+ // already revoked grant.
+ setIsRevoking(true);
+
+ try {
+ await revokeWorkspaceCreditGrant({
+ variables: { workspaceId, creditGrantId },
+ });
+
+ enqueueSuccessSnackBar({ message: t`Credit grant revoked.` });
+ } catch (error) {
+ enqueueErrorSnackBar({
+ apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,
+ });
+ } finally {
+ setIsRevoking(false);
+ setGrantPendingRevocation(null);
+ }
+ };
+
+ return (
+ <>
+ <SettingsTableListSection<CreditGrant>
+ title={t`Granted credits`}
+ description={t`Credits handed out on top of the plan allowance`}
+ items={creditGrants}
+ columns={[
+ {
+ label: t`Amount`,
+ Cell: ({ item }) => <>{formatCredits(item.amount)}</>,
+ },
+ {
+ label: t`Type`,
+ Cell: ({ item }) => (
+ <Tag
+ color={CREDIT_GRANT_TYPE_COLORS[item.type]}
+ text={t(CREDIT_GRANT_TYPE_LABELS[item.type])}
+ />
+ ),
+ },
+ {
+ label: t`Status`,
+ Cell: ({ item }) => {
+ const status = getStatus(item);
+
+ return <Tag color={status.color} text={t(status.label)} />;
+ },
+ },
+ {
+ label: t`Expires`,
+ Cell: ({ item }) => <>{beautifyExactDate(item.expiresAt)}</>,
+ },
+ {
+ label: t`Reason`,
+ overflow: 'hidden',
+ Cell: ({ item }) => (
+ <OverflowingTextWithTooltip text={item.reason ?? EM_DASH} />
+ ),
+ },
+ {
+ label: '',
+ align: 'right',
+ Cell: ({ item }) =>
+ item.isActive ? (
+ <SettingsAdminWorkspaceCreditGrantRowDropdownMenu
+ creditGrantId={item.id}
+ onRevoke={() => handleRevokeClick(item)}
+ />
+ ) : null,
+ },
+ ]}
+ gridAutoColumns={CREDIT_GRANTS_GRID_AUTO_COLUMNS}
+ footerButtonLabel={t`Grant credits`}
+ onFooterButtonClick={onGrantCreditsClick}
+ />
+
+ <ConfirmationModal
+ modalInstanceId={REVOKE_CREDIT_GRANT_MODAL_ID}
+ title={t`Revoke credit grant`}
+ subtitle={
+ isDefined(grantPendingRevocation)
+ ? t`This takes ${formatCredits(grantPendingRevocation.amount)} credits back off this workspace straight away. Revoking cannot be undone.`
+ : ''
+ }
+ confirmButtonText={t`Revoke`}
+ loading={isRevoking}
+ onConfirmClick={() => {
+ if (isDefined(grantPendingRevocation)) {
+ handleRevoke(grantPendingRevocation.id);
+ }
+ }}
+ onClose={() => setGrantPendingRevocation(null)}
+ />
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeColors.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeColors.ts
new file mode 100644
index 00000000000..c18b7b88e7c
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeColors.ts
@@ -0,0 +1,13 @@
+import { type ThemeColor } from 'twenty-ui/theme';
+
+import { BillingCreditGrantType } from '~/generated-admin/graphql';
+
+export const CREDIT_GRANT_TYPE_COLORS: Record<
+ BillingCreditGrantType,
+ ThemeColor
+> = {
+ [BillingCreditGrantType.COMPENSATION]: 'orange',
+ [BillingCreditGrantType.SALES]: 'purple',
+ [BillingCreditGrantType.ONBOARDING_REWARD]: 'blue',
+ [BillingCreditGrantType.ROLLOVER]: 'green',
+};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeLabels.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeLabels.ts
new file mode 100644
index 00000000000..8b823d76afc
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantTypeLabels.ts
@@ -0,0 +1,14 @@
+import { type MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+
+import { BillingCreditGrantType } from '~/generated-admin/graphql';
+
+export const CREDIT_GRANT_TYPE_LABELS: Record<
+ BillingCreditGrantType,
+ MessageDescriptor
+> = {
+ [BillingCreditGrantType.COMPENSATION]: msg`Compensation`,
+ [BillingCreditGrantType.SALES]: msg`Sales`,
+ [BillingCreditGrantType.ONBOARDING_REWARD]: msg`Onboarding reward`,
+ [BillingCreditGrantType.ROLLOVER]: msg`Rollover`,
+};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.ts
new file mode 100644
index 00000000000..3c2346456e1
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/GrantableCreditGrantTypes.ts
@@ -0,0 +1,9 @@
+import { BillingCreditGrantType } from '~/generated-admin/graphql';
+
+// Rollover grants are written by the period transition and onboarding rewards
+// by the onboarding jobs, so neither can be written by hand. The server
+// enforces this too, in ADMIN_GRANTABLE_CREDIT_GRANT_TYPES.
+export const GRANTABLE_CREDIT_GRANT_TYPES: BillingCreditGrantType[] = [
+ BillingCreditGrantType.COMPENSATION,
+ BillingCreditGrantType.SALES,
+];
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/graphql/mutations/grantWorkspaceCredits.ts b/packages/twenty-front/src/modules/settings/admin-panel/graphql/mutations/grantWorkspaceCredits.ts
new file mode 100644
index 00000000000..9a89903423e
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/graphql/mutations/grantWorkspaceCredits.ts
@@ -0,0 +1,29 @@
+import { gql } from '@apollo/client';
+
+export const GRANT_WORKSPACE_CREDITS = gql`
+ mutation GrantWorkspaceCredits(
+ $workspaceId: UUID!
+ $amount: Float!
+ $type: BillingCreditGrantType!
+ $reason: String
+ $clientOperationId: UUID!
+ ) {
+ grantWorkspaceCredits(
+ workspaceId: $workspaceId
+ amount: $amount
+ type: $type
+ reason: $reason
+ clientOperationId: $clientOperationId
+ ) {
+ id
+ amount
+ type
+ effectiveAt
+ expiresAt
+ revokedAt
+ reason
+ isActive
+ createdAt
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/graphql/mutations/revokeWorkspaceCreditGrant.ts b/packages/twenty-front/src/modules/settings/admin-panel/graphql/mutations/revokeWorkspaceCreditGrant.ts
new file mode 100644
index 00000000000..ba866a5a669
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/graphql/mutations/revokeWorkspaceCreditGrant.ts
@@ -0,0 +1,23 @@
+import { gql } from '@apollo/client';
+
+export const REVOKE_WORKSPACE_CREDIT_GRANT = gql`
+ mutation RevokeWorkspaceCreditGrant(
+ $workspaceId: UUID!
+ $creditGrantId: UUID!
+ ) {
+ revokeWorkspaceCreditGrant(
+ workspaceId: $workspaceId
+ creditGrantId: $creditGrantId
+ ) {
+ id
+ amount
+ type
+ effectiveAt
+ expiresAt
+ revokedAt
+ reason
+ isActive
+ createdAt
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel.ts b/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel.ts
index 12cf5d90b30..1d89e4102fb 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/getWorkspaceBillingAdminPanel.ts
@@ -5,6 +5,17 @@ export const GET_WORKSPACE_BILLING_ADMIN_PANEL = gql`
workspaceBillingAdminPanel(workspaceId: $workspaceId) {
stripeCustomerId
creditBalance
+ creditGrants {
+ id
+ amount
+ type
+ effectiveAt
+ expiresAt
+ revokedAt
+ reason
+ isActive
+ createdAt
+ }
usage {
periodStart
periodEnd
diff --git a/packages/twenty-front/src/modules/settings/components/SettingsTableListSection.tsx b/packages/twenty-front/src/modules/settings/components/SettingsTableListSection.tsx
index 3fd3c310d9c..774ce1a744e 100644
--- a/packages/twenty-front/src/modules/settings/components/SettingsTableListSection.tsx
+++ b/packages/twenty-front/src/modules/settings/components/SettingsTableListSection.tsx
@@ -45,6 +45,7 @@ const HEADER_PADDING = `0 ${themeCssVariables.spacing[2]} 0 ${themeCssVariables.
export type SettingsTableListSectionColumn<Item> = {
label: string;
align?: 'left' | 'right';
+ overflow?: string;
Cell: ComponentType<{ item: Item }>;
};
@@ -111,7 +112,11 @@ export const SettingsTableListSection = <
onClick={onRowClick ? () => onRowClick(item) : undefined}
>
{columns.map((column) => (
- <TableCell key={column.label} align={column.align}>
+ <TableCell
+ key={column.label}
+ align={column.align}
+ overflow={column.overflow}
+ >
<column.Cell item={item} />
</TableCell>
))}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-31/2-31-instance-command-fast-1786532184000-create-billing-credit-grant-table.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-31/2-31-instance-command-fast-1786532184000-create-billing-credit-grant-table.ts
new file mode 100644
index 00000000000..1bc29beabcf
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-31/2-31-instance-command-fast-1786532184000-create-billing-credit-grant-table.ts
@@ -0,0 +1,83 @@
+import { QueryRunner } from 'typeorm';
+
+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';
+
+// Creates core."billingCreditGrant" backing BillingCreditGrantEntity.
+// Constraint names reproduce the ones TypeORM generated for this entity so the
+// entity and the table stay in sync. Trimmed from the output of
+// npx nx run twenty-server:database:migrate:generate --name create-billing-credit-grant-table --type fast
+// which also reported pre-existing drift on other billing tables, left alone
+// here on purpose.
+@RegisteredInstanceCommand('2.31.0', 1786532184000)
+export class CreateBillingCreditGrantTableFastInstanceCommand
+ implements FastInstanceCommand
+{
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ // Billing entities only exist when billing is enabled, so an instance
+ // without billing must not grow a billing table its entity set has no
+ // counterpart for.
+ const isBillingSchemaPresent = await queryRunner.query(
+ `SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = 'billingCustomer'`,
+ );
+
+ if (isBillingSchemaPresent.length === 0) {
+ return;
+ }
+
+ await queryRunner.query(
+ `DO $$ BEGIN CREATE TYPE "core"."billingCreditGrant_type_enum" AS ENUM ('ROLLOVER', 'ONBOARDING_REWARD', 'COMPENSATION', 'SALES'); EXCEPTION WHEN duplicate_object THEN null; END $$`,
+ );
+
+ // An instance that ran a pre-release build of this command has the type
+ // already, so the create above is swallowed and its value set is whatever
+ // that build declared. Reconcile rather than leave a value the entity can
+ // write but the type does not accept.
+ await queryRunner.query(
+ `ALTER TYPE "core"."billingCreditGrant_type_enum" ADD VALUE IF NOT EXISTS 'SALES'`,
+ );
+
+ await queryRunner.query(
+ `CREATE TABLE IF NOT EXISTS "core"."billingCreditGrant" (
+ "id" uuid NOT NULL DEFAULT uuid_generate_v4(),
+ "workspaceId" uuid NOT NULL,
+ "amountMicro" bigint NOT NULL,
+ "type" "core"."billingCreditGrant_type_enum" NOT NULL,
+ "effectiveAt" TIMESTAMP WITH TIME ZONE NOT NULL,
+ "expiresAt" TIMESTAMP WITH TIME ZONE NOT NULL,
+ "revokedAt" TIMESTAMP WITH TIME ZONE,
+ "revokedByUserId" uuid,
+ "grantedByUserId" uuid,
+ "reason" character varying(500),
+ "idempotencyKey" character varying,
+ "sourceGrantId" uuid,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ CONSTRAINT "PK_eef2376084c6ef14cf8a6ffb3c4" PRIMARY KEY ("id"),
+ CONSTRAINT "FK_e516eeab5b1dda05b823f235041" FOREIGN KEY ("workspaceId") REFERENCES "core"."workspace"("id") ON DELETE CASCADE ON UPDATE NO ACTION
+ )`,
+ );
+
+ // Nulls never conflict in a Postgres unique index, so grants without an
+ // idempotency key are unconstrained.
+ await queryRunner.query(
+ `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_BILLING_CREDIT_GRANT_IDEMPOTENCY_KEY_UNIQUE"
+ ON "core"."billingCreditGrant" ("idempotencyKey")`,
+ );
+
+ await queryRunner.query(
+ `CREATE INDEX IF NOT EXISTS "IDX_BILLING_CREDIT_GRANT_WORKSPACE_ID_EXPIRES_AT"
+ ON "core"."billingCreditGrant" ("workspaceId", "expiresAt")`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`DROP TABLE IF EXISTS "core"."billingCreditGrant"`);
+
+ // After the table, which depends on it. Leaving it behind would make a
+ // later re-run reuse the old value set rather than create the current one.
+ await queryRunner.query(
+ `DROP TYPE IF EXISTS "core"."billingCreditGrant_type_enum"`,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-31/2-31-instance-command-fast-1786532184002-add-previous-period-start-to-billing-subscription.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-31/2-31-instance-command-fast-1786532184002-add-previous-period-start-to-billing-subscription.ts
new file mode 100644
index 00000000000..194674ad2ed
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-31/2-31-instance-command-fast-1786532184002-add-previous-period-start-to-billing-subscription.ts
@@ -0,0 +1,41 @@
+import { QueryRunner } from 'typeorm';
+
+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';
+
+// Records where the period before the current one began, which Stripe never
+// reports. Left null on existing rows: the rollover falls back to the ledger
+// and then to calendar arithmetic until each subscription's next transition
+// fills it in.
+@RegisteredInstanceCommand('2.31.0', 1786532184002)
+export class AddPreviousPeriodStartToBillingSubscriptionFastInstanceCommand
+ implements FastInstanceCommand
+{
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ const isBillingSchemaPresent = await queryRunner.query(
+ `SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = 'billingSubscription'`,
+ );
+
+ if (isBillingSchemaPresent.length === 0) {
+ return;
+ }
+
+ await queryRunner.query(
+ `ALTER TABLE "core"."billingSubscription" ADD COLUMN IF NOT EXISTS "previousPeriodStart" TIMESTAMP WITH TIME ZONE`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ const isBillingSchemaPresent = await queryRunner.query(
+ `SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = 'billingSubscription'`,
+ );
+
+ if (isBillingSchemaPresent.length === 0) {
+ return;
+ }
+
+ await queryRunner.query(
+ `ALTER TABLE "core"."billingSubscription" DROP COLUMN IF EXISTS "previousPeriodStart"`,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-31/2-31-instance-command-slow-1786532184001-backfill-credit-balance-into-grants.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-31/2-31-instance-command-slow-1786532184001-backfill-credit-balance-into-grants.ts
new file mode 100644
index 00000000000..20de2fbefef
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-31/2-31-instance-command-slow-1786532184001-backfill-credit-balance-into-grants.ts
@@ -0,0 +1,88 @@
+import { DataSource, QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { SlowInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/slow-instance-command.interface';
+
+const BACKFILL_IDEMPOTENCY_KEY_PREFIX = 'backfill-credit-balance:';
+
+// Turns the single billingCustomer.creditBalanceMicro number into one grant per
+// workspace. Until this runs, BillingCreditGrantService falls back to the
+// mirror column for workspaces that have no grant yet, so credit balances stay
+// correct whether or not the upgrade was invoked with --include-slow.
+//
+// The column keeps being written as a mirror of the ledger until it is dropped
+// in a later release, so this stays reversible.
+@RegisteredInstanceCommand('2.31.0', 1786532184001, { type: 'slow' })
+export class BackfillCreditBalanceIntoGrantsSlowInstanceCommand
+ implements SlowInstanceCommand
+{
+ async runDataMigration(dataSource: DataSource): Promise<void> {
+ const presentTables = await dataSource.query(
+ `SELECT tablename FROM pg_tables
+ WHERE schemaname = 'core'
+ AND tablename IN ('billingCreditGrant', 'billingCustomer', 'billingSubscription')`,
+ );
+
+ // Nothing to move on an instance without billing: neither the ledger nor
+ // the column it mirrors exists there.
+ if (presentTables.length < 3) {
+ return;
+ }
+
+ // Expiry follows the workspace's current period, but never lands in the
+ // past: a backfilled grant that expires on creation would silently delete
+ // the balance it was meant to preserve.
+ await dataSource.query(
+ `INSERT INTO "core"."billingCreditGrant" (
+ "workspaceId", "amountMicro", "type", "effectiveAt", "expiresAt", "reason", "idempotencyKey"
+ )
+ SELECT
+ "billingCustomer"."workspaceId",
+ "billingCustomer"."creditBalanceMicro",
+ 'ROLLOVER',
+ now(),
+ GREATEST(
+ COALESCE(
+ (
+ SELECT "billingSubscription"."currentPeriodEnd"
+ FROM "core"."billingSubscription"
+ WHERE "billingSubscription"."workspaceId" = "billingCustomer"."workspaceId"
+ AND "billingSubscription"."status" <> 'canceled'
+ ORDER BY "billingSubscription"."currentPeriodEnd" DESC
+ LIMIT 1
+ ),
+ now()
+ ),
+ now() + interval '1 day'
+ ),
+ 'Backfilled from billingCustomer.creditBalanceMicro',
+ $1 || "billingCustomer"."workspaceId"
+ FROM "core"."billingCustomer"
+ WHERE "billingCustomer"."creditBalanceMicro" > 0
+ ON CONFLICT ("idempotencyKey") DO NOTHING`,
+ [BACKFILL_IDEMPOTENCY_KEY_PREFIX],
+ );
+ }
+
+ public async up(_queryRunner: QueryRunner): Promise<void> {
+ return;
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ // An instance without billing never grew the table, so deleting from it
+ // unconditionally would fail the rollback on exactly the instances that
+ // had nothing to roll back.
+ const isLedgerPresent = await queryRunner.query(
+ `SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = 'billingCreditGrant'`,
+ );
+
+ if (isLedgerPresent.length === 0) {
+ return;
+ }
+
+ await queryRunner.query(
+ `DELETE FROM "core"."billingCreditGrant" WHERE "idempotencyKey" LIKE $1`,
+ [`${BACKFILL_IDEMPOTENCY_KEY_PREFIX}%`],
+ );
+ }
+}
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.ts
index 04c12ba5d33..6cad172e69f 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
@@ -140,6 +140,9 @@ import { AddMessageChannelDisplayNameFastInstanceCommand } from './2-25/2-25-ins
import { AddAppTokenSsoExchangeIndexFastInstanceCommand } from './2-25/2-25-instance-command-fast-1785143586000-add-app-token-sso-exchange-index';
import { AddMessageCampaignWidgetTypeFastInstanceCommand } from './2-25/2-25-instance-command-fast-1785229950000-add-message-campaign-widget-type';
import { AddIsHiddenToAgentMessageFastInstanceCommand } from './2-25/2-25-instance-command-fast-1785230296000-add-is-hidden-to-agent-message';
+import { CreateBillingCreditGrantTableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-31/2-31-instance-command-fast-1786532184000-create-billing-credit-grant-table';
+import { BackfillCreditBalanceIntoGrantsSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-31/2-31-instance-command-slow-1786532184001-backfill-credit-balance-into-grants';
+import { AddPreviousPeriodStartToBillingSubscriptionFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-31/2-31-instance-command-fast-1786532184002-add-previous-period-start-to-billing-subscription';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -282,4 +285,7 @@ export const INSTANCE_COMMANDS = [
AddListWidgetViewTypeFastInstanceCommand,
AddIsSystemSideEffectToViewFieldGroupFastInstanceCommand,
AddFrontComponentSharedDependenciesToApplicationFastInstanceCommand,
+ CreateBillingCreditGrantTableFastInstanceCommand,
+ BackfillCreditBalanceIntoGrantsSlowInstanceCommand,
+ AddPreviousPeriodStartToBillingSubscriptionFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
index cf9ebd009fb..a70a7e81c29 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
@@ -20,6 +20,9 @@ import { AdminPanelRecentUserDTO } from 'src/engine/core-modules/admin-panel/dto
import { PaginatedAdminChatThreadsDTO } from 'src/engine/core-modules/admin-panel/dtos/paginated-admin-chat-threads.dto';
import { AdminPanelTopWorkspaceDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-top-workspace.dto';
import { AdminPanelWorkspaceBillingDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-billing.dto';
+import { AdminPanelWorkspaceCreditGrantDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto';
+import { GrantWorkspaceCreditsInput } from 'src/engine/core-modules/admin-panel/dtos/grant-workspace-credits.input';
+import { RevokeWorkspaceCreditGrantInput } from 'src/engine/core-modules/admin-panel/dtos/revoke-workspace-credit-grant.input';
import { AdminWorkspaceChatThreadDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-workspace-chat-thread.dto';
import { ConfigVariableDTO } from 'src/engine/core-modules/admin-panel/dtos/config-variable.dto';
import { ConfigVariablesDTO } from 'src/engine/core-modules/admin-panel/dtos/config-variables.dto';
@@ -787,6 +790,35 @@ export class AdminPanelResolver {
return this.adminBillingService.getWorkspaceBilling(workspaceId);
}
+ @UseGuards(AdminPanelGuard)
+ @Mutation(() => AdminPanelWorkspaceCreditGrantDTO)
+ async grantWorkspaceCredits(
+ @Args() input: GrantWorkspaceCreditsInput,
+ @AuthUser() actor: AuthContextUser,
+ ): Promise<AdminPanelWorkspaceCreditGrantDTO> {
+ return this.adminBillingService.grantWorkspaceCredits({
+ workspaceId: input.workspaceId,
+ amount: input.amount,
+ type: input.type,
+ reason: input.reason,
+ clientOperationId: input.clientOperationId,
+ grantedByUserId: actor.id,
+ });
+ }
+
+ @UseGuards(AdminPanelGuard)
+ @Mutation(() => AdminPanelWorkspaceCreditGrantDTO)
+ async revokeWorkspaceCreditGrant(
+ @Args() input: RevokeWorkspaceCreditGrantInput,
+ @AuthUser() actor: AuthContextUser,
+ ): Promise<AdminPanelWorkspaceCreditGrantDTO> {
+ return this.adminBillingService.revokeWorkspaceCreditGrant({
+ workspaceId: input.workspaceId,
+ creditGrantId: input.creditGrantId,
+ revokedByUserId: actor.id,
+ });
+ }
+
@UseGuards(ServerLevelImpersonateGuard)
@Query(() => [AdminWorkspaceChatThreadDTO])
async getAdminWorkspaceChatThreads(
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-billing.dto.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-billing.dto.ts
index 118fb200240..0f2d87d6229 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-billing.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-billing.dto.ts
@@ -1,5 +1,6 @@
import { Field, Float, ObjectType } from '@nestjs/graphql';
+import { AdminPanelWorkspaceCreditGrantDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto';
import { AdminPanelWorkspaceSubscriptionDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-subscription.dto';
import { AdminPanelWorkspaceUsageDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-usage.dto';
@@ -11,6 +12,9 @@ export class AdminPanelWorkspaceBillingDTO {
@Field(() => Float, { nullable: true })
creditBalance: number | null;
+ @Field(() => [AdminPanelWorkspaceCreditGrantDTO])
+ creditGrants: AdminPanelWorkspaceCreditGrantDTO[];
+
@Field(() => AdminPanelWorkspaceSubscriptionDTO, { nullable: true })
subscription: AdminPanelWorkspaceSubscriptionDTO | null;
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto.ts
new file mode 100644
index 00000000000..bc9d38b86e3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto.ts
@@ -0,0 +1,34 @@
+import { Field, Float, ObjectType } from '@nestjs/graphql';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
+
+@ObjectType('AdminPanelWorkspaceCreditGrant')
+export class AdminPanelWorkspaceCreditGrantDTO {
+ @Field(() => UUIDScalarType)
+ id: string;
+
+ @Field(() => Float)
+ amount: number;
+
+ @Field(() => BillingCreditGrantType)
+ type: BillingCreditGrantType;
+
+ @Field(() => Date)
+ effectiveAt: Date;
+
+ @Field(() => Date)
+ expiresAt: Date;
+
+ @Field(() => Date, { nullable: true })
+ revokedAt: Date | null;
+
+ @Field(() => String, { nullable: true })
+ reason: string | null;
+
+ @Field(() => Boolean)
+ isActive: boolean;
+
+ @Field(() => Date)
+ createdAt: Date;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/grant-workspace-credits.input.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/grant-workspace-credits.input.ts
new file mode 100644
index 00000000000..f36461b2475
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/grant-workspace-credits.input.ts
@@ -0,0 +1,44 @@
+import { ArgsType, Field, Float } from '@nestjs/graphql';
+
+import {
+ IsEnum,
+ IsNotEmpty,
+ IsOptional,
+ IsPositive,
+ IsString,
+ IsUUID,
+ MaxLength,
+} from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
+
+@ArgsType()
+export class GrantWorkspaceCreditsInput {
+ @Field(() => UUIDScalarType)
+ @IsNotEmpty()
+ @IsUUID()
+ workspaceId: string;
+
+ // In display credits ($1 = 1 credit), converted to micro-credits server side.
+ @Field(() => Float)
+ @IsPositive()
+ amount: number;
+
+ @Field(() => BillingCreditGrantType)
+ @IsEnum(BillingCreditGrantType)
+ type: BillingCreditGrantType;
+
+ @Field(() => String, { nullable: true })
+ @IsOptional()
+ @IsString()
+ @MaxLength(500)
+ reason?: string;
+
+ // Identifies one intended grant, so a retried mutation returns the grant the
+ // first attempt wrote instead of handing out the credits a second time.
+ @Field(() => UUIDScalarType)
+ @IsNotEmpty()
+ @IsUUID()
+ clientOperationId: string;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/revoke-workspace-credit-grant.input.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/revoke-workspace-credit-grant.input.ts
new file mode 100644
index 00000000000..6df572922fc
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/revoke-workspace-credit-grant.input.ts
@@ -0,0 +1,18 @@
+import { ArgsType, Field } from '@nestjs/graphql';
+
+import { IsNotEmpty, IsUUID } from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@ArgsType()
+export class RevokeWorkspaceCreditGrantInput {
+ @Field(() => UUIDScalarType)
+ @IsNotEmpty()
+ @IsUUID()
+ workspaceId: string;
+
+ @Field(() => UUIDScalarType)
+ @IsNotEmpty()
+ @IsUUID()
+ creditGrantId: string;
+}
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.ts
index 49d57817b18..20109995ebf 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
@@ -1,22 +1,36 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
+import { isDefined } from 'twenty-shared/utils';
import { In, type Repository } from 'typeorm';
import { AdminPanelWorkspaceBillingDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-billing.dto';
+import { type AdminPanelWorkspaceCreditGrantDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-credit-grant.dto';
import { type AdminPanelWorkspaceUsageDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-usage.dto';
+import {
+ BillingException,
+ BillingExceptionCode,
+} from 'src/engine/core-modules/billing/billing.exception';
+import { type 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 { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/billing-price.entity';
+import {
+ ADMIN_GRANTABLE_CREDIT_GRANT_TYPES,
+ type BillingCreditGrantType,
+} from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';
+import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
+import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
+import {
+ INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
+ toDisplayCredits,
+} from 'src/engine/core-modules/usage/utils/to-display-credits.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
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';
-const CREDIT_BALANCE_MICRO_UNIT = 1_000_000;
-
const KNOWN_PLAN_KEYS: ReadonlySet<string> = new Set(
Object.values(BillingPlanKey),
);
@@ -34,9 +48,136 @@ export class AdminPanelBillingService {
private readonly workspaceRepository: Repository<WorkspaceEntity>,
private readonly billingSubscriptionService: BillingSubscriptionService,
private readonly billingUsageService: BillingUsageService,
+ private readonly billingCreditService: BillingCreditService,
+ private readonly billingCreditGrantService: BillingCreditGrantService,
private readonly twentyConfigService: TwentyConfigService,
) {}
+ async grantWorkspaceCredits({
+ workspaceId,
+ amount,
+ type,
+ reason,
+ clientOperationId,
+ grantedByUserId,
+ }: {
+ workspaceId: string;
+ amount: number;
+ type: BillingCreditGrantType;
+ reason?: string;
+ clientOperationId: string;
+ grantedByUserId: string;
+ }): Promise<AdminPanelWorkspaceCreditGrantDTO> {
+ // Enforced server side because the mutation is reachable directly, not only
+ // through the admin panel's picker. See ADMIN_GRANTABLE_CREDIT_GRANT_TYPES
+ // for why these two are excluded.
+ if (!ADMIN_GRANTABLE_CREDIT_GRANT_TYPES.includes(type)) {
+ throw new BillingException(
+ `Cannot grant credits of type ${type} by hand`,
+ BillingExceptionCode.BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE,
+ );
+ }
+
+ const amountMicro = Math.round(
+ amount * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
+ );
+
+ const maxAmountMicro = this.twentyConfigService.get(
+ 'BILLING_MAX_ADMIN_CREDIT_GRANT_MICRO',
+ );
+
+ // The field is micro-denominated, so a slipped decimal is four orders of
+ // magnitude. Bound what a single grant can hand out.
+ if (amountMicro > maxAmountMicro) {
+ throw new BillingException(
+ `Cannot grant ${toDisplayCredits(amountMicro)} credits at once, the maximum is ${toDisplayCredits(maxAmountMicro)}`,
+ BillingExceptionCode.BILLING_CREDIT_AMOUNT_INVALID,
+ );
+ }
+
+ const idempotencyKey = buildAdminGrantIdempotencyKey(clientOperationId);
+
+ const grant = await this.billingCreditService.grantCredits({
+ workspaceId,
+ amountMicro,
+ type,
+ reason,
+ idempotencyKey,
+ grantedByUserId,
+ });
+
+ if (isDefined(grant)) {
+ return this.toCreditGrantDTO(grant);
+ }
+
+ // A null grant is either a replay of this same operation, which must answer
+ // with the grant the first attempt wrote rather than hand out the credits
+ // again, or an instance without billing. The ledger table only exists in
+ // the first case, so it is only queried there.
+ const replayedGrant = this.twentyConfigService.get('IS_BILLING_ENABLED')
+ ? await this.billingCreditGrantService.findGrantByIdempotencyKey(
+ workspaceId,
+ idempotencyKey,
+ )
+ : null;
+
+ if (!isDefined(replayedGrant)) {
+ throw new BillingException(
+ `Could not grant credits to workspace ${workspaceId}, billing is disabled on this instance`,
+ BillingExceptionCode.BILLING_CUSTOMER_NOT_FOUND,
+ );
+ }
+
+ return this.toCreditGrantDTO(replayedGrant);
+ }
+
+ async revokeWorkspaceCreditGrant({
+ workspaceId,
+ creditGrantId,
+ revokedByUserId,
+ }: {
+ workspaceId: string;
+ creditGrantId: string;
+ revokedByUserId: string;
+ }): Promise<AdminPanelWorkspaceCreditGrantDTO> {
+ const grant = await this.billingCreditService.revokeGrant({
+ workspaceId,
+ grantId: creditGrantId,
+ revokedByUserId,
+ });
+
+ return this.toCreditGrantDTO(grant);
+ }
+
+ private async getWorkspaceCreditGrants(
+ workspaceId: string,
+ ): Promise<AdminPanelWorkspaceCreditGrantDTO[]> {
+ const grants = await this.billingCreditGrantService.listGrants(workspaceId);
+
+ return grants.map((grant) => this.toCreditGrantDTO(grant));
+ }
+
+ private toCreditGrantDTO(
+ grant: BillingCreditGrantEntity,
+ ): AdminPanelWorkspaceCreditGrantDTO {
+ const now = Date.now();
+
+ return {
+ id: grant.id,
+ amount: toDisplayCredits(grant.amountMicro),
+ type: grant.type,
+ effectiveAt: grant.effectiveAt,
+ expiresAt: grant.expiresAt,
+ revokedAt: grant.revokedAt,
+ reason: grant.reason,
+ isActive:
+ !isDefined(grant.revokedAt) &&
+ grant.effectiveAt.getTime() <= now &&
+ grant.expiresAt.getTime() > now,
+ createdAt: grant.createdAt,
+ };
+ }
+
async getWorkspaceBilling(
workspaceId: string,
): Promise<AdminPanelWorkspaceBillingDTO | null> {
@@ -44,27 +185,33 @@ export class AdminPanelBillingService {
return null;
}
- const [customer, subscription] = await Promise.all([
+ const [customer, subscription, creditGrants] = await Promise.all([
this.billingCustomerRepository.findOne(workspaceId, { where: {} }),
this.billingSubscriptionService.getCurrentBillingSubscription({
workspaceId,
}),
+ this.getWorkspaceCreditGrants(workspaceId),
]);
- if (!customer && !subscription) {
+ // A workspace can hold granted credits before it has a customer or a
+ // subscription, and the admin panel still has to show and manage them.
+ if (!customer && !subscription && creditGrants.length === 0) {
return null;
}
const stripeCustomerId =
customer?.stripeCustomerId ?? subscription?.stripeCustomerId ?? null;
- const creditBalance = customer
- ? customer.creditBalanceMicro / CREDIT_BALANCE_MICRO_UNIT
- : null;
+ const creditBalance = toDisplayCredits(
+ await this.billingCreditGrantService.getSpendableCreditsMicro(
+ workspaceId,
+ ),
+ );
if (!subscription) {
return {
stripeCustomerId,
creditBalance,
+ creditGrants,
subscription: null,
usage: null,
};
@@ -92,6 +239,7 @@ export class AdminPanelBillingService {
return {
stripeCustomerId,
creditBalance,
+ creditGrants,
usage,
subscription: {
stripeSubscriptionId: subscription.stripeSubscriptionId,
@@ -170,3 +318,8 @@ export class AdminPanelBillingService {
}
}
}
+
+// Namespaced so an operation id can never collide with the carry-forward or
+// backfill keys, which live in the same unique index.
+const buildAdminGrantIdempotencyKey = (clientOperationId: string): string =>
+ `admin-grant:${clientOperationId}`;
diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.spec.ts
index cc87a765435..ea62d3b1462 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.spec.ts
@@ -118,7 +118,7 @@ const createSignInUpServiceForTests = () => {
}),
} as any,
{
- creditWorkspaceBalance: jest.fn(),
+ grantCredits: jest.fn(),
} as any,
{
isBillingEnabled: jest.fn(),
diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
index d312c2f8e5c..c0c406ec516 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/services/sign-in-up.service.ts
@@ -24,6 +24,7 @@ import {
AppTokenType,
} from 'src/engine/core-modules/app-token/app-token.entity';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
import {
@@ -245,11 +246,14 @@ export class SignInUpService {
params.userData.type === 'newUserWithPicture'
) {
try {
- await this.billingCreditService.creditWorkspaceBalance({
+ await this.billingCreditService.grantCredits({
workspaceId: invitationValidation.workspace.id,
amountMicro: this.twentyConfigService.get(
'ONBOARDING_INVITE_TEAM_CREDITS_REWARD_PER_USER',
),
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ reason: 'Onboarding reward: invited teammate signed up',
+ idempotencyKey: `onboarding-invite-team:${invitationValidation.workspace.id}:${updatedUser.id}`,
});
} catch (error) {
this.logger.error(
diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/__tests__/billing-webhook-subscription.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/__tests__/billing-webhook-subscription.service.spec.ts
index 46c2c67af47..2546e0486fa 100644
--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/__tests__/billing-webhook-subscription.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/__tests__/billing-webhook-subscription.service.spec.ts
@@ -12,6 +12,7 @@ import { BillingWebhookSubscriptionService } from 'src/engine/core-modules/billi
import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';
import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
+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';
@@ -93,6 +94,8 @@ describe('BillingWebhookSubscriptionService', () => {
id: 'billing-subscription-id',
stripeSubscriptionId:
mockStripeSubscriptionUpdatedEventWithoutUpdatedItem.data.object.id,
+ currentPeriodStart: new Date('2026-01-01T00:00:00.000Z'),
+ previousPeriodStart: null,
}),
};
@@ -128,6 +131,12 @@ describe('BillingWebhookSubscriptionService', () => {
provide: StripeSubscriptionScheduleService,
useValue: stripeSubscriptionScheduleService,
},
+ {
+ provide: BillingCreditService,
+ useValue: {
+ reconcileMirroredBalance: jest.fn().mockResolvedValue(undefined),
+ },
+ },
{
provide: BillingUsageCacheService,
useValue: { flushAvailableCredits: jest.fn() },
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.ts
index 5e59353b1e1..69768c70c12 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,6 +13,7 @@ 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';
@@ -28,6 +29,7 @@ export class BillingWebhookCustomerService {
@InjectRepository(BillingCustomerEntity)
private readonly billingCustomerRepositoryUnscoped: Repository<BillingCustomerEntity>,
private readonly stripeCustomerService: StripeCustomerService,
+ private readonly billingCreditService: BillingCreditService,
) {}
async processStripeEvent(
@@ -69,6 +71,11 @@ 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-invoice.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts
index d4054b8b7a5..044735dcd3a 100644
--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts
@@ -18,10 +18,13 @@ import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/
import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';
import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
import { BillingWebhookEvent } from 'src/engine/core-modules/billing/enums/billing-webhook-events.enum';
+import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
import { BillingCreditRolloverService } from 'src/engine/core-modules/billing/services/billing-credit-rollover.service';
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
+import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { ResourceCreditService } from 'src/engine/core-modules/billing/services/resource-credit.service';
import { StripeInvoiceService } from 'src/engine/core-modules/billing/stripe/services/stripe-invoice.service';
+import { deriveBillingPeriodTransition } from 'src/engine/core-modules/billing/utils/derive-billing-period-transition.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
const SUBSCRIPTION_CYCLE_BILLING_REASON = 'subscription_cycle';
@@ -40,7 +43,9 @@ export class BillingWebhookInvoiceService {
@InjectRepository(WorkspaceEntity)
private readonly workspaceRepository: Repository<WorkspaceEntity>,
private readonly billingSubscriptionService: BillingSubscriptionService,
+ private readonly billingCreditGrantService: BillingCreditGrantService,
private readonly billingCreditRolloverService: BillingCreditRolloverService,
+ private readonly billingUsageService: BillingUsageService,
private readonly resourceCreditService: ResourceCreditService,
private readonly stripeInvoiceService: StripeInvoiceService,
private readonly eventLogEmitterService: EventLogEmitterService,
@@ -87,7 +92,7 @@ export class BillingWebhookInvoiceService {
{ hasReachedCurrentPeriodCap: false },
);
- if (!isDefined(stripeCustomerId) || !periodEnd) {
+ if (!isDefined(stripeCustomerId) || !periodEnd || !periodStart) {
return;
}
@@ -108,18 +113,27 @@ export class BillingWebhookInvoiceService {
const isFirstPeriodAfterTrial =
isDefined(trialEnd) &&
- isDefined(periodStart) &&
Math.abs(periodStart - trialEnd) <= TRIAL_END_TOLERANCE_SECONDS;
- if (periodStart && !isFirstPeriodAfterTrial) {
- await this.processRollover(subscription, new Date(periodStart * 1000));
- }
+ await this.processRollover({
+ subscription,
+ invoicePeriodStart: new Date(periodStart * 1000),
+ invoicePeriodEnd: new Date(periodEnd * 1000),
+ isFirstPeriodAfterTrial,
+ });
}
- private async processRollover(
- subscription: BillingSubscriptionEntity,
- invoicedPeriodStart: Date,
- ): Promise<void> {
+ private async processRollover({
+ subscription,
+ invoicePeriodStart,
+ invoicePeriodEnd,
+ isFirstPeriodAfterTrial,
+ }: {
+ subscription: BillingSubscriptionEntity;
+ invoicePeriodStart: Date;
+ invoicePeriodEnd: Date;
+ isFirstPeriodAfterTrial: boolean;
+ }): Promise<void> {
const params =
await this.resourceCreditService.getResourceCreditRolloverParameters(
subscription.workspaceId,
@@ -130,11 +144,46 @@ export class BillingWebhookInvoiceService {
return;
}
+ // Only needed while subscriptions that predate previousPeriodStart are
+ // still transitioning for the first time.
+ const ledgerPeriodStart =
+ await this.billingCreditGrantService.findPeriodStartBefore({
+ workspaceId: subscription.workspaceId,
+ boundary: invoicePeriodStart,
+ });
+
+ const {
+ closingPeriodStart,
+ closingPeriodEnd,
+ nextPeriodStart,
+ nextPeriodEnd,
+ } = deriveBillingPeriodTransition({
+ invoicePeriodStart,
+ invoicePeriodEnd,
+ subscriptionCurrentPeriodStart: subscription.currentPeriodStart,
+ subscriptionCurrentPeriodEnd: subscription.currentPeriodEnd,
+ subscriptionInterval: subscription.interval,
+ trialStart: subscription.trialStart,
+ isFirstPeriodAfterTrial,
+ subscriptionPreviousPeriodStart: subscription.previousPeriodStart,
+ ledgerPeriodStart,
+ });
+
+ // Credits earned during the trial follow the workspace into its first paid
+ // period, so the trial closes like any other period. Its allowance comes
+ // from config rather than the price, which only applies once paid.
+ const closingAllowanceMicro = isFirstPeriodAfterTrial
+ ? this.billingUsageService.getTrialResourceUsageCap(subscription)
+ : params.tierQuantity;
+
await this.billingCreditRolloverService.processRolloverOnPeriodTransition({
workspaceId: subscription.workspaceId,
- stripeCustomerId: subscription.stripeCustomerId,
- tierQuantity: params.tierQuantity,
- previousPeriodStart: invoicedPeriodStart,
+ closingPeriodStart,
+ closingPeriodEnd,
+ closingAllowanceMicro,
+ nextPeriodStart,
+ nextPeriodEnd,
+ nextAllowanceMicro: params.tierQuantity,
});
}
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.ts
index cd05a3aee70..221a229711a 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,10 +24,12 @@ import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/e
import { 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';
import { type SubscriptionWithSchedule } from 'src/engine/core-modules/billing/types/billing-subscription-with-schedule.type';
+import { resolveBillingPeriodBoundaryUpdate } from 'src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
@@ -64,6 +66,7 @@ export class BillingWebhookSubscriptionService {
private readonly workspaceService: WorkspaceService,
private readonly stripeSubscriptionScheduleService: StripeSubscriptionScheduleService,
private readonly billingUsageCacheService: BillingUsageCacheService,
+ private readonly billingCreditService: BillingCreditService,
private readonly workspaceCacheService: WorkspaceCacheService,
) {}
@@ -113,6 +116,10 @@ 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),
@@ -132,11 +139,33 @@ export class BillingWebhookSubscriptionService {
? liveCustomerSubscriptions
: [...liveCustomerSubscriptions, subscriptionWithSchedule];
- await this.billingSubscriptionRepository.upsert(
+ const incomingSubscription =
transformStripeSubscriptionEventToDatabaseSubscription(
workspaceId,
subscriptionWithSchedule,
- ),
+ );
+
+ const storedSubscription = await this.billingSubscriptionRepository.findOne(
+ {
+ where: {
+ stripeSubscriptionId: incomingSubscription.stripeSubscriptionId,
+ },
+ select: {
+ id: true,
+ currentPeriodStart: true,
+ currentPeriodEnd: true,
+ },
+ },
+ );
+
+ await this.billingSubscriptionRepository.upsert(
+ {
+ ...incomingSubscription,
+ ...resolveBillingPeriodBoundaryUpdate({
+ incomingPeriodStart: incomingSubscription.currentPeriodStart,
+ storedSubscription,
+ }),
+ },
{
conflictPaths: ['stripeSubscriptionId'],
skipUpdateIfNoValuesChanged: true,
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 1fa3446f41e..04796482334 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
@@ -35,6 +35,10 @@ export enum BillingExceptionCode {
BILLING_CREDITS_EXHAUSTED = 'BILLING_CREDITS_EXHAUSTED',
BILLING_SUBSCRIPTION_NOT_CANCELED = 'BILLING_SUBSCRIPTION_NOT_CANCELED',
BILLING_CREDIT_AMOUNT_INVALID = 'BILLING_CREDIT_AMOUNT_INVALID',
+ BILLING_CREDIT_GRANT_NOT_FOUND = 'BILLING_CREDIT_GRANT_NOT_FOUND',
+ 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',
}
const getBillingExceptionUserFriendlyMessage = (code: BillingExceptionCode) => {
@@ -93,6 +97,14 @@ const getBillingExceptionUserFriendlyMessage = (code: BillingExceptionCode) => {
return msg`Workspace cannot be deleted: subscription is not yet canceled.`;
case BillingExceptionCode.BILLING_CREDIT_AMOUNT_INVALID:
return msg`Invalid credit amount.`;
+ case BillingExceptionCode.BILLING_CREDIT_GRANT_NOT_FOUND:
+ return msg`Credit grant not found.`;
+ case BillingExceptionCode.BILLING_CREDIT_GRANT_VALIDITY_INVALID:
+ return msg`Credit grant must expire after it becomes effective.`;
+ case BillingExceptionCode.BILLING_USAGE_UNAVAILABLE:
+ 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.`;
default:
assertUnreachable(code);
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts
index 427bb6b4f3c..854908f9f96 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts
@@ -11,6 +11,7 @@ import { BillingResolver } from 'src/engine/core-modules/billing/billing.resolve
import { BillingSyncCustomerDataCommand } from 'src/engine/core-modules/billing/commands/billing-sync-customer-data.command';
import { BillingSyncPlansDataCommand } from 'src/engine/core-modules/billing/commands/billing-sync-plans-data.command';
import { BillingUpdateSubscriptionPriceCommand } from 'src/engine/core-modules/billing/commands/billing-update-subscription-price.command';
+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 { BillingEntitlementEntity } from 'src/engine/core-modules/billing/entities/billing-entitlement.entity';
import { BillingMeterEntity } from 'src/engine/core-modules/billing/entities/billing-meter.entity';
@@ -20,6 +21,7 @@ import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/e
import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
import { BillingRestApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-api-exception.filter';
import { BillingWorkspaceMemberListener } from 'src/engine/core-modules/billing/listeners/billing-workspace-member.listener';
+import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
import { BillingCreditRolloverService } from 'src/engine/core-modules/billing/services/billing-credit-rollover.service';
import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';
import { BillingPlanService } from 'src/engine/core-modules/billing/services/billing-plan.service';
@@ -37,6 +39,7 @@ import { BillingService } from 'src/engine/core-modules/billing/services/billing
import { ResourceCreditService } from 'src/engine/core-modules/billing/services/resource-credit.service';
import { WorkspaceCurrentBillingSubscriptionCacheService } from 'src/engine/core-modules/billing/services/workspace-current-billing-subscription-cache.service';
import { StripeModule } from 'src/engine/core-modules/billing/stripe/stripe.module';
+import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';
import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';
import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';
@@ -51,6 +54,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
@Module({
imports: [
+ CacheLockModule,
ClickHouseModule,
CoreEntityCacheModule,
FeatureFlagModule,
@@ -67,6 +71,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
BillingPriceEntity,
BillingMeterEntity,
BillingEntitlementEntity,
+ BillingCreditGrantEntity,
WorkspaceEntity,
UserWorkspaceEntity,
FeatureFlagEntity,
@@ -95,11 +100,13 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
BillingUsageCapService,
BillingPriceService,
BillingCreditRolloverService,
+ BillingCreditGrantService,
BillingCreditService,
ResourceCreditService,
BillingGaugeService,
WorkspaceCurrentBillingSubscriptionCacheService,
provideWorkspaceScopedRepository(BillingEntitlementEntity),
+ provideWorkspaceScopedRepository(BillingCreditGrantEntity),
provideWorkspaceScopedRepository(BillingCustomerEntity),
provideWorkspaceScopedRepository(BillingSubscriptionEntity),
],
@@ -114,6 +121,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
BillingUsageCacheService,
BillingUsageCapService,
BillingCreditRolloverService,
+ BillingCreditGrantService,
BillingCreditService,
ResourceCreditService,
],
diff --git a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-credit-grant.entity.ts b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-credit-grant.entity.ts
new file mode 100644
index 00000000000..1b5f2daf13e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-credit-grant.entity.ts
@@ -0,0 +1,74 @@
+/* @license Enterprise */
+
+import {
+ Column,
+ CreateDateColumn,
+ Entity,
+ Index,
+ PrimaryGeneratedColumn,
+ UpdateDateColumn,
+} from 'typeorm';
+
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
+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: 'billingCreditGrant', schema: 'core' })
+@Index('IDX_BILLING_CREDIT_GRANT_WORKSPACE_ID_EXPIRES_AT', [
+ 'workspaceId',
+ 'expiresAt',
+])
+export class BillingCreditGrantEntity extends WorkspaceRelatedEntity {
+ @PrimaryGeneratedColumn('uuid')
+ id: string;
+
+ @Column({
+ nullable: false,
+ type: 'bigint',
+ transformer: bigintColumnTransformer,
+ })
+ amountMicro: number;
+
+ @Column({
+ nullable: false,
+ type: 'enum',
+ enum: Object.values(BillingCreditGrantType),
+ })
+ type: BillingCreditGrantType;
+
+ @Column({ nullable: false, type: 'timestamptz' })
+ effectiveAt: Date;
+
+ // Always the end of the billing period the grant belongs to. The available
+ // credit count is cached in Redis until period end and never recomputed
+ // mid-period, so an expiry inside a period would go unnoticed by the only
+ // code path that gates usage.
+ @Column({ nullable: false, type: 'timestamptz' })
+ expiresAt: Date;
+
+ @Column({ nullable: true, type: 'timestamptz' })
+ revokedAt: Date | null;
+
+ @Column({ nullable: true, type: 'uuid' })
+ revokedByUserId: string | null;
+
+ @Column({ nullable: true, type: 'uuid' })
+ grantedByUserId: string | null;
+
+ @Column({ nullable: true, type: 'varchar', length: 500 })
+ reason: string | null;
+
+ @Index('IDX_BILLING_CREDIT_GRANT_IDEMPOTENCY_KEY_UNIQUE', { unique: true })
+ @Column({ nullable: true, type: 'varchar' })
+ idempotencyKey: string | null;
+
+ // Set when this grant carries forward the unspent part of another one.
+ @Column({ nullable: true, type: 'uuid' })
+ sourceGrantId: string | null;
+
+ @CreateDateColumn({ type: 'timestamptz' })
+ createdAt: Date;
+
+ @UpdateDateColumn({ type: 'timestamptz' })
+ updatedAt: Date;
+}
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.ts
index d4dcc515ccf..8523fa08faa 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,6 +15,7 @@ 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' })
@@ -48,11 +49,7 @@ export class BillingCustomerEntity extends WorkspaceRelatedEntity {
type: 'bigint',
nullable: false,
default: 0,
- transformer: {
- to: (value: number) => value,
- from: (value: string | number | null) =>
- typeof value === 'string' ? Number(value) : (value ?? 0),
- },
+ transformer: bigintColumnTransformer,
})
creditBalanceMicro: number;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts
index 9690d2b1f34..cb97c70b3f8 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts
@@ -132,6 +132,15 @@ export class BillingSubscriptionEntity extends WorkspaceRelatedEntity {
})
currentPeriodStart: Date;
+ // Where the period before the current one began. Stripe only ever reports the
+ // current window, so once currentPeriodStart advances the previous boundary
+ // is unrecoverable: calendar arithmetic clamps month-end anchors, and the
+ // ledger only shows it when the last transition happened to close a grant.
+ // Written whenever the period moves, and read by the rollover to bound the
+ // usage it settles.
+ @Column({ nullable: true, type: 'timestamptz' })
+ previousPeriodStart: Date | null;
+
@Field(() => graphqlTypeJson)
@Column({ nullable: false, type: 'jsonb', default: {} })
metadata: Stripe.Metadata;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.ts b/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.ts
new file mode 100644
index 00000000000..5045220892e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/enums/billing-credit-grant-type.enum.ts
@@ -0,0 +1,33 @@
+/* @license Enterprise */
+
+import { registerEnumType } from '@nestjs/graphql';
+
+// Why a workspace was given credits, not how. Whether a human wrote the grant
+// is already on the row as grantedByUserId, so there is no "manual" type.
+export enum BillingCreditGrantType {
+ ROLLOVER = 'ROLLOVER',
+ ONBOARDING_REWARD = 'ONBOARDING_REWARD',
+ COMPENSATION = 'COMPENSATION',
+ SALES = 'SALES',
+}
+
+registerEnumType(BillingCreditGrantType, {
+ name: 'BillingCreditGrantType',
+ description: 'The origin of a batch of credits granted to a workspace',
+});
+
+// Only ROLLOVER credits are capped when they carry over to the next period.
+// Credits we granted deliberately (compensation, sales, onboarding rewards)
+// keep their full value until spent or expired.
+export const CAPPED_BILLING_CREDIT_GRANT_TYPES: BillingCreditGrantType[] = [
+ BillingCreditGrantType.ROLLOVER,
+];
+
+// What an operator may write by hand. ROLLOVER belongs to the period
+// transition and ONBOARDING_REWARD to the onboarding jobs, so granting either
+// by hand would change carry-forward behaviour and misclassify the audit
+// trail.
+export const ADMIN_GRANTABLE_CREDIT_GRANT_TYPES: BillingCreditGrantType[] = [
+ BillingCreditGrantType.COMPENSATION,
+ BillingCreditGrantType.SALES,
+];
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit-grant.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit-grant.service.spec.ts
new file mode 100644
index 00000000000..51958250c24
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit-grant.service.spec.ts
@@ -0,0 +1,325 @@
+/* @license Enterprise */
+
+import { Test, type TestingModule } from '@nestjs/testing';
+
+import { BillingException } 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 { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
+import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
+
+const workspaceId = 'ws_123';
+const EFFECTIVE_AT = new Date('2026-01-01T00:00:00.000Z');
+const EXPIRES_AT = new Date('2026-02-01T00:00:00.000Z');
+
+const validParams = {
+ workspaceId,
+ amountMicro: 2_000_000,
+ type: BillingCreditGrantType.COMPENSATION,
+ effectiveAt: EFFECTIVE_AT,
+ expiresAt: EXPIRES_AT,
+};
+
+describe('BillingCreditGrantService', () => {
+ let service: BillingCreditGrantService;
+ let repository: jest.Mocked<{
+ insert: jest.Mock;
+ findOne: jest.Mock;
+ findOneOrFail: jest.Mock;
+ find: jest.Mock;
+ update: jest.Mock;
+ createQueryBuilder: jest.Mock;
+ exists: jest.Mock;
+ }>;
+ let billingCustomerRepository: jest.Mocked<{ findOne: jest.Mock }>;
+ let queryBuilder: { getRawOne: jest.Mock } & Record<string, jest.Mock>;
+
+ beforeEach(async () => {
+ queryBuilder = {
+ select: jest.fn(),
+ where: jest.fn(),
+ andWhere: jest.fn(),
+ getRawOne: jest.fn().mockResolvedValue({ total: '3000000' }),
+ };
+ queryBuilder.select.mockReturnValue(queryBuilder);
+ queryBuilder.where.mockReturnValue(queryBuilder);
+ queryBuilder.andWhere.mockReturnValue(queryBuilder);
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ BillingCreditGrantService,
+ {
+ provide: getWorkspaceScopedRepositoryToken(BillingCreditGrantEntity),
+ useValue: {
+ insert: jest.fn().mockResolvedValue({
+ identifiers: [{ id: 'grant_1' }],
+ generatedMaps: [{ id: 'grant_1' }],
+ }),
+ findOne: jest.fn().mockResolvedValue({ id: 'grant_1' }),
+ findOneOrFail: jest
+ .fn()
+ .mockResolvedValue({ id: 'grant_1', revokedAt: new Date() }),
+ find: jest.fn().mockResolvedValue([]),
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
+ createQueryBuilder: jest.fn().mockReturnValue(queryBuilder),
+ exists: jest.fn().mockResolvedValue(true),
+ },
+ },
+ {
+ provide: getWorkspaceScopedRepositoryToken(BillingCustomerEntity),
+ useValue: {
+ findOne: jest.fn().mockResolvedValue({ creditBalanceMicro: 0 }),
+ },
+ },
+ ],
+ }).compile();
+
+ service = module.get<BillingCreditGrantService>(BillingCreditGrantService);
+ repository = module.get(
+ getWorkspaceScopedRepositoryToken(BillingCreditGrantEntity),
+ );
+ billingCustomerRepository = module.get(
+ getWorkspaceScopedRepositoryToken(BillingCustomerEntity),
+ );
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe('createGrant', () => {
+ it('inserts the grant and returns it', async () => {
+ const grant = await service.createGrant(validParams);
+
+ expect(repository.insert).toHaveBeenCalledWith(
+ workspaceId,
+ expect.objectContaining({
+ amountMicro: 2_000_000,
+ type: BillingCreditGrantType.COMPENSATION,
+ effectiveAt: EFFECTIVE_AT,
+ expiresAt: EXPIRES_AT,
+ }),
+ );
+ expect(grant).toEqual({ id: 'grant_1' });
+ });
+
+ it.each([
+ 0,
+ -1,
+ 1.5,
+ Number.NaN,
+ Number.POSITIVE_INFINITY,
+ Number.MAX_SAFE_INTEGER + 1,
+ ])(
+ 'throws on a non-positive, non-integer or unsafe-integer amount (%p)',
+ async (amountMicro) => {
+ await expect(
+ service.createGrant({ ...validParams, amountMicro }),
+ ).rejects.toThrow(BillingException);
+
+ expect(repository.insert).not.toHaveBeenCalled();
+ },
+ );
+
+ it('throws when the grant would expire before it becomes effective', async () => {
+ await expect(
+ service.createGrant({
+ ...validParams,
+ effectiveAt: EXPIRES_AT,
+ expiresAt: EFFECTIVE_AT,
+ }),
+ ).rejects.toThrow(BillingException);
+
+ expect(repository.insert).not.toHaveBeenCalled();
+ });
+
+ it('returns null instead of duplicating a grant with a used idempotency key', async () => {
+ repository.insert.mockRejectedValue(
+ Object.assign(new Error('duplicate key'), { code: '23505' }),
+ );
+
+ const grant = await service.createGrant({
+ ...validParams,
+ idempotencyKey: 'onboarding-import-contacts:ws_123',
+ });
+
+ expect(grant).toBeNull();
+ });
+
+ it('returns null when the unique violation is wrapped in a driver error', async () => {
+ repository.insert.mockRejectedValue(
+ Object.assign(new Error('duplicate key'), {
+ driverError: { code: '23505' },
+ }),
+ );
+
+ const grant = await service.createGrant({
+ ...validParams,
+ idempotencyKey: 'onboarding-import-contacts:ws_123',
+ });
+
+ expect(grant).toBeNull();
+ });
+
+ it('rethrows a unique violation when no idempotency key was given', async () => {
+ repository.insert.mockRejectedValue(
+ Object.assign(new Error('duplicate key'), { code: '23505' }),
+ );
+
+ await expect(service.createGrant(validParams)).rejects.toThrow(
+ 'duplicate key',
+ );
+ });
+
+ it('rethrows errors that are not unique violations', async () => {
+ repository.insert.mockRejectedValue(new Error('connection lost'));
+
+ await expect(
+ service.createGrant({
+ ...validParams,
+ idempotencyKey: 'some-key',
+ }),
+ ).rejects.toThrow('connection lost');
+ });
+ });
+
+ describe('getActiveCreditsMicro', () => {
+ it('sums the grants that are live right now', async () => {
+ const total = await service.getActiveCreditsMicro(workspaceId);
+
+ expect(total).toBe(3_000_000);
+ expect(queryBuilder.andWhere).toHaveBeenCalledWith(
+ '"billingCreditGrant"."revokedAt" IS NULL',
+ );
+ });
+
+ it('returns zero when the workspace has no live grant', async () => {
+ queryBuilder.getRawOne.mockResolvedValue({ total: null });
+
+ expect(await service.getActiveCreditsMicro(workspaceId)).toBe(0);
+ });
+
+ it('throws rather than serving a balance it cannot represent exactly', async () => {
+ queryBuilder.getRawOne.mockResolvedValue({
+ total: String(Number.MAX_SAFE_INTEGER) + '0',
+ });
+
+ await expect(service.getActiveCreditsMicro(workspaceId)).rejects.toThrow(
+ BillingException,
+ );
+ });
+ });
+
+ describe('getSpendableCreditsMicro', () => {
+ it('reads the ledger once the workspace has a grant', async () => {
+ repository.exists.mockResolvedValue(true);
+
+ expect(await service.getSpendableCreditsMicro(workspaceId)).toBe(
+ 3_000_000,
+ );
+ expect(billingCustomerRepository.findOne).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the mirror column before the backfill has run', async () => {
+ repository.exists.mockResolvedValue(false);
+ billingCustomerRepository.findOne.mockResolvedValue({
+ creditBalanceMicro: 200_000_000,
+ });
+
+ expect(await service.getSpendableCreditsMicro(workspaceId)).toBe(
+ 200_000_000,
+ );
+ });
+
+ it('returns zero when the workspace has neither a grant nor a customer', async () => {
+ repository.exists.mockResolvedValue(false);
+ billingCustomerRepository.findOne.mockResolvedValue(null);
+
+ expect(await service.getSpendableCreditsMicro(workspaceId)).toBe(0);
+ });
+ });
+
+ describe('closeGrantsAtPeriodEnd', () => {
+ it('pulls expiries back to the period end', async () => {
+ await service.closeGrantsAtPeriodEnd({
+ workspaceId,
+ periodEnd: EXPIRES_AT,
+ });
+
+ expect(repository.update).toHaveBeenCalledWith(
+ workspaceId,
+ expect.objectContaining({ expiresAt: expect.anything() }),
+ { expiresAt: EXPIRES_AT },
+ );
+ });
+
+ it('matches by predicate so a grant written mid-transition is closed too', async () => {
+ await service.closeGrantsAtPeriodEnd({
+ workspaceId,
+ periodEnd: EXPIRES_AT,
+ });
+
+ const [, criteria] = repository.update.mock.calls[0];
+
+ expect(Object.keys(criteria)).toEqual(
+ expect.arrayContaining(['revokedAt', 'effectiveAt', 'expiresAt']),
+ );
+ expect(criteria).not.toHaveProperty('id');
+ });
+ });
+
+ describe('revokeGrant', () => {
+ it('stamps revokedAt', async () => {
+ repository.findOne.mockResolvedValue({ id: 'grant_1', revokedAt: null });
+
+ const { wasRevokedNow } = await service.revokeGrant({
+ workspaceId,
+ grantId: 'grant_1',
+ revokedByUserId: 'user_1',
+ });
+
+ expect(wasRevokedNow).toBe(true);
+ expect(repository.update).toHaveBeenCalledWith(
+ workspaceId,
+ expect.objectContaining({ id: 'grant_1' }),
+ expect.objectContaining({ revokedByUserId: 'user_1' }),
+ );
+ });
+
+ it('reports that it did not revoke when a concurrent call won the race', async () => {
+ repository.findOne.mockResolvedValue({ id: 'grant_1', revokedAt: null });
+ repository.update.mockResolvedValue({ affected: 0 });
+
+ const { wasRevokedNow } = await service.revokeGrant({
+ workspaceId,
+ grantId: 'grant_1',
+ });
+
+ expect(wasRevokedNow).toBe(false);
+ });
+
+ it('leaves an already revoked grant alone', async () => {
+ const revokedAt = new Date('2026-01-15T00:00:00.000Z');
+
+ repository.findOne.mockResolvedValue({ id: 'grant_1', revokedAt });
+
+ const { grant, wasRevokedNow } = await service.revokeGrant({
+ workspaceId,
+ grantId: 'grant_1',
+ });
+
+ expect(grant.revokedAt).toEqual(revokedAt);
+ expect(wasRevokedNow).toBe(false);
+ expect(repository.update).not.toHaveBeenCalled();
+ });
+
+ it('throws when the grant belongs to another workspace or does not exist', async () => {
+ repository.findOne.mockResolvedValue(null);
+
+ await expect(
+ service.revokeGrant({ workspaceId, grantId: 'grant_unknown' }),
+ ).rejects.toThrow(BillingException);
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit-rollover.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit-rollover.service.spec.ts
index d0a486df815..e4d402dee65 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit-rollover.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit-rollover.service.spec.ts
@@ -2,16 +2,46 @@
import { Test, type TestingModule } from '@nestjs/testing';
-import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
+import { BillingExceptionCode } from 'src/engine/core-modules/billing/billing.exception';
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
+import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
import { BillingCreditRolloverService } from 'src/engine/core-modules/billing/services/billing-credit-rollover.service';
+import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
-import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+
+const workspaceId = 'ws_123';
+const CLOSING_PERIOD_START = new Date('2026-01-01T00:00:00.000Z');
+const CLOSING_PERIOD_END = new Date('2026-02-01T00:00:00.000Z');
+const NEXT_PERIOD_END = new Date('2026-03-01T00:00:00.000Z');
+const ALLOWANCE = 1_000_000;
+const ROLLOVER_ADJUSTMENT_KEY = `rollover:${CLOSING_PERIOD_END.toISOString()}`;
+
+const baseParams = {
+ workspaceId,
+ closingPeriodStart: CLOSING_PERIOD_START,
+ closingPeriodEnd: CLOSING_PERIOD_END,
+ closingAllowanceMicro: ALLOWANCE,
+ nextPeriodStart: CLOSING_PERIOD_END,
+ nextPeriodEnd: NEXT_PERIOD_END,
+ nextAllowanceMicro: ALLOWANCE,
+};
+
describe('BillingCreditRolloverService', () => {
let service: BillingCreditRolloverService;
- let billingUsageService: jest.Mocked<
- Pick<BillingUsageService, 'getCurrentPeriodCreditsUsed'>
- >;
- let billingCustomerRepository: jest.Mocked<{ update: jest.Mock }>;
+ let billingUsageService: jest.Mocked<{
+ getCreditsUsedBetweenOrNull: jest.Mock;
+ }>;
+ let billingCreditGrantService: jest.Mocked<{
+ findGrantsLiveDuringPeriod: jest.Mock;
+ closeGrantsAtPeriodEnd: jest.Mock;
+ createGrant: jest.Mock;
+ materializeLegacyBalance: jest.Mock;
+ }>;
+ let billingCreditService: jest.Mocked<{
+ refreshWorkspaceCreditState: jest.Mock;
+ }>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
@@ -20,15 +50,36 @@ describe('BillingCreditRolloverService', () => {
{
provide: BillingUsageService,
useValue: {
- getCurrentPeriodCreditsUsed: jest.fn().mockResolvedValue(0),
+ getCreditsUsedBetweenOrNull: jest.fn().mockResolvedValue(0),
+ },
+ },
+ {
+ provide: BillingCreditGrantService,
+ useValue: {
+ findGrantsLiveDuringPeriod: jest.fn().mockResolvedValue([]),
+ closeGrantsAtPeriodEnd: jest.fn().mockResolvedValue(undefined),
+ createGrant: jest
+ .fn()
+ .mockImplementation((params) =>
+ Promise.resolve({ id: 'grant_new', ...params }),
+ ),
+ materializeLegacyBalance: jest.fn().mockResolvedValue(undefined),
},
},
{
- provide: getWorkspaceScopedRepositoryToken(BillingCustomerEntity),
+ provide: BillingCreditService,
useValue: {
- update: jest.fn(),
+ refreshWorkspaceCreditState: jest.fn().mockResolvedValue(undefined),
},
},
+ {
+ provide: CacheLockService,
+ useValue: { withLock: jest.fn((fn: () => unknown) => fn()) },
+ },
+ {
+ provide: TwentyConfigService,
+ useValue: { get: jest.fn().mockReturnValue(2) },
+ },
],
}).compile();
@@ -36,9 +87,8 @@ describe('BillingCreditRolloverService', () => {
BillingCreditRolloverService,
);
billingUsageService = module.get(BillingUsageService);
- billingCustomerRepository = module.get(
- getWorkspaceScopedRepositoryToken(BillingCustomerEntity),
- );
+ billingCreditGrantService = module.get(BillingCreditGrantService);
+ billingCreditService = module.get(BillingCreditService);
});
afterEach(() => {
@@ -46,81 +96,228 @@ describe('BillingCreditRolloverService', () => {
});
describe('processRolloverOnPeriodTransition', () => {
- const baseParams = {
- workspaceId: 'ws_123',
- stripeCustomerId: 'cus_123',
- tierQuantity: 1000,
- previousPeriodStart: new Date('2024-01-01'),
- };
-
- it('writes rollover amount to creditBalanceMicro when credits unused', async () => {
- (
- billingUsageService.getCurrentPeriodCreditsUsed as jest.Mock
- ).mockResolvedValue(300);
+ it('grants the unspent allowance for the new period', async () => {
+ billingUsageService.getCreditsUsedBetweenOrNull.mockResolvedValue(
+ 300_000,
+ );
+
+ await service.processRolloverOnPeriodTransition(baseParams);
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workspaceId,
+ amountMicro: 700_000,
+ type: BillingCreditGrantType.ROLLOVER,
+ effectiveAt: CLOSING_PERIOD_END,
+ expiresAt: NEXT_PERIOD_END,
+ }),
+ );
+ });
+
+ it('reads usage over the closing period, not the one that just started', async () => {
await service.processRolloverOnPeriodTransition(baseParams);
- expect(billingCustomerRepository.update).toHaveBeenCalledWith(
- 'ws_123',
- { stripeCustomerId: 'cus_123' },
- { creditBalanceMicro: 700 },
+ expect(
+ billingUsageService.getCreditsUsedBetweenOrNull,
+ ).toHaveBeenCalledWith({
+ workspaceId,
+ from: CLOSING_PERIOD_START,
+ to: CLOSING_PERIOD_END,
+ });
+ });
+
+ it('grants nothing when the whole allowance was spent', async () => {
+ billingUsageService.getCreditsUsedBetweenOrNull.mockResolvedValue(
+ ALLOWANCE,
);
+
+ await service.processRolloverOnPeriodTransition(baseParams);
+
+ expect(billingCreditGrantService.createGrant).not.toHaveBeenCalled();
+ });
+
+ it('refreshes the credit state once even when nothing carried forward', async () => {
+ billingUsageService.getCreditsUsedBetweenOrNull.mockResolvedValue(
+ ALLOWANCE,
+ );
+
+ await service.processRolloverOnPeriodTransition(baseParams);
+
+ expect(
+ billingCreditService.refreshWorkspaceCreditState,
+ ).toHaveBeenCalledTimes(1);
+ expect(
+ billingCreditService.refreshWorkspaceCreditState,
+ ).toHaveBeenCalledWith({
+ workspaceId,
+ availableDeltaMicro: 0,
+ addsCredits: true,
+ isReplay: false,
+ adjustmentKey: ROLLOVER_ADJUSTMENT_KEY,
+ });
+ });
+
+ // A redelivery after the rows were inserted carries nothing forward, so a
+ // delta of zero would leave the carried credits out of the counter for the
+ // whole period. Whether the counter actually needs rebuilding is decided by
+ // the refresh, which owns the adjustment marker; the transition only
+ // reports that it saw a replay.
+ it('reports a replay when the carry-forward grants already existed', async () => {
+ billingCreditGrantService.createGrant.mockResolvedValue(null);
+
+ await service.processRolloverOnPeriodTransition(baseParams);
+
+ expect(
+ billingCreditService.refreshWorkspaceCreditState,
+ ).toHaveBeenCalledWith({
+ workspaceId,
+ availableDeltaMicro: 0,
+ addsCredits: true,
+ isReplay: true,
+ adjustmentKey: ROLLOVER_ADJUSTMENT_KEY,
+ });
});
- it('sets creditBalanceMicro to tierQuantity when no credits used', async () => {
- (
- billingUsageService.getCurrentPeriodCreditsUsed as jest.Mock
- ).mockResolvedValue(0);
+ it('refreshes the credit state once for the whole transition', async () => {
+ billingCreditGrantService.findGrantsLiveDuringPeriod.mockResolvedValue([
+ {
+ id: 'compensation_1',
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 500_000,
+ createdAt: CLOSING_PERIOD_START,
+ },
+ ]);
await service.processRolloverOnPeriodTransition(baseParams);
- expect(billingCustomerRepository.update).toHaveBeenCalledWith(
- 'ws_123',
- { stripeCustomerId: 'cus_123' },
- { creditBalanceMicro: 1000 },
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledTimes(2);
+ expect(
+ billingCreditService.refreshWorkspaceCreditState,
+ ).toHaveBeenCalledTimes(1);
+ });
+
+ it('caps the rollover so the new period totals at most twice the allowance', async () => {
+ billingCreditGrantService.findGrantsLiveDuringPeriod.mockResolvedValue([
+ {
+ id: 'previous_rollover',
+ type: BillingCreditGrantType.ROLLOVER,
+ amountMicro: ALLOWANCE,
+ createdAt: CLOSING_PERIOD_START,
+ },
+ ]);
+
+ await service.processRolloverOnPeriodTransition(baseParams);
+
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledTimes(1);
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledWith(
+ expect.objectContaining({ amountMicro: ALLOWANCE }),
);
});
- it('sets creditBalanceMicro to 0 when all credits used', async () => {
- (
- billingUsageService.getCurrentPeriodCreditsUsed as jest.Mock
- ).mockResolvedValue(1000);
+ it('carries a compensation grant over untouched by the cap', async () => {
+ billingCreditGrantService.findGrantsLiveDuringPeriod.mockResolvedValue([
+ {
+ id: 'compensation_1',
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 200_000_000,
+ createdAt: CLOSING_PERIOD_START,
+ },
+ ]);
await service.processRolloverOnPeriodTransition(baseParams);
- expect(billingCustomerRepository.update).toHaveBeenCalledWith(
- 'ws_123',
- { stripeCustomerId: 'cus_123' },
- { creditBalanceMicro: 0 },
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledWith(
+ expect.objectContaining({
+ amountMicro: 200_000_000,
+ type: BillingCreditGrantType.COMPENSATION,
+ sourceGrantId: 'compensation_1',
+ }),
);
});
- it('sets creditBalanceMicro to 0 when usage exceeds tier', async () => {
- (
- billingUsageService.getCurrentPeriodCreditsUsed as jest.Mock
- ).mockResolvedValue(1500);
+ it('closes the grants it carried forward so they cannot be counted twice', async () => {
+ billingCreditGrantService.findGrantsLiveDuringPeriod.mockResolvedValue([
+ {
+ id: 'compensation_1',
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 500_000,
+ createdAt: CLOSING_PERIOD_START,
+ },
+ ]);
+
+ await service.processRolloverOnPeriodTransition(baseParams);
+ expect(
+ billingCreditGrantService.closeGrantsAtPeriodEnd,
+ ).toHaveBeenCalledWith({
+ workspaceId,
+ periodEnd: CLOSING_PERIOD_END,
+ });
+ });
+
+ it('gives every carried grant a replay-safe idempotency key', async () => {
await service.processRolloverOnPeriodTransition(baseParams);
- expect(billingCustomerRepository.update).toHaveBeenCalledWith(
- 'ws_123',
- { stripeCustomerId: 'cus_123' },
- { creditBalanceMicro: 0 },
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledWith(
+ expect.objectContaining({
+ idempotencyKey: `carry-forward:${workspaceId}:${CLOSING_PERIOD_END.toISOString()}:ROLLOVER:allowance`,
+ }),
);
});
- it('caps rollover at tierQuantity', async () => {
- (
- billingUsageService.getCurrentPeriodCreditsUsed as jest.Mock
- ).mockResolvedValue(0);
- const params = { ...baseParams, tierQuantity: 500 };
+ // Returning normally would answer the webhook 200 and Stripe would never
+ // redeliver, so the transition would never run: no grant closed, nothing
+ // carried forward, and the balance lost at expiry.
+ it('fails the transition when usage could not be read so Stripe redelivers', async () => {
+ billingUsageService.getCreditsUsedBetweenOrNull.mockResolvedValue(null);
- await service.processRolloverOnPeriodTransition(params);
+ await expect(
+ service.processRolloverOnPeriodTransition(baseParams),
+ ).rejects.toMatchObject({
+ code: BillingExceptionCode.BILLING_USAGE_UNAVAILABLE,
+ });
+
+ expect(billingCreditGrantService.createGrant).not.toHaveBeenCalled();
+ expect(
+ billingCreditGrantService.closeGrantsAtPeriodEnd,
+ ).not.toHaveBeenCalled();
+ expect(
+ billingCreditService.refreshWorkspaceCreditState,
+ ).not.toHaveBeenCalled();
+ });
- expect(billingCustomerRepository.update).toHaveBeenCalledWith(
- 'ws_123',
- { stripeCustomerId: 'cus_123' },
- { creditBalanceMicro: 500 },
+ it('carries trial credits into the first paid period', async () => {
+ const trialAllowance = 500_000;
+
+ billingCreditGrantService.findGrantsLiveDuringPeriod.mockResolvedValue([
+ {
+ id: 'reward_1',
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ amountMicro: 1_000_000,
+ createdAt: CLOSING_PERIOD_START,
+ },
+ ]);
+ billingUsageService.getCreditsUsedBetweenOrNull.mockResolvedValue(
+ 200_000,
+ );
+
+ await service.processRolloverOnPeriodTransition({
+ ...baseParams,
+ closingAllowanceMicro: trialAllowance,
+ });
+
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledWith(
+ expect.objectContaining({
+ amountMicro: 300_000,
+ type: BillingCreditGrantType.ROLLOVER,
+ }),
+ );
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledWith(
+ expect.objectContaining({
+ amountMicro: 1_000_000,
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ sourceGrantId: 'reward_1',
+ }),
);
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit.service.spec.ts
index 7178454c9c1..60949dd1acb 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-credit.service.spec.ts
@@ -2,22 +2,60 @@
import { Test, type TestingModule } from '@nestjs/testing';
-import { BillingException } from 'src/engine/core-modules/billing/billing.exception';
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 { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
+import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';
+import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
+import { BillingUsageCapService } from 'src/engine/core-modules/billing/services/billing-usage-cap.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const workspaceId = 'ws_123';
+const DAY_IN_MS = 24 * 60 * 60 * 1000;
+// Relative to now so the period stays current: a lapsed period end takes a
+// different branch, which is covered by its own test below.
+const PERIOD_START = new Date(Date.now() - 10 * DAY_IN_MS);
+const PERIOD_END = new Date(Date.now() + 20 * DAY_IN_MS);
+
+const subscription = {
+ status: SubscriptionStatus.Active,
+ currentPeriodStart: PERIOD_START,
+ currentPeriodEnd: PERIOD_END,
+ trialStart: null,
+ trialEnd: null,
+};
describe('BillingCreditService', () => {
let service: BillingCreditService;
- let billingService: jest.Mocked<Pick<BillingService, 'isBillingEnabled'>>;
- let billingUsageCacheService: jest.Mocked<
- Pick<BillingUsageCacheService, 'flushAvailableCredits'>
- >;
- let billingCustomerRepository: jest.Mocked<{ increment: jest.Mock }>;
-
- const workspaceId = 'ws_123';
+ let billingService: jest.Mocked<{ isBillingEnabled: jest.Mock }>;
+ let billingCreditGrantService: jest.Mocked<{
+ createGrant: jest.Mock;
+ getActiveCreditsMicro: jest.Mock;
+ revokeGrant: jest.Mock;
+ materializeLegacyBalance: jest.Mock;
+ hasAnyGrant: jest.Mock;
+ }>;
+ let billingSubscriptionService: jest.Mocked<{
+ getCurrentBillingSubscription: jest.Mock;
+ }>;
+ let billingUsageCacheService: jest.Mocked<{
+ getAvailableCredits: jest.Mock;
+ adjustAvailableCredits: jest.Mock;
+ invalidateAvailableCredits: jest.Mock;
+ hasCounterAdjustmentBeenApplied: jest.Mock;
+ markCounterAdjustmentApplied: jest.Mock;
+ }>;
+ let billingUsageCapService: jest.Mocked<{
+ clearHasReachedCapForWorkspace: jest.Mock;
+ }>;
+ let cacheLockService: jest.Mocked<{ withLock: jest.Mock }>;
+ let workspaceCacheService: jest.Mocked<{ invalidateAndRecompute: jest.Mock }>;
+ let billingCustomerRepository: jest.Mocked<{ update: jest.Mock }>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
@@ -25,28 +63,82 @@ describe('BillingCreditService', () => {
BillingCreditService,
{
provide: BillingService,
+ useValue: { isBillingEnabled: jest.fn().mockReturnValue(true) },
+ },
+ {
+ provide: BillingCreditGrantService,
+ useValue: {
+ createGrant: jest
+ .fn()
+ .mockResolvedValue({ id: 'grant_1', amountMicro: 2_000_000 }),
+ getActiveCreditsMicro: jest.fn().mockResolvedValue(2_000_000),
+ hasAnyGrant: jest.fn().mockResolvedValue(true),
+ materializeLegacyBalance: jest.fn().mockResolvedValue(undefined),
+ revokeGrant: jest.fn().mockResolvedValue({
+ grant: {
+ id: 'grant_1',
+ amountMicro: 2_000_000,
+ effectiveAt: PERIOD_START,
+ expiresAt: PERIOD_END,
+ revokedAt: new Date(),
+ },
+ wasRevokedNow: true,
+ }),
+ },
+ },
+ {
+ provide: BillingSubscriptionService,
useValue: {
- isBillingEnabled: jest.fn().mockReturnValue(true),
+ getCurrentBillingSubscription: jest
+ .fn()
+ .mockResolvedValue(subscription),
},
},
{
provide: BillingUsageCacheService,
useValue: {
- flushAvailableCredits: jest.fn().mockResolvedValue(undefined),
+ getAvailableCredits: jest.fn().mockResolvedValue(undefined),
+ adjustAvailableCredits: jest.fn().mockResolvedValue(0),
+ invalidateAvailableCredits: jest.fn().mockResolvedValue(undefined),
+ hasCounterAdjustmentBeenApplied: jest.fn().mockResolvedValue(false),
+ markCounterAdjustmentApplied: jest
+ .fn()
+ .mockResolvedValue(undefined),
},
},
{
- provide: getWorkspaceScopedRepositoryToken(BillingCustomerEntity),
+ provide: BillingUsageCapService,
useValue: {
- increment: jest.fn().mockResolvedValue({ affected: 1 }),
+ clearHasReachedCapForWorkspace: jest
+ .fn()
+ .mockResolvedValue(undefined),
},
},
+ {
+ provide: CacheLockService,
+ useValue: { withLock: jest.fn((fn: () => unknown) => fn()) },
+ },
+ {
+ provide: WorkspaceCacheService,
+ useValue: {
+ invalidateAndRecompute: jest.fn().mockResolvedValue(undefined),
+ },
+ },
+ {
+ provide: getWorkspaceScopedRepositoryToken(BillingCustomerEntity),
+ useValue: { update: jest.fn().mockResolvedValue({ affected: 1 }) },
+ },
],
}).compile();
service = module.get<BillingCreditService>(BillingCreditService);
billingService = module.get(BillingService);
+ billingCreditGrantService = module.get(BillingCreditGrantService);
+ billingSubscriptionService = module.get(BillingSubscriptionService);
billingUsageCacheService = module.get(BillingUsageCacheService);
+ billingUsageCapService = module.get(BillingUsageCapService);
+ cacheLockService = module.get(CacheLockService);
+ workspaceCacheService = module.get(WorkspaceCacheService);
billingCustomerRepository = module.get(
getWorkspaceScopedRepositoryToken(BillingCustomerEntity),
);
@@ -56,68 +148,418 @@ describe('BillingCreditService', () => {
jest.clearAllMocks();
});
- describe('creditWorkspaceBalance', () => {
- it('increments the credit balance and flushes the usage cache', async () => {
- await service.creditWorkspaceBalance({
+ describe('grantCredits', () => {
+ const params = {
+ workspaceId,
+ amountMicro: 2_000_000,
+ type: BillingCreditGrantType.COMPENSATION,
+ };
+
+ it('records the grant with the current period end as its expiry', async () => {
+ await service.grantCredits(params);
+
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workspaceId,
+ amountMicro: 2_000_000,
+ type: BillingCreditGrantType.COMPENSATION,
+ expiresAt: PERIOD_END,
+ }),
+ );
+ });
+
+ it('writes the ledger row and the counter under the workspace credit state lock', async () => {
+ await service.grantCredits(params);
+
+ expect(cacheLockService.withLock).toHaveBeenCalledWith(
+ expect.any(Function),
+ `billing-credit-state:${workspaceId}`,
+ );
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalled();
+ });
+
+ // Reading the period before waiting for the lock would date the grant to
+ // the period the wait started in, so it would land already expired while
+ // its amount still went onto the counter for the period now running.
+ it('takes its validity window from the period that is current once the lock is held', async () => {
+ const NEXT_PERIOD_END = new Date(PERIOD_END.getTime() + 30 * DAY_IN_MS);
+
+ cacheLockService.withLock.mockImplementation(
+ async (fn: () => Promise<unknown>) => {
+ billingSubscriptionService.getCurrentBillingSubscription.mockResolvedValue(
+ {
+ ...subscription,
+ currentPeriodStart: PERIOD_END,
+ currentPeriodEnd: NEXT_PERIOD_END,
+ },
+ );
+
+ return fn();
+ },
+ );
+
+ await service.grantCredits(params);
+
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledWith(
+ expect.objectContaining({ expiresAt: NEXT_PERIOD_END }),
+ );
+ });
+
+ it('expires on trial end while the workspace is trialing', async () => {
+ const trialEnd = new Date(Date.now() + 5 * DAY_IN_MS);
+
+ billingSubscriptionService.getCurrentBillingSubscription.mockResolvedValue(
+ {
+ ...subscription,
+ status: SubscriptionStatus.Trialing,
+ trialStart: PERIOD_START,
+ trialEnd,
+ },
+ );
+
+ await service.grantCredits(params);
+
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalledWith(
+ expect.objectContaining({ expiresAt: trialEnd }),
+ );
+ });
+
+ it('does not expire on creation when the subscription period has lapsed', async () => {
+ const lapsedPeriodEnd = new Date(Date.now() - 60_000);
+
+ billingSubscriptionService.getCurrentBillingSubscription.mockResolvedValue(
+ { ...subscription, currentPeriodEnd: lapsedPeriodEnd },
+ );
+
+ await service.grantCredits(params);
+
+ const { expiresAt } =
+ billingCreditGrantService.createGrant.mock.calls[0][0];
+
+ expect(expiresAt.getTime()).toBeGreaterThan(Date.now());
+ });
+
+ it('still records the grant when the workspace has no subscription yet', async () => {
+ billingSubscriptionService.getCurrentBillingSubscription.mockResolvedValue(
+ undefined,
+ );
+
+ const grant = await service.grantCredits(params);
+
+ expect(grant).not.toBeNull();
+ expect(billingCreditGrantService.createGrant).toHaveBeenCalled();
+ });
+
+ it('mirrors the ledger balance onto the billing customer', async () => {
+ await service.grantCredits(params);
+
+ expect(billingCustomerRepository.update).toHaveBeenCalledWith(
+ workspaceId,
+ {},
+ { creditBalanceMicro: 2_000_000 },
+ );
+ });
+
+ it('lifts the cap so the no-more-credits banner disappears', async () => {
+ await service.grantCredits(params);
+
+ expect(
+ billingUsageCapService.clearHasReachedCapForWorkspace,
+ ).toHaveBeenCalledWith(workspaceId);
+ expect(workspaceCacheService.invalidateAndRecompute).toHaveBeenCalledWith(
workspaceId,
- amountMicro: 2_000_000,
+ ['currentBillingSubscription'],
+ );
+ });
+
+ // An execution can overrun the balance it checked, leaving the counter
+ // below zero, and a grant smaller than the overrun does not make the
+ // workspace spendable again.
+ it('leaves the cap in place when the grant does not bring the counter above zero', async () => {
+ billingUsageCacheService.getAvailableCredits.mockResolvedValue(
+ -3_000_000,
+ );
+
+ await service.grantCredits(params);
+
+ expect(
+ billingUsageCapService.clearHasReachedCapForWorkspace,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('adjusts the warm usage counter instead of flushing it', async () => {
+ billingUsageCacheService.getAvailableCredits.mockResolvedValue(500_000);
+
+ await service.grantCredits(params);
+
+ expect(
+ billingUsageCacheService.adjustAvailableCredits,
+ ).toHaveBeenCalledWith(workspaceId, PERIOD_START, 2_000_000);
+ });
+
+ it('leaves a cold usage counter cold', async () => {
+ billingUsageCacheService.getAvailableCredits.mockResolvedValue(undefined);
+
+ await service.grantCredits(params);
+
+ expect(
+ billingUsageCacheService.adjustAvailableCredits,
+ ).not.toHaveBeenCalled();
+ });
+
+ // The first attempt can insert the row and then fail on the refresh, so a
+ // replay has to repair the projections rather than assume they are built.
+ it('repairs derived state on a replayed grant without moving the counter', async () => {
+ billingCreditGrantService.createGrant.mockResolvedValue(null);
+
+ const grant = await service.grantCredits({
+ ...params,
+ idempotencyKey: 'onboarding-import-contacts:ws_123',
});
- expect(billingCustomerRepository.increment).toHaveBeenCalledWith(
+ expect(grant).toBeNull();
+ expect(billingCustomerRepository.update).toHaveBeenCalledWith(
workspaceId,
{},
- 'creditBalanceMicro',
- 2_000_000,
+ { creditBalanceMicro: 2_000_000 },
);
expect(
- billingUsageCacheService.flushAvailableCredits,
+ billingUsageCacheService.invalidateAvailableCredits,
+ ).toHaveBeenCalledWith(workspaceId, PERIOD_START);
+ expect(
+ billingUsageCacheService.adjustAvailableCredits,
+ ).not.toHaveBeenCalled();
+ expect(
+ billingUsageCapService.clearHasReachedCapForWorkspace,
).toHaveBeenCalledWith(workspaceId);
});
+ // A reader that missed the counter before the grant landed would otherwise
+ // warm it from a balance predating the grant, and that value would stand
+ // until the period ended.
+ // A reader can only warm the counter while holding the same lock this
+ // write holds, so it cannot be mid-computation, and the next reader to take
+ // the lock sees a ledger that already contains this grant.
+ it('leaves a cold counter alone rather than seeding it', async () => {
+ billingUsageCacheService.getAvailableCredits.mockResolvedValue(undefined);
+
+ await service.grantCredits(params);
+
+ expect(
+ billingUsageCacheService.adjustAvailableCredits,
+ ).not.toHaveBeenCalled();
+ expect(
+ billingUsageCacheService.invalidateAvailableCredits,
+ ).not.toHaveBeenCalled();
+ });
+
it('no-ops when billing is disabled', async () => {
billingService.isBillingEnabled.mockReturnValue(false);
- await service.creditWorkspaceBalance({
+ const grant = await service.grantCredits(params);
+
+ expect(grant).toBeNull();
+ expect(billingCreditGrantService.createGrant).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('revokeGrant', () => {
+ it('marks the grant revoked and moves the counter under the workspace credit state lock', async () => {
+ await service.revokeGrant({ workspaceId, grantId: 'grant_1' });
+
+ expect(cacheLockService.withLock).toHaveBeenCalledWith(
+ expect.any(Function),
+ `billing-credit-state:${workspaceId}`,
+ );
+ expect(billingCreditGrantService.revokeGrant).toHaveBeenCalled();
+ });
+
+ it('takes the revoked amount back off the warm usage counter', async () => {
+ billingUsageCacheService.getAvailableCredits.mockResolvedValue(3_000_000);
+ billingCreditGrantService.getActiveCreditsMicro.mockResolvedValue(0);
+
+ await service.revokeGrant({ workspaceId, grantId: 'grant_1' });
+
+ expect(
+ billingUsageCacheService.adjustAvailableCredits,
+ ).toHaveBeenCalledWith(workspaceId, PERIOD_START, -2_000_000);
+ expect(billingCustomerRepository.update).toHaveBeenCalledWith(
workspaceId,
- amountMicro: 2_000_000,
+ {},
+ { creditBalanceMicro: 0 },
+ );
+ });
+
+ // The mutation takes any grant id and a grant can expire between the admin
+ // panel rendering and the revoke landing. Those credits were never in the
+ // counter, so taking them off would block usage until the period ends.
+ it.each([
+ [
+ 'expired',
+ {
+ effectiveAt: new Date(Date.now() - 40 * DAY_IN_MS),
+ expiresAt: new Date(Date.now() - 1 * DAY_IN_MS),
+ },
+ ],
+ [
+ 'not yet effective',
+ {
+ effectiveAt: new Date(Date.now() + 1 * DAY_IN_MS),
+ expiresAt: new Date(Date.now() + 40 * DAY_IN_MS),
+ },
+ ],
+ ])(
+ 'leaves the usage counter alone when revoking a grant that was %s',
+ async (_label, window) => {
+ billingUsageCacheService.getAvailableCredits.mockResolvedValue(
+ 3_000_000,
+ );
+ billingCreditGrantService.revokeGrant.mockResolvedValue({
+ grant: {
+ id: 'grant_1',
+ amountMicro: 2_000_000,
+ revokedAt: new Date(),
+ ...window,
+ },
+ wasRevokedNow: true,
+ });
+
+ await service.revokeGrant({ workspaceId, grantId: 'grant_1' });
+
+ expect(
+ billingUsageCacheService.adjustAvailableCredits,
+ ).not.toHaveBeenCalled();
+ },
+ );
+
+ // The attempt that did revoke failed before reaching the counter, so the
+ // revoked credits are still spendable and only a rebuild from the ledger
+ // can repair that without decrementing a second time.
+ it('rebuilds the counter when the first revoke never reached it', async () => {
+ billingUsageCacheService.hasCounterAdjustmentBeenApplied.mockResolvedValue(
+ false,
+ );
+ billingCreditGrantService.getActiveCreditsMicro.mockResolvedValue(0);
+ billingCreditGrantService.revokeGrant.mockResolvedValue({
+ grant: { id: 'grant_1', amountMicro: 2_000_000 },
+ wasRevokedNow: false,
+ });
+
+ await service.revokeGrant({ workspaceId, grantId: 'grant_1' });
+
+ expect(
+ billingUsageCacheService.invalidateAvailableCredits,
+ ).toHaveBeenCalledWith(workspaceId, PERIOD_START);
+ expect(
+ billingUsageCacheService.adjustAvailableCredits,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('records that a revocation moved the counter so a retry can tell', async () => {
+ await service.revokeGrant({ workspaceId, grantId: 'grant_1' });
+
+ expect(
+ billingUsageCacheService.markCounterAdjustmentApplied,
+ ).toHaveBeenCalledWith(workspaceId, 'revoke:grant_1', PERIOD_END);
+ });
+
+ // The first attempt recorded that it moved the counter, so the retry must
+ // not move it again and must not rebuild either.
+ it('leaves the counter alone when the first revoke already adjusted it', async () => {
+ billingUsageCacheService.hasCounterAdjustmentBeenApplied.mockResolvedValue(
+ true,
+ );
+ billingUsageCacheService.getAvailableCredits.mockResolvedValue(3_000_000);
+ billingCreditGrantService.getActiveCreditsMicro.mockResolvedValue(0);
+ billingCreditGrantService.revokeGrant.mockResolvedValue({
+ grant: { id: 'grant_1', amountMicro: 2_000_000 },
+ wasRevokedNow: false,
});
- expect(billingCustomerRepository.increment).not.toHaveBeenCalled();
+ await service.revokeGrant({ workspaceId, grantId: 'grant_1' });
+
+ expect(
+ billingUsageCacheService.adjustAvailableCredits,
+ ).not.toHaveBeenCalled();
+ expect(
+ billingUsageCacheService.invalidateAvailableCredits,
+ ).not.toHaveBeenCalled();
+ expect(billingCustomerRepository.update).toHaveBeenCalledWith(
+ workspaceId,
+ {},
+ { creditBalanceMicro: 0 },
+ );
+ expect(
+ billingUsageCapService.clearHasReachedCapForWorkspace,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('leaves the cap in place when the revoke empties the balance', async () => {
+ billingCreditGrantService.getActiveCreditsMicro.mockResolvedValue(0);
+
+ await service.revokeGrant({ workspaceId, grantId: 'grant_1' });
+
expect(
- billingUsageCacheService.flushAvailableCredits,
+ billingUsageCapService.clearHasReachedCapForWorkspace,
).not.toHaveBeenCalled();
});
- it('does not flush the cache when no billing customer exists', async () => {
- billingCustomerRepository.increment.mockResolvedValue({ affected: 0 });
+ // Taking credits away can never make the workspace spendable again: the
+ // grants it leaves behind may already be spent, and the ledger total says
+ // nothing about that.
+ it('leaves the cap in place even when the revoke leaves other credits behind', async () => {
+ billingCreditGrantService.getActiveCreditsMicro.mockResolvedValue(
+ 500_000,
+ );
+
+ await service.revokeGrant({ workspaceId, grantId: 'grant_1' });
+
+ expect(
+ billingUsageCapService.clearHasReachedCapForWorkspace,
+ ).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('refreshWorkspaceCreditState', () => {
+ // Stripe redelivers events it already handled. The grants are still live in
+ // the ledger, but the workspace may have spent them since, and this replay
+ // adds nothing on top.
+ it('leaves the cap in place when a replay finds the counter already moved', async () => {
+ billingUsageCacheService.hasCounterAdjustmentBeenApplied.mockResolvedValue(
+ true,
+ );
- await service.creditWorkspaceBalance({
+ await service.refreshWorkspaceCreditState({
workspaceId,
- amountMicro: 2_000_000,
+ availableDeltaMicro: 0,
+ addsCredits: true,
+ isReplay: true,
+ adjustmentKey: 'rollover:2026-02-01T00:00:00.000Z',
});
- expect(billingCustomerRepository.increment).toHaveBeenCalled();
expect(
- billingUsageCacheService.flushAvailableCredits,
+ billingUsageCapService.clearHasReachedCapForWorkspace,
).not.toHaveBeenCalled();
});
- it.each([
- 0,
- -1,
- 1.5,
- Number.NaN,
- Number.POSITIVE_INFINITY,
- Number.MAX_SAFE_INTEGER + 1,
- ])(
- 'throws on a non-positive, non-integer or unsafe-integer amount (%p)',
- async (amountMicro) => {
- await expect(
- service.creditWorkspaceBalance({ workspaceId, amountMicro }),
- ).rejects.toThrow(BillingException);
+ // The delivery that wrote the grants never reached the counter, so this one
+ // rebuilds it and the credits become spendable here.
+ it('lifts the cap when a replay rebuilds the counter', async () => {
+ billingUsageCacheService.hasCounterAdjustmentBeenApplied.mockResolvedValue(
+ false,
+ );
- expect(billingCustomerRepository.increment).not.toHaveBeenCalled();
- },
- );
+ await service.refreshWorkspaceCreditState({
+ workspaceId,
+ availableDeltaMicro: 0,
+ addsCredits: true,
+ isReplay: true,
+ adjustmentKey: 'rollover:2026-02-01T00:00:00.000Z',
+ });
+
+ expect(
+ billingUsageCapService.clearHasReachedCapForWorkspace,
+ ).toHaveBeenCalledWith(workspaceId);
+ });
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-usage-cap.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-usage-cap.service.spec.ts
index 0b56204ef00..afd41098831 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-usage-cap.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-usage-cap.service.spec.ts
@@ -4,134 +4,113 @@ import { Test, type TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
-import { ClickHouseService } from 'src/database/clickHouse/clickHouse.service';
+import { Not } from 'typeorm';
+
+import { BillingException } from 'src/engine/core-modules/billing/billing.exception';
import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';
+import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
import { BillingUsageCapService } from 'src/engine/core-modules/billing/services/billing-usage-cap.service';
-import { ResourceCreditService } from 'src/engine/core-modules/billing/services/resource-credit.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+
+const workspaceId = 'ws_123';
describe('BillingUsageCapService', () => {
let service: BillingUsageCapService;
- let clickHouseService: jest.Mocked<ClickHouseService>;
- let twentyConfigService: jest.Mocked<TwentyConfigService>;
+ let billingSubscriptionItemRepository: jest.Mocked<{
+ find: jest.Mock;
+ update: jest.Mock;
+ }>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
BillingUsageCapService,
- {
- provide: ClickHouseService,
- useValue: {
- select: jest.fn(),
- },
- },
- {
- provide: ResourceCreditService,
- useValue: {
- extractResourceCreditPricingInfo: jest.fn(),
- },
- },
- {
- provide: TwentyConfigService,
- useValue: {
- get: jest.fn(),
- },
- },
{
provide: getRepositoryToken(BillingSubscriptionItemEntity),
useValue: {
- find: jest.fn(),
- update: jest.fn(),
+ find: jest.fn().mockResolvedValue([{ id: 'item_1' }]),
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
},
},
],
}).compile();
service = module.get<BillingUsageCapService>(BillingUsageCapService);
- clickHouseService = module.get(ClickHouseService);
- twentyConfigService = module.get(TwentyConfigService);
+ billingSubscriptionItemRepository = module.get(
+ getRepositoryToken(BillingSubscriptionItemEntity),
+ );
});
afterEach(() => {
jest.clearAllMocks();
});
- describe('isClickHouseEnabled', () => {
- it('returns true when CLICKHOUSE_URL is configured', () => {
- twentyConfigService.get.mockReturnValue('http://clickhouse:8123');
+ describe('setSubscriptionItemHasReachedCap', () => {
+ it('flags the resource credit item', async () => {
+ await service.setSubscriptionItemHasReachedCap(workspaceId, true);
- expect(service.isClickHouseEnabled()).toBe(true);
+ expect(billingSubscriptionItemRepository.update).toHaveBeenCalledWith(
+ { id: 'item_1' },
+ { hasReachedCurrentPeriodCap: true },
+ );
});
- it('returns false when CLICKHOUSE_URL is empty', () => {
- twentyConfigService.get.mockReturnValue('');
+ it("looks only at the workspace's non-canceled resource credit items", async () => {
+ await service.setSubscriptionItemHasReachedCap(workspaceId, true);
- expect(service.isClickHouseEnabled()).toBe(false);
- });
- });
-
- describe('getBatchPeriodCreditsUsed', () => {
- beforeEach(() => {
- twentyConfigService.get.mockReturnValue('http://clickhouse:8123');
+ expect(billingSubscriptionItemRepository.find).toHaveBeenCalledWith({
+ where: {
+ billingSubscription: {
+ workspaceId,
+ status: Not(SubscriptionStatus.Canceled),
+ },
+ billingProduct: { metadata: expect.anything() },
+ },
+ });
});
- it('returns empty map when ClickHouse is disabled', async () => {
- twentyConfigService.get.mockReturnValue('');
+ it('throws when the workspace has no resource credit item', async () => {
+ billingSubscriptionItemRepository.find.mockResolvedValue([]);
- const result = await service.getBatchPeriodCreditsUsed(
- ['ws_1', 'ws_2'],
- new Date('2026-04-01T00:00:00Z'),
- );
-
- expect(result.size).toBe(0);
- expect(clickHouseService.select).not.toHaveBeenCalled();
+ await expect(
+ service.setSubscriptionItemHasReachedCap(workspaceId, true),
+ ).rejects.toThrow(BillingException);
});
- it('returns empty map when workspaceIds is empty', async () => {
- const result = await service.getBatchPeriodCreditsUsed(
- [],
- new Date('2026-04-01T00:00:00Z'),
- );
+ it('throws when the workspace has more than one resource credit item', async () => {
+ billingSubscriptionItemRepository.find.mockResolvedValue([
+ { id: 'item_1' },
+ { id: 'item_2' },
+ ]);
- expect(result.size).toBe(0);
- expect(clickHouseService.select).not.toHaveBeenCalled();
+ await expect(
+ service.setSubscriptionItemHasReachedCap(workspaceId, true),
+ ).rejects.toThrow(BillingException);
});
+ });
- it('returns usage grouped by workspaceId', async () => {
- clickHouseService.select.mockResolvedValue([
- { workspaceId: 'ws_1', total: 500_000 },
- { workspaceId: 'ws_2', total: 1_200_000 },
+ describe('clearHasReachedCapForWorkspace', () => {
+ it('clears the flag on every resource credit item', async () => {
+ billingSubscriptionItemRepository.find.mockResolvedValue([
+ { id: 'item_1' },
+ { id: 'item_2' },
]);
- const result = await service.getBatchPeriodCreditsUsed(
- ['ws_1', 'ws_2', 'ws_3'],
- new Date('2026-04-01T00:00:00Z'),
- );
-
- expect(result.get('ws_1')).toBe(500_000);
- expect(result.get('ws_2')).toBe(1_200_000);
- expect(result.has('ws_3')).toBe(false);
-
- const [query, params] = clickHouseService.select.mock.calls[0];
+ await service.clearHasReachedCapForWorkspace(workspaceId);
- expect(query).toContain('GROUP BY workspaceId');
- expect(query).toContain('IN {workspaceIds:Array(String)}');
- expect(params).toMatchObject({
- workspaceIds: ['ws_1', 'ws_2', 'ws_3'],
- });
+ expect(billingSubscriptionItemRepository.update).toHaveBeenCalledWith(
+ { id: expect.objectContaining({ _value: ['item_1', 'item_2'] }) },
+ { hasReachedCurrentPeriodCap: false },
+ );
});
- it('coerces string totals from ClickHouse', async () => {
- clickHouseService.select.mockResolvedValue([
- { workspaceId: 'ws_1', total: '9876543210' },
- ]);
+ it('does nothing rather than throwing when there is no item to clear', async () => {
+ billingSubscriptionItemRepository.find.mockResolvedValue([]);
- const result = await service.getBatchPeriodCreditsUsed(
- ['ws_1'],
- new Date('2026-04-01T00:00:00Z'),
- );
+ await expect(
+ service.clearHasReachedCapForWorkspace(workspaceId),
+ ).resolves.not.toThrow();
- expect(result.get('ws_1')).toBe(9876543210);
+ expect(billingSubscriptionItemRepository.update).not.toHaveBeenCalled();
});
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-usage.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-usage.service.spec.ts
new file mode 100644
index 00000000000..a77551e86c3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/billing-usage.service.spec.ts
@@ -0,0 +1,250 @@
+/* @license Enterprise */
+
+import { Test, type TestingModule } from '@nestjs/testing';
+
+import { ClickHouseService } from 'src/database/clickHouse/clickHouse.service';
+import { CoreEntityCacheService } from 'src/engine/core-entity-cache/services/core-entity-cache.service';
+import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
+import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';
+import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
+import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
+import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';
+import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
+import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
+import { BillingUsageCapService } from 'src/engine/core-modules/billing/services/billing-usage-cap.service';
+import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import {
+ CacheLockException,
+ CacheLockExceptionCode,
+} from 'src/engine/core-modules/cache-lock/exceptions/cache-lock.exception';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const workspaceId = 'ws_123';
+const PERIOD_START = new Date('2026-01-01T00:00:00.000Z');
+const PERIOD_END = new Date('2026-02-01T00:00:00.000Z');
+const ALLOWANCE = 1_000_000;
+
+const currentBillingSubscription = {
+ workspaceId,
+ status: SubscriptionStatus.Active,
+ currentPeriodStart: PERIOD_START,
+ currentPeriodEnd: PERIOD_END,
+};
+
+const subscriptionWithAllowance = {
+ workspaceId,
+ status: SubscriptionStatus.Active,
+ currentPeriodStart: PERIOD_START,
+ currentPeriodEnd: PERIOD_END,
+ billingSubscriptionItems: [
+ {
+ stripePriceId: 'price_1',
+ billingProduct: {
+ metadata: { productKey: BillingProductKey.RESOURCE_CREDIT },
+ billingPrices: [
+ {
+ stripePriceId: 'price_1',
+ metadata: { credit_amount: String(ALLOWANCE) },
+ },
+ ],
+ },
+ },
+ ],
+};
+
+describe('BillingUsageService', () => {
+ let service: BillingUsageService;
+ let billingUsageCacheService: jest.Mocked<{
+ getAvailableCredits: jest.Mock;
+ warmAvailableCredits: jest.Mock;
+ adjustAvailableCredits: jest.Mock;
+ }>;
+ let billingCreditGrantService: jest.Mocked<{
+ getSpendableCreditsMicro: jest.Mock;
+ }>;
+ let cacheLockService: jest.Mocked<{ withLock: jest.Mock }>;
+ let clickHouseService: jest.Mocked<{ select: jest.Mock }>;
+
+ beforeEach(async () => {
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ BillingUsageService,
+ {
+ provide: BillingCreditGrantService,
+ useValue: {
+ getSpendableCreditsMicro: jest.fn().mockResolvedValue(0),
+ },
+ },
+ {
+ provide: BillingSubscriptionService,
+ useValue: {
+ getTrialPeriodFreeWorkflowCredits: jest.fn().mockReturnValue(0),
+ },
+ },
+ {
+ provide: TwentyConfigService,
+ useValue: { get: jest.fn().mockReturnValue(true) },
+ },
+ {
+ provide: BillingSubscriptionItemService,
+ useValue: {
+ getResourceCreditSubscriptionItemDetails: jest.fn(),
+ },
+ },
+ {
+ provide: BillingUsageCacheService,
+ useValue: {
+ getAvailableCredits: jest.fn().mockResolvedValue(undefined),
+ warmAvailableCredits: jest.fn().mockResolvedValue(undefined),
+ adjustAvailableCredits: jest.fn().mockResolvedValue(0),
+ },
+ },
+ {
+ provide: getWorkspaceScopedRepositoryToken(BillingSubscriptionEntity),
+ useValue: {
+ findOne: jest.fn().mockResolvedValue(subscriptionWithAllowance),
+ },
+ },
+ {
+ provide: WorkspaceCacheService,
+ useValue: {
+ getOrRecompute: jest
+ .fn()
+ .mockResolvedValue({ currentBillingSubscription }),
+ },
+ },
+ {
+ provide: ClickHouseService,
+ useValue: { select: jest.fn().mockResolvedValue([{ total: 0 }]) },
+ },
+ {
+ provide: BillingUsageCapService,
+ useValue: {
+ setSubscriptionItemHasReachedCap: jest
+ .fn()
+ .mockResolvedValue(undefined),
+ },
+ },
+ {
+ provide: CacheLockService,
+ useValue: { withLock: jest.fn((fn: () => unknown) => fn()) },
+ },
+ {
+ provide: CoreEntityCacheService,
+ useValue: { get: jest.fn().mockResolvedValue(undefined) },
+ },
+ ],
+ }).compile();
+
+ service = module.get<BillingUsageService>(BillingUsageService);
+ billingUsageCacheService = module.get(BillingUsageCacheService);
+ billingCreditGrantService = module.get(BillingCreditGrantService);
+ cacheLockService = module.get(CacheLockService);
+ clickHouseService = module.get(ClickHouseService);
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe('hasAvailableCredits', () => {
+ it('answers from the warm counter without taking the lock', async () => {
+ billingUsageCacheService.getAvailableCredits.mockResolvedValue(500);
+
+ expect(await service.hasAvailableCredits(workspaceId)).toBe(true);
+ expect(cacheLockService.withLock).not.toHaveBeenCalled();
+ expect(clickHouseService.select).not.toHaveBeenCalled();
+ });
+
+ // Computing from the ledger and warming the counter are a read and a write
+ // that a concurrent grant must not slip between, or the grant is counted
+ // here and then added to the counter a second time.
+ it('takes the credit state lock before computing a cold counter', async () => {
+ expect(await service.hasAvailableCredits(workspaceId)).toBe(true);
+
+ expect(cacheLockService.withLock).toHaveBeenCalledWith(
+ expect.any(Function),
+ `billing-credit-state:${workspaceId}`,
+ expect.any(Object),
+ );
+ expect(billingUsageCacheService.warmAvailableCredits).toHaveBeenCalled();
+ });
+
+ it('skips the recompute when another reader warmed the counter first', async () => {
+ billingUsageCacheService.getAvailableCredits
+ .mockResolvedValueOnce(undefined)
+ .mockResolvedValue(400);
+
+ expect(await service.hasAvailableCredits(workspaceId)).toBe(true);
+ expect(clickHouseService.select).not.toHaveBeenCalled();
+ expect(
+ billingUsageCacheService.warmAvailableCredits,
+ ).not.toHaveBeenCalled();
+ });
+
+ // Failing the execution because someone is writing a grant would be worse
+ // than answering from a value this call computed itself. It must not warm
+ // though: holding the lock is what makes installing a value safe.
+ it('computes without warming rather than failing when the lock times out', async () => {
+ cacheLockService.withLock.mockRejectedValue(
+ new CacheLockException(
+ 'Failed to acquire lock',
+ CacheLockExceptionCode.LOCK_ACQUISITION_TIMEOUT,
+ ),
+ );
+
+ expect(await service.hasAvailableCredits(workspaceId)).toBe(true);
+ expect(
+ billingUsageCacheService.warmAvailableCredits,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('propagates failures that are not a lock timeout', async () => {
+ cacheLockService.withLock.mockRejectedValue(new Error('redis is down'));
+
+ await expect(service.hasAvailableCredits(workspaceId)).rejects.toThrow(
+ 'redis is down',
+ );
+ });
+ });
+
+ describe('decrementAvailableCreditsInCache', () => {
+ it('decrements the warm counter without taking the lock', async () => {
+ billingUsageCacheService.getAvailableCredits.mockResolvedValue(500);
+ billingUsageCacheService.adjustAvailableCredits.mockResolvedValue(300);
+
+ expect(
+ await service.decrementAvailableCreditsInCache({
+ workspaceId,
+ usedCredits: 200,
+ }),
+ ).toBe(300);
+ expect(cacheLockService.withLock).not.toHaveBeenCalled();
+ });
+
+ // Incrementing an absent key would install -usedCredits as the whole
+ // balance, so a call that could not warm the counter only computes.
+ it('subtracts locally when the lock timed out and nothing was warmed', async () => {
+ billingCreditGrantService.getSpendableCreditsMicro.mockResolvedValue(0);
+ cacheLockService.withLock.mockRejectedValue(
+ new CacheLockException(
+ 'Failed to acquire lock',
+ CacheLockExceptionCode.LOCK_ACQUISITION_TIMEOUT,
+ ),
+ );
+
+ expect(
+ await service.decrementAvailableCreditsInCache({
+ workspaceId,
+ usedCredits: 200,
+ }),
+ ).toBe(ALLOWANCE - 200);
+ expect(
+ billingUsageCacheService.adjustAvailableCredits,
+ ).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/resource-credit.service.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/resource-credit.service.spec.ts
index 7649ac51d7f..c46eba2d0b6 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/__test__/resource-credit.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/__test__/resource-credit.service.spec.ts
@@ -131,7 +131,7 @@ describe('ResourceCreditService', () => {
'sub_123',
);
- expect(result).toEqual({ tierQuantity: 5000, unitPriceCents: 5 });
+ expect(result).toEqual({ tierQuantity: 5000 });
});
it('returns null when subscription not found', async () => {
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.ts
new file mode 100644
index 00000000000..66851d73e07
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts
@@ -0,0 +1,352 @@
+/* @license Enterprise */
+
+import { Injectable } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+import { IsNull, LessThan, MoreThan } from 'typeorm';
+
+import { POSTGRESQL_ERROR_CODES } from 'src/engine/api/graphql/workspace-query-runner/constants/postgres-error-codes.constants';
+import {
+ BillingException,
+ 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 { 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;
+ type: BillingCreditGrantType;
+ effectiveAt: Date;
+ expiresAt: Date;
+ reason?: string | null;
+ grantedByUserId?: string | null;
+ idempotencyKey?: string | null;
+ sourceGrantId?: string | null;
+};
+
+const getPostgresErrorCode = (error: unknown): string | undefined => {
+ if (!isDefined(error) || typeof error !== 'object' || !('code' in error)) {
+ return undefined;
+ }
+
+ return typeof error.code === 'string' ? error.code : undefined;
+};
+
+// TypeORM wraps the driver error, and which of the two carries the code
+// depends on how the query was issued.
+const isUniqueViolation = (error: unknown): boolean => {
+ if (getPostgresErrorCode(error) === POSTGRESQL_ERROR_CODES.UNIQUE_VIOLATION) {
+ return true;
+ }
+
+ if (
+ !isDefined(error) ||
+ typeof error !== 'object' ||
+ !('driverError' in error)
+ ) {
+ return false;
+ }
+
+ return (
+ getPostgresErrorCode(error.driverError) ===
+ POSTGRESQL_ERROR_CODES.UNIQUE_VIOLATION
+ );
+};
+
+// Owns the billingCreditGrant table. Deliberately free of side effects so that
+// read paths (available credits) can depend on it without pulling in the cache
+// and subscription services that BillingCreditService needs.
+@Injectable()
+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
+ // a fresh grant from a replayed one.
+ async createGrant(
+ params: CreateBillingCreditGrantParams,
+ ): Promise<BillingCreditGrantEntity | null> {
+ const {
+ workspaceId,
+ amountMicro,
+ type,
+ effectiveAt,
+ expiresAt,
+ reason = null,
+ grantedByUserId = null,
+ idempotencyKey = null,
+ sourceGrantId = null,
+ } = params;
+
+ if (!Number.isSafeInteger(amountMicro) || amountMicro <= 0) {
+ throw new BillingException(
+ `Cannot grant an amount (${amountMicro}) that is not a positive safe integer to workspace ${workspaceId}`,
+ BillingExceptionCode.BILLING_CREDIT_AMOUNT_INVALID,
+ );
+ }
+
+ if (expiresAt.getTime() <= effectiveAt.getTime()) {
+ throw new BillingException(
+ `Cannot grant credits to workspace ${workspaceId} expiring at ${expiresAt.toISOString()}, before or when they become effective at ${effectiveAt.toISOString()}`,
+ BillingExceptionCode.BILLING_CREDIT_GRANT_VALIDITY_INVALID,
+ );
+ }
+
+ try {
+ const { identifiers, generatedMaps } =
+ await this.billingCreditGrantRepository.insert(workspaceId, {
+ amountMicro,
+ type,
+ effectiveAt,
+ expiresAt,
+ reason,
+ grantedByUserId,
+ idempotencyKey,
+ sourceGrantId,
+ });
+
+ const insertedId = identifiers[0]?.id ?? generatedMaps[0]?.id;
+ const grantId = typeof insertedId === 'string' ? insertedId : undefined;
+
+ if (!isDefined(grantId)) {
+ return null;
+ }
+
+ return this.billingCreditGrantRepository.findOne(workspaceId, {
+ where: { id: grantId },
+ });
+ } catch (error) {
+ if (isDefined(idempotencyKey) && isUniqueViolation(error)) {
+ return null;
+ }
+
+ throw error;
+ }
+ }
+
+ async getActiveCreditsMicro(workspaceId: string): Promise<number> {
+ const result = await this.billingCreditGrantRepository
+ .createQueryBuilder('billingCreditGrant')
+ .select('COALESCE(SUM("billingCreditGrant"."amountMicro"), 0)', 'total')
+ .where('"billingCreditGrant"."workspaceId" = :workspaceId', {
+ workspaceId,
+ })
+ .andWhere('"billingCreditGrant"."revokedAt" IS NULL')
+ .andWhere('"billingCreditGrant"."effectiveAt" <= now()')
+ .andWhere('"billingCreditGrant"."expiresAt" > now()')
+ .getRawOne<{ total: string | number | null }>();
+
+ const total = Number(result?.total ?? 0);
+
+ // Rounding a balance would hand out or withhold credits that were never
+ // granted, so refuse rather than serve a number we cannot represent.
+ if (!Number.isSafeInteger(total)) {
+ throw new BillingException(
+ `Credit balance for workspace ${workspaceId} is not a safe integer (${total})`,
+ BillingExceptionCode.BILLING_CREDIT_AMOUNT_INVALID,
+ );
+ }
+
+ 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,
+ periodStart,
+ periodEnd,
+ }: {
+ workspaceId: string;
+ periodStart: Date;
+ periodEnd: Date;
+ }): Promise<BillingCreditGrantEntity[]> {
+ return this.billingCreditGrantRepository.find(workspaceId, {
+ where: {
+ revokedAt: IsNull(),
+ effectiveAt: LessThan(periodEnd),
+ expiresAt: MoreThan(periodStart),
+ },
+ order: { createdAt: 'ASC' },
+ });
+ }
+
+ // The previous transition pulled every grant it closed back to the instant
+ // the period ended, so the ledger records where the closing period started.
+ // Calendar arithmetic cannot recover it once the subscription has moved on:
+ // a month-end anchor clamps, and subtracting a month from February 28 gives
+ // January 28 rather than the January 31 the period actually started on.
+ async findPeriodStartBefore({
+ workspaceId,
+ boundary,
+ }: {
+ workspaceId: string;
+ boundary: Date;
+ }): Promise<Date | null> {
+ const [row] = await this.billingCreditGrantRepository.find(workspaceId, {
+ where: { expiresAt: LessThan(boundary) },
+ order: { expiresAt: 'DESC' },
+ take: 1,
+ });
+
+ return row?.expiresAt ?? null;
+ }
+
+ // Enforces the one-grant-per-period invariant at the point where periods
+ // actually roll: whatever a writer guessed for expiresAt, a grant never
+ // outlives the period it was carried forward from. Matched by predicate
+ // rather than by id so a grant created while the transition runs is covered
+ // too.
+ async closeGrantsAtPeriodEnd({
+ workspaceId,
+ periodEnd,
+ }: {
+ workspaceId: string;
+ periodEnd: Date;
+ }): Promise<void> {
+ await this.billingCreditGrantRepository.update(
+ workspaceId,
+ {
+ revokedAt: IsNull(),
+ effectiveAt: LessThan(periodEnd),
+ expiresAt: MoreThan(periodEnd),
+ },
+ { expiresAt: periodEnd },
+ );
+ }
+
+ async listGrants(workspaceId: string): Promise<BillingCreditGrantEntity[]> {
+ return this.billingCreditGrantRepository.find(workspaceId, {
+ order: { createdAt: 'DESC' },
+ });
+ }
+
+ // wasRevokedNow tells a retried revocation apart from the one that actually
+ // took the credits away, so callers only adjust balances once.
+ async revokeGrant({
+ workspaceId,
+ grantId,
+ revokedByUserId,
+ }: {
+ workspaceId: string;
+ grantId: string;
+ revokedByUserId?: string | null;
+ }): Promise<{ grant: BillingCreditGrantEntity; wasRevokedNow: boolean }> {
+ const grant = await this.billingCreditGrantRepository.findOne(workspaceId, {
+ where: { id: grantId },
+ });
+
+ if (!isDefined(grant)) {
+ throw new BillingException(
+ `Credit grant ${grantId} not found for workspace ${workspaceId}`,
+ BillingExceptionCode.BILLING_CREDIT_GRANT_NOT_FOUND,
+ );
+ }
+
+ if (isDefined(grant.revokedAt)) {
+ return { grant, wasRevokedNow: false };
+ }
+
+ const { affected } = await this.billingCreditGrantRepository.update(
+ workspaceId,
+ { id: grantId, revokedAt: IsNull() },
+ { revokedAt: new Date(), revokedByUserId: revokedByUserId ?? null },
+ );
+
+ const revokedGrant = await this.billingCreditGrantRepository.findOneOrFail(
+ workspaceId,
+ { where: { id: grantId } },
+ );
+
+ // Two concurrent revocations both read an unrevoked grant; only the one
+ // whose UPDATE matched may move the balance.
+ return {
+ grant: revokedGrant,
+ wasRevokedNow: isDefined(affected) && affected > 0,
+ };
+ }
+
+ async findGrantByIdempotencyKey(
+ workspaceId: string,
+ idempotencyKey: string,
+ ): Promise<BillingCreditGrantEntity | null> {
+ const grant = await this.billingCreditGrantRepository.findOne(workspaceId, {
+ where: { idempotencyKey },
+ });
+
+ 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.ts
index 21e0b6f5027..aebc9f3b0b3 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
@@ -2,42 +2,193 @@
import { Injectable } from '@nestjs/common';
-import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ BillingException,
+ BillingExceptionCode,
+} from 'src/engine/core-modules/billing/billing.exception';
+import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
+import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.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 { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';
+import { computeCarryForwardGrants } from 'src/engine/core-modules/billing/utils/compute-carry-forward-grants.util';
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+
+export type ProcessRolloverParams = {
+ workspaceId: string;
+ closingPeriodStart: Date;
+ closingPeriodEnd: Date;
+ closingAllowanceMicro: number;
+ nextPeriodStart: Date;
+ nextPeriodEnd: Date;
+ nextAllowanceMicro: number;
+};
+
+// The transition writes more rows than a single grant does, so it is given more
+// room than the lock's default before it gives up.
+const ROLLOVER_LOCK_OPTIONS = { ms: 200, maxRetries: 50, ttl: 30_000 };
+
@Injectable()
export class BillingCreditRolloverService {
constructor(
private readonly billingUsageService: BillingUsageService,
- @InjectWorkspaceScopedRepository(BillingCustomerEntity)
- private readonly billingCustomerRepository: WorkspaceScopedRepository<BillingCustomerEntity>,
+ private readonly billingCreditGrantService: BillingCreditGrantService,
+ private readonly billingCreditService: BillingCreditService,
+ private readonly cacheLockService: CacheLockService,
+ private readonly twentyConfigService: TwentyConfigService,
) {}
- async processRolloverOnPeriodTransition({
- workspaceId,
- stripeCustomerId,
- tierQuantity,
- previousPeriodStart,
- }: {
- workspaceId: string;
- stripeCustomerId: string;
- tierQuantity: number;
- previousPeriodStart: Date;
- }): Promise<void> {
- const usedCredits =
- await this.billingUsageService.getCurrentPeriodCreditsUsed(
+ async processRolloverOnPeriodTransition(
+ params: ProcessRolloverParams,
+ ): Promise<void> {
+ const { workspaceId, closingPeriodStart, closingPeriodEnd } = params;
+
+ // Read outside the lock: usage comes from ClickHouse and no credit write
+ // can change it, so paying that latency while holding the lock would only
+ // stall concurrent grants.
+ const usageMicro =
+ await this.billingUsageService.getCreditsUsedBetweenOrNull({
workspaceId,
- previousPeriodStart,
+ from: closingPeriodStart,
+ to: closingPeriodEnd,
+ });
+
+ // Reading usage as zero when the query failed would roll a full unused
+ // allowance over to every workspace invoiced during the outage. Throwing
+ // fails the webhook so Stripe redelivers it; returning normally would
+ // answer 200 and the transition would never run, closing no grants and
+ // carrying nothing forward, so the workspace silently loses its balance
+ // at expiry.
+ if (!isDefined(usageMicro)) {
+ throw new BillingException(
+ `Cannot roll credits over for workspace ${workspaceId}: usage for the period starting ${closingPeriodStart.toISOString()} could not be read`,
+ BillingExceptionCode.BILLING_USAGE_UNAVAILABLE,
);
+ }
- const unusedCredits = Math.max(0, tierQuantity - usedCredits);
- const rolloverAmount = Math.min(unusedCredits, tierQuantity);
+ // Everything from here reads the ledger, decides from that snapshot, then
+ // writes it back. A grant landing in between would either be carried twice
+ // or dropped, so the whole read-decide-write runs alone.
+ await this.cacheLockService.withLock(
+ () => this.carryGrantsForward({ ...params, usageMicro }),
+ buildBillingCreditStateLockKey(workspaceId),
+ ROLLOVER_LOCK_OPTIONS,
+ );
+ }
- await this.billingCustomerRepository.update(
+ private async carryGrantsForward({
+ workspaceId,
+ closingPeriodStart,
+ closingPeriodEnd,
+ closingAllowanceMicro,
+ nextPeriodStart,
+ nextPeriodEnd,
+ nextAllowanceMicro,
+ usageMicro,
+ }: ProcessRolloverParams & { usageMicro: number }): Promise<void> {
+ await this.billingCreditGrantService.materializeLegacyBalance({
workspaceId,
- { stripeCustomerId },
- { creditBalanceMicro: rolloverAmount },
+ effectiveAt: closingPeriodStart,
+ expiresAt: closingPeriodEnd,
+ });
+
+ const closingGrants =
+ await this.billingCreditGrantService.findGrantsLiveDuringPeriod({
+ workspaceId,
+ periodStart: closingPeriodStart,
+ periodEnd: closingPeriodEnd,
+ });
+
+ const rolloverCapMultiplier = this.twentyConfigService.get(
+ 'BILLING_ROLLOVER_TOTAL_CAP_MULTIPLIER',
);
+
+ const carryForwardGrants = computeCarryForwardGrants({
+ allowanceMicro: closingAllowanceMicro,
+ liveGrants: closingGrants.map((grant) => ({
+ grantId: grant.id,
+ type: grant.type,
+ amountMicro: grant.amountMicro,
+ createdAt: grant.createdAt,
+ })),
+ usageMicro,
+ rolloverCapMicro: (rolloverCapMultiplier - 1) * nextAllowanceMicro,
+ });
+
+ await this.billingCreditGrantService.closeGrantsAtPeriodEnd({
+ workspaceId,
+ periodEnd: closingPeriodEnd,
+ });
+
+ let carriedForwardMicro = 0;
+ let hasReplayedGrant = false;
+
+ // Writes the grants directly rather than through grantCredits: the cache,
+ // cap flag and workspace cache only need refreshing once for the whole
+ // transition, and this runs inside a Stripe webhook.
+ for (const carryForwardGrant of carryForwardGrants) {
+ const grant = await this.billingCreditGrantService.createGrant({
+ workspaceId,
+ amountMicro: carryForwardGrant.amountMicro,
+ type: carryForwardGrant.type,
+ sourceGrantId: carryForwardGrant.sourceGrantId,
+ effectiveAt: nextPeriodStart,
+ expiresAt: nextPeriodEnd,
+ reason: `Carried over from the period starting ${closingPeriodStart.toISOString()}`,
+ idempotencyKey: buildCarryForwardIdempotencyKey({
+ workspaceId,
+ nextPeriodStart,
+ type: carryForwardGrant.type,
+ sourceGrantId: carryForwardGrant.sourceGrantId,
+ }),
+ });
+
+ if (isDefined(grant)) {
+ carriedForwardMicro += grant.amountMicro;
+ } else {
+ hasReplayedGrant = true;
+ }
+ }
+
+ // A replay only tells us the rows already exist, not whether the delivery
+ // that wrote them got as far as the counter. Stripe also redelivers events
+ // it already handled successfully, and rebuilding then would throw away a
+ // correct warm counter and recompute it from ClickHouse, crediting back
+ // whatever usage has not been ingested yet. So the transition records under
+ // adjustmentKey that it moved the counter, and the refresh rebuilds only
+ // when that record is absent.
+ //
+ // Runs unconditionally: closing the old grants moves the balance on its
+ // own, so a period where everything was spent still needs the refresh.
+ await this.billingCreditService.refreshWorkspaceCreditState({
+ workspaceId,
+ availableDeltaMicro: carriedForwardMicro,
+ addsCredits: true,
+ isReplay: hasReplayedGrant,
+ adjustmentKey: buildRolloverAdjustmentKey(nextPeriodStart),
+ });
}
}
+
+// Scopes the completion marker to one period transition, so only a redelivery
+// of that transition can see it.
+const buildRolloverAdjustmentKey = (nextPeriodStart: Date): string =>
+ `rollover:${nextPeriodStart.toISOString()}`;
+
+// Stripe redelivers webhooks, so the whole transition has to be replayable.
+const buildCarryForwardIdempotencyKey = ({
+ workspaceId,
+ nextPeriodStart,
+ type,
+ sourceGrantId,
+}: {
+ workspaceId: string;
+ nextPeriodStart: Date;
+ type: string;
+ sourceGrantId: string | null;
+}): string =>
+ `carry-forward:${workspaceId}:${nextPeriodStart.toISOString()}:${type}:${
+ sourceGrantId ?? 'allowance'
+ }`;
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.ts
index c7818f70b0e..b44bb602bdd 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
@@ -2,17 +2,41 @@
import { Injectable, Logger } from '@nestjs/common';
+import { addDays } from 'date-fns';
import { isDefined } from 'twenty-shared/utils';
-import {
- BillingException,
- BillingExceptionCode,
-} from 'src/engine/core-modules/billing/billing.exception';
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';
+import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
+import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
+import { BillingUsageCapService } from 'src/engine/core-modules/billing/services/billing-usage-cap.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
+import { 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
+// granted during signup. The next period transition re-emits the unspent part
+// aligned on the real billing period.
+const PROVISIONAL_GRANT_VALIDITY_IN_DAYS = 31;
+
+export type GrantCreditsParams = {
+ workspaceId: string;
+ amountMicro: number;
+ type: BillingCreditGrantType;
+ reason?: string | null;
+ grantedByUserId?: string | null;
+ idempotencyKey?: string | null;
+ effectiveAt?: Date;
+ expiresAt?: Date;
+ sourceGrantId?: string | null;
+};
@Injectable()
export class BillingCreditService {
@@ -20,44 +44,411 @@ export class BillingCreditService {
constructor(
private readonly billingService: BillingService,
+ private readonly billingCreditGrantService: BillingCreditGrantService,
+ private readonly billingSubscriptionService: BillingSubscriptionService,
private readonly billingUsageCacheService: BillingUsageCacheService,
+ private readonly billingUsageCapService: BillingUsageCapService,
+ private readonly cacheLockService: CacheLockService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
@InjectWorkspaceScopedRepository(BillingCustomerEntity)
private readonly billingCustomerRepository: WorkspaceScopedRepository<BillingCustomerEntity>,
) {}
- async creditWorkspaceBalance({
+ async grantCredits(
+ params: GrantCreditsParams,
+ ): Promise<BillingCreditGrantEntity | null> {
+ if (!this.billingService.isBillingEnabled()) {
+ return null;
+ }
+
+ const { workspaceId } = params;
+
+ // Writing the row and moving the counter are two steps, and a reader that
+ // computes availability between them counts the grant from the ledger and
+ // then has it added a second time. Locking keeps the pair indivisible for
+ // anything else touching this workspace's credit state.
+ return this.cacheLockService.withLock(
+ () => this.writeGrantAndRefreshState(params),
+ buildBillingCreditStateLockKey(workspaceId),
+ );
+ }
+
+ private async writeGrantAndRefreshState(
+ params: GrantCreditsParams,
+ ): Promise<BillingCreditGrantEntity | null> {
+ const { workspaceId, amountMicro } = params;
+
+ // Read once for the whole write: the validity window and the state refresh
+ // both need it, and both run inside the lock. Reading it here rather than
+ // before the lock is what keeps a grant that waited behind a period
+ // transition from carrying the period the wait started in, which would
+ // land it already expired while its amount still went onto the counter for
+ // the period that had meanwhile opened.
+ const subscription =
+ await this.billingSubscriptionService.getCurrentBillingSubscription({
+ workspaceId,
+ });
+
+ const { effectiveAt, expiresAt } = resolveGrantValidity(
+ params,
+ subscription,
+ );
+
+ await this.billingCreditGrantService.materializeLegacyBalance({
+ workspaceId,
+ effectiveAt,
+ expiresAt,
+ });
+
+ const grant = await this.billingCreditGrantService.createGrant({
+ ...params,
+ effectiveAt,
+ expiresAt,
+ });
+
+ // A replay only means the ledger row exists, not that the projections
+ // built from it do: the first attempt can have inserted the row and then
+ // failed on the refresh, and onboarding callers swallow that error. Repair
+ // rather than return, with no counter delta since the original attempt may
+ // already have applied it.
+ if (!isDefined(grant)) {
+ this.logger.log(
+ `Replayed credit grant for workspace ${workspaceId} (idempotency key ${params.idempotencyKey}), repairing derived state`,
+ );
+
+ // Rebuilding from the ledger can overstate the balance by whatever
+ // usage ClickHouse has not ingested yet, and that value then stands for
+ // the period. Accepted here because the alternative is a grant that
+ // stays invisible for the whole period, and erring high is the direction
+ // the grant intended. The cap is left to be derived from the rebuilt
+ // balance, since the replayed grant may since have been revoked.
+ await this.refreshWorkspaceCreditState({
+ workspaceId,
+ availableDeltaMicro: 0,
+ addsCredits: true,
+ isReplay: true,
+ subscription,
+ });
+
+ return null;
+ }
+
+ await this.refreshWorkspaceCreditState({
+ workspaceId,
+ availableDeltaMicro: amountMicro,
+ addsCredits: true,
+ subscription,
+ });
+
+ return grant;
+ }
+
+ async revokeGrant({
workspaceId,
- amountMicro,
+ grantId,
+ revokedByUserId,
}: {
workspaceId: string;
- amountMicro: number;
- }): Promise<void> {
+ grantId: string;
+ revokedByUserId?: string | null;
+ }): Promise<BillingCreditGrantEntity> {
+ return this.cacheLockService.withLock(
+ () =>
+ this.markGrantRevokedAndRefreshState({
+ workspaceId,
+ grantId,
+ revokedByUserId,
+ }),
+ buildBillingCreditStateLockKey(workspaceId),
+ );
+ }
+
+ private async markGrantRevokedAndRefreshState({
+ workspaceId,
+ grantId,
+ revokedByUserId,
+ }: {
+ workspaceId: string;
+ grantId: string;
+ revokedByUserId?: string | null;
+ }): Promise<BillingCreditGrantEntity> {
+ const { grant, wasRevokedNow } =
+ await this.billingCreditGrantService.revokeGrant({
+ workspaceId,
+ grantId,
+ revokedByUserId,
+ });
+
+ const adjustmentKey = buildRevocationAdjustmentKey(grantId);
+
+ // A retried revocation must not take the same credits off the usage
+ // counter twice, which would block a workspace that still has credits.
+ // Whether the attempt that did revoke got as far as the counter is
+ // recorded under adjustmentKey, so the refresh can tell the two apart:
+ // already applied means repair the rest and leave the counter alone, never
+ // applied means rebuild from the ledger. Guessing either way is wrong,
+ // since always rebuilding freezes ClickHouse lag in as extra credit on
+ // every double click and never rebuilding leaves revoked credits spendable
+ // until the period ends.
+ if (!wasRevokedNow) {
+ await this.refreshWorkspaceCreditState({
+ workspaceId,
+ availableDeltaMicro: 0,
+ addsCredits: false,
+ isReplay: true,
+ adjustmentKey,
+ });
+
+ return grant;
+ }
+
+ // Only credits the counter actually holds may come off it. The mutation
+ // accepts any grant id, and a grant can expire between the admin panel
+ // rendering and the revoke landing, so subtracting unconditionally would
+ // take away credits that were never counted and block usage until the
+ // period ends.
+ const revokedAtMs = (grant.revokedAt ?? new Date()).getTime();
+ const wasActiveWhenRevoked =
+ grant.effectiveAt.getTime() <= revokedAtMs &&
+ grant.expiresAt.getTime() > revokedAtMs;
+
+ await this.refreshWorkspaceCreditState({
+ workspaceId,
+ availableDeltaMicro: wasActiveWhenRevoked ? -grant.amountMicro : 0,
+ addsCredits: false,
+ adjustmentKey,
+ });
+
+ 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;
}
- if (!Number.isSafeInteger(amountMicro) || amountMicro <= 0) {
- throw new BillingException(
- `Cannot credit an amount (${amountMicro}) that is not a positive safe integer to workspace ${workspaceId}`,
- BillingExceptionCode.BILLING_CREDIT_AMOUNT_INVALID,
- );
+ 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;
}
- const { affected } = await this.billingCustomerRepository.increment(
+ await this.billingCustomerRepository.update(
workspaceId,
{},
- 'creditBalanceMicro',
- amountMicro,
+ { creditBalanceMicro: activeCreditsMicro },
);
- if (!isDefined(affected) || affected === 0) {
- this.logger.warn(
- `Skipped crediting ${amountMicro} credits: no billing customer for workspace ${workspaceId}`,
- );
+ return activeCreditsMicro;
+ }
+
+ // Keeps everything that reads a credit balance consistent with the ledger:
+ // the mirror column, the Redis counter that gates usage, the flag that drives
+ // the "no more credits" banner, 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,
+ addsCredits,
+ isReplay = false,
+ adjustmentKey,
+ subscription: knownSubscription,
+ }: {
+ workspaceId: string;
+ availableDeltaMicro: number;
+ // Whether the write that led here could have made credits spendable. Only
+ // the caller knows: a replay of either a grant or a revocation carries a
+ // delta of zero, and the sign cannot tell them apart.
+ addsCredits: boolean;
+ // A replay cannot know how far the original attempt got, so the counter is
+ // recomputed from the ledger unless adjustmentKey says it already moved.
+ isReplay?: boolean;
+ // Names a one-off adjustment so a retry can see it already landed.
+ adjustmentKey?: string;
+ // Saves a re-read for a caller that already has it in hand.
+ subscription?: BillingSubscriptionEntity;
+ }): Promise<void> {
+ const activeCreditsMicro = await this.syncMirrorBalance(workspaceId);
+
+ const subscription =
+ knownSubscription ??
+ (await this.billingSubscriptionService.getCurrentBillingSubscription({
+ workspaceId,
+ }));
+ if (!isDefined(subscription)) {
return;
}
- await this.billingUsageCacheService.flushAvailableCredits(workspaceId);
+ // Deliberately not getBillingSubscriptionPeriod, which reports the trial
+ // window while trialing: every usage path keys this counter off
+ // currentPeriodStart, so taking the period from anywhere else would move a
+ // key the gate never reads.
+ const periodStart = subscription.currentPeriodStart;
+
+ const rebuildCounter =
+ isReplay &&
+ (!isDefined(adjustmentKey) ||
+ !(await this.billingUsageCacheService.hasCounterAdjustmentBeenApplied(
+ workspaceId,
+ adjustmentKey,
+ )));
+
+ const counterAfterWriteMicro = await this.applyCounterWrite({
+ workspaceId,
+ periodStart,
+ availableDeltaMicro,
+ shouldRebuild: rebuildCounter,
+ });
+
+ if (isDefined(adjustmentKey)) {
+ await this.billingUsageCacheService.markCounterAdjustmentApplied(
+ workspaceId,
+ adjustmentKey,
+ subscription.currentPeriodEnd,
+ );
+ }
+
+ // The banner may only come down when this write actually put something
+ // spendable in front of the workspace: the caller says whether it could,
+ // the counter says whether it did, and what is left decides. A replay that
+ // finds the counter already moved did nothing, and its grants may well
+ // have been spent since, so it leaves the banner alone, while a replay
+ // that rebuilt the counter is the repair that lifts it.
+ //
+ // With no counter to speak for the workspace the ledger stands in, which
+ // ignores usage. Erring towards lifting the banner is deliberate there:
+ // the counter is cold exactly after a period transition or a cache flush,
+ // which is when grants land, and leaving it up would hide credits someone
+ // deliberately gave for the rest of the period.
+ const spendableAfterWriteMicro =
+ counterAfterWriteMicro ?? activeCreditsMicro;
+
+ return this.clearCapAndSubscriptionCache(workspaceId, {
+ shouldClearCap:
+ addsCredits &&
+ spendableAfterWriteMicro > 0 &&
+ (rebuildCounter || availableDeltaMicro > 0),
+ });
+ }
+
+ // Returns what the counter holds afterwards, or null when there is no warm
+ // counter to speak for the workspace.
+ private async applyCounterWrite({
+ workspaceId,
+ periodStart,
+ availableDeltaMicro,
+ shouldRebuild,
+ }: {
+ workspaceId: string;
+ periodStart: Date;
+ availableDeltaMicro: number;
+ shouldRebuild: boolean;
+ }): Promise<number | null> {
+ if (shouldRebuild) {
+ await this.billingUsageCacheService.invalidateAvailableCredits(
+ workspaceId,
+ periodStart,
+ );
+
+ return null;
+ }
+
+ if (availableDeltaMicro === 0) {
+ return null;
+ }
+
+ // Adjusting the warm counter instead of flushing it avoids recomputing
+ // from ClickHouse while its async inserts for recent usage are still
+ // landing, which would credit the workspace for usage it already spent.
+ const cachedAvailableCredits =
+ await this.billingUsageCacheService.getAvailableCredits(
+ workspaceId,
+ periodStart,
+ );
+
+ // Nothing to do when the counter is cold. A reader can only warm it while
+ // holding this same lock, so it cannot be mid-computation now, and the
+ // next one to take the lock reads a ledger that already has this write.
+ if (!isDefined(cachedAvailableCredits)) {
+ return null;
+ }
+
+ await this.billingUsageCacheService.adjustAvailableCredits(
+ workspaceId,
+ periodStart,
+ availableDeltaMicro,
+ );
+
+ return cachedAvailableCredits + availableDeltaMicro;
+ }
+
+ private async clearCapAndSubscriptionCache(
+ workspaceId: string,
+ { shouldClearCap }: { shouldClearCap: boolean },
+ ): Promise<void> {
+ if (shouldClearCap) {
+ await this.billingUsageCapService.clearHasReachedCapForWorkspace(
+ workspaceId,
+ );
+ }
+
+ await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
+ 'currentBillingSubscription',
+ ]);
}
}
+
+// Scopes the completion marker to one revocation, so retrying it is the only
+// thing that can see it.
+const buildRevocationAdjustmentKey = (grantId: string): string =>
+ `revoke:${grantId}`;
+
+const resolveGrantValidity = (
+ params: GrantCreditsParams,
+ subscription: BillingSubscriptionEntity | undefined,
+): { effectiveAt: Date; expiresAt: Date } => {
+ const effectiveAt = params.effectiveAt ?? new Date();
+
+ if (isDefined(params.expiresAt)) {
+ return { effectiveAt, expiresAt: params.expiresAt };
+ }
+
+ // A lapsed subscription still carries the period that just ended, and that is
+ // exactly the workspace someone is most likely to be granting credits to.
+ // Falling back keeps the grant from expiring on creation.
+ const currentPeriodEnd = isDefined(subscription)
+ ? getBillingSubscriptionPeriod(subscription).periodEnd
+ : null;
+ const hasUsablePeriodEnd =
+ isDefined(currentPeriodEnd) &&
+ currentPeriodEnd.getTime() > effectiveAt.getTime();
+
+ return {
+ effectiveAt,
+ expiresAt: hasUsablePeriodEnd
+ ? currentPeriodEnd
+ : addDays(effectiveAt, PROVISIONAL_GRANT_VALIDITY_IN_DAYS),
+ };
+};
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 0088f31715d..9f5c764d80d 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
@@ -36,6 +36,7 @@ import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/se
import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';
import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';
import { getPlanKeyFromSubscription } from 'src/engine/core-modules/billing/utils/get-plan-key-from-subscription.util';
+import { resolveBillingPeriodBoundaryUpdate } from 'src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util';
import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -330,12 +331,35 @@ export class BillingSubscriptionService {
},
);
- await this.billingSubscriptionRepository.upsert(
- workspaceId,
+ const incomingSubscription =
transformStripeSubscriptionEventToDatabaseSubscription(
workspaceId,
subscription,
- ),
+ );
+
+ const storedSubscription = await this.billingSubscriptionRepository.findOne(
+ workspaceId,
+ {
+ where: {
+ stripeSubscriptionId: incomingSubscription.stripeSubscriptionId,
+ },
+ select: {
+ id: true,
+ currentPeriodStart: true,
+ currentPeriodEnd: true,
+ },
+ },
+ );
+
+ await this.billingSubscriptionRepository.upsert(
+ workspaceId,
+ {
+ ...incomingSubscription,
+ ...resolveBillingPeriodBoundaryUpdate({
+ incomingPeriodStart: incomingSubscription.currentPeriodStart,
+ storedSubscription,
+ }),
+ },
{
conflictPaths: ['stripeSubscriptionId'],
skipUpdateIfNoValuesChanged: true,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.ts
index e813d2c67ad..a99c7b118be 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cache.service.ts
@@ -4,6 +4,8 @@ import { Injectable } from '@nestjs/common';
import { buildBillingUsageAvailableCreditsCacheKey } from 'src/engine/core-modules/billing/utils/build-billing-usage-available-credits-cache-key.util';
import { buildBillingUsageAvailableCreditsCachePattern } from 'src/engine/core-modules/billing/utils/build-billing-usage-available-credits-cache-pattern.util';
+import { buildBillingUsageCounterAdjustmentKey } from 'src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util';
+import { buildBillingUsageCounterAdjustmentPattern } from 'src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-pattern.util';
import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
@@ -24,29 +26,53 @@ export class BillingUsageCacheService {
);
}
+ // Callers must hold buildBillingCreditStateLockKey: that is what stops a
+ // value computed before a grant landed from being installed after it.
async warmAvailableCredits(
workspaceId: string,
periodStart: Date | string,
periodEnd: Date | string,
availableCredits: number,
): Promise<void> {
- const ttlMs = Math.max(new Date(periodEnd).getTime() - Date.now(), 0);
-
await this.billingUsageCacheStorage.set(
buildBillingUsageAvailableCreditsCacheKey(workspaceId, periodStart),
availableCredits,
- ttlMs,
+ msUntil(periodEnd),
+ );
+ }
+
+ async hasCounterAdjustmentBeenApplied(
+ workspaceId: string,
+ adjustmentKey: string,
+ ): Promise<boolean> {
+ const marker = await this.billingUsageCacheStorage.get<boolean>(
+ buildBillingUsageCounterAdjustmentKey(workspaceId, adjustmentKey),
+ );
+
+ return marker === true;
+ }
+
+ async markCounterAdjustmentApplied(
+ workspaceId: string,
+ adjustmentKey: string,
+ periodEnd: Date | string,
+ ): Promise<void> {
+ await this.billingUsageCacheStorage.set(
+ buildBillingUsageCounterAdjustmentKey(workspaceId, adjustmentKey),
+ true,
+ msUntil(periodEnd),
);
}
- async decrementAvailableCredits(
+ // Signed: usage moves it down, a grant moves it up.
+ async adjustAvailableCredits(
workspaceId: string,
periodStart: Date | string,
- usedCredits: number,
+ deltaCredits: number,
): Promise<number> {
return this.billingUsageCacheStorage.incrBy(
buildBillingUsageAvailableCreditsCacheKey(workspaceId, periodStart),
- -usedCredits,
+ deltaCredits,
);
}
@@ -64,4 +90,13 @@ export class BillingUsageCacheService {
buildBillingUsageAvailableCreditsCachePattern(workspaceId),
);
}
+
+ async flushCounterAdjustmentMarkers(workspaceId: string): Promise<void> {
+ await this.billingUsageCacheStorage.flushByPattern(
+ buildBillingUsageCounterAdjustmentPattern(workspaceId),
+ );
+ }
}
+
+const msUntil = (date: Date | string): number =>
+ Math.max(new Date(date).getTime() - Date.now(), 0);
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cap.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cap.service.ts
index aea905a405c..9cfcb372eb3 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cap.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage-cap.service.ts
@@ -1,10 +1,10 @@
/* @license Enterprise */
import { Injectable } from '@nestjs/common';
-
import { InjectRepository } from '@nestjs/typeorm';
-import { ClickHouseService } from 'src/database/clickHouse/clickHouse.service';
-import { formatDateForClickHouse } from 'src/database/clickHouse/clickHouse.util';
+
+import { In, Not, Raw, Repository } from 'typeorm';
+
import {
BillingException,
BillingExceptionCode,
@@ -12,96 +12,20 @@ import {
import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';
import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';
import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
-import { ResourceCreditService } from 'src/engine/core-modules/billing/services/resource-credit.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { Not, Raw, Repository } from 'typeorm';
-
-export type BillingCapEvaluation =
- | {
- skipped: false;
- hasReachedCap: boolean;
- usage: number;
- allowance: number;
- tierCap: number;
- creditBalance: number;
- }
- | {
- skipped: true;
- reason: 'no-metered-item' | 'clickhouse-disabled';
- };
-
-type BatchUsageSumRow = {
- workspaceId: string;
- total: string | number | null;
-};
@Injectable()
export class BillingUsageCapService {
constructor(
- private readonly clickHouseService: ClickHouseService,
- private readonly resourceCreditService: ResourceCreditService,
- private readonly twentyConfigService: TwentyConfigService,
@InjectRepository(BillingSubscriptionItemEntity)
private readonly billingSubscriptionItemRepository: Repository<BillingSubscriptionItemEntity>,
) {}
- isClickHouseEnabled(): boolean {
- return Boolean(this.twentyConfigService.get('CLICKHOUSE_URL'));
- }
-
- async getBatchPeriodCreditsUsed(
- workspaceIds: string[],
- periodStart: Date,
- ): Promise<Map<string, number>> {
- const result = new Map<string, number>();
-
- if (!this.isClickHouseEnabled() || workspaceIds.length === 0) {
- return result;
- }
-
- const query = `
- SELECT workspaceId, sum(creditsUsedMicro) AS total
- FROM usageEvent
- WHERE workspaceId IN {workspaceIds:Array(String)}
- AND periodStart = {periodStart:Date}
- GROUP BY workspaceId
- `;
-
- const rows = await this.clickHouseService.select<BatchUsageSumRow>(query, {
- workspaceIds,
- periodStart: formatDateForClickHouse(periodStart),
- });
-
- for (const row of rows) {
- const rawTotal = row.total ?? 0;
- const total = typeof rawTotal === 'string' ? Number(rawTotal) : rawTotal;
-
- result.set(row.workspaceId, Number.isFinite(total) ? total : 0);
- }
-
- return result;
- }
-
async setSubscriptionItemHasReachedCap(
workspaceId: string,
hasReachedCap: boolean,
): Promise<void> {
const billingSubscriptionItems =
- await this.billingSubscriptionItemRepository.find({
- where: {
- billingSubscription: {
- workspaceId,
- status: Not(SubscriptionStatus.Canceled),
- },
- billingProduct: {
- metadata: Raw((alias) => `${alias} @> :metadata::jsonb`, {
- metadata: JSON.stringify({
- productKey: BillingProductKey.RESOURCE_CREDIT,
- }),
- }),
- },
- },
- });
+ await this.findResourceCreditSubscriptionItems(workspaceId);
if (billingSubscriptionItems.length !== 1) {
throw new BillingException(
@@ -115,4 +39,41 @@ export class BillingUsageCapService {
{ hasReachedCurrentPeriodCap: hasReachedCap },
);
}
+
+ // Lifting the cap must never fail the operation that granted the credits, so
+ // unlike setSubscriptionItemHasReachedCap this tolerates a workspace with no
+ // resource credit item.
+ async clearHasReachedCapForWorkspace(workspaceId: string): Promise<void> {
+ const billingSubscriptionItems =
+ await this.findResourceCreditSubscriptionItems(workspaceId);
+
+ if (billingSubscriptionItems.length === 0) {
+ return;
+ }
+
+ await this.billingSubscriptionItemRepository.update(
+ { id: In(billingSubscriptionItems.map((item) => item.id)) },
+ { hasReachedCurrentPeriodCap: false },
+ );
+ }
+
+ private async findResourceCreditSubscriptionItems(
+ workspaceId: string,
+ ): Promise<BillingSubscriptionItemEntity[]> {
+ return this.billingSubscriptionItemRepository.find({
+ where: {
+ billingSubscription: {
+ workspaceId,
+ status: Not(SubscriptionStatus.Canceled),
+ },
+ billingProduct: {
+ metadata: Raw((alias) => `${alias} @> :metadata::jsonb`, {
+ metadata: JSON.stringify({
+ productKey: BillingProductKey.RESOURCE_CREDIT,
+ }),
+ }),
+ },
+ },
+ });
+ }
}
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.ts
index 5e0f5728e26..91b14b9cb82 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
@@ -5,7 +5,6 @@ import { Injectable, Logger } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
-import { differenceInDays } from 'date-fns';
import { ClickHouseService } from 'src/database/clickHouse/clickHouse.service';
import { formatDateTimeForClickHouse } from 'src/database/clickHouse/clickHouse.util';
import { CoreEntityCacheService } from 'src/engine/core-entity-cache/services/core-entity-cache.service';
@@ -15,14 +14,21 @@ import {
} from 'src/engine/core-modules/billing/billing.exception';
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
import { type BillingResourceCreditUsageDTO } from 'src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto';
-import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';
import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
+import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';
import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
import { BillingUsageCapService } from 'src/engine/core-modules/billing/services/billing-usage-cap.service';
+import { 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 {
+ CacheLockException,
+ CacheLockExceptionCode,
+} from 'src/engine/core-modules/cache-lock/exceptions/cache-lock.exception';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
@@ -33,12 +39,31 @@ type UsageSumRow = {
total: string | number | null;
};
+type AvailableCreditsParams = {
+ workspaceId: string;
+ currentPeriodStart: Date;
+ currentPeriodEnd: Date;
+};
+
+type ResolvedAvailableCredits = {
+ availableCredits: number;
+ isCounterWarm: boolean;
+};
+
+// This gate runs before every credit-consuming execution, so it waits far less
+// than a writer does and falls back to computing unlocked rather than failing
+// the execution outright.
+const AVAILABLE_CREDITS_WARM_UP_LOCK_OPTIONS = {
+ ms: 50,
+ maxRetries: 20,
+ ttl: 10_000,
+};
+
@Injectable()
export class BillingUsageService {
protected readonly logger = new Logger(BillingUsageService.name);
constructor(
- @InjectWorkspaceScopedRepository(BillingCustomerEntity)
- private readonly billingCustomerRepository: WorkspaceScopedRepository<BillingCustomerEntity>,
+ private readonly billingCreditGrantService: BillingCreditGrantService,
private readonly billingSubscriptionService: BillingSubscriptionService,
private readonly twentyConfigService: TwentyConfigService,
private readonly billingSubscriptionItemService: BillingSubscriptionItemService,
@@ -48,6 +73,7 @@ export class BillingUsageService {
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly clickHouseService: ClickHouseService,
private readonly billingUsageCapService: BillingUsageCapService,
+ private readonly cacheLockService: CacheLockService,
private readonly coreEntityCacheService: CoreEntityCacheService,
) {}
@@ -87,7 +113,8 @@ export class BillingUsageService {
);
}
- const { periodStart, periodEnd } = this.getSubscriptionPeriod(subscription);
+ const { periodStart, periodEnd } =
+ getBillingSubscriptionPeriod(subscription);
return [
await this.buildResourceCreditUsage(
@@ -113,22 +140,16 @@ export class BillingUsageService {
periodStart: Date,
periodEnd: Date,
): Promise<BillingResourceCreditUsageDTO> {
- const usedCredits = await this.getCurrentPeriodCreditsUsed(
- workspaceId,
- periodStart,
- );
+ const [usedCredits, rolloverCredits] = await Promise.all([
+ this.getCurrentPeriodCreditsUsed(workspaceId, periodStart),
+ this.billingCreditGrantService.getSpendableCreditsMicro(workspaceId),
+ ]);
const grantedCredits =
subscription.status === SubscriptionStatus.Trialing
? item.freeTrialQuantity
: item.creditAmount;
- const billingCustomer = await this.billingCustomerRepository.findOne(
- workspaceId,
- { where: {} },
- );
- const rolloverCredits = billingCustomer?.creditBalanceMicro ?? 0;
-
return {
productKey: item.productKey,
periodStart,
@@ -141,28 +162,6 @@ export class BillingUsageService {
};
}
- private getSubscriptionPeriod(subscription: BillingSubscriptionEntity): {
- periodStart: Date;
- periodEnd: Date;
- } {
- const isTrialing =
- subscription.status === SubscriptionStatus.Trialing &&
- isDefined(subscription.trialStart) &&
- isDefined(subscription.trialEnd);
-
- if (isTrialing) {
- return {
- periodStart: subscription.trialStart!,
- periodEnd: subscription.trialEnd!,
- };
- }
-
- return {
- periodStart: subscription.currentPeriodStart,
- periodEnd: subscription.currentPeriodEnd,
- };
- }
-
private async getAvailableCreditsFromClickHouse({
workspaceId,
currentPeriodStart,
@@ -191,40 +190,28 @@ export class BillingUsageService {
const resourceUsageCap = this.getResourceUsageCap(subscription);
- const { creditBalanceMicro: creditBalance } =
- await this.billingCustomerRepository.findOneOrFail(workspaceId, {
- select: { creditBalanceMicro: true },
- where: {},
- });
-
- const usage = await this.getCurrentPeriodCreditsUsed(
- subscription.workspaceId,
- subscription.currentPeriodStart,
- );
+ const [creditBalance, usage] = await Promise.all([
+ this.billingCreditGrantService.getSpendableCreditsMicro(workspaceId),
+ this.getCurrentPeriodCreditsUsed(
+ subscription.workspaceId,
+ subscription.currentPeriodStart,
+ ),
+ ]);
return resourceUsageCap + creditBalance - usage;
}
+ getTrialResourceUsageCap(subscription: BillingSubscriptionEntity): number {
+ return this.billingSubscriptionService.getTrialPeriodFreeWorkflowCredits(
+ subscription,
+ );
+ }
+
getResourceUsageCap(subscription: BillingSubscriptionEntity): number {
const isInFreeTrial = subscription.status === SubscriptionStatus.Trialing;
if (isInFreeTrial) {
- const trialDuration =
- isDefined(subscription.trialEnd) && isDefined(subscription.trialStart)
- ? differenceInDays(subscription.trialEnd, subscription.trialStart)
- : 0;
-
- const trialWithCreditCardDuration = this.twentyConfigService.get(
- 'BILLING_FREE_TRIAL_WITH_CREDIT_CARD_DURATION_IN_DAYS',
- );
-
- return trialDuration === trialWithCreditCardDuration
- ? this.twentyConfigService.get(
- 'BILLING_FREE_WORKFLOW_CREDITS_FOR_TRIAL_PERIOD_WITH_CREDIT_CARD',
- )
- : this.twentyConfigService.get(
- 'BILLING_FREE_WORKFLOW_CREDITS_FOR_TRIAL_PERIOD_WITHOUT_CREDIT_CARD',
- );
+ return this.getTrialResourceUsageCap(subscription);
}
const resourceCreditItem = subscription.billingSubscriptionItems.find(
@@ -266,34 +253,24 @@ export class BillingUsageService {
const { currentPeriodStart, currentPeriodEnd } = currentBillingSubscription;
- const cachedAvailableCredits =
- await this.billingUsageCacheService.getAvailableCredits(
+ const { availableCredits, isCounterWarm } =
+ await this.resolveAvailableCredits({
workspaceId,
currentPeriodStart,
- );
+ currentPeriodEnd,
+ });
- const availableCredits = isDefined(cachedAvailableCredits)
- ? cachedAvailableCredits
- : await this.getAvailableCreditsFromClickHouse({
+ // A counter held stale by a recent grant must not be created from a value
+ // that may predate it: incrementing an absent key would install
+ // -usedCredits as the whole balance. Compute this turn locally instead and
+ // let the next read rebuild once the marker lapses.
+ const decrementedAvailableCredits = isCounterWarm
+ ? await this.billingUsageCacheService.adjustAvailableCredits(
workspaceId,
currentPeriodStart,
- });
-
- if (!isDefined(cachedAvailableCredits)) {
- await this.billingUsageCacheService.warmAvailableCredits(
- workspaceId,
- currentPeriodStart,
- currentPeriodEnd,
- availableCredits,
- );
- }
-
- const decrementedAvailableCredits =
- await this.billingUsageCacheService.decrementAvailableCredits(
- workspaceId,
- currentPeriodStart,
- usedCredits,
- );
+ -usedCredits,
+ )
+ : availableCredits - usedCredits;
const hasJustReachedCap =
availableCredits > 0 && decrementedAvailableCredits <= 0;
@@ -308,6 +285,84 @@ export class BillingUsageService {
return decrementedAvailableCredits;
}
+ // Warming is a read of the ledger followed by a write of what it implies, so
+ // a grant landing in between would be counted from the ledger here and then
+ // added to the counter again by the grant itself. Taking the writers' lock on
+ // the cold path closes that; a hit returns before the lock, keeping the warm
+ // path, which is the overwhelming majority of calls, free of Redis round
+ // trips.
+ private async readWarmAvailableCredits(
+ params: AvailableCreditsParams,
+ ): Promise<ResolvedAvailableCredits | undefined> {
+ const availableCredits =
+ await this.billingUsageCacheService.getAvailableCredits(
+ params.workspaceId,
+ params.currentPeriodStart,
+ );
+
+ return isDefined(availableCredits)
+ ? { availableCredits, isCounterWarm: true }
+ : undefined;
+ }
+
+ private async resolveAvailableCredits(
+ params: AvailableCreditsParams,
+ ): Promise<ResolvedAvailableCredits> {
+ const warmAvailableCredits = await this.readWarmAvailableCredits(params);
+
+ if (isDefined(warmAvailableCredits)) {
+ return warmAvailableCredits;
+ }
+
+ try {
+ return await this.cacheLockService.withLock(
+ async () =>
+ // Another reader may have warmed it while this one waited, so a burst
+ // of cold reads pays for ClickHouse once rather than once each.
+ (await this.readWarmAvailableCredits(params)) ??
+ (await this.computeAndWarmAvailableCredits(params)),
+ buildBillingCreditStateLockKey(params.workspaceId),
+ AVAILABLE_CREDITS_WARM_UP_LOCK_OPTIONS,
+ );
+ } catch (error) {
+ if (
+ !(error instanceof CacheLockException) ||
+ error.code !== CacheLockExceptionCode.LOCK_ACQUISITION_TIMEOUT
+ ) {
+ throw error;
+ }
+
+ // Failing the execution because a grant is being written would be worse
+ // than answering from a value this call computed itself. Deliberately
+ // does not warm: holding the lock is what makes installing a computed
+ // value safe, so the counter stays cold until an uncontended read.
+ this.logger.warn(
+ `Computing available credits for workspace ${params.workspaceId} without the credit state lock: ${error.message}`,
+ );
+
+ return {
+ availableCredits: await this.getAvailableCreditsFromClickHouse(params),
+ isCounterWarm: false,
+ };
+ }
+ }
+
+ private async computeAndWarmAvailableCredits(
+ params: AvailableCreditsParams,
+ ): Promise<ResolvedAvailableCredits> {
+ const availableCredits =
+ await this.getAvailableCreditsFromClickHouse(params);
+
+ await this.billingUsageCacheService.warmAvailableCredits(
+ params.workspaceId,
+ params.currentPeriodStart,
+ params.currentPeriodEnd,
+ availableCredits,
+ );
+
+ return { availableCredits, isCounterWarm: true };
+ }
+
async hasAvailableCredits(workspaceId: string): Promise<boolean> {
if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
return true;
@@ -336,27 +391,12 @@ export class BillingUsageService {
const subscription = currentBillingSubscription;
- const cached = await this.billingUsageCacheService.getAvailableCredits(
- subscription.workspaceId,
- subscription.currentPeriodStart,
- );
-
- if (isDefined(cached)) {
- return cached > 0;
- }
-
- const availableCredits = await this.getAvailableCreditsFromClickHouse({
+ const { availableCredits } = await this.resolveAvailableCredits({
workspaceId: subscription.workspaceId,
currentPeriodStart: subscription.currentPeriodStart,
+ currentPeriodEnd: subscription.currentPeriodEnd,
});
- await this.billingUsageCacheService.warmAvailableCredits(
- subscription.workspaceId,
- subscription.currentPeriodStart,
- subscription.currentPeriodEnd,
- availableCredits,
- );
-
return availableCredits > 0;
}
@@ -371,25 +411,69 @@ export class BillingUsageService {
}
}
- async getCurrentPeriodCreditsUsed(
- workspaceId: string,
- periodStart: Date,
- ): Promise<number> {
- const query = `
- SELECT sum(creditsUsedMicro) AS total
- FROM usageEvent
- WHERE workspaceId = {workspaceId:String}
- AND periodStart = {periodStart:DateTime64(3)}
- `;
-
- const rows = await this.clickHouseService.select<UsageSumRow>(query, {
- workspaceId,
- periodStart: formatDateTimeForClickHouse(periodStart),
- });
+ // Returns null when usage could not be read. ClickHouseService.select
+ // swallows query errors and returns [], but a bare sum() aggregate always
+ // yields exactly one row, so an empty result means the read failed rather
+ // than "nothing was used". Callers that hand out credits must not confuse
+ // the two.
+ private async sumCreditsUsedMicroOrNull(
+ condition: string,
+ params: Record<string, unknown>,
+ ): Promise<number | null> {
+ const rows = await this.clickHouseService.select<UsageSumRow>(
+ `SELECT sum(creditsUsedMicro) AS total
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND ${condition}`,
+ params,
+ );
+
+ if (rows.length === 0) {
+ return null;
+ }
const rawTotal = rows[0]?.total ?? 0;
const total = typeof rawTotal === 'string' ? Number(rawTotal) : rawTotal;
return Number.isFinite(total) ? total : 0;
}
+
+ // Sums by event timestamp rather than by the stamped periodStart dimension.
+ // At a period transition the subscription's currentPeriodStart has already
+ // moved on, so an equality match on periodStart would read the new period
+ // and report a period that has barely started as unused.
+ async getCreditsUsedBetweenOrNull({
+ workspaceId,
+ from,
+ to,
+ }: {
+ workspaceId: string;
+ from: Date;
+ to: Date;
+ }): Promise<number | null> {
+ return this.sumCreditsUsedMicroOrNull(
+ 'timestamp >= {from:DateTime64(3)} AND timestamp < {to:DateTime64(3)}',
+ {
+ workspaceId,
+ from: formatDateTimeForClickHouse(from),
+ to: formatDateTimeForClickHouse(to),
+ },
+ );
+ }
+
+ // Fails open: an unreadable usage total must never block a paying workspace.
+ async getCurrentPeriodCreditsUsed(
+ workspaceId: string,
+ periodStart: Date,
+ ): Promise<number> {
+ const usedMicro = await this.sumCreditsUsedMicroOrNull(
+ 'periodStart = {periodStart:DateTime64(3)}',
+ {
+ workspaceId,
+ periodStart: formatDateTimeForClickHouse(periodStart),
+ },
+ );
+
+ return usedMicro ?? 0;
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/resource-credit.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/resource-credit.service.ts
index b8b85f0c1f5..cbb674113cc 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/resource-credit.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/resource-credit.service.ts
@@ -59,10 +59,7 @@ export class ResourceCreditService {
async getResourceCreditRolloverParameters(
workspaceId: string,
subscriptionId: string,
- ): Promise<{
- tierQuantity: number;
- unitPriceCents: number;
- } | null> {
+ ): Promise<{ tierQuantity: number } | null> {
const subscription = await this.billingSubscriptionRepository.findOne(
workspaceId,
{
@@ -85,9 +82,6 @@ export class ResourceCreditService {
return null;
}
- return {
- tierQuantity: pricingInfo.tierCap,
- unitPriceCents: pricingInfo.unitPriceCents,
- };
+ return { tierQuantity: pricingInfo.tierCap };
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service.ts
deleted file mode 100644
index 04973e7005d..00000000000
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-/* @license Enterprise */
-
-import { Injectable } from '@nestjs/common';
-
-import type Stripe from 'stripe';
-
-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';
-
-@Injectable()
-export class StripeCreditGrantService {
- private readonly stripe: Stripe;
-
- constructor(
- private readonly twentyConfigService: TwentyConfigService,
- private readonly stripeSDKService: StripeSDKService,
- ) {
- if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
- return;
- }
- this.stripe = this.stripeSDKService.getStripe(
- this.twentyConfigService.get('BILLING_STRIPE_API_KEY'),
- );
- }
-
- async createCreditGrant({
- customerId,
- creditUnits,
- unitPriceCents,
- expiresAt,
- metadata,
- }: {
- customerId: string;
- creditUnits: number;
- unitPriceCents: number;
- expiresAt: Date;
- metadata: Record<string, string>;
- }): Promise<Stripe.Billing.CreditGrant> {
- const monetaryAmount = this.convertCreditsToMonetary(
- creditUnits,
- unitPriceCents,
- );
-
- // Add 60 seconds buffer to ensure effective_at is in the future when Stripe processes it
- const effectiveAt = Math.floor(Date.now() / 1000) + 60;
-
- return this.stripe.billing.creditGrants.create({
- customer: customerId,
- amount: {
- type: 'monetary',
- monetary: { currency: 'usd', value: monetaryAmount },
- },
- applicability_config: {
- scope: { price_type: 'metered' },
- },
- category: 'promotional',
- effective_at: effectiveAt,
- expires_at: Math.floor(expiresAt.getTime() / 1000),
- name: 'Rollover credits',
- metadata,
- });
- }
-
- async getCustomerCreditBalance(
- customerId: string,
- unitPriceCents: number,
- ): Promise<number> {
- const balance = await this.stripe.billing.creditBalanceSummary.retrieve({
- customer: customerId,
- filter: {
- type: 'applicability_scope',
- applicability_scope: { price_type: 'metered' },
- },
- });
-
- const availableAmount =
- balance.balances?.[0]?.available_balance?.monetary?.value;
-
- if (!availableAmount) {
- return 0;
- }
-
- return this.convertMonetaryToCredits(availableAmount, unitPriceCents);
- }
-
- async voidCreditGrant(creditGrantId: string): Promise<void> {
- await this.stripe.billing.creditGrants.voidGrant(creditGrantId);
- }
-
- async listCreditGrants(
- customerId: string,
- ): Promise<Stripe.Billing.CreditGrant[]> {
- const grants = await this.stripe.billing.creditGrants.list({
- customer: customerId,
- });
-
- return grants.data;
- }
-
- private convertCreditsToMonetary(
- creditUnits: number,
- unitPriceCents: number,
- ): number {
- return Math.round(creditUnits * unitPriceCents);
- }
-
- private convertMonetaryToCredits(
- monetaryAmountCents: number,
- unitPriceCents: number,
- ): number {
- if (unitPriceCents === 0) {
- return 0;
- }
-
- return Math.round(monetaryAmountCents / unitPriceCents);
- }
-}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/stripe/stripe.module.ts b/packages/twenty-server/src/engine/core-modules/billing/stripe/stripe.module.ts
index 8c0f231b3fc..76c31b91891 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/stripe/stripe.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/stripe/stripe.module.ts
@@ -14,7 +14,6 @@ import { StripeSubscriptionItemService } from 'src/engine/core-modules/billing/s
import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';
import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';
import { StripeWebhookService } from 'src/engine/core-modules/billing/stripe/services/stripe-webhook.service';
-import { StripeCreditGrantService } from 'src/engine/core-modules/billing/stripe/services/stripe-credit-grant.service';
import { StripeInvoiceService } from 'src/engine/core-modules/billing/stripe/services/stripe-invoice.service';
import { StripeSDKModule } from 'src/engine/core-modules/billing/stripe/stripe-sdk/stripe-sdk.module';
import { BillingCustomerEntity } from 'src/engine/core-modules/billing/entities/billing-customer.entity';
@@ -38,7 +37,6 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
StripePriceService,
StripeProductService,
StripeBillingMeterEventService,
- StripeCreditGrantService,
StripeInvoiceService,
provideWorkspaceScopedRepository(BillingCustomerEntity),
],
@@ -54,7 +52,6 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
StripeProductService,
StripeBillingMeterEventService,
StripeSubscriptionScheduleService,
- StripeCreditGrantService,
StripeInvoiceService,
],
})
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts
new file mode 100644
index 00000000000..8a3696e6aba
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts
@@ -0,0 +1,295 @@
+/* @license Enterprise */
+
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
+import {
+ computeCarryForwardGrants,
+ type CarryForwardGrantInput,
+} from 'src/engine/core-modules/billing/utils/compute-carry-forward-grants.util';
+
+const grant = (
+ overrides: Partial<CarryForwardGrantInput> = {},
+): CarryForwardGrantInput => ({
+ grantId: 'grant_1',
+ type: BillingCreditGrantType.ROLLOVER,
+ amountMicro: 0,
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ ...overrides,
+});
+
+const ALLOWANCE = 1_000_000;
+// A cap multiplier of 2 means total credits never exceed twice the allowance,
+// so at most one full allowance can roll over.
+const ROLLOVER_CAP = ALLOWANCE;
+
+describe('computeCarryForwardGrants', () => {
+ describe('plan allowance', () => {
+ it('rolls the unspent allowance over', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [],
+ usageMicro: 300_000,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([
+ {
+ type: BillingCreditGrantType.ROLLOVER,
+ amountMicro: 700_000,
+ sourceGrantId: null,
+ },
+ ]);
+ });
+
+ it('returns nothing when the allowance was fully spent', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [],
+ usageMicro: ALLOWANCE,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([]);
+ });
+
+ it('returns nothing when usage exceeded everything available', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [grant({ amountMicro: 200_000 })],
+ usageMicro: 5_000_000,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([]);
+ });
+ });
+
+ describe('rollover cap', () => {
+ it('clamps the rolled-over amount to the cap', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [
+ grant({ grantId: 'previous_rollover', amountMicro: ALLOWANCE }),
+ ],
+ usageMicro: 0,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([
+ {
+ type: BillingCreditGrantType.ROLLOVER,
+ amountMicro: ROLLOVER_CAP,
+ sourceGrantId: null,
+ },
+ ]);
+ });
+
+ it('merges the allowance and previous rollovers into a single grant', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [
+ grant({ grantId: 'previous_rollover', amountMicro: 400_000 }),
+ ],
+ usageMicro: 1_200_000,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([
+ {
+ type: BillingCreditGrantType.ROLLOVER,
+ amountMicro: 200_000,
+ sourceGrantId: null,
+ },
+ ]);
+ });
+
+ it('rolls nothing over when the cap is zero', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [],
+ usageMicro: 0,
+ rolloverCapMicro: 0,
+ });
+
+ expect(result).toEqual([]);
+ });
+ });
+
+ describe('granted credits', () => {
+ it('carries a compensation grant over in full, past the rollover cap', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [
+ grant({
+ grantId: 'compensation_1',
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 200_000_000,
+ }),
+ ],
+ usageMicro: 0,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([
+ {
+ type: BillingCreditGrantType.ROLLOVER,
+ amountMicro: ROLLOVER_CAP,
+ sourceGrantId: null,
+ },
+ {
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 200_000_000,
+ sourceGrantId: 'compensation_1',
+ },
+ ]);
+ });
+
+ it('spends the plan allowance before touching granted credits', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [
+ grant({
+ grantId: 'compensation_1',
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 500_000,
+ }),
+ ],
+ usageMicro: ALLOWANCE,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([
+ {
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 500_000,
+ sourceGrantId: 'compensation_1',
+ },
+ ]);
+ });
+
+ it('eats into granted credits once the allowance and rollovers are gone', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [
+ grant({ grantId: 'previous_rollover', amountMicro: 500_000 }),
+ grant({
+ grantId: 'reward_1',
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ amountMicro: 1_000_000,
+ }),
+ ],
+ usageMicro: 2_000_000,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([
+ {
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ amountMicro: 500_000,
+ sourceGrantId: 'reward_1',
+ },
+ ]);
+ });
+
+ it('keeps each granted credit as its own grant, oldest spent first', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: 0,
+ liveGrants: [
+ grant({
+ grantId: 'reward_old',
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ amountMicro: 400_000,
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ }),
+ grant({
+ grantId: 'compensation_new',
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 600_000,
+ createdAt: new Date('2026-02-01T00:00:00.000Z'),
+ }),
+ ],
+ usageMicro: 500_000,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([
+ {
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 500_000,
+ sourceGrantId: 'compensation_new',
+ },
+ ]);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('treats a negative allowance as zero', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: -1_000,
+ liveGrants: [],
+ usageMicro: 0,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([]);
+ });
+
+ it('treats negative usage as zero', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [],
+ usageMicro: -500_000,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([
+ {
+ type: BillingCreditGrantType.ROLLOVER,
+ amountMicro: ALLOWANCE,
+ sourceGrantId: null,
+ },
+ ]);
+ });
+
+ it('emits whole micro-credits only', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: ALLOWANCE,
+ liveGrants: [
+ grant({
+ grantId: 'compensation_1',
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 1_000,
+ }),
+ ],
+ usageMicro: 999_999.5,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ // The half micro-credit left of the allowance floors to nothing, so no
+ // rollover grant is emitted at all.
+ expect(result).toEqual([
+ {
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 1_000,
+ sourceGrantId: 'compensation_1',
+ },
+ ]);
+ });
+
+ it('ignores grants with no remaining amount', () => {
+ const result = computeCarryForwardGrants({
+ allowanceMicro: 0,
+ liveGrants: [
+ grant({
+ grantId: 'empty',
+ type: BillingCreditGrantType.COMPENSATION,
+ amountMicro: 0,
+ }),
+ ],
+ usageMicro: 0,
+ rolloverCapMicro: ROLLOVER_CAP,
+ });
+
+ expect(result).toEqual([]);
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/derive-billing-period-transition.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/derive-billing-period-transition.util.spec.ts
new file mode 100644
index 00000000000..0a863328913
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/derive-billing-period-transition.util.spec.ts
@@ -0,0 +1,239 @@
+/* @license Enterprise */
+
+import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';
+import { deriveBillingPeriodTransition } from 'src/engine/core-modules/billing/utils/derive-billing-period-transition.util';
+
+const JANUARY = new Date('2026-01-01T00:00:00.000Z');
+const FEBRUARY = new Date('2026-02-01T00:00:00.000Z');
+const MARCH = new Date('2026-03-01T00:00:00.000Z');
+
+describe('deriveBillingPeriodTransition', () => {
+ it('treats the invoiced period start as the boundary between the two periods', () => {
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: FEBRUARY,
+ invoicePeriodEnd: MARCH,
+ subscriptionCurrentPeriodStart: JANUARY,
+ subscriptionCurrentPeriodEnd: FEBRUARY,
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart: null,
+ isFirstPeriodAfterTrial: false,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart: null,
+ });
+
+ expect(result).toEqual({
+ closingPeriodStart: JANUARY,
+ closingPeriodEnd: FEBRUARY,
+ nextPeriodStart: FEBRUARY,
+ nextPeriodEnd: MARCH,
+ });
+ });
+
+ it('closes the trial period when the trial just ended', () => {
+ const trialStart = new Date('2026-01-20T00:00:00.000Z');
+
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: FEBRUARY,
+ invoicePeriodEnd: MARCH,
+ subscriptionCurrentPeriodStart: FEBRUARY,
+ subscriptionCurrentPeriodEnd: MARCH,
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart,
+ isFirstPeriodAfterTrial: true,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart: null,
+ });
+
+ expect(result).toEqual({
+ closingPeriodStart: trialStart,
+ closingPeriodEnd: FEBRUARY,
+ nextPeriodStart: FEBRUARY,
+ nextPeriodEnd: MARCH,
+ });
+ });
+
+ // The invoiced period is 28 days here while the closing one is 31, so
+ // subtracting the invoiced duration would land on January 4 and drop three
+ // days of usage.
+ it('falls back one calendar month when the subscription already advanced', () => {
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: FEBRUARY,
+ invoicePeriodEnd: MARCH,
+ subscriptionCurrentPeriodStart: FEBRUARY,
+ subscriptionCurrentPeriodEnd: MARCH,
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart: null,
+ isFirstPeriodAfterTrial: false,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart: null,
+ });
+
+ expect(result.closingPeriodStart).toEqual(JANUARY);
+ expect(result.closingPeriodEnd).toEqual(FEBRUARY);
+ });
+
+ it('falls back one calendar year for a yearly subscription', () => {
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: JANUARY,
+ invoicePeriodEnd: new Date('2027-01-01T00:00:00.000Z'),
+ subscriptionCurrentPeriodStart: JANUARY,
+ subscriptionCurrentPeriodEnd: new Date('2027-01-01T00:00:00.000Z'),
+ subscriptionInterval: SubscriptionInterval.Year,
+ trialStart: null,
+ isFirstPeriodAfterTrial: false,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart: null,
+ });
+
+ expect(result.closingPeriodStart).toEqual(
+ new Date('2025-01-01T00:00:00.000Z'),
+ );
+ });
+
+ it('keeps the closing period aligned across a leap February', () => {
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: new Date('2024-03-01T00:00:00.000Z'),
+ invoicePeriodEnd: new Date('2024-04-01T00:00:00.000Z'),
+ subscriptionCurrentPeriodStart: new Date('2024-03-01T00:00:00.000Z'),
+ subscriptionCurrentPeriodEnd: new Date('2024-04-01T00:00:00.000Z'),
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart: null,
+ isFirstPeriodAfterTrial: false,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart: null,
+ });
+
+ expect(result.closingPeriodStart).toEqual(
+ new Date('2024-02-01T00:00:00.000Z'),
+ );
+ });
+
+ it('falls back to the trial period start only when the trial actually ran', () => {
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: FEBRUARY,
+ invoicePeriodEnd: MARCH,
+ subscriptionCurrentPeriodStart: JANUARY,
+ subscriptionCurrentPeriodEnd: FEBRUARY,
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart: null,
+ isFirstPeriodAfterTrial: true,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart: null,
+ });
+
+ expect(result.closingPeriodStart).toEqual(JANUARY);
+ });
+
+ // A subscription anchored on the 31st runs January 31 to February 28, and
+ // subMonths clamps February 28 back to January 28. Three days of the previous
+ // period would count as usage here, and grants that expired on January 31
+ // would read as live and be carried forward a second time.
+ it('prefers the period start the ledger recorded over clamped calendar arithmetic', () => {
+ const monthEndBoundary = new Date('2026-02-28T00:00:00.000Z');
+ const ledgerPeriodStart = new Date('2026-01-31T00:00:00.000Z');
+
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: monthEndBoundary,
+ invoicePeriodEnd: new Date('2026-03-31T00:00:00.000Z'),
+ subscriptionCurrentPeriodStart: monthEndBoundary,
+ subscriptionCurrentPeriodEnd: new Date('2026-03-31T00:00:00.000Z'),
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart: null,
+ isFirstPeriodAfterTrial: false,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart,
+ });
+
+ expect(result.closingPeriodStart).toEqual(ledgerPeriodStart);
+ });
+
+ it('ignores a ledger period start that is not before the boundary', () => {
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: FEBRUARY,
+ invoicePeriodEnd: MARCH,
+ subscriptionCurrentPeriodStart: FEBRUARY,
+ subscriptionCurrentPeriodEnd: MARCH,
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart: null,
+ isFirstPeriodAfterTrial: false,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart: MARCH,
+ });
+
+ expect(result.closingPeriodStart).toEqual(JANUARY);
+ });
+
+ it('falls back to calendar arithmetic when the ledger has nothing to say', () => {
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: FEBRUARY,
+ invoicePeriodEnd: MARCH,
+ subscriptionCurrentPeriodStart: FEBRUARY,
+ subscriptionCurrentPeriodEnd: MARCH,
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart: null,
+ isFirstPeriodAfterTrial: false,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart: null,
+ });
+
+ expect(result.closingPeriodStart).toEqual(JANUARY);
+ });
+
+ // The subscription still carries the closing period, so it is authoritative
+ // and the ledger must not override it.
+ it('keeps the subscription period start when it precedes the boundary', () => {
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: FEBRUARY,
+ invoicePeriodEnd: MARCH,
+ subscriptionCurrentPeriodStart: JANUARY,
+ subscriptionCurrentPeriodEnd: FEBRUARY,
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart: null,
+ isFirstPeriodAfterTrial: false,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart: new Date('2026-01-15T00:00:00.000Z'),
+ });
+
+ expect(result.closingPeriodStart).toEqual(JANUARY);
+ });
+
+ // The subscription records the boundary when it advances, so it is exact for
+ // any anchor. The ledger only knows it when the previous transition happened
+ // to close a grant there.
+ it('prefers the period start the subscription recorded over the ledger', () => {
+ const monthEndBoundary = new Date('2026-02-28T00:00:00.000Z');
+
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: monthEndBoundary,
+ invoicePeriodEnd: new Date('2026-03-31T00:00:00.000Z'),
+ subscriptionCurrentPeriodStart: monthEndBoundary,
+ subscriptionCurrentPeriodEnd: new Date('2026-03-31T00:00:00.000Z'),
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart: null,
+ isFirstPeriodAfterTrial: false,
+ subscriptionPreviousPeriodStart: new Date('2026-01-31T00:00:00.000Z'),
+ ledgerPeriodStart: new Date('2026-01-20T00:00:00.000Z'),
+ });
+
+ expect(result.closingPeriodStart).toEqual(
+ new Date('2026-01-31T00:00:00.000Z'),
+ );
+ });
+
+ it('uses the subscription period end when the invoice carries no forward period', () => {
+ const result = deriveBillingPeriodTransition({
+ invoicePeriodStart: FEBRUARY,
+ invoicePeriodEnd: FEBRUARY,
+ subscriptionCurrentPeriodStart: JANUARY,
+ subscriptionCurrentPeriodEnd: MARCH,
+ subscriptionInterval: SubscriptionInterval.Month,
+ trialStart: null,
+ isFirstPeriodAfterTrial: false,
+ subscriptionPreviousPeriodStart: null,
+ ledgerPeriodStart: null,
+ });
+
+ expect(result.nextPeriodStart).toEqual(FEBRUARY);
+ expect(result.nextPeriodEnd).toEqual(MARCH);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.ts
new file mode 100644
index 00000000000..797a4bb6b74
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.ts
@@ -0,0 +1,69 @@
+/* @license Enterprise */
+
+import { resolveBillingPeriodBoundaryUpdate } from 'src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util';
+
+const JANUARY = new Date('2026-01-01T00:00:00.000Z');
+const FEBRUARY = new Date('2026-02-01T00:00:00.000Z');
+const MARCH = new Date('2026-03-01T00:00:00.000Z');
+
+describe('resolveBillingPeriodBoundaryUpdate', () => {
+ it('records the period the subscription just moved off', () => {
+ expect(
+ resolveBillingPeriodBoundaryUpdate({
+ incomingPeriodStart: FEBRUARY,
+ storedSubscription: {
+ currentPeriodStart: JANUARY,
+ currentPeriodEnd: FEBRUARY,
+ },
+ }),
+ ).toEqual({ previousPeriodStart: JANUARY });
+ });
+
+ it('leaves the boundary alone when the period has not moved', () => {
+ expect(
+ resolveBillingPeriodBoundaryUpdate({
+ incomingPeriodStart: FEBRUARY,
+ storedSubscription: {
+ currentPeriodStart: FEBRUARY,
+ currentPeriodEnd: MARCH,
+ },
+ }),
+ ).toEqual({});
+ });
+
+ // Two subscription events for the same subscription can be processed out of
+ // order, and the older one would otherwise rewind the window the rollover
+ // settles against.
+ it('keeps the stored window when a late event carries an older one', () => {
+ expect(
+ resolveBillingPeriodBoundaryUpdate({
+ incomingPeriodStart: JANUARY,
+ storedSubscription: {
+ currentPeriodStart: FEBRUARY,
+ currentPeriodEnd: MARCH,
+ },
+ }),
+ ).toEqual({ currentPeriodStart: FEBRUARY, currentPeriodEnd: MARCH });
+ });
+
+ it('has nothing to record for a subscription seen for the first time', () => {
+ expect(
+ resolveBillingPeriodBoundaryUpdate({
+ incomingPeriodStart: FEBRUARY,
+ storedSubscription: null,
+ }),
+ ).toEqual({});
+ });
+
+ it('has nothing to record when the event carries no period', () => {
+ expect(
+ resolveBillingPeriodBoundaryUpdate({
+ incomingPeriodStart: undefined,
+ storedSubscription: {
+ currentPeriodStart: JANUARY,
+ currentPeriodEnd: FEBRUARY,
+ },
+ }),
+ ).toEqual({});
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/bigint-column-transformer.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/bigint-column-transformer.util.ts
new file mode 100644
index 00000000000..9abe0ade85d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/bigint-column-transformer.util.ts
@@ -0,0 +1,16 @@
+/* @license Enterprise */
+
+// Postgres returns bigint as a string, so it needs coercing back. Shared by the
+// micro-denominated credit columns so the ledger and the mirror it sums into
+// cannot coerce differently.
+//
+// Number() is only lossless below 2^53, which is 9e9 credits at
+// INTERNAL_CREDITS_PER_DISPLAY_CREDIT. Balances are bounded well under that by
+// BILLING_MAX_ADMIN_CREDIT_GRANT_MICRO and the rollover cap, and
+// getActiveCreditsMicro throws rather than serve a total that is not a safe
+// integer, so the range is asserted rather than assumed.
+export const bigintColumnTransformer = {
+ to: (value: number) => value,
+ from: (value: string | number | null) =>
+ typeof value === 'string' ? Number(value) : (value ?? 0),
+};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts
new file mode 100644
index 00000000000..b9e4f8f8932
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util.ts
@@ -0,0 +1,11 @@
+/* @license Enterprise */
+
+// Serializes everything that moves a workspace's credit state: writing to the
+// ledger and adjusting the counter derived from it. Readers take it too, but
+// only when the counter is cold, so the warm path stays lock-free.
+//
+// Without it the ledger write and the counter update are two independent
+// steps, and a reader computing availability in between either counts a grant
+// that the writer then adds again, or installs a balance that predates it.
+export const buildBillingCreditStateLockKey = (workspaceId: string): string =>
+ `billing-credit-state:${workspaceId}`;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util.ts
new file mode 100644
index 00000000000..63202b6b01c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-key.util.ts
@@ -0,0 +1,9 @@
+// Records that a one-off adjustment (a revocation, a period transition) already
+// moved the counter, so a retry can tell "already applied" from "never got that
+// far".
+export const buildBillingUsageCounterAdjustmentKey = (
+ workspaceId: string,
+ adjustmentKey: string,
+): string => {
+ return `available-credits-adjusted:${workspaceId}:${adjustmentKey}`;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-pattern.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-pattern.util.ts
new file mode 100644
index 00000000000..517bf5dd029
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/build-billing-usage-counter-adjustment-pattern.util.ts
@@ -0,0 +1,5 @@
+export const buildBillingUsageCounterAdjustmentPattern = (
+ workspaceId: string,
+): string => {
+ return `available-credits-adjusted:${workspaceId}:*`;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts
new file mode 100644
index 00000000000..be59a647308
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts
@@ -0,0 +1,115 @@
+/* @license Enterprise */
+
+import {
+ BillingCreditGrantType,
+ CAPPED_BILLING_CREDIT_GRANT_TYPES,
+} from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
+
+export type CarryForwardGrantInput = {
+ grantId: string;
+ type: BillingCreditGrantType;
+ amountMicro: number;
+ createdAt: Date;
+};
+
+export type CarryForwardGrantOutput = {
+ type: BillingCreditGrantType;
+ amountMicro: number;
+ sourceGrantId: string | null;
+};
+
+type CreditBucket = {
+ grantId: string | null;
+ type: BillingCreditGrantType;
+ amountMicro: number;
+ createdAt: Date;
+};
+
+const isCappedType = (type: BillingCreditGrantType): boolean =>
+ CAPPED_BILLING_CREDIT_GRANT_TYPES.includes(type);
+
+// Capped credits are spent first so that deliberately granted credits
+// (compensation, partnership, onboarding rewards) survive the period and carry
+// over at their full value instead of being clipped by the rollover cap.
+const compareSpendingOrder = (a: CreditBucket, b: CreditBucket): number => {
+ const [isACapped, isBCapped] = [isCappedType(a.type), isCappedType(b.type)];
+
+ if (isACapped !== isBCapped) {
+ return isACapped ? -1 : 1;
+ }
+
+ const byCreatedAt = a.createdAt.getTime() - b.createdAt.getTime();
+
+ if (byCreatedAt !== 0) {
+ return byCreatedAt;
+ }
+
+ // Grants written in the same transaction share a timestamp, and the order
+ // decides which grant id ends up on which carry-forward row. That id is part
+ // of the replay key, so without a stable tie-break a redelivery could write
+ // a second set of rows for the same credits.
+ return (a.grantId ?? '').localeCompare(b.grantId ?? '');
+};
+
+export const computeCarryForwardGrants = ({
+ allowanceMicro,
+ liveGrants,
+ usageMicro,
+ rolloverCapMicro,
+}: {
+ allowanceMicro: number;
+ liveGrants: CarryForwardGrantInput[];
+ usageMicro: number;
+ rolloverCapMicro: number;
+}): CarryForwardGrantOutput[] => {
+ const allowanceBucket: CreditBucket = {
+ grantId: null,
+ type: BillingCreditGrantType.ROLLOVER,
+ amountMicro: Math.max(0, allowanceMicro),
+ createdAt: new Date(0),
+ };
+
+ const buckets = [
+ allowanceBucket,
+ ...liveGrants.filter((grant) => grant.amountMicro > 0),
+ ].sort(compareSpendingOrder);
+
+ let remainingUsageMicro = Math.max(0, usageMicro);
+
+ const unspentBuckets = buckets.map((bucket) => {
+ const consumedMicro = Math.min(bucket.amountMicro, remainingUsageMicro);
+
+ remainingUsageMicro -= consumedMicro;
+
+ return { ...bucket, amountMicro: bucket.amountMicro - consumedMicro };
+ });
+
+ const cappedUnspentMicro = unspentBuckets
+ .filter((bucket) => isCappedType(bucket.type))
+ .reduce((total, bucket) => total + bucket.amountMicro, 0);
+
+ const rolloverMicro = Math.floor(
+ Math.min(cappedUnspentMicro, Math.max(0, rolloverCapMicro)),
+ );
+
+ const rolloverGrants: CarryForwardGrantOutput[] =
+ rolloverMicro > 0
+ ? [
+ {
+ type: BillingCreditGrantType.ROLLOVER,
+ amountMicro: rolloverMicro,
+ sourceGrantId: null,
+ },
+ ]
+ : [];
+
+ const preservedGrants: CarryForwardGrantOutput[] = unspentBuckets
+ .filter((bucket) => !isCappedType(bucket.type) && bucket.amountMicro >= 1)
+ .map((bucket) => ({
+ type: bucket.type,
+ amountMicro: Math.floor(bucket.amountMicro),
+ sourceGrantId: bucket.grantId,
+ }));
+
+ return [...rolloverGrants, ...preservedGrants];
+};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/derive-billing-period-transition.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/derive-billing-period-transition.util.ts
new file mode 100644
index 00000000000..41a0f369547
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/derive-billing-period-transition.util.ts
@@ -0,0 +1,98 @@
+/* @license Enterprise */
+
+import { subMonths, subYears } from 'date-fns';
+import { isDefined } from 'twenty-shared/utils';
+
+import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';
+
+export type BillingPeriodTransition = {
+ closingPeriodStart: Date;
+ closingPeriodEnd: Date;
+ nextPeriodStart: Date;
+ nextPeriodEnd: Date;
+};
+
+// A subscription_cycle invoice is raised at the instant one period hands over
+// to the next, and Stripe stamps it with the period it bills in advance. So its
+// period_start is the transition instant: the closing period ends there and the
+// new one starts there.
+export const deriveBillingPeriodTransition = ({
+ invoicePeriodStart,
+ invoicePeriodEnd,
+ subscriptionCurrentPeriodStart,
+ subscriptionCurrentPeriodEnd,
+ subscriptionInterval,
+ trialStart,
+ isFirstPeriodAfterTrial,
+ subscriptionPreviousPeriodStart,
+ ledgerPeriodStart,
+}: {
+ invoicePeriodStart: Date;
+ invoicePeriodEnd: Date;
+ subscriptionCurrentPeriodStart: Date;
+ subscriptionCurrentPeriodEnd: Date;
+ subscriptionInterval: SubscriptionInterval;
+ trialStart: Date | null | undefined;
+ isFirstPeriodAfterTrial: boolean;
+ // Where the subscription recorded the previous period starting, captured when
+ // it advanced. Null for a subscription that has not transitioned since the
+ // column was added.
+ subscriptionPreviousPeriodStart: Date | null;
+ // Where the ledger says the closing period started, used only when the
+ // subscription has no record of it.
+ ledgerPeriodStart: Date | null;
+}): BillingPeriodTransition => {
+ const boundary = invoicePeriodStart;
+
+ const nextPeriodEnd =
+ invoicePeriodEnd.getTime() > boundary.getTime()
+ ? invoicePeriodEnd
+ : subscriptionCurrentPeriodEnd;
+
+ const closingPeriodStart = (() => {
+ if (isFirstPeriodAfterTrial && isDefined(trialStart)) {
+ return trialStart;
+ }
+
+ if (subscriptionCurrentPeriodStart.getTime() < boundary.getTime()) {
+ return subscriptionCurrentPeriodStart;
+ }
+
+ // Recorded when the subscription advanced, so it is exact whatever the
+ // anchor. Calendar arithmetic cannot reproduce it for month-end anchors: a
+ // period running January 31 to February 28 comes back as starting January
+ // 28, which widens the usage window into the period before and drags
+ // already expired grants back into the carry-forward.
+ if (
+ isDefined(subscriptionPreviousPeriodStart) &&
+ subscriptionPreviousPeriodStart.getTime() < boundary.getTime()
+ ) {
+ return subscriptionPreviousPeriodStart;
+ }
+
+ // Only until each subscription has transitioned once with the column in
+ // place. The ledger records the boundary whenever the previous transition
+ // closed a grant there, which is most workspaces but not all.
+ if (
+ isDefined(ledgerPeriodStart) &&
+ ledgerPeriodStart.getTime() < boundary.getTime()
+ ) {
+ return ledgerPeriodStart;
+ }
+
+ // Calendar arithmetic, not the invoiced duration: consecutive periods
+ // differ in length, so a February renewal bills 28 days and subtracting
+ // those from February 1 would place the closing period at January 4 and
+ // drop three days of usage, which then reads as unspent allowance.
+ return subscriptionInterval === SubscriptionInterval.Year
+ ? subYears(boundary, 1)
+ : subMonths(boundary, 1);
+ })();
+
+ return {
+ closingPeriodStart,
+ closingPeriodEnd: boundary,
+ nextPeriodStart: boundary,
+ nextPeriodEnd,
+ };
+};
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 b0afe13dbe5..eb448f1fc26 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
@@ -18,6 +18,7 @@ export const getBillingExceptionStatusCode = (
case BillingExceptionCode.BILLING_METER_NOT_FOUND:
case BillingExceptionCode.BILLING_SUBSCRIPTION_ITEM_NOT_FOUND:
case BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_FOUND:
+ case BillingExceptionCode.BILLING_CREDIT_GRANT_NOT_FOUND:
return 404;
case BillingExceptionCode.BILLING_METER_EVENT_FAILED:
case BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_IN_TRIAL_PERIOD:
@@ -25,6 +26,8 @@ export const getBillingExceptionStatusCode = (
case BillingExceptionCode.BILLING_SUBSCRIPTION_PLAN_NOT_SWITCHABLE:
case BillingExceptionCode.BILLING_MISSING_REQUEST_BODY:
case BillingExceptionCode.BILLING_CREDIT_AMOUNT_INVALID:
+ case BillingExceptionCode.BILLING_CREDIT_GRANT_VALIDITY_INVALID:
+ case BillingExceptionCode.BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE:
return 400;
case BillingExceptionCode.BILLING_CREDITS_EXHAUSTED:
return 402;
@@ -41,6 +44,7 @@ export const getBillingExceptionStatusCode = (
case BillingExceptionCode.BILLING_SUBSCRIPTION_PHASE_NOT_FOUND:
case BillingExceptionCode.BILLING_TOO_MUCH_SUBSCRIPTIONS_FOUND:
case BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_CANCELED:
+ case BillingExceptionCode.BILLING_USAGE_UNAVAILABLE:
return 500;
default: {
return assertUnreachable(exception.code);
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-subscription-period.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-subscription-period.util.ts
new file mode 100644
index 00000000000..ebb4aba851d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/get-billing-subscription-period.util.ts
@@ -0,0 +1,25 @@
+/* @license Enterprise */
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
+import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';
+
+export const getBillingSubscriptionPeriod = (
+ subscription: BillingSubscriptionEntity,
+): { periodStart: Date; periodEnd: Date } => {
+ const { trialStart, trialEnd } = subscription;
+
+ if (
+ subscription.status === SubscriptionStatus.Trialing &&
+ isDefined(trialStart) &&
+ isDefined(trialEnd)
+ ) {
+ return { periodStart: trialStart, periodEnd: trialEnd };
+ }
+
+ return {
+ periodStart: subscription.currentPeriodStart,
+ periodEnd: subscription.currentPeriodEnd,
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.ts
new file mode 100644
index 00000000000..f3eb40a41b9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.ts
@@ -0,0 +1,45 @@
+/* @license Enterprise */
+
+import { isDefined } from 'twenty-shared/utils';
+
+type StoredBillingPeriod = {
+ currentPeriodStart: Date;
+ currentPeriodEnd: Date;
+};
+
+type BillingPeriodBoundaryUpdate = {
+ previousPeriodStart?: Date;
+ currentPeriodStart?: Date;
+ currentPeriodEnd?: Date;
+};
+
+// Stripe only ever reports the current window, so the boundary a period moves
+// off is captured at the moment it moves or lost for good. The rollover needs
+// it to bound the usage it settles, which is why every path that writes a
+// subscription resolves its period fields through this.
+export const resolveBillingPeriodBoundaryUpdate = ({
+ incomingPeriodStart,
+ storedSubscription,
+}: {
+ incomingPeriodStart: Date | undefined;
+ storedSubscription: StoredBillingPeriod | null;
+}): BillingPeriodBoundaryUpdate => {
+ if (!isDefined(storedSubscription) || !isDefined(incomingPeriodStart)) {
+ return {};
+ }
+
+ const { currentPeriodStart, currentPeriodEnd } = storedSubscription;
+
+ if (incomingPeriodStart.getTime() > currentPeriodStart.getTime()) {
+ return { previousPeriodStart: currentPeriodStart };
+ }
+
+ // Stripe never moves a period backwards, so an older window is an event
+ // delivered late. Letting it land would rewind the boundary the rollover
+ // settles against and leave it behind the one already recorded.
+ if (incomingPeriodStart.getTime() < currentPeriodStart.getTime()) {
+ return { currentPeriodStart, currentPeriodEnd };
+ }
+
+ return {};
+};
diff --git a/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts b/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts
index b29f8c08ef3..4c115bd2881 100644
--- a/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/cache-storage/services/cache-storage.service.ts
@@ -221,7 +221,10 @@ export class CacheStorageService {
do {
const result = await redisClient.scan(cursor, {
- MATCH: `${this.namespace}:${scanPattern}`,
+ // Through getKey, not the namespace alone: under NODE_ENV=test every
+ // key carries a further prefix, so a raw namespace match scans for
+ // keys that do not exist and the flush silently does nothing.
+ MATCH: this.getKey(scanPattern),
COUNT: 100,
});
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.spec.ts b/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.spec.ts
index c2ecf80e2e3..ac3407ff1e3 100644
--- a/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.spec.ts
@@ -4,6 +4,7 @@ import { getDataSourceToken, getRepositoryToken } from '@nestjs/typeorm';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
import { type DataSource, type QueryRunner, Repository } from 'typeorm';
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
@@ -55,7 +56,7 @@ describe('OnboardingService', () => {
{
provide: BillingCreditService,
useValue: {
- creditWorkspaceBalance: jest.fn(),
+ grantCredits: jest.fn(),
},
},
{
@@ -233,10 +234,14 @@ describe('OnboardingService', () => {
workspaceId,
key: OnboardingStepKeys.ONBOARDING_CONNECT_ACCOUNT_PENDING,
});
- expect(billingCreditService.creditWorkspaceBalance).toHaveBeenCalledWith({
- workspaceId,
- amountMicro: 2_000_000,
- });
+ expect(billingCreditService.grantCredits).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workspaceId,
+ amountMicro: 2_000_000,
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ idempotencyKey: `onboarding-import-contacts:${workspaceId}`,
+ }),
+ );
});
it('should claim the step but not credit when the workspace has more than one member', async () => {
@@ -253,9 +258,7 @@ describe('OnboardingService', () => {
workspaceId,
key: OnboardingStepKeys.ONBOARDING_CONNECT_ACCOUNT_PENDING,
});
- expect(
- billingCreditService.creditWorkspaceBalance,
- ).not.toHaveBeenCalled();
+ expect(billingCreditService.grantCredits).not.toHaveBeenCalled();
});
it('should not credit anything when the step was already consumed', async () => {
@@ -266,9 +269,7 @@ describe('OnboardingService', () => {
workspaceId,
});
- expect(
- billingCreditService.creditWorkspaceBalance,
- ).not.toHaveBeenCalled();
+ expect(billingCreditService.grantCredits).not.toHaveBeenCalled();
});
it('should credit only once when two completions race for the same step', async () => {
@@ -284,9 +285,7 @@ describe('OnboardingService', () => {
service.completeOnboardingConnectAccountStep({ userId, workspaceId }),
]);
- expect(billingCreditService.creditWorkspaceBalance).toHaveBeenCalledTimes(
- 1,
- );
+ expect(billingCreditService.grantCredits).toHaveBeenCalledTimes(1);
});
it('should not throw when crediting fails', async () => {
@@ -294,7 +293,7 @@ describe('OnboardingService', () => {
jest.spyOn(userWorkspaceRepository, 'countBy').mockResolvedValue(1);
jest.spyOn(twentyConfigService, 'get').mockReturnValue(2_000_000);
jest
- .spyOn(billingCreditService, 'creditWorkspaceBalance')
+ .spyOn(billingCreditService, 'grantCredits')
.mockRejectedValue(new Error('billing failure'));
await expect(
@@ -318,9 +317,7 @@ describe('OnboardingService', () => {
}),
).resolves.not.toThrow();
- expect(
- billingCreditService.creditWorkspaceBalance,
- ).not.toHaveBeenCalled();
+ expect(billingCreditService.grantCredits).not.toHaveBeenCalled();
});
});
@@ -350,9 +347,7 @@ describe('OnboardingService', () => {
},
{ id: `${INSTALL_ONBOARDING_APPS_JOB_NAME}-${workspaceId}` },
);
- expect(
- billingCreditService.creditWorkspaceBalance,
- ).not.toHaveBeenCalled();
+ expect(billingCreditService.grantCredits).not.toHaveBeenCalled();
});
it('should not enqueue anything when the step was already consumed', async () => {
@@ -473,16 +468,20 @@ describe('OnboardingService', () => {
rewardAppsCount: 2,
});
- expect(billingCreditService.creditWorkspaceBalance).toHaveBeenCalledWith({
- workspaceId,
- amountMicro: 2_000_000,
- });
+ expect(billingCreditService.grantCredits).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workspaceId,
+ amountMicro: 2_000_000,
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ idempotencyKey: `onboarding-install-apps:${workspaceId}`,
+ }),
+ );
});
it('should not throw when crediting fails', async () => {
jest.spyOn(twentyConfigService, 'get').mockReturnValue(1_000_000);
jest
- .spyOn(billingCreditService, 'creditWorkspaceBalance')
+ .spyOn(billingCreditService, 'grantCredits')
.mockRejectedValue(new Error('billing failure'));
await expect(
diff --git a/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts b/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts
index dcc0f31008e..7e81ef45d89 100644
--- a/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/onboarding/onboarding.service.ts
@@ -6,6 +6,7 @@ import { isDefined } from 'twenty-shared/utils';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
import { type DataSource, type QueryRunner, Repository } from 'typeorm';
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
import { BillingCreditService } from 'src/engine/core-modules/billing/services/billing-credit.service';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
@@ -262,11 +263,14 @@ export class OnboardingService {
return;
}
- await this.billingCreditService.creditWorkspaceBalance({
+ await this.billingCreditService.grantCredits({
workspaceId,
amountMicro: this.twentyConfigService.get(
'ONBOARDING_IMPORT_CONTACTS_CREDITS_REWARD',
),
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ reason: 'Onboarding reward: import contacts',
+ idempotencyKey: `onboarding-import-contacts:${workspaceId}`,
});
} catch (error) {
this.logger.error(
@@ -405,12 +409,15 @@ export class OnboardingService {
rewardAppsCount: number;
}) {
try {
- await this.billingCreditService.creditWorkspaceBalance({
+ await this.billingCreditService.grantCredits({
workspaceId,
amountMicro:
this.twentyConfigService.get(
'ONBOARDING_INSTALL_APPS_CREDITS_REWARD_PER_APP',
) * rewardAppsCount,
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ reason: `Onboarding reward: install ${rewardAppsCount} app(s)`,
+ idempotencyKey: `onboarding-install-apps:${workspaceId}`,
});
} catch (error) {
this.logger.error(
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index b548bb39c88..3598e847261 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -1018,6 +1018,27 @@ export class ConfigVariables {
@IsOptional()
BILLING_USAGE_CAP_CLICKHOUSE_ENABLED = false;
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.BILLING_CONFIG,
+ description:
+ 'Cap on the credits available in a period, as a multiple of the plan allowance. 2 means a workspace can hold at most its allowance plus one full allowance rolled over',
+ type: ConfigVariableType.NUMBER,
+ })
+ @CastToPositiveNumber()
+ @IsOptional()
+ BILLING_ROLLOVER_TOTAL_CAP_MULTIPLIER = 2;
+
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.BILLING_CONFIG,
+ description:
+ 'Largest credit amount a single admin panel grant can hand out (in microCredits)',
+ type: ConfigVariableType.NUMBER,
+ })
+ @CastToPositiveNumber()
+ @IsInt()
+ @IsOptional()
+ BILLING_MAX_ADMIN_CREDIT_GRANT_MICRO = 1_000_000_000;
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.BILLING_CONFIG,
description:
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.ts
new file mode 100644
index 00000000000..10765294cc9
--- /dev/null
+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts
@@ -0,0 +1,234 @@
+import { randomUUID } from 'node:crypto';
+
+import { addMonths, startOfMonth } from 'date-fns';
+import request from 'supertest';
+import {
+ getBillingUsageCacheService,
+ getMirroredCreditBalance,
+ getSeededBillingWorkspaceId,
+ listCreditGrants,
+ resetBillingCreditState,
+ setupResourceCreditSubscription,
+} from 'test/integration/billing/utils/billing-credit-fixtures.util';
+
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
+import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
+
+const client = request(`http://localhost:${APP_PORT}`);
+
+const PERIOD_START = startOfMonth(new Date());
+const PERIOD_END = addMonths(PERIOD_START, 1);
+const ALLOWANCE_MICRO = 1_000_000;
+
+const GRANT_MUTATION = `
+ mutation GrantWorkspaceCredits(
+ $workspaceId: UUID!
+ $amount: Float!
+ $type: BillingCreditGrantType!
+ $reason: String
+ $clientOperationId: UUID!
+ ) {
+ grantWorkspaceCredits(
+ workspaceId: $workspaceId
+ amount: $amount
+ type: $type
+ reason: $reason
+ clientOperationId: $clientOperationId
+ ) {
+ id
+ amount
+ type
+ reason
+ isActive
+ }
+ }
+`;
+
+const REVOKE_MUTATION = `
+ mutation RevokeWorkspaceCreditGrant($workspaceId: UUID!, $creditGrantId: UUID!) {
+ revokeWorkspaceCreditGrant(
+ workspaceId: $workspaceId
+ creditGrantId: $creditGrantId
+ ) {
+ id
+ revokedAt
+ }
+ }
+`;
+
+const grantCredits = (variables: Record<string, unknown>) =>
+ callAdminGraphql(GRANT_MUTATION, {
+ clientOperationId: randomUUID(),
+ ...variables,
+ });
+
+const callAdminGraphql = (query: string, variables: Record<string, unknown>) =>
+ client
+ .post('/admin-panel')
+ .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
+ .set('Content-Type', 'application/json')
+ .send({ query, variables });
+
+describe('Admin credit grant and revoke (integration)', () => {
+ let workspaceId: string;
+
+ beforeAll(async () => {
+ workspaceId = await getSeededBillingWorkspaceId();
+ });
+
+ beforeEach(async () => {
+ await resetBillingCreditState(workspaceId);
+ await setupResourceCreditSubscription({
+ workspaceId,
+ periodStart: PERIOD_START,
+ periodEnd: PERIOD_END,
+ creditAmountMicro: ALLOWANCE_MICRO,
+ });
+ });
+
+ afterEach(async () => {
+ await resetBillingCreditState(workspaceId);
+ });
+
+ it('records a granted amount on the ledger and mirrors it', async () => {
+ const response = await grantCredits({
+ workspaceId,
+ amount: 2,
+ type: BillingCreditGrantType.COMPENSATION,
+ reason: 'Outage on the 3rd',
+ });
+
+ expect(response.body.errors).toBeUndefined();
+
+ const grants = await listCreditGrants(workspaceId);
+
+ expect(grants).toHaveLength(1);
+ expect(grants[0]).toMatchObject({
+ amountMicro: 2 * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
+ type: BillingCreditGrantType.COMPENSATION,
+ 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 () => {
+ const cache = getBillingUsageCacheService();
+
+ await cache.warmAvailableCredits(
+ workspaceId,
+ PERIOD_START,
+ PERIOD_END,
+ 500_000,
+ );
+
+ await grantCredits({
+ workspaceId,
+ amount: 2,
+ type: BillingCreditGrantType.COMPENSATION,
+ reason: null,
+ });
+
+ expect(await cache.getAvailableCredits(workspaceId, PERIOD_START)).toBe(
+ 500_000 + 2 * INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
+ );
+ });
+
+ it('takes a revoked grant back off the ledger and the counter', async () => {
+ const cache = getBillingUsageCacheService();
+
+ await cache.warmAvailableCredits(
+ workspaceId,
+ PERIOD_START,
+ PERIOD_END,
+ 500_000,
+ );
+
+ const granted = await grantCredits({
+ workspaceId,
+ amount: 2,
+ type: BillingCreditGrantType.COMPENSATION,
+ reason: null,
+ });
+ const creditGrantId = granted.body.data.grantWorkspaceCredits.id;
+
+ const revoked = await callAdminGraphql(REVOKE_MUTATION, {
+ workspaceId,
+ creditGrantId,
+ });
+
+ expect(revoked.body.errors).toBeUndefined();
+ expect(
+ revoked.body.data.revokeWorkspaceCreditGrant.revokedAt,
+ ).not.toBeNull();
+
+ 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,
+ );
+ });
+
+ // The panel only offers the three operator types, but the mutation is
+ // reachable directly and these two are written by the period transition and
+ // the onboarding jobs.
+ it.each([
+ BillingCreditGrantType.ROLLOVER,
+ BillingCreditGrantType.ONBOARDING_REWARD,
+ ])('refuses to grant a %s by hand', async (type) => {
+ const response = await grantCredits({
+ workspaceId,
+ amount: 1,
+ type,
+ reason: null,
+ });
+
+ expect(response.body.errors?.[0]?.extensions?.subCode).toBe(
+ 'BILLING_CREDIT_GRANT_TYPE_NOT_GRANTABLE',
+ );
+ expect(await listCreditGrants(workspaceId)).toHaveLength(0);
+ });
+
+ it('refuses an amount above the configured ceiling', async () => {
+ const response = await grantCredits({
+ workspaceId,
+ amount: 1_000_000_000,
+ type: BillingCreditGrantType.COMPENSATION,
+ reason: null,
+ });
+
+ expect(response.body.errors?.[0]?.extensions?.subCode).toBe(
+ 'BILLING_CREDIT_AMOUNT_INVALID',
+ );
+ expect(await listCreditGrants(workspaceId)).toHaveLength(0);
+ });
+
+ // The admin panel keeps one operation id per open modal, so an Apollo retry
+ // or a resubmit after a lost response must answer with the grant the first
+ // attempt wrote rather than crediting the workspace a second time.
+ it('answers a retried grant with the original instead of granting twice', async () => {
+ const clientOperationId = randomUUID();
+ const variables = {
+ workspaceId,
+ amount: 25,
+ type: BillingCreditGrantType.COMPENSATION,
+ reason: 'Retried by the client',
+ clientOperationId,
+ };
+
+ const first = await callAdminGraphql(GRANT_MUTATION, variables);
+ const second = await callAdminGraphql(GRANT_MUTATION, variables);
+
+ expect(second.body.data.grantWorkspaceCredits.id).toBe(
+ 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.ts
new file mode 100644
index 00000000000..a8bb2f2c1ae
--- /dev/null
+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts
@@ -0,0 +1,336 @@
+import { addMonths, startOfMonth, subMonths } from 'date-fns';
+import request from 'supertest';
+import { createMockStripeInvoiceFinalizedData } from 'test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util';
+import {
+ getBillingUsageCacheService,
+ getMirroredCreditBalance,
+ getSeededBillingWorkspaceId,
+ insertCreditGrant,
+ listCreditGrants,
+ resetBillingCreditState,
+ setupResourceCreditSubscription,
+ TEST_STRIPE_CUSTOMER_ID,
+} from 'test/integration/billing/utils/billing-credit-fixtures.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+
+import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
+import { type BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
+
+const 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.
+const PERIOD_BOUNDARY = startOfMonth(new Date());
+const CLOSING_PERIOD_START = subMonths(PERIOD_BOUNDARY, 1);
+const CLOSING_PERIOD_END = PERIOD_BOUNDARY;
+const NEXT_PERIOD_END = addMonths(PERIOD_BOUNDARY, 1);
+
+const ALLOWANCE_MICRO = 1_000_000;
+
+const postInvoiceFinalized = (
+ invoiceId = 'in_test_default',
+ { periodStart = CLOSING_PERIOD_END, periodEnd = NEXT_PERIOD_END } = {},
+) =>
+ client
+ .post('/webhooks/stripe')
+ .set('stripe-signature', 'correct-signature')
+ .set('Content-Type', 'application/json')
+ .send(
+ JSON.stringify({
+ type: 'invoice.finalized',
+ data: createMockStripeInvoiceFinalizedData({
+ periodStart,
+ periodEnd,
+ stripeCustomerId: TEST_STRIPE_CUSTOMER_ID,
+ invoiceId,
+ }),
+ }),
+ );
+
+describe('Billing credit rollover (integration)', () => {
+ let workspaceId: string;
+ let billingUsageService: BillingUsageService;
+ let usageSpy: jest.SpyInstance;
+
+ beforeAll(async () => {
+ workspaceId = await getSeededBillingWorkspaceId();
+ billingUsageService = getAppProviderByClassName<BillingUsageService>(
+ 'BillingUsageService',
+ );
+ });
+
+ beforeEach(async () => {
+ await resetBillingCreditState(workspaceId);
+ await setupResourceCreditSubscription({
+ workspaceId,
+ periodStart: CLOSING_PERIOD_START,
+ periodEnd: CLOSING_PERIOD_END,
+ creditAmountMicro: ALLOWANCE_MICRO,
+ });
+
+ // Usage is read from ClickHouse, whose inserts are asynchronous. Stubbing
+ // the read keeps every expectation exact instead of racing ingestion; the
+ // query itself has its own unit coverage.
+ usageSpy = jest.spyOn(billingUsageService, 'getCreditsUsedBetweenOrNull');
+ });
+
+ afterEach(async () => {
+ usageSpy?.mockRestore();
+ await resetBillingCreditState(workspaceId);
+ });
+
+ it('carries the unspent allowance into the next period', async () => {
+ usageSpy.mockResolvedValue(300_000);
+
+ await postInvoiceFinalized().expect(200);
+
+ const grants = await listCreditGrants(workspaceId);
+
+ expect(grants).toHaveLength(1);
+ expect(grants[0]).toMatchObject({
+ amountMicro: 700_000,
+ type: BillingCreditGrantType.ROLLOVER,
+ revokedAt: null,
+ });
+ expect(new Date(grants[0].effectiveAt)).toEqual(CLOSING_PERIOD_END);
+ expect(new Date(grants[0].expiresAt)).toEqual(NEXT_PERIOD_END);
+ });
+
+ it('reads usage over the closing period, not the one just opened', async () => {
+ usageSpy.mockResolvedValue(0);
+
+ await postInvoiceFinalized().expect(200);
+
+ expect(usageSpy).toHaveBeenCalledWith({
+ workspaceId,
+ from: CLOSING_PERIOD_START,
+ to: CLOSING_PERIOD_END,
+ });
+ });
+
+ it('carries nothing when the whole allowance was spent', async () => {
+ usageSpy.mockResolvedValue(ALLOWANCE_MICRO);
+
+ await postInvoiceFinalized().expect(200);
+
+ expect(await listCreditGrants(workspaceId)).toHaveLength(0);
+ });
+
+ it('closes the grants it carried forward so they cannot be counted twice', async () => {
+ usageSpy.mockResolvedValue(0);
+ await insertCreditGrant({
+ workspaceId,
+ amountMicro: 500_000,
+ type: BillingCreditGrantType.COMPENSATION,
+ effectiveAt: CLOSING_PERIOD_START,
+ expiresAt: NEXT_PERIOD_END,
+ });
+
+ await postInvoiceFinalized().expect(200);
+
+ const grants = await listCreditGrants(workspaceId);
+ const compensation = grants.find(
+ (grant) =>
+ grant.type === BillingCreditGrantType.COMPENSATION &&
+ grant.sourceGrantId === null,
+ );
+
+ expect(compensation).toBeDefined();
+
+ // Its expiry was pulled back to the boundary, so the balance counts it
+ // once through its carried-forward copy rather than twice.
+ expect(new Date(compensation!.expiresAt)).toEqual(CLOSING_PERIOD_END);
+ expect(
+ grants.some(
+ (grant) =>
+ grant.type === BillingCreditGrantType.COMPENSATION &&
+ grant.sourceGrantId === compensation!.id,
+ ),
+ ).toBe(true);
+ });
+
+ it('caps the carried rollover at the configured multiple of the allowance', async () => {
+ usageSpy.mockResolvedValue(0);
+ await insertCreditGrant({
+ workspaceId,
+ amountMicro: ALLOWANCE_MICRO,
+ type: BillingCreditGrantType.ROLLOVER,
+ effectiveAt: CLOSING_PERIOD_START,
+ expiresAt: CLOSING_PERIOD_END,
+ });
+
+ await postInvoiceFinalized().expect(200);
+
+ const carried = (await listCreditGrants(workspaceId)).filter(
+ (grant) => grant.sourceGrantId !== null || grant.idempotencyKey !== null,
+ );
+ const carriedRollover = carried.filter(
+ (grant) => grant.type === BillingCreditGrantType.ROLLOVER,
+ );
+
+ // allowance + expiring rollover = 2M unspent, clamped to (2 - 1) x 1M.
+ expect(
+ carriedRollover.reduce((total, grant) => total + grant.amountMicro, 0),
+ ).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);
+
+ await postInvoiceFinalized().expect(200);
+ const afterFirst = await listCreditGrants(workspaceId);
+
+ await postInvoiceFinalized().expect(200);
+ const afterSecond = await listCreditGrants(workspaceId);
+
+ expect(afterSecond).toHaveLength(afterFirst.length);
+ 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
+ // the transition would be lost and the balance would expire unrolled.
+ it('fails the webhook when usage cannot be read so Stripe redelivers', async () => {
+ usageSpy.mockResolvedValue(null);
+
+ 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 () => {
+ usageSpy.mockResolvedValue(300_000);
+ const cache = getBillingUsageCacheService();
+
+ // The counter is keyed by the period the subscription is currently in,
+ // which is the one the invoice is closing: Stripe moves the subscription
+ // forward in a separate event.
+ await cache.warmAvailableCredits(
+ workspaceId,
+ CLOSING_PERIOD_START,
+ NEXT_PERIOD_END,
+ 120_000,
+ );
+
+ await postInvoiceFinalized().expect(200);
+
+ expect(
+ await cache.getAvailableCredits(workspaceId, CLOSING_PERIOD_START),
+ ).toBe(120_000 + 700_000);
+ });
+
+ // Stripe redelivers events it already handled. Rebuilding on that redelivery
+ // would drop a counter that is already correct and recompute it from
+ // ClickHouse, handing back every credit whose usage has not been ingested yet.
+ it('leaves a warm counter alone when a successful delivery is repeated', async () => {
+ usageSpy.mockResolvedValue(300_000);
+ const cache = getBillingUsageCacheService();
+
+ await cache.warmAvailableCredits(
+ workspaceId,
+ CLOSING_PERIOD_START,
+ NEXT_PERIOD_END,
+ 120_000,
+ );
+
+ await postInvoiceFinalized().expect(200);
+ const afterFirst = await cache.getAvailableCredits(
+ workspaceId,
+ CLOSING_PERIOD_START,
+ );
+
+ await postInvoiceFinalized().expect(200);
+
+ expect(afterFirst).toBe(120_000 + 700_000);
+ expect(
+ await cache.getAvailableCredits(workspaceId, CLOSING_PERIOD_START),
+ ).toBe(afterFirst);
+ });
+
+ // A subscription anchored on the 31st runs January 31 to February 28. Once
+ // the subscription.updated webhook has moved the subscription on, calendar
+ // arithmetic clamps February 28 back to January 28 and the closing period
+ // swallows three days of the period before it.
+ describe('a month-end anchor whose subscription already advanced', () => {
+ const MONTH_END_BOUNDARY = new Date('2026-02-28T00:00:00.000Z');
+ const TRUE_CLOSING_PERIOD_START = new Date('2026-01-31T00:00:00.000Z');
+ const MONTH_END_NEXT_PERIOD_END = new Date('2026-03-31T00:00:00.000Z');
+
+ it('reads the closing period start off the ledger rather than the calendar', async () => {
+ usageSpy.mockResolvedValue(0);
+ await setupResourceCreditSubscription({
+ workspaceId,
+ periodStart: MONTH_END_BOUNDARY,
+ periodEnd: MONTH_END_NEXT_PERIOD_END,
+ creditAmountMicro: ALLOWANCE_MICRO,
+ });
+ // What the previous transition left behind: a grant closed at the instant
+ // the period it belonged to ended.
+ await insertCreditGrant({
+ workspaceId,
+ amountMicro: 100_000,
+ type: BillingCreditGrantType.ROLLOVER,
+ effectiveAt: new Date('2025-12-31T00:00:00.000Z'),
+ expiresAt: TRUE_CLOSING_PERIOD_START,
+ });
+
+ await postInvoiceFinalized('in_test_month_end', {
+ periodStart: MONTH_END_BOUNDARY,
+ periodEnd: MONTH_END_NEXT_PERIOD_END,
+ }).expect(200);
+
+ expect(usageSpy).toHaveBeenCalledWith({
+ workspaceId,
+ from: TRUE_CLOSING_PERIOD_START,
+ to: MONTH_END_BOUNDARY,
+ });
+ });
+ });
+
+ describe('closing a trial', () => {
+ it('carries credits earned during the trial into the first paid period', async () => {
+ usageSpy.mockResolvedValue(0);
+ await setupResourceCreditSubscription({
+ workspaceId,
+ periodStart: CLOSING_PERIOD_START,
+ periodEnd: CLOSING_PERIOD_END,
+ creditAmountMicro: ALLOWANCE_MICRO,
+ status: 'trialing',
+ trialStart: CLOSING_PERIOD_START,
+ trialEnd: CLOSING_PERIOD_END,
+ });
+ await insertCreditGrant({
+ workspaceId,
+ amountMicro: 250_000,
+ type: BillingCreditGrantType.ONBOARDING_REWARD,
+ effectiveAt: CLOSING_PERIOD_START,
+ expiresAt: CLOSING_PERIOD_END,
+ });
+
+ await postInvoiceFinalized('in_test_trial').expect(200);
+
+ const reward = (await listCreditGrants(workspaceId)).find(
+ (grant) =>
+ grant.type === BillingCreditGrantType.ONBOARDING_REWARD &&
+ grant.sourceGrantId !== null,
+ );
+
+ expect(reward).toBeDefined();
+ expect(reward!.amountMicro).toBe(250_000);
+ expect(new Date(reward!.expiresAt)).toEqual(NEXT_PERIOD_END);
+ });
+ });
+});
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.ts
new file mode 100644
index 00000000000..5fa1a912b1a
--- /dev/null
+++ b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts
@@ -0,0 +1,203 @@
+import { type BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';
+import { type BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
+
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+
+// The dev seeder gives every workspace a billingCustomer and an active
+// billingSubscription, but no subscription item, and no period. Rollover needs
+// the whole chain — subscription -> item -> product -> price with a
+// credit_amount — so these helpers finish the fixture and put the period where
+// the test wants it.
+export const TEST_STRIPE_CUSTOMER_ID = 'cus_default0';
+export const TEST_STRIPE_SUBSCRIPTION_ID = 'sub_default0';
+
+const TEST_STRIPE_PRODUCT_ID = 'prod_resource_credit_test';
+const TEST_STRIPE_PRICE_ID = 'price_resource_credit_test';
+const TEST_STRIPE_SUBSCRIPTION_ITEM_ID = 'si_resource_credit_test';
+
+export type CreditGrantRow = {
+ id: string;
+ amountMicro: number;
+ type: BillingCreditGrantType;
+ effectiveAt: Date;
+ expiresAt: Date;
+ revokedAt: Date | null;
+ reason: string | null;
+ idempotencyKey: string | null;
+ sourceGrantId: string | null;
+};
+
+const query = async <T>(sql: string, params: unknown[] = []): Promise<T[]> =>
+ global.testDataSource.query(sql, params);
+
+// The billing seeds insert with orIgnore, so the customer and subscription
+// land on exactly one workspace and which one is not worth hardcoding.
+export const getSeededBillingWorkspaceId = async (): Promise<string> => {
+ const [row] = await query<{ workspaceId: string }>(
+ `SELECT "workspaceId" FROM core."billingSubscription" WHERE "stripeSubscriptionId" = $1`,
+ [TEST_STRIPE_SUBSCRIPTION_ID],
+ );
+
+ if (!row) {
+ throw new Error(
+ `No seeded billing subscription ${TEST_STRIPE_SUBSCRIPTION_ID}: the dev seeder did not run`,
+ );
+ }
+
+ return row.workspaceId;
+};
+
+export const setupResourceCreditSubscription = async ({
+ workspaceId,
+ periodStart,
+ periodEnd,
+ creditAmountMicro,
+ status = 'active',
+ trialStart = null,
+ trialEnd = null,
+}: {
+ workspaceId: string;
+ periodStart: Date;
+ periodEnd: Date;
+ creditAmountMicro: number;
+ status?: string;
+ trialStart?: Date | null;
+ trialEnd?: Date | null;
+}): Promise<{ subscriptionId: string }> => {
+ await query(
+ `UPDATE core."billingSubscription"
+ SET "currentPeriodStart" = $2, "currentPeriodEnd" = $3, status = $4,
+ "trialStart" = $5, "trialEnd" = $6, interval = 'month'
+ WHERE "workspaceId" = $1 AND "stripeSubscriptionId" = $7`,
+ [
+ workspaceId,
+ periodStart,
+ periodEnd,
+ status,
+ trialStart,
+ trialEnd,
+ TEST_STRIPE_SUBSCRIPTION_ID,
+ ],
+ );
+
+ const [subscription] = await query<{ id: string }>(
+ `SELECT id FROM core."billingSubscription"
+ WHERE "workspaceId" = $1 AND "stripeSubscriptionId" = $2`,
+ [workspaceId, TEST_STRIPE_SUBSCRIPTION_ID],
+ );
+
+ await query(
+ `INSERT INTO core."billingProduct"
+ ("stripeProductId", active, name, description, metadata)
+ VALUES ($1, true, 'Test resource credit', '', $2)
+ ON CONFLICT ("stripeProductId") DO UPDATE SET metadata = EXCLUDED.metadata`,
+ [TEST_STRIPE_PRODUCT_ID, JSON.stringify({ productKey: 'RESOURCE_CREDIT' })],
+ );
+
+ await query(
+ `INSERT INTO core."billingPrice"
+ ("stripePriceId", "stripeProductId", active, currency, "taxBehavior",
+ type, "billingScheme", "usageType", interval, "unitAmount", metadata)
+ VALUES ($1, $2, true, 'usd', 'UNSPECIFIED', 'RECURRING', 'PER_UNIT',
+ 'LICENSED', 'month', 1000, $3)
+ ON CONFLICT ("stripePriceId") DO UPDATE SET metadata = EXCLUDED.metadata`,
+ [
+ TEST_STRIPE_PRICE_ID,
+ TEST_STRIPE_PRODUCT_ID,
+ JSON.stringify({ credit_amount: String(creditAmountMicro) }),
+ ],
+ );
+
+ await query(
+ `INSERT INTO core."billingSubscriptionItem"
+ ("billingSubscriptionId", "stripeSubscriptionId", "stripeProductId",
+ "stripePriceId", "stripeSubscriptionItemId", quantity)
+ VALUES ($1, $2, $3, $4, $5, 1)
+ ON CONFLICT ("stripeSubscriptionItemId") DO UPDATE
+ SET "stripePriceId" = EXCLUDED."stripePriceId",
+ "stripeProductId" = EXCLUDED."stripeProductId"`,
+ [
+ subscription.id,
+ TEST_STRIPE_SUBSCRIPTION_ID,
+ TEST_STRIPE_PRODUCT_ID,
+ TEST_STRIPE_PRICE_ID,
+ TEST_STRIPE_SUBSCRIPTION_ITEM_ID,
+ ],
+ );
+
+ return { subscriptionId: subscription.id };
+};
+
+export const insertCreditGrant = async ({
+ workspaceId,
+ amountMicro,
+ type,
+ effectiveAt,
+ expiresAt,
+ idempotencyKey = null,
+}: {
+ workspaceId: string;
+ amountMicro: number;
+ type: BillingCreditGrantType;
+ effectiveAt: Date;
+ expiresAt: Date;
+ idempotencyKey?: string | null;
+}): Promise<string> => {
+ const [row] = await query<{ id: string }>(
+ `INSERT INTO core."billingCreditGrant"
+ ("workspaceId", "amountMicro", type, "effectiveAt", "expiresAt", "idempotencyKey")
+ VALUES ($1, $2, $3, $4, $5, $6)
+ RETURNING id`,
+ [workspaceId, amountMicro, type, effectiveAt, expiresAt, idempotencyKey],
+ );
+
+ return row.id;
+};
+
+export const listCreditGrants = async (
+ workspaceId: string,
+): Promise<CreditGrantRow[]> =>
+ query<CreditGrantRow>(
+ `SELECT id, "amountMicro"::bigint::int AS "amountMicro", type, "effectiveAt",
+ "expiresAt", "revokedAt", reason, "idempotencyKey", "sourceGrantId"
+ FROM core."billingCreditGrant"
+ WHERE "workspaceId" = $1
+ ORDER BY "createdAt" ASC`,
+ [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> => {
+ await query(
+ `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);
+ // Adjustment markers outlive a counter flush by design, so a transition in
+ // one test would otherwise make the next one read its first delivery as a
+ // replay that had already moved the counter.
+ await cache.flushCounterAdjustmentMarkers(workspaceId);
+};
+
+export const getBillingUsageCacheService = (): BillingUsageCacheService =>
+ getAppProviderByClassName<BillingUsageCacheService>(
+ 'BillingUsageCacheService',
+ );
diff --git a/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util.ts b/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util.ts
new file mode 100644
index 00000000000..2bfbbba70ab
--- /dev/null
+++ b/packages/twenty-server/test/integration/billing/utils/create-mock-stripe-invoice-finalized-data.util.ts
@@ -0,0 +1,52 @@
+// Typed to what the handler actually reads rather than to Stripe.Invoice: the
+// payload crosses the wire as JSON, so the runtime shape is what matters, and
+// a full Stripe.Invoice fixture would be a few hundred lines of noise.
+export type MockStripeInvoiceFinalizedData = {
+ object: {
+ id: string;
+ object: 'invoice';
+ billing_reason: string;
+ customer: string;
+ period_start: number;
+ period_end: number;
+ parent: {
+ subscription_details: {
+ subscription: string;
+ };
+ };
+ };
+};
+
+const toUnixSeconds = (date: Date): number => Math.floor(date.getTime() / 1000);
+
+export const createMockStripeInvoiceFinalizedData = ({
+ periodStart,
+ periodEnd,
+ stripeCustomerId = 'cus_default0',
+ stripeSubscriptionId = 'sub_default0',
+ billingReason = 'subscription_cycle',
+ invoiceId = 'in_test_default',
+}: {
+ periodStart: Date;
+ periodEnd: Date;
+ stripeCustomerId?: string;
+ stripeSubscriptionId?: string;
+ billingReason?: string;
+ invoiceId?: string;
+}): MockStripeInvoiceFinalizedData => ({
+ object: {
+ id: invoiceId,
+ object: 'invoice',
+ billing_reason: billingReason,
+ customer: stripeCustomerId,
+ // The invoice for a subscription_cycle bills the period it opens, so its
+ // period_start is the instant the previous period closed.
+ period_start: toUnixSeconds(periodStart),
+ period_end: toUnixSeconds(periodEnd),
+ parent: {
+ subscription_details: {
+ subscription: stripeSubscriptionId,
+ },
+ },
+ },
+});