The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(billing): stop granted credits expiring when a period transition misfires (#25603)
Félix Malfait649f303ec62e
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.tsindex 44bf8042601..e39e9b130ec 100644--- a/packages/twenty-front/src/generated-admin/graphql.ts+++ b/packages/twenty-front/src/generated-admin/graphql.ts@@ -179,11 +179,12 @@ export type AdminPanelWorkspaceCreditGrant = {amount: Scalars['Float']['output'];createdAt: Scalars['DateTime']['output'];effectiveAt: Scalars['DateTime']['output'];- expiresAt: Scalars['DateTime']['output'];+ expiresAt?: Maybe<Scalars['DateTime']['output']>;id: Scalars['UUID']['output'];isActive: Scalars['Boolean']['output'];reason?: Maybe<Scalars['String']['output']>;revokedAt?: Maybe<Scalars['DateTime']['output']>;+ sourceGrantId?: Maybe<Scalars['UUID']['output']>;type: BillingCreditGrantType;};@@ -580,6 +581,7 @@ export type MutationDeleteJobsArgs = {export type MutationGrantWorkspaceCreditsArgs = {amount: Scalars['Float']['input'];clientOperationId: Scalars['UUID']['input'];+ expiresInDays?: InputMaybe<Scalars['Int']['input']>;reason?: InputMaybe<Scalars['String']['input']>;type: BillingCreditGrantType;workspaceId: Scalars['UUID']['input'];@@ -1307,11 +1309,12 @@ export type GrantWorkspaceCreditsMutationVariables = Exact<{amount: Scalars['Float']['input'];type: BillingCreditGrantType;reason?: InputMaybe<Scalars['String']['input']>;+ expiresInDays?: InputMaybe<Scalars['Int']['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 GrantWorkspaceCreditsMutation = { __typename?: 'Mutation', grantWorkspaceCredits: { __typename?: 'AdminPanelWorkspaceCreditGrant', id: string, amount: number, type: BillingCreditGrantType, effectiveAt: string, expiresAt?: string | null, revokedAt?: string | null, sourceGrantId?: string | null, reason?: string | null, isActive: boolean, createdAt: string } };export type RevokeWorkspaceCreditGrantMutationVariables = Exact<{workspaceId: Scalars['UUID']['input'];@@ -1319,7 +1322,7 @@ export type RevokeWorkspaceCreditGrantMutationVariables = Exact<{}>;-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 RevokeWorkspaceCreditGrantMutation = { __typename?: 'Mutation', revokeWorkspaceCreditGrant: { __typename?: 'AdminPanelWorkspaceCreditGrant', id: string, amount: number, type: BillingCreditGrantType, effectiveAt: string, expiresAt?: string | null, revokedAt?: string | null, sourceGrantId?: string | null, reason?: string | null, isActive: boolean, createdAt: string } };export type UpdateServerAdminAccessMutationVariables = Exact<{userId: Scalars['UUID']['input'];@@ -1411,7 +1414,7 @@ export type WorkspaceBillingAdminPanelQueryVariables = Exact<{}>;-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 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 | null, revokedAt?: string | null, sourceGrantId?: 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'];@@ -1546,8 +1549,8 @@ export const DeleteDatabaseConfigVariableDocument = {"kind":"Document","definitiexport 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 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":"expiresInDays"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"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":"expiresInDays"},"value":{"kind":"Variable","name":{"kind":"Name","value":"expiresInDays"}}},{"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":"sourceGrantId"}},{"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":"sourceGrantId"}},{"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>;@@ -1559,7 +1562,7 @@ export const GetAdminWorkspaceChatThreadsDocument = {"kind":"Document","definitiexport 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":"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 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":"sourceGrantId"}},{"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/SettingsAdminWorkspaceCreditGrantModal.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal.tsxindex 7adf6b777bd..aad12a470fd 100644--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal.tsx+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantModal.tsx@@ -10,6 +10,7 @@ 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_EXPIRY_OPTIONS } from '@/settings/admin-panel/constants/CreditGrantExpiryOptions';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';@@ -64,6 +65,7 @@ export const SettingsAdminWorkspaceCreditGrantModal = ({BillingCreditGrantType.COMPENSATION,);const [reason, setReason] = useState('');+ const [expiresInDays, setExpiresInDays] = useState<number | null>(null);// 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@@ -91,6 +93,7 @@ export const SettingsAdminWorkspaceCreditGrantModal = ({setAmount('');setType(BillingCreditGrantType.COMPENSATION);setReason('');+ setExpiresInDays(null);setSubmittedGrant(null);closeModal(modalInstanceId);};@@ -101,7 +104,12 @@ export const SettingsAdminWorkspaceCreditGrantModal = ({}const trimmedReason = reason.trim();- const payload = JSON.stringify([parsedAmount, type, trimmedReason]);+ const payload = JSON.stringify([+ parsedAmount,+ type,+ trimmedReason,+ expiresInDays,+ ]);const clientOperationId =submittedGrant?.payload === payload@@ -117,6 +125,7 @@ export const SettingsAdminWorkspaceCreditGrantModal = ({amount: parsedAmount,type,reason: trimmedReason || null,+ expiresInDays,clientOperationId,},});@@ -157,7 +166,7 @@ export const SettingsAdminWorkspaceCreditGrantModal = ({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.`}+ {t`Credits are added on top of the plan allowance and are spent only once it runs out. They carry over in full from one billing period to the next, and stay available until they are used up or, where an expiry is set, until the end of the billing period that expiry falls in.`}</Section></StyledSectionContainer>@@ -188,6 +197,19 @@ export const SettingsAdminWorkspaceCreditGrantModal = ({fullWidth/>+ <Select+ dropdownId={`${modalInstanceId}-expires-in-days`}+ label={t`Expires`}+ value={expiresInDays}+ options={CREDIT_GRANT_EXPIRY_OPTIONS.map((option) => ({+ value: option.value,+ label: t(option.label),+ }))}+ onChange={setExpiresInDays}+ isDropdownInModal+ fullWidth+ />+<SettingsTextInputinstanceId={`${modalInstanceId}-reason`}label={t`Reason`}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.tsxindex efad1722b7c..a5440d42ba0 100644--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantsTable.tsx+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceCreditGrantsTable.tsx@@ -15,6 +15,10 @@ import { CREDIT_GRANT_TYPE_COLORS } from '@/settings/admin-panel/constants/Crediimport { 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 {+ collapseCreditGrantChains,+ type CollapsedCreditGrant,+} from '@/settings/admin-panel/utils/collapseCreditGrantChains';import { SettingsTableListSection } from '@/settings/components/SettingsTableListSection';import { useNumberFormat } from '@/localization/hooks/useNumberFormat';import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';@@ -37,7 +41,7 @@ type SettingsAdminWorkspaceCreditGrantsTableProps = {// 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 CREDIT_GRANTS_GRID_AUTO_COLUMNS = '88px 140px 88px 108px 108px 1fr 36px';const REVOKE_CREDIT_GRANT_MODAL_ID = 'revoke-credit-grant-modal';const EM_DASH = '—';@@ -55,6 +59,8 @@ const getStatus = (return { label: msg`Expired`, color: 'gray' };};+type CreditGrantRow = CollapsedCreditGrant<CreditGrant>;+export const SettingsAdminWorkspaceCreditGrantsTable = ({workspaceId,creditGrants,@@ -68,6 +74,8 @@ export const SettingsAdminWorkspaceCreditGrantsTable = ({const [grantPendingRevocation, setGrantPendingRevocation] =useState<CreditGrant | null>(null);++ const creditGrantRows = collapseCreditGrantChains(creditGrants);const [isRevoking, setIsRevoking] = useState(false);const [revokeWorkspaceCreditGrant] = useMutation(@@ -110,51 +118,63 @@ export const SettingsAdminWorkspaceCreditGrantsTable = ({return (<>- <SettingsTableListSection<CreditGrant>+ <SettingsTableListSection<CreditGrantRow>title={t`Granted credits`}- description={t`Credits handed out on top of the plan allowance`}- items={creditGrants}+ description={t`Credits handed out on top of the plan allowance. They stay spendable until used up.`}+ items={creditGrantRows}columns={[{label: t`Amount`,- Cell: ({ item }) => <>{formatCredits(item.amount)}</>,+ Cell: ({ item }) => <>{formatCredits(item.current.amount)}</>,},{label: t`Type`,Cell: ({ item }) => (<Tag- color={CREDIT_GRANT_TYPE_COLORS[item.type]}- text={t(CREDIT_GRANT_TYPE_LABELS[item.type])}+ color={CREDIT_GRANT_TYPE_COLORS[item.current.type]}+ text={t(CREDIT_GRANT_TYPE_LABELS[item.current.type])}/>),},{label: t`Status`,Cell: ({ item }) => {- const status = getStatus(item);+ const status = getStatus(item.current);return <Tag color={status.color} text={t(status.label)} />;},},+ {+ label: t`Granted`,+ Cell: ({ item }) => <>{beautifyExactDate(item.origin.createdAt)}</>,+ },{label: t`Expires`,- Cell: ({ item }) => <>{beautifyExactDate(item.expiresAt)}</>,+ Cell: ({ item }) => (+ <>+ {isDefined(item.current.expiresAt)+ ? beautifyExactDate(item.current.expiresAt)+ : t`Never`}+ </>+ ),},{label: t`Reason`,overflow: 'hidden',Cell: ({ item }) => (- <OverflowingTextWithTooltip text={item.reason ?? EM_DASH} />+ <OverflowingTextWithTooltip+ text={item.origin.reason ?? EM_DASH}+ />),},{label: '',align: 'right',Cell: ({ item }) =>- item.isActive ? (+ item.current.isActive ? (<SettingsAdminWorkspaceCreditGrantRowDropdownMenu- creditGrantId={item.id}- onRevoke={() => handleRevokeClick(item)}+ creditGrantId={item.current.id}+ onRevoke={() => handleRevokeClick(item.current)}/>) : null,},diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantExpiryOptions.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantExpiryOptions.tsnew file mode 100644index 00000000000..ce26a9a20d7--- /dev/null+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/CreditGrantExpiryOptions.ts@@ -0,0 +1,18 @@+import { type MessageDescriptor } from '@lingui/core';+import { msg } from '@lingui/core/macro';++// Null is the default: credits stay spendable until they are used up. The+// bounded choices exist for deliberately time-boxed handouts. The server rounds+// the chosen day up to the end of the billing period it falls in, because+// credits are only ever spent and settled a period at a time.+export const CREDIT_GRANT_EXPIRY_OPTIONS: {+ value: number | null;+ label: MessageDescriptor;+}[] = [+ { value: null, label: msg`Never` },+ { value: 30, label: msg`After 30 days` },+ { value: 60, label: msg`After 60 days` },+ { value: 90, label: msg`After 90 days` },+ { value: 180, label: msg`After 180 days` },+ { value: 365, label: msg`After a year` },+];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.tsindex 9a89903423e..20102d59550 100644--- 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@@ -6,6 +6,7 @@ export const GRANT_WORKSPACE_CREDITS = gql`$amount: Float!$type: BillingCreditGrantType!$reason: String+ $expiresInDays: Int$clientOperationId: UUID!) {grantWorkspaceCredits(@@ -13,6 +14,7 @@ export const GRANT_WORKSPACE_CREDITS = gql`amount: $amounttype: $typereason: $reason+ expiresInDays: $expiresInDaysclientOperationId: $clientOperationId) {id@@ -21,6 +23,7 @@ export const GRANT_WORKSPACE_CREDITS = gql`effectiveAtexpiresAtrevokedAt+ sourceGrantIdreasonisActivecreatedAtdiff --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.tsindex ba866a5a669..e1a71cf3c7d 100644--- 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@@ -15,6 +15,7 @@ export const REVOKE_WORKSPACE_CREDIT_GRANT = gql`effectiveAtexpiresAtrevokedAt+ sourceGrantIdreasonisActivecreatedAtdiff --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.tsindex 1d89e4102fb..7cc85f03e67 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@@ -12,6 +12,7 @@ export const GET_WORKSPACE_BILLING_ADMIN_PANEL = gql`effectiveAtexpiresAtrevokedAt+ sourceGrantIdreasonisActivecreatedAtdiff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/collapseCreditGrantChains.test.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/collapseCreditGrantChains.test.tsnew file mode 100644index 00000000000..ea6db8cd820--- /dev/null+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/collapseCreditGrantChains.test.ts@@ -0,0 +1,66 @@+import { collapseCreditGrantChains } from '@/settings/admin-panel/utils/collapseCreditGrantChains';++type TestGrant = {+ id: string;+ sourceGrantId?: string | null;+ amount: number;+ reason?: string | null;+};++const grant = (+ id: string,+ amount: number,+ sourceGrantId: string | null = null,+ reason: string | null = null,+): TestGrant => ({ id, amount, sourceGrantId, reason });++describe('collapseCreditGrantChains', () => {+ it('keeps an unchained grant as its own row', () => {+ const only = grant('a', 50);++ expect(collapseCreditGrantChains([only])).toEqual([+ { id: 'a', current: only, origin: only },+ ]);+ });++ it('shows the balance left on the chain against the reason it was granted for', () => {+ const carried = grant('c', 40, 'b', 'Carried over from the period ...');+ const middle = grant('b', 70, 'a', 'Carried over from the period ...');+ const origin = grant('a', 100, null, "It's our own workspace");++ const [row] = collapseCreditGrantChains([carried, middle, origin]);++ expect(row.current).toBe(carried);+ expect(row.origin).toBe(origin);+ });++ it('collapses each chain separately and keeps the server ordering', () => {+ const newerOrigin = grant('b', 50);+ const carried = grant('a2', 20, 'a1');+ const olderOrigin = grant('a1', 30);++ const rows = collapseCreditGrantChains([newerOrigin, carried, olderOrigin]);++ expect(rows.map((row) => row.origin.id)).toEqual(['b', 'a1']);+ expect(rows.map((row) => row.current.id)).toEqual(['b', 'a2']);+ });++ // Revoking a grant leaves its successors behind, and a truncated list is the+ // normal case once older rows are filtered out server side.+ it('treats a grant whose source is missing as an origin of its own', () => {+ const orphan = grant('b', 20, 'missing');++ expect(collapseCreditGrantChains([orphan])).toEqual([+ { id: 'b', current: orphan, origin: orphan },+ ]);+ });++ it('still lists every grant when the chain points back at itself', () => {+ const first = grant('a', 10, 'b');+ const second = grant('b', 10, 'a');++ const rows = collapseCreditGrantChains([first, second]);++ expect(rows.map((row) => row.current.id).sort()).toEqual(['a', 'b']);+ });+});diff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/collapseCreditGrantChains.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/collapseCreditGrantChains.tsnew file mode 100644index 00000000000..1f031e14b6b--- /dev/null+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/collapseCreditGrantChains.ts@@ -0,0 +1,79 @@+import { isDefined } from 'twenty-shared/utils';++type CreditGrantChainLink = {+ id: string;+ sourceGrantId?: string | null;+};++export type CollapsedCreditGrant<TGrant extends CreditGrantChainLink> = {+ // The origin's id, which stays the same as the grant is settled from one+ // period to the next.+ id: string;+ // The row still holding the credits: its amount is what is left of the grant+ // and its status is the one that matters.+ current: TGrant;+ // The row the operator actually created, which carries the reason they typed+ // and the date they handed the credits out.+ origin: TGrant;+};++// Every period transition settles a grant and writes its unspent part as a new+// row, so one handout of credits shows up once per period it survived. The rows+// are linked by sourceGrantId, so the chain can be shown as the single grant it+// represents.+export const collapseCreditGrantChains = <TGrant extends CreditGrantChainLink>(+ creditGrants: TGrant[],+): CollapsedCreditGrant<TGrant>[] => {+ const grantById = new Map(creditGrants.map((grant) => [grant.id, grant]));++ const successorBySourceId = new Map<string, TGrant>();++ for (const grant of creditGrants) {+ const sourceGrantId = grant.sourceGrantId;++ if (isDefined(sourceGrantId) && grantById.has(sourceGrantId)) {+ successorBySourceId.set(sourceGrantId, grant);+ }+ }++ const collapsedIds = new Set<string>();++ const collapseFrom = (origin: TGrant): CollapsedCreditGrant<TGrant> => {+ const chainIds = new Set([origin.id]);+ let current = origin;+ let successor = successorBySourceId.get(origin.id);++ while (isDefined(successor) && !chainIds.has(successor.id)) {+ chainIds.add(successor.id);+ current = successor;+ successor = successorBySourceId.get(successor.id);+ }++ for (const chainId of chainIds) {+ collapsedIds.add(chainId);+ }++ return { id: origin.id, current, origin };+ };++ // A grant whose source is not in the list still reads as an origin, because+ // truncating the chain is better than dropping the row.+ const rows = creditGrants+ .filter(+ (grant) =>+ !isDefined(grant.sourceGrantId) || !grantById.has(grant.sourceGrantId),+ )+ .map(collapseFrom);++ if (collapsedIds.size === creditGrants.length) {+ return rows;+ }++ // Only reachable if the ledger ever held a cycle, which it should not. Rows+ // no walk touched are still shown on their own rather than disappearing.+ const orphanedRows = creditGrants+ .filter((grant) => !collapsedIds.has(grant.id))+ .map((grant) => ({ id: grant.id, current: grant, origin: grant }));++ return [...rows, ...orphanedRows];+};diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788871259040-make-billing-credit-grant-expires-at-nullable.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788871259040-make-billing-credit-grant-expires-at-nullable.tsnew file mode 100644index 00000000000..7c87559fca2--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788871259040-make-billing-credit-grant-expires-at-nullable.ts@@ -0,0 +1,44 @@+import { QueryRunner } from 'typeorm';++import { isCoreTablePresent } from 'src/database/commands/upgrade-version-command/2-40/utils/is-core-table-present.util';+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';++// An expiry is now written when a grant is settled rather than when it is+// created, so credits no longer carry a deadline that a period transition has+// to run for them to survive.+//+// Rows already on the ledger also have to be converted, which the paired slow+// command does: this one only permits the null. See that command for why the+// conversion matters and what an upgrade that skips it leaves behind.+//+// down() cannot restore the column without inventing a date, so it stamps any+// row still holding a null with the instant of the rollback. That is the same+// tombstone the settlement would have written, and it keeps the balance out of+// the workspace rather than granting it indefinitely.+@RegisteredInstanceCommand('2.40.0', 1788871259040)+export class MakeBillingCreditGrantExpiresAtNullableFastInstanceCommand implements FastInstanceCommand {+ public async up(queryRunner: QueryRunner): Promise<void> {+ if (!(await isCoreTablePresent(queryRunner, 'billingCreditGrant'))) {+ return;+ }++ await queryRunner.query(+ `ALTER TABLE "core"."billingCreditGrant" ALTER COLUMN "expiresAt" DROP NOT NULL`,+ );+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ if (!(await isCoreTablePresent(queryRunner, 'billingCreditGrant'))) {+ return;+ }++ await queryRunner.query(+ `UPDATE "core"."billingCreditGrant" SET "expiresAt" = now() WHERE "expiresAt" IS NULL`,+ );++ await queryRunner.query(+ `ALTER TABLE "core"."billingCreditGrant" ALTER COLUMN "expiresAt" SET NOT NULL`,+ );+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/2-40-instance-command-slow-1788877128693-convert-live-credit-grants-to-no-expiry.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/2-40-instance-command-slow-1788877128693-convert-live-credit-grants-to-no-expiry.tsnew file mode 100644index 00000000000..e1f433d6164--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/2-40-instance-command-slow-1788877128693-convert-live-credit-grants-to-no-expiry.ts@@ -0,0 +1,76 @@+import { DataSource, QueryRunner } from 'typeorm';++import { isCoreTablePresent } from 'src/database/commands/upgrade-version-command/2-40/utils/is-core-table-present.util';+import { MakeBillingCreditGrantExpiresAtNullableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788871259040-make-billing-credit-grant-expires-at-nullable';+import {+ getRegisteredInstanceCommandMetadata,+ 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';++// Converts the grants already on the ledger to the model the paired fast+// command opened the column for. Under the old one a live grant carried the end+// of its own period; the new settlement reads a deadline at or before the+// boundary it is closing as already spent, drops the grant and carries nothing+// forward. Every still-live legacy grant therefore has to give up its deadline,+// or the first period transition after this upgrade destroys the balances the+// change exists to protect.+//+// Until this runs, a workspace whose transition lands first loses the unspent+// part of its granted credits, so an upgrade that skips --include-slow should+// run this before the next billing cycle. Rows already expired are left alone:+// those are tombstones under both models, and clearing them would hand back+// credits that had genuinely lapsed.+@RegisteredInstanceCommand('2.40.0', 1788877128693, { type: 'slow' })+export class ConvertLiveCreditGrantsToNoExpirySlowInstanceCommand implements SlowInstanceCommand {+ async runDataMigration(dataSource: DataSource): Promise<void> {+ if (!(await isCoreTablePresent(dataSource, 'billingCreditGrant'))) {+ return;+ }++ // Bounded by when the column became nullable, because a grant written after+ // that came from the new code: its future deadline is an operator's+ // time-boxed grant, not a period end the old model stamped, and clearing it+ // would make those credits permanent. Falling back to now() when the fast+ // command left no record converts those few too, which costs a grant that+ // outlives its window rather than a workspace that loses paid-for credits.+ await dataSource.query(+ `UPDATE "core"."billingCreditGrant"+ SET "expiresAt" = NULL+ WHERE "revokedAt" IS NULL+ AND "expiresAt" > now()+ AND "createdAt" <= COALESCE(+ (SELECT "createdAt" FROM "core"."upgradeMigration"+ WHERE "workspaceId" IS NULL+ AND name = $1+ AND status = 'completed'+ ORDER BY "createdAt" DESC+ LIMIT 1),+ now()+ )`,+ [buildColumnMadeNullableCommandName()],+ );+ }++ public async up(_queryRunner: QueryRunner): Promise<void> {+ return;+ }++ // The column is left nullable by the paired fast command, so there is no+ // schema state to undo here and no date to invent for the rows cleared above.+ public async down(_queryRunner: QueryRunner): Promise<void> {+ return;+ }+}++// Mirrors how the runner records a command it has run. Derived from the class+// rather than written out, so renaming or re-timestamping the fast command+// cannot silently turn the bound above into now().+const buildColumnMadeNullableCommandName = (): string => {+ const { name } = MakeBillingCreditGrantExpiresAtNullableFastInstanceCommand;+ const metadata = getRegisteredInstanceCommandMetadata(+ MakeBillingCreditGrantExpiresAtNullableFastInstanceCommand,+ );++ return `${metadata?.version}_${name}_${metadata?.timestamp}`;+};diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/__tests__/2-40-instance-command-slow-1788877128693-convert-live-credit-grants-to-no-expiry.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/__tests__/2-40-instance-command-slow-1788877128693-convert-live-credit-grants-to-no-expiry.spec.tsnew file mode 100644index 00000000000..80c096ba369--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/__tests__/2-40-instance-command-slow-1788877128693-convert-live-credit-grants-to-no-expiry.spec.ts@@ -0,0 +1,87 @@+import { type DataSource } from 'typeorm';++import { MakeBillingCreditGrantExpiresAtNullableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788871259040-make-billing-credit-grant-expires-at-nullable';+import { ConvertLiveCreditGrantsToNoExpirySlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-40/2-40-instance-command-slow-1788877128693-convert-live-credit-grants-to-no-expiry';+import { getRegisteredInstanceCommandMetadata } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';++const buildFakeDataSource = ({+ hasBillingCreditGrantTable,+}: {+ hasBillingCreditGrantTable: boolean;+}): {+ dataSource: DataSource;+ queries: { sql: string; params?: unknown[] }[];+} => {+ const queries: { sql: string; params?: unknown[] }[] = [];++ const dataSource = {+ query: jest.fn(async (sql: string, params?: unknown[]) => {+ queries.push({ sql, params });++ if (sql.includes('pg_tables')) {+ return hasBillingCreditGrantTable ? [{ '?column?': 1 }] : [];+ }++ return [];+ }),+ } as unknown as DataSource;++ return { dataSource, queries };+};++describe('ConvertLiveCreditGrantsToNoExpirySlowInstanceCommand', () => {+ it('leaves an instance without billing alone', async () => {+ const { dataSource, queries } = buildFakeDataSource({+ hasBillingCreditGrantTable: false,+ });++ await new ConvertLiveCreditGrantsToNoExpirySlowInstanceCommand().runDataMigration(+ dataSource,+ );++ expect(queries).toHaveLength(1);+ expect(queries[0].sql).toContain('pg_tables');+ });++ it('only clears deadlines the old model stamped', async () => {+ const { dataSource, queries } = buildFakeDataSource({+ hasBillingCreditGrantTable: true,+ });++ await new ConvertLiveCreditGrantsToNoExpirySlowInstanceCommand().runDataMigration(+ dataSource,+ );++ const update = queries.find(({ sql }) => sql.startsWith('UPDATE'));++ expect(update?.sql).toContain('"revokedAt" IS NULL');+ expect(update?.sql).toContain('"expiresAt" > now()');+ expect(update?.sql).toContain('"createdAt" <=');+ });++ // The bound is a lookup by name into the runner's own record of the paired+ // fast command. Nothing else ties the two together, and a name that no longer+ // matches silently converts the operator-set deadlines this bound exists to+ // protect.+ it('asks for the paired fast command under the name the runner records it as', async () => {+ const { dataSource, queries } = buildFakeDataSource({+ hasBillingCreditGrantTable: true,+ });++ await new ConvertLiveCreditGrantsToNoExpirySlowInstanceCommand().runDataMigration(+ dataSource,+ );++ const metadata = getRegisteredInstanceCommandMetadata(+ MakeBillingCreditGrantExpiresAtNullableFastInstanceCommand,+ );+ const update = queries.find(({ sql }) => sql.startsWith('UPDATE'));++ expect(update?.params).toEqual([+ `${metadata?.version}_${MakeBillingCreditGrantExpiresAtNullableFastInstanceCommand.name}_${metadata?.timestamp}`,+ ]);+ expect(update?.params?.[0]).toBe(+ '2.40.0_MakeBillingCreditGrantExpiresAtNullableFastInstanceCommand_1788871259040',+ );+ });+});diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/utils/is-core-table-present.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/utils/is-core-table-present.util.tsnew file mode 100644index 00000000000..4a82cc566df--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/utils/is-core-table-present.util.ts@@ -0,0 +1,17 @@+import { type DataSource, type QueryRunner } from 'typeorm';++// An instance without billing never grew the billing tables, so a command+// touching one has to check first. Version-local rather than shared with the+// identical 2-38 util because upgrade command directories are append-only:+// widening that one to take a DataSource would edit a shipped version.+export const isCoreTablePresent = async (+ runner: QueryRunner | DataSource,+ tableName: string,+): Promise<boolean> => {+ const rows = await runner.query(+ `SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = $1`,+ [tableName],+ );++ return rows.length > 0;+};diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.tsindex 7d747061f88..228a3017b76 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@@ -179,6 +179,8 @@ import { ReshapeUsageLimitPeriodFastInstanceCommand } from 'src/database/commandimport { AddLogoToConnectionProviderFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-39/2-39-instance-command-fast-1788542613404-add-logo-to-connection-provider';import { AddReadabilityToObjectMetadataFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-39/2-39-instance-command-fast-1788548844925-add-readability-to-object-metadata';import { AddAuthFailedReasonToConnectedAccountFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788781233982-add-auth-failed-reason-to-connected-account';+import { MakeBillingCreditGrantExpiresAtNullableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788871259040-make-billing-credit-grant-expires-at-nullable';+import { ConvertLiveCreditGrantsToNoExpirySlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-40/2-40-instance-command-slow-1788877128693-convert-live-credit-grants-to-no-expiry';export const INSTANCE_COMMANDS = [AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,@@ -360,4 +362,6 @@ export const INSTANCE_COMMANDS = [AddCommandMenuItemConditionalPinnedExpressionFastInstanceCommand,AddCampaignDeliveryClaimTokenIndexFastInstanceCommand,AddAuthFailedReasonToConnectedAccountFastInstanceCommand,+ MakeBillingCreditGrantExpiresAtNullableFastInstanceCommand,+ ConvertLiveCreditGrantsToNoExpirySlowInstanceCommand,];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.tsindex 4475d12b243..7fc47876b15 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@@ -646,6 +646,7 @@ export class AdminPanelResolver {amount: input.amount,type: input.type,reason: input.reason,+ expiresInDays: input.expiresInDays,clientOperationId: input.clientOperationId,grantedByUserId: actor.id,});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.tsindex bc9d38b86e3..02c8f2ffbcc 100644--- 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@@ -17,12 +17,17 @@ export class AdminPanelWorkspaceCreditGrantDTO {@Field(() => Date)effectiveAt: Date;- @Field(() => Date)- expiresAt: Date;+ @Field(() => Date, { nullable: true })+ expiresAt: Date | null;@Field(() => Date, { nullable: true })revokedAt: Date | null;+ // Set when this grant carries the unspent part of an earlier one forward, so+ // the admin panel can show one row per grant instead of one row per period.+ @Field(() => UUIDScalarType, { nullable: true })+ sourceGrantId: string | null;+@Field(() => String, { nullable: true })reason: string | null;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.tsindex f36461b2475..985dac44632 100644--- 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@@ -1,18 +1,26 @@-import { ArgsType, Field, Float } from '@nestjs/graphql';+import { ArgsType, Field, Float, Int } from '@nestjs/graphql';import {IsEnum,+ IsInt,IsNotEmpty,IsOptional,IsPositive,IsString,IsUUID,+ Max,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';+// Kept at a year, which is the longest the picker offers and comfortably+// inside the number of periods alignGrantExpiryToPeriodEnd will walk on the+// shortest interval. Raising it means raising MAX_PERIODS_AHEAD with it, or a+// long validity silently comes back short.+const MAX_CREDIT_GRANT_VALIDITY_IN_DAYS = 365;+@ArgsType()export class GrantWorkspaceCreditsInput {@Field(() => UUIDScalarType)@@ -35,6 +43,15 @@ export class GrantWorkspaceCreditsInput {@MaxLength(500)reason?: string;+ // Left out, the credits do not expire: they stay spendable until a period+ // transition settles them against usage. Set only for a time-boxed grant.+ @Field(() => Int, { nullable: true })+ @IsOptional()+ @IsInt()+ @IsPositive()+ @Max(MAX_CREDIT_GRANT_VALIDITY_IN_DAYS)+ expiresInDays?: number;+// 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)diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.tsindex 76016ed5eab..585a404556a 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@@ -58,6 +58,7 @@ export class AdminPanelBillingService {amount,type,reason,+ expiresInDays,clientOperationId,grantedByUserId,}: {@@ -65,6 +66,7 @@ export class AdminPanelBillingService {amount: number;type: BillingCreditGrantType;reason?: string;+ expiresInDays?: number;clientOperationId: string;grantedByUserId: string;}): Promise<AdminPanelWorkspaceCreditGrantDTO> {@@ -102,33 +104,22 @@ export class AdminPanelBillingService {amountMicro,type,reason,+ expiresInDays,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)) {+ // Answered with the grant either way, whether this attempt wrote it or a+ // previous one did, so nothing is left but the instance that has no ledger+ // to write to at all.+ if (!isDefined(grant)) {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);+ return this.toCreditGrantDTO(grant);}async revokeWorkspaceCreditGrant({@@ -169,11 +160,12 @@ export class AdminPanelBillingService {effectiveAt: grant.effectiveAt,expiresAt: grant.expiresAt,revokedAt: grant.revokedAt,+ sourceGrantId: grant.sourceGrantId,reason: grant.reason,isActive:!isDefined(grant.revokedAt) &&grant.effectiveAt.getTime() <= now &&- grant.expiresAt.getTime() > now,+ (!isDefined(grant.expiresAt) || grant.expiresAt.getTime() > now),createdAt: grant.createdAt,};}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.tsindex 36ab9628017..b420bb8a5a9 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@@ -24,6 +24,7 @@ import { BillingUsageService } from 'src/engine/core-modules/billing/services/biimport { 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 { resolveBillingTransitionBoundary } from 'src/engine/core-modules/billing/utils/resolve-billing-transition-boundary.util';import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';const SUBSCRIPTION_CYCLE_BILLING_REASON = 'subscription_cycle';@@ -70,8 +71,7 @@ export class BillingWebhookInvoiceService {const {billing_reason: billingReason,customer,- period_start: periodStart,- period_end: periodEnd,+ created: invoiceCreatedAtInSeconds,} = data.object;const stripeSubscriptionId = getSubscriptionIdFromInvoice(data.object);@@ -84,7 +84,7 @@ export class BillingWebhookInvoiceService {return;}- if (!isDefined(stripeCustomerId) || !periodEnd || !periodStart) {+ if (!isDefined(stripeCustomerId)) {return;}@@ -97,34 +97,20 @@ export class BillingWebhookInvoiceService {return;}- const trialEnd = isDefined(subscription.trialEnd)- ? Math.floor(subscription.trialEnd.getTime() / 1000)- : undefined;-- const TRIAL_END_TOLERANCE_SECONDS = 60;-- const isFirstPeriodAfterTrial =- isDefined(trialEnd) &&- Math.abs(periodStart - trialEnd) <= TRIAL_END_TOLERANCE_SECONDS;-await this.processRollover({subscription,- invoicePeriodStart: new Date(periodStart * 1000),- invoicePeriodEnd: new Date(periodEnd * 1000),- isFirstPeriodAfterTrial,+ // Stripe's own clock, so it can be compared to the subscription's+ // boundaries without allowing for skew against ours.+ invoiceCreatedAt: new Date(invoiceCreatedAtInSeconds * 1000),});}private async processRollover({subscription,- invoicePeriodStart,- invoicePeriodEnd,- isFirstPeriodAfterTrial,+ invoiceCreatedAt,}: {subscription: BillingSubscriptionEntity;- invoicePeriodStart: Date;- invoicePeriodEnd: Date;- isFirstPeriodAfterTrial: boolean;+ invoiceCreatedAt: Date;}): Promise<void> {const workspaceExists = await this.workspaceRepository.exists({where: { id: subscription.workspaceId },@@ -141,31 +127,42 @@ export class BillingWebhookInvoiceService {subscription.id,);+ // Skipping the transition leaves every grant of this workspace to reach its+ // expiry with nothing carrying the unspent part forward, so it is the one+ // early return here that costs the workspace credits it was given.if (!isDefined(params)) {+ this.logger.error(+ `Skipping credit rollover for workspace ${subscription.workspaceId}: subscription ${subscription.id} carries no priced resource credit item`,+ );+return;}+ const boundary = resolveBillingTransitionBoundary({+ invoiceCreatedAt,+ subscriptionCurrentPeriodStart: subscription.currentPeriodStart,+ subscriptionCurrentPeriodEnd: subscription.currentPeriodEnd,+ });+// 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,+ boundary,});const {closingPeriodStart,closingPeriodEnd,nextPeriodStart,- nextPeriodEnd,+ isFirstPeriodAfterTrial,} = deriveBillingPeriodTransition({- invoicePeriodStart,- invoicePeriodEnd,+ boundary,subscriptionCurrentPeriodStart: subscription.currentPeriodStart,- subscriptionCurrentPeriodEnd: subscription.currentPeriodEnd,subscriptionInterval: subscription.interval,trialStart: subscription.trialStart,- isFirstPeriodAfterTrial,+ trialEnd: subscription.trialEnd,subscriptionPreviousPeriodStart: subscription.previousPeriodStart,ledgerPeriodStart,});@@ -183,7 +180,6 @@ export class BillingWebhookInvoiceService {closingPeriodEnd,closingAllowanceMicro,nextPeriodStart,- nextPeriodEnd,nextAllowanceMicro: params.tierQuantity,});}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.tsindex 1b5f2daf13e..aa6647bcc1d 100644--- 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@@ -39,12 +39,14 @@ export class BillingCreditGrantEntity extends WorkspaceRelatedEntity {@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;+ // A tombstone rather than a deadline: null while the credits are spendable,+ // then the instant they stopped being. Writing a future expiry at grant time+ // would put the balance at the mercy of the period transition running, and a+ // transition that never fires would delete credits nobody spent. Only an+ // operator asking for a time-boxed grant sets one in advance, and that date+ // caps how long the available credit count may stay cached.+ @Column({ nullable: true, type: 'timestamptz' })+ expiresAt: Date | null;@Column({ nullable: true, type: 'timestamptz' })revokedAt: Date | null;diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.tsindex 49dcca298c1..388bfce15fc 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-grant.service.ts@@ -3,9 +3,8 @@import { Injectable } from '@nestjs/common';import { isDefined } from 'twenty-shared/utils';-import { IsNull, LessThan, MoreThan } from 'typeorm';+import { And, type EntityManager, 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,@@ -20,42 +19,15 @@ export type CreateBillingCreditGrantParams = {amountMicro: number;type: BillingCreditGrantType;effectiveAt: Date;- expiresAt: Date;+ // Null means the credits stay spendable until something settles them, which+ // is the default. See the entity for why an expiry is a tombstone here.+ expiresAt: Date | null;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.@@ -70,6 +42,7 @@ export class BillingCreditGrantService {// a fresh grant from a replayed one.async createGrant(params: CreateBillingCreditGrantParams,+ entityManager?: EntityManager,): Promise<BillingCreditGrantEntity | null> {const {workspaceId,@@ -90,43 +63,47 @@ export class BillingCreditGrantService {);}- if (expiresAt.getTime() <= effectiveAt.getTime()) {+ if (isDefined(expiresAt) && 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;+ const repository = this.getRepository(entityManager);++ // Idempotency is enforced by letting Postgres drop the duplicate rather+ // than by catching the unique violation: the rollover inserts inside a+ // transaction, where a raised constraint error would abort every write+ // that came before it.+ const { raw } = await repository+ .createQueryBuilder()+ .insert()+ .values({+ workspaceId,+ amountMicro,+ type,+ effectiveAt,+ expiresAt,+ reason,+ grantedByUserId,+ idempotencyKey,+ sourceGrantId,+ })+ .orIgnore()+ .returning('id')+ .execute();++ const [insertedRow] = raw as { id?: string }[];+ const grantId = insertedRow?.id;++ if (!isDefined(grantId)) {+ return null;}++ // Read back rather than returning the raw row, which skips the bigint+ // transformer and would hand callers amountMicro as a string.+ return repository.findOne(workspaceId, { where: { id: grantId } });}async getActiveCreditsMicro(workspaceId: string): Promise<number> {@@ -138,7 +115,9 @@ export class BillingCreditGrantService {}).andWhere('"billingCreditGrant"."revokedAt" IS NULL').andWhere('"billingCreditGrant"."effectiveAt" <= now()')- .andWhere('"billingCreditGrant"."expiresAt" > now()')+ .andWhere(+ '("billingCreditGrant"."expiresAt" IS NULL OR "billingCreditGrant"."expiresAt" > now())',+ ).getRawOne<{ total: string | number | null }>();const total = Number(result?.total ?? 0);@@ -156,23 +135,56 @@ export class BillingCreditGrantService {}// Grants that were spendable at any point during the given period.- async findGrantsLiveDuringPeriod({+ async findGrantsLiveDuringPeriod(+ {+ workspaceId,+ periodStart,+ periodEnd,+ }: {+ workspaceId: string;+ periodStart: Date;+ periodEnd: Date;+ },+ entityManager?: EntityManager,+ ): Promise<BillingCreditGrantEntity[]> {+ return this.getRepository(entityManager).find(workspaceId, {+ where: [+ {+ revokedAt: IsNull(),+ effectiveAt: LessThan(periodEnd),+ expiresAt: IsNull(),+ },+ {+ revokedAt: IsNull(),+ effectiveAt: LessThan(periodEnd),+ expiresAt: MoreThan(periodStart),+ },+ ],+ order: { createdAt: 'ASC' },+ });+ }++ // The one place that says when a credit balance stops being trustworthy+ // before the period is out: an operator-set expiry falling inside it would+ // otherwise go unnoticed until the next one, and the workspace would keep+ // spending credits that already lapsed.+ async findEarliestExpiryBefore({workspaceId,- periodStart,- periodEnd,+ boundary,}: {workspaceId: string;- periodStart: Date;- periodEnd: Date;- }): Promise<BillingCreditGrantEntity[]> {- return this.billingCreditGrantRepository.find(workspaceId, {+ boundary: Date;+ }): Promise<Date | null> {+ const [row] = await this.billingCreditGrantRepository.find(workspaceId, {where: {revokedAt: IsNull(),- effectiveAt: LessThan(periodEnd),- expiresAt: MoreThan(periodStart),+ expiresAt: And(MoreThan(new Date()), LessThan(boundary)),},- order: { createdAt: 'ASC' },+ order: { expiresAt: 'ASC' },+ take: 1,});++ return row?.expiresAt ?? null;}// The previous transition pulled every grant it closed back to the instant@@ -196,27 +208,36 @@ export class BillingCreditGrantService {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(+ // Settles every grant the closing period could still spend, so that the+ // carry-forward rows written next in the same transaction are the only ones+ // left live. Matched by predicate rather than by id so a grant created while+ // the transition runs is covered too.+ async closeGrantsAtPeriodEnd(+ {workspaceId,- {- revokedAt: IsNull(),- effectiveAt: LessThan(periodEnd),- expiresAt: MoreThan(periodEnd),- },- { expiresAt: periodEnd },- );+ periodEnd,+ }: {+ workspaceId: string;+ periodEnd: Date;+ },+ entityManager?: EntityManager,+ ): Promise<void> {+ const repository = this.getRepository(entityManager);++ // The OR keeps an operator-set expiry already inside the period alone,+ // which it has to stay: stamping it forward would hand back credits that+ // had lapsed before the boundary.+ await repository+ .createQueryBuilder()+ .update()+ .set({ expiresAt: periodEnd })+ .where('"workspaceId" = :workspaceId', { workspaceId })+ .andWhere('"revokedAt" IS NULL')+ .andWhere('"effectiveAt" < :periodEnd', { periodEnd })+ .andWhere('("expiresAt" IS NULL OR "expiresAt" > :periodEnd)', {+ periodEnd,+ })+ .execute();}async listGrants(workspaceId: string): Promise<BillingCreditGrantEntity[]> {@@ -280,4 +301,12 @@ export class BillingCreditGrantService {return grant ?? null;}++ private getRepository(+ entityManager?: EntityManager,+ ): WorkspaceScopedRepository<BillingCreditGrantEntity> {+ return isDefined(entityManager)+ ? this.billingCreditGrantRepository.withManager(entityManager)+ : this.billingCreditGrantRepository;+ }}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.tsindex 6a3deeae76a..1e27bee6cc2 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@@ -1,8 +1,10 @@/* @license Enterprise */import { Injectable } from '@nestjs/common';+import { InjectDataSource } from '@nestjs/typeorm';import { isDefined } from 'twenty-shared/utils';+import { DataSource, type EntityManager } from 'typeorm';import {BillingException,@@ -22,7 +24,6 @@ type ProcessRolloverParams = {closingPeriodEnd: Date;closingAllowanceMicro: number;nextPeriodStart: Date;- nextPeriodEnd: Date;nextAllowanceMicro: number;};@@ -38,6 +39,8 @@ export class BillingCreditRolloverService {private readonly billingCreditService: BillingCreditService,private readonly cacheLockService: CacheLockService,private readonly twentyConfigService: TwentyConfigService,+ @InjectDataSource()+ private readonly dataSource: DataSource,) {}async processRolloverOnPeriodTransition(@@ -78,26 +81,58 @@ export class BillingCreditRolloverService {);}- private async carryGrantsForward({+ private async carryGrantsForward(+ params: ProcessRolloverParams & { usageMicro: number },+ ): Promise<void> {+ const { workspaceId, nextPeriodStart, nextAllowanceMicro } = params;++ const rolloverCapMultiplier = this.twentyConfigService.get(+ 'BILLING_ROLLOVER_TOTAL_CAP_MULTIPLIER',+ );++ // Closing the old grants and writing their successors is one settlement:+ // committing the first half alone would leave the workspace with every+ // grant closed and nothing carrying the unspent part forward.+ const { carriedForwardMicro, hasReplayedGrant } =+ await this.dataSource.transaction(async (entityManager) =>+ this.settleGrants({+ ...params,+ entityManager,+ rolloverCapMicro: (rolloverCapMultiplier - 1) * nextAllowanceMicro,+ }),+ );++ await this.billingCreditService.refreshWorkspaceCreditState({+ workspaceId,+ availableDeltaMicro: carriedForwardMicro,+ isReplay: hasReplayedGrant,+ adjustmentKey: buildRolloverAdjustmentKey(nextPeriodStart),+ });+ }++ private async settleGrants({+ entityManager,workspaceId,closingPeriodStart,closingPeriodEnd,closingAllowanceMicro,nextPeriodStart,- nextPeriodEnd,- nextAllowanceMicro,usageMicro,- }: ProcessRolloverParams & { usageMicro: number }): Promise<void> {+ rolloverCapMicro,+ }: ProcessRolloverParams & {+ usageMicro: number;+ rolloverCapMicro: number;+ entityManager: EntityManager;+ }): Promise<{ carriedForwardMicro: number; hasReplayedGrant: boolean }> {const closingGrants =- await this.billingCreditGrantService.findGrantsLiveDuringPeriod({- workspaceId,- periodStart: closingPeriodStart,- periodEnd: closingPeriodEnd,- });-- const rolloverCapMultiplier = this.twentyConfigService.get(- 'BILLING_ROLLOVER_TOTAL_CAP_MULTIPLIER',- );+ await this.billingCreditGrantService.findGrantsLiveDuringPeriod(+ {+ workspaceId,+ periodStart: closingPeriodStart,+ periodEnd: closingPeriodEnd,+ },+ entityManager,+ );const carryForwardGrants = computeCarryForwardGrants({allowanceMicro: closingAllowanceMicro,@@ -106,35 +141,44 @@ export class BillingCreditRolloverService {type: grant.type,amountMicro: grant.amountMicro,createdAt: grant.createdAt,+ expiresAt: grant.expiresAt,})),usageMicro,- rolloverCapMicro: (rolloverCapMultiplier - 1) * nextAllowanceMicro,+ rolloverCapMicro,+ boundary: closingPeriodEnd,});- await this.billingCreditGrantService.closeGrantsAtPeriodEnd({- workspaceId,- periodEnd: closingPeriodEnd,- });+ await this.billingCreditGrantService.closeGrantsAtPeriodEnd(+ { workspaceId, periodEnd: closingPeriodEnd },+ entityManager,+ );let carriedForwardMicro = 0;let hasReplayedGrant = false;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({+ const grant = await this.billingCreditGrantService.createGrant(+ {workspaceId,- nextPeriodStart,+ amountMicro: carryForwardGrant.amountMicro,type: carryForwardGrant.type,sourceGrantId: carryForwardGrant.sourceGrantId,- }),- });+ effectiveAt: nextPeriodStart,+ // Null for everything but a time-boxed grant, whose deadline the+ // successor inherits. Stamping the period end here instead would make+ // every balance depend on the next transition running, which is the+ // failure this settlement exists to survive.+ expiresAt: carryForwardGrant.expiresAt,+ reason: `Carried over from the period starting ${closingPeriodStart.toISOString()}`,+ idempotencyKey: buildCarryForwardIdempotencyKey({+ workspaceId,+ nextPeriodStart,+ type: carryForwardGrant.type,+ sourceGrantId: carryForwardGrant.sourceGrantId,+ }),+ },+ entityManager,+ );if (isDefined(grant)) {carriedForwardMicro += grant.amountMicro;@@ -143,12 +187,7 @@ export class BillingCreditRolloverService {}}- await this.billingCreditService.refreshWorkspaceCreditState({- workspaceId,- availableDeltaMicro: carriedForwardMicro,- isReplay: hasReplayedGrant,- adjustmentKey: buildRolloverAdjustmentKey(nextPeriodStart),- });+ return { carriedForwardMicro, hasReplayedGrant };}}diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit.service.tsindex aee5e100469..17d1c8dab42 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,9 +2,12 @@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 { 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';@@ -13,17 +16,12 @@ import { BillingSubscriptionService } from 'src/engine/core-modules/billing/servimport { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';+import { alignGrantExpiryToPeriodEnd } from 'src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util';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 { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';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;-type GrantCreditsParams = {workspaceId: string;amountMicro: number;@@ -32,7 +30,11 @@ type GrantCreditsParams = {grantedByUserId?: string | null;idempotencyKey?: string | null;effectiveAt?: Date;- expiresAt?: Date;+ // Only set for a deliberately time-boxed grant. Left out, the credits stay+ // spendable until a period transition settles them. Taken as the operator's+ // intent rather than a date so that the alignment onto a period end happens+ // here, where the invariant belongs, whoever the caller is.+ expiresInDays?: number | null;sourceGrantId?: string | null;};@@ -76,18 +78,36 @@ export class BillingCreditService {workspaceId,});- const { effectiveAt, expiresAt } = computeGrantValidity(- params,- subscription,- );-- const grant = await this.billingCreditGrantService.createGrant({- ...params,- effectiveAt,- expiresAt,- });-+ const effectiveAt = params.effectiveAt ?? new Date();++ // A replay answers with what the first attempt wrote, so the operator's+ // intent is never re-derived: the subscription that anchored the original+ // expiry may have been canceled since, and the insert would discard the+ // answer anyway.+ const knownGrant = await this.findGrantByIdempotencyKey(params);++ const grant = isDefined(knownGrant)+ ? null+ : await this.billingCreditGrantService.createGrant({+ ...params,+ effectiveAt,+ expiresAt: resolveGrantExpiry({+ effectiveAt,+ expiresInDays: params.expiresInDays,+ subscription,+ workspaceId,+ }),+ });++ // Answers with the row that already exists rather than null, so a caller+ // recovering from a lost response does not have to look it up again. Read+ // again when the check above came back empty: the insert still reported a+ // duplicate, so another attempt won the key between the two, and only the+ // second read can see it.if (!isDefined(grant)) {+ const alreadyWrittenGrant =+ knownGrant ?? (await this.findGrantByIdempotencyKey(params));+this.logger.log(`Replayed credit grant for workspace ${workspaceId} (idempotency key ${params.idempotencyKey}), repairing derived state`,);@@ -99,7 +119,7 @@ export class BillingCreditService {subscription,});- return null;+ return alreadyWrittenGrant;}await this.refreshWorkspaceCreditState({@@ -111,6 +131,20 @@ export class BillingCreditService {return grant;}+ private async findGrantByIdempotencyKey({+ workspaceId,+ idempotencyKey,+ }: GrantCreditsParams): Promise<BillingCreditGrantEntity | null> {+ if (!isDefined(idempotencyKey)) {+ return null;+ }++ return this.billingCreditGrantService.findGrantByIdempotencyKey(+ workspaceId,+ idempotencyKey,+ );+ }+async revokeGrant({workspaceId,grantId,@@ -163,7 +197,7 @@ export class BillingCreditService {const revokedAtMs = (grant.revokedAt ?? new Date()).getTime();const wasActiveWhenRevoked =grant.effectiveAt.getTime() <= revokedAtMs &&- grant.expiresAt.getTime() > revokedAtMs;+ (!isDefined(grant.expiresAt) || grant.expiresAt.getTime() > revokedAtMs);await this.refreshWorkspaceCreditState({workspaceId,@@ -213,6 +247,16 @@ export class BillingCreditService {availableDeltaMicro,isReplay,adjustmentKey,+ // Incrementing a warm counter leaves its lifetime in place, so credits+ // lapsing before the period ends would stay spendable through the+ // cache. Checked here rather than at each call site so that the+ // rollover, which carries deadlines forward too, cannot miss it.+ mustRebuildCounter: isDefined(+ await this.billingCreditGrantService.findEarliestExpiryBefore({+ workspaceId,+ boundary: subscription.currentPeriodEnd,+ }),+ ),});}@@ -234,6 +278,7 @@ export class BillingCreditService {availableDeltaMicro,isReplay,adjustmentKey,+ mustRebuildCounter,}: {workspaceId: string;periodStart: Date;@@ -241,14 +286,16 @@ export class BillingCreditService {availableDeltaMicro: number;isReplay: boolean;adjustmentKey?: string;+ mustRebuildCounter: boolean;}): Promise<void> {const rebuildCounter =- isReplay &&- (!isDefined(adjustmentKey) ||- !(await this.billingUsageCacheService.hasCounterAdjustmentBeenApplied(- workspaceId,- adjustmentKey,- )));+ mustRebuildCounter ||+ (isReplay &&+ (!isDefined(adjustmentKey) ||+ !(await this.billingUsageCacheService.hasCounterAdjustmentBeenApplied(+ workspaceId,+ adjustmentKey,+ ))));await this.applyCounterWrite({workspaceId,@@ -310,33 +357,50 @@ export class BillingCreditService {}}+// Exact 24-hour days rather than calendar ones: the result is only ever+// compared against UTC period boundaries, and local-time day arithmetic drifts+// by an hour across a DST change.+const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;+const buildRevocationAdjustmentKey = (grantId: string): string =>`revoke:${grantId}`;-const computeGrantValidity = (- params: GrantCreditsParams,- subscription: BillingSubscriptionEntity | undefined,-): { effectiveAt: Date; expiresAt: Date } => {- const effectiveAt = params.effectiveAt ?? new Date();+// Null unless the caller asked for a time-boxed grant, and then a period end+// rather than the exact day, for the reasons alignGrantExpiryToPeriodEnd+// documents.+//+// Refuses rather than falling back to null when there is no period to align to:+// returning null there would read as "no expiry" and hand out credits that+// never lapse, which is the opposite of what was asked for and cannot be+// noticed from the result.+const resolveGrantExpiry = ({+ effectiveAt,+ expiresInDays,+ subscription,+ workspaceId,+}: {+ effectiveAt: Date;+ expiresInDays: number | null | undefined;+ subscription: BillingSubscriptionEntity | undefined;+ workspaceId: string;+}): Date | null => {+ if (!isDefined(expiresInDays)) {+ return null;+ }- if (isDefined(params.expiresAt)) {- return { effectiveAt, expiresAt: params.expiresAt };+ if (!isDefined(subscription)) {+ throw new BillingException(+ `Cannot grant credits to workspace ${workspaceId} expiring in ${expiresInDays} days: it has no subscription, so there is no billing period to expire them at`,+ BillingExceptionCode.BILLING_SUBSCRIPTION_NOT_FOUND,+ );}- // 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),- };+ return alignGrantExpiryToPeriodEnd({+ requestedExpiresAt: new Date(+ effectiveAt.getTime() + expiresInDays * MILLISECONDS_PER_DAY,+ ),+ currentPeriodStart: subscription.currentPeriodStart,+ currentPeriodEnd: subscription.currentPeriodEnd,+ interval: subscription.interval,+ });};diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.tsindex 541fbe541cc..41a1fd2504b 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@@ -514,13 +514,23 @@ export class BillingUsageService {private async computeAndWarmAvailableCredits(params: AvailableCreditsParams,): Promise<AvailableCreditsRead> {- const availableCredits =- await this.getAvailableCreditsFromClickHouse(params);+ const [availableCredits, earliestExpiry] = await Promise.all([+ this.getAvailableCreditsFromClickHouse(params),+ this.billingCreditGrantService.findEarliestExpiryBefore({+ workspaceId: params.workspaceId,+ boundary: params.currentPeriodEnd,+ }),+ ]);++ // A time-boxed grant lapsing before the period ends has to shorten the+ // cache with it, otherwise the counter keeps handing out credits that+ // getActiveCreditsMicro no longer counts.+ const cacheUntil = earliestExpiry ?? params.currentPeriodEnd;await this.billingUsageCacheService.warmAvailableCredits(params.workspaceId,params.currentPeriodStart,- params.currentPeriodEnd,+ cacheUntil,availableCredits,);diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/align-grant-expiry-to-period-end.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/align-grant-expiry-to-period-end.util.spec.tsnew file mode 100644index 00000000000..2dd45e22094--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/align-grant-expiry-to-period-end.util.spec.ts@@ -0,0 +1,169 @@+/* @license Enterprise */++import { isDefined } from 'twenty-shared/utils';++import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';+import { alignGrantExpiryToPeriodEnd } from 'src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util';++const CURRENT_PERIOD_START = new Date('2026-01-01T00:00:00.000Z');+const CURRENT_PERIOD_END = new Date('2026-02-01T00:00:00.000Z');++const alignFrom = (+ requestedExpiresAt: Date,+ interval: SubscriptionInterval | null = SubscriptionInterval.Month,+) =>+ alignGrantExpiryToPeriodEnd({+ requestedExpiresAt,+ currentPeriodStart: CURRENT_PERIOD_START,+ currentPeriodEnd: CURRENT_PERIOD_END,+ interval,+ });++describe('alignGrantExpiryToPeriodEnd', () => {+ it('keeps a deadline inside the current period at its end', () => {+ expect(alignFrom(new Date('2026-01-20T00:00:00.000Z'))).toEqual(+ CURRENT_PERIOD_END,+ );+ });++ it('takes the period end a later deadline falls in', () => {+ expect(alignFrom(new Date('2026-03-15T00:00:00.000Z'))).toEqual(+ new Date('2026-04-01T00:00:00.000Z'),+ );+ });++ it('does not extend a deadline that already lands on a period end', () => {+ expect(alignFrom(new Date('2026-03-01T00:00:00.000Z'))).toEqual(+ new Date('2026-03-01T00:00:00.000Z'),+ );+ });++ it('walks yearly periods for a yearly subscription', () => {+ expect(+ alignFrom(+ new Date('2027-06-01T00:00:00.000Z'),+ SubscriptionInterval.Year,+ ),+ ).toEqual(new Date('2028-01-01T00:00:00.000Z'));+ });++ // Stripe re-expands a month-end anchor rather than walking it down: a+ // subscription anchored on the 31st renews Feb 28, Mar 31, Apr 30. Stepping+ // off each clamped result instead would stamp the grant with Mar 28 and+ // Apr 28, dates the subscription never renews on, putting the deadline back+ // inside a period.+ it('keeps a month-end anchor on the days the subscription actually renews', () => {+ const alignOnMonthEndAnchor = (requestedExpiresAt: Date) =>+ alignGrantExpiryToPeriodEnd({+ requestedExpiresAt,+ currentPeriodStart: new Date('2026-01-31T00:00:00.000Z'),+ currentPeriodEnd: new Date('2026-02-28T00:00:00.000Z'),+ interval: SubscriptionInterval.Month,+ });++ expect(alignOnMonthEndAnchor(new Date('2026-02-20T00:00:00.000Z'))).toEqual(+ new Date('2026-02-28T00:00:00.000Z'),+ );+ expect(alignOnMonthEndAnchor(new Date('2026-03-15T00:00:00.000Z'))).toEqual(+ new Date('2026-03-31T00:00:00.000Z'),+ );+ expect(alignOnMonthEndAnchor(new Date('2026-04-15T00:00:00.000Z'))).toEqual(+ new Date('2026-04-30T00:00:00.000Z'),+ );+ });++ // The subscription has already renewed into a short month, so its stored+ // start is the clamped February date and no boundary on record holds the+ // anchor on its own. Projecting straight off that start would give Apr 28.+ it('recovers a month-end anchor the stored period start no longer carries', () => {+ const result = alignGrantExpiryToPeriodEnd({+ requestedExpiresAt: new Date('2026-04-15T00:00:00.000Z'),+ currentPeriodStart: new Date('2026-02-28T00:00:00.000Z'),+ currentPeriodEnd: new Date('2026-03-31T00:00:00.000Z'),+ interval: SubscriptionInterval.Month,+ });++ expect(result).toEqual(new Date('2026-04-30T00:00:00.000Z'));+ });++ // A leap-day yearly anchor clamps to the 28th in common years and re-expands+ // to the 29th when it lands back on a leap one.+ it('keeps a leap-day yearly anchor on the day each year actually has', () => {+ const alignOnLeapDayAnchor = (requestedExpiresAt: Date) =>+ alignGrantExpiryToPeriodEnd({+ requestedExpiresAt,+ currentPeriodStart: new Date('2024-02-29T00:00:00.000Z'),+ currentPeriodEnd: new Date('2025-02-28T00:00:00.000Z'),+ interval: SubscriptionInterval.Year,+ });++ expect(alignOnLeapDayAnchor(new Date('2026-06-01T00:00:00.000Z'))).toEqual(+ new Date('2027-02-28T00:00:00.000Z'),+ );+ expect(alignOnLeapDayAnchor(new Date('2027-06-01T00:00:00.000Z'))).toEqual(+ new Date('2028-02-29T00:00:00.000Z'),+ );+ });++ // Between leap years a Feb 29 anchor is indistinguishable from a Feb 28 one:+ // both boundaries read 28. Landing a day early costs the tail of one period,+ // where landing a day late would carry the grant into the whole next one.+ it('reads an anchor it cannot tell apart as the earlier day', () => {+ const result = alignGrantExpiryToPeriodEnd({+ requestedExpiresAt: new Date('2027-06-01T00:00:00.000Z'),+ currentPeriodStart: new Date('2025-02-28T00:00:00.000Z'),+ currentPeriodEnd: new Date('2026-02-28T00:00:00.000Z'),+ interval: SubscriptionInterval.Year,+ });++ expect(result).toEqual(new Date('2028-02-28T00:00:00.000Z'));+ });++ // The column is nullable, and the interval is only needed to project past the+ // current period. Falling back to null expiry instead would read as "never+ // expires" and hand out permanent credits for a time-boxed request.+ it('stops at the current period end when the interval is unknown', () => {+ expect(alignFrom(new Date('2026-06-15T00:00:00.000Z'), null)).toEqual(+ CURRENT_PERIOD_END,+ );+ });++ it('gives up rather than looping on an unreachable deadline', () => {+ const result = alignFrom(new Date('2099-01-01T00:00:00.000Z'));++ expect(result.getTime()).toBeLessThan(+ new Date('2099-01-01T00:00:00.000Z').getTime(),+ );+ });++ // Stripe's boundaries are UTC instants. Projecting them with local-time+ // arithmetic moves each one by the server's offset, which lands the expiry+ // inside the period it is meant to close: under Europe/Paris this case+ // returned 2026-03-31T23:00:00Z.+ describe.each(['Europe/Paris', 'Pacific/Kiritimati', 'America/Los_Angeles'])(+ 'with the server in %s',+ (timeZone) => {+ const originalTimeZone = process.env.TZ;++ beforeAll(() => {+ process.env.TZ = timeZone;+ });++ afterAll(() => {+ // Assigning undefined would leave the string 'undefined' behind, which+ // is not the unset state the process started in.+ if (isDefined(originalTimeZone)) {+ process.env.TZ = originalTimeZone;+ } else {+ delete process.env.TZ;+ }+ });++ it('projects the boundary in UTC regardless', () => {+ expect(alignFrom(new Date('2026-03-15T00:00:00.000Z'))).toEqual(+ new Date('2026-04-01T00:00:00.000Z'),+ );+ });+ },+ );+});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.tsindex 8a3696e6aba..db75ca4eb1e 100644--- 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@@ -6,6 +6,8 @@ import {type CarryForwardGrantInput,} from 'src/engine/core-modules/billing/utils/compute-carry-forward-grants.util';+const BOUNDARY = new Date('2026-02-01T00:00:00.000Z');+const grant = (overrides: Partial<CarryForwardGrantInput> = {},): CarryForwardGrantInput => ({@@ -13,6 +15,7 @@ const grant = (type: BillingCreditGrantType.ROLLOVER,amountMicro: 0,createdAt: new Date('2026-01-01T00:00:00.000Z'),+ expiresAt: null,...overrides,});@@ -29,6 +32,7 @@ describe('computeCarryForwardGrants', () => {liveGrants: [],usageMicro: 300_000,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([@@ -36,6 +40,7 @@ describe('computeCarryForwardGrants', () => {type: BillingCreditGrantType.ROLLOVER,amountMicro: 700_000,sourceGrantId: null,+ expiresAt: null,},]);});@@ -46,6 +51,7 @@ describe('computeCarryForwardGrants', () => {liveGrants: [],usageMicro: ALLOWANCE,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([]);@@ -57,6 +63,7 @@ describe('computeCarryForwardGrants', () => {liveGrants: [grant({ amountMicro: 200_000 })],usageMicro: 5_000_000,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([]);@@ -72,6 +79,7 @@ describe('computeCarryForwardGrants', () => {],usageMicro: 0,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([@@ -79,6 +87,7 @@ describe('computeCarryForwardGrants', () => {type: BillingCreditGrantType.ROLLOVER,amountMicro: ROLLOVER_CAP,sourceGrantId: null,+ expiresAt: null,},]);});@@ -91,6 +100,7 @@ describe('computeCarryForwardGrants', () => {],usageMicro: 1_200_000,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([@@ -98,6 +108,7 @@ describe('computeCarryForwardGrants', () => {type: BillingCreditGrantType.ROLLOVER,amountMicro: 200_000,sourceGrantId: null,+ expiresAt: null,},]);});@@ -108,6 +119,7 @@ describe('computeCarryForwardGrants', () => {liveGrants: [],usageMicro: 0,rolloverCapMicro: 0,+ boundary: BOUNDARY,});expect(result).toEqual([]);@@ -127,6 +139,7 @@ describe('computeCarryForwardGrants', () => {],usageMicro: 0,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([@@ -134,11 +147,13 @@ describe('computeCarryForwardGrants', () => {type: BillingCreditGrantType.ROLLOVER,amountMicro: ROLLOVER_CAP,sourceGrantId: null,+ expiresAt: null,},{type: BillingCreditGrantType.COMPENSATION,amountMicro: 200_000_000,sourceGrantId: 'compensation_1',+ expiresAt: null,},]);});@@ -155,6 +170,7 @@ describe('computeCarryForwardGrants', () => {],usageMicro: ALLOWANCE,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([@@ -162,6 +178,7 @@ describe('computeCarryForwardGrants', () => {type: BillingCreditGrantType.COMPENSATION,amountMicro: 500_000,sourceGrantId: 'compensation_1',+ expiresAt: null,},]);});@@ -179,6 +196,7 @@ describe('computeCarryForwardGrants', () => {],usageMicro: 2_000_000,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([@@ -186,6 +204,7 @@ describe('computeCarryForwardGrants', () => {type: BillingCreditGrantType.ONBOARDING_REWARD,amountMicro: 500_000,sourceGrantId: 'reward_1',+ expiresAt: null,},]);});@@ -209,6 +228,7 @@ describe('computeCarryForwardGrants', () => {],usageMicro: 500_000,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([@@ -216,6 +236,7 @@ describe('computeCarryForwardGrants', () => {type: BillingCreditGrantType.COMPENSATION,amountMicro: 500_000,sourceGrantId: 'compensation_new',+ expiresAt: null,},]);});@@ -228,6 +249,7 @@ describe('computeCarryForwardGrants', () => {liveGrants: [],usageMicro: 0,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([]);@@ -239,6 +261,7 @@ describe('computeCarryForwardGrants', () => {liveGrants: [],usageMicro: -500_000,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([@@ -246,6 +269,7 @@ describe('computeCarryForwardGrants', () => {type: BillingCreditGrantType.ROLLOVER,amountMicro: ALLOWANCE,sourceGrantId: null,+ expiresAt: null,},]);});@@ -262,6 +286,7 @@ describe('computeCarryForwardGrants', () => {],usageMicro: 999_999.5,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});// The half micro-credit left of the allowance floors to nothing, so no@@ -271,6 +296,7 @@ describe('computeCarryForwardGrants', () => {type: BillingCreditGrantType.COMPENSATION,amountMicro: 1_000,sourceGrantId: 'compensation_1',+ expiresAt: null,},]);});@@ -287,9 +313,114 @@ describe('computeCarryForwardGrants', () => {],usageMicro: 0,rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([]);+ });+ });++ describe('time-boxed grants', () => {+ const IN_THE_NEXT_PERIOD = new Date('2026-02-20T00:00:00.000Z');+ const INSIDE_THE_CLOSING_PERIOD = new Date('2026-01-10T00:00:00.000Z');++ it('carries the deadline over so a grant does not become permanent', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ liveGrants: [+ grant({+ grantId: 'sales_1',+ type: BillingCreditGrantType.SALES,+ amountMicro: 500_000,+ expiresAt: IN_THE_NEXT_PERIOD,+ }),+ ],+ usageMicro: 0,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.SALES,+ amountMicro: 500_000,+ sourceGrantId: 'sales_1',+ expiresAt: IN_THE_NEXT_PERIOD,+ },+ ]);+ });++ it('drops a grant whose deadline fell inside the closing period', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ liveGrants: [+ grant({+ grantId: 'sales_1',+ type: BillingCreditGrantType.SALES,+ amountMicro: 500_000,+ expiresAt: INSIDE_THE_CLOSING_PERIOD,+ }),+ ],+ usageMicro: 0,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,});expect(result).toEqual([]);});++ it('drops a grant that lapses exactly on the boundary', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ liveGrants: [+ grant({+ grantId: 'sales_1',+ type: BillingCreditGrantType.SALES,+ amountMicro: 500_000,+ expiresAt: BOUNDARY,+ }),+ ],+ usageMicro: 0,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([]);+ });++ // It was spendable for part of the period, so the usage it absorbed must+ // not fall back onto the grants that outlive it.+ it('still absorbs usage before lapsing', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ liveGrants: [+ grant({+ grantId: 'sales_1',+ type: BillingCreditGrantType.SALES,+ amountMicro: 500_000,+ createdAt: new Date('2026-01-01T00:00:00.000Z'),+ expiresAt: INSIDE_THE_CLOSING_PERIOD,+ }),+ grant({+ grantId: 'compensation_1',+ type: BillingCreditGrantType.COMPENSATION,+ amountMicro: 500_000,+ createdAt: new Date('2026-01-02T00:00:00.000Z'),+ }),+ ],+ usageMicro: 500_000,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.COMPENSATION,+ amountMicro: 500_000,+ sourceGrantId: 'compensation_1',+ expiresAt: null,+ },+ ]);+ });});});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.tsindex 0a863328913..248b320177b 100644--- 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@@ -7,123 +7,104 @@ 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,- });+const deriveFrom = (+ overrides: Partial<Parameters<typeof deriveBillingPeriodTransition>[0]> = {},+) =>+ deriveBillingPeriodTransition({+ boundary: FEBRUARY,+ subscriptionCurrentPeriodStart: JANUARY,+ subscriptionInterval: SubscriptionInterval.Month,+ trialStart: null,+ trialEnd: null,+ subscriptionPreviousPeriodStart: null,+ ledgerPeriodStart: null,+ ...overrides,+ });- expect(result).toEqual({+describe('deriveBillingPeriodTransition', () => {+ it('closes the period the boundary ends and opens the next one there', () => {+ expect(deriveFrom()).toEqual({closingPeriodStart: JANUARY,closingPeriodEnd: FEBRUARY,nextPeriodStart: FEBRUARY,- nextPeriodEnd: MARCH,+ isFirstPeriodAfterTrial: false,});});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,+ const result = deriveFrom({subscriptionCurrentPeriodStart: FEBRUARY,- subscriptionCurrentPeriodEnd: MARCH,- subscriptionInterval: SubscriptionInterval.Month,trialStart,- isFirstPeriodAfterTrial: true,- subscriptionPreviousPeriodStart: null,- ledgerPeriodStart: null,+ trialEnd: FEBRUARY,});- expect(result).toEqual({- closingPeriodStart: trialStart,- closingPeriodEnd: FEBRUARY,- nextPeriodStart: FEBRUARY,- nextPeriodEnd: MARCH,- });+ expect(result.isFirstPeriodAfterTrial).toBe(true);+ expect(result.closingPeriodStart).toEqual(trialStart);});- // 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,- });+ it('falls back to the trial period start only when the trial actually ran', () => {+ const result = deriveFrom({ trialEnd: FEBRUARY });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,+ // The whole point of resolving the boundary from the subscription is that the+ // invoice's stamped period is unreliable. Classifying the trial off that same+ // stamped period_start put an arrears-stamped first paid period on the paid+ // tier allowance instead of the trial one.+ it('reads the trial from the boundary, not from where the closing period began', () => {+ const trialStart = new Date('2026-01-20T00:00:00.000Z');++ const result = deriveFrom({+ subscriptionCurrentPeriodStart: FEBRUARY,+ trialStart,+ trialEnd: new Date('2026-02-01T00:00:30.000Z'),});- expect(result.closingPeriodStart).toEqual(- new Date('2025-01-01T00:00:00.000Z'),- );+ expect(result.isFirstPeriodAfterTrial).toBe(true);});- 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,+ it('does not read an unrelated renewal as the end of a trial', () => {+ const result = deriveFrom({+ trialStart: new Date('2025-12-20T00:00:00.000Z'),+ trialEnd: JANUARY,});- expect(result.closingPeriodStart).toEqual(- new Date('2024-02-01T00:00:00.000Z'),- );+ expect(result.isFirstPeriodAfterTrial).toBe(false);+ expect(result.closingPeriodStart).toEqual(JANUARY);});- 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,+ // The subscription still carries the closing period, so it is exact and+ // nothing has to be reconstructed from a calendar or from the ledger.+ it('keeps the subscription period start when it precedes the boundary', () => {+ const result = deriveFrom({+ ledgerPeriodStart: new Date('2026-01-15T00:00:00.000Z'),+ subscriptionPreviousPeriodStart: new Date('2025-12-01T00: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 = deriveFrom({+ boundary: monthEndBoundary,+ subscriptionCurrentPeriodStart: monthEndBoundary,+ 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'),+ );+ });+// 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@@ -132,15 +113,9 @@ describe('deriveBillingPeriodTransition', () => {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'),+ const result = deriveFrom({+ boundary: monthEndBoundary,subscriptionCurrentPeriodStart: monthEndBoundary,- subscriptionCurrentPeriodEnd: new Date('2026-03-31T00:00:00.000Z'),- subscriptionInterval: SubscriptionInterval.Month,- trialStart: null,- isFirstPeriodAfterTrial: false,- subscriptionPreviousPeriodStart: null,ledgerPeriodStart,});@@ -148,92 +123,64 @@ describe('deriveBillingPeriodTransition', () => {});it('ignores a ledger period start that is not before the boundary', () => {- const result = deriveBillingPeriodTransition({- invoicePeriodStart: FEBRUARY,- invoicePeriodEnd: MARCH,+ const result = deriveFrom({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,- });+ it('falls back one calendar month when the subscription already advanced', () => {+ const result = deriveFrom({ subscriptionCurrentPeriodStart: FEBRUARY });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,+ it('falls back one calendar year for a yearly subscription', () => {+ const result = deriveFrom({+ boundary: JANUARY,subscriptionCurrentPeriodStart: JANUARY,- subscriptionCurrentPeriodEnd: FEBRUARY,- subscriptionInterval: SubscriptionInterval.Month,- trialStart: null,- isFirstPeriodAfterTrial: false,- subscriptionPreviousPeriodStart: null,- ledgerPeriodStart: new Date('2026-01-15T00:00:00.000Z'),+ subscriptionInterval: SubscriptionInterval.Year,});- expect(result.closingPeriodStart).toEqual(JANUARY);+ expect(result.closingPeriodStart).toEqual(+ new Date('2025-01-01T00:00:00.000Z'),+ );});- // 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'),+ it('keeps the closing period aligned across a leap February', () => {+ const result = deriveFrom({+ boundary: new Date('2024-03-01T00:00:00.000Z'),+ subscriptionCurrentPeriodStart: new Date('2024-03-01T00:00:00.000Z'),});expect(result.closingPeriodStart).toEqual(- new Date('2026-01-31T00:00:00.000Z'),+ new Date('2024-02-01T00: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,+ // The column is nullable while its type says otherwise. Treating a missing+ // interval as monthly would settle a yearly subscription against one month of+ // usage and carry eleven months of allowance forward as unspent.+ it('refuses to guess a period length when the subscription records no interval', () => {+ expect(() =>+ deriveFrom({+ subscriptionCurrentPeriodStart: FEBRUARY,+ subscriptionInterval: null,+ }),+ ).toThrow(/records no interval/);+ });++ // Only the calendar fallback needs the interval, so an exact source still+ // settles correctly without one.+ it('settles without an interval when the subscription recorded the period start', () => {+ const result = deriveFrom({+ subscriptionCurrentPeriodStart: FEBRUARY,+ subscriptionInterval: null,+ subscriptionPreviousPeriodStart: JANUARY,});- expect(result.nextPeriodStart).toEqual(FEBRUARY);- expect(result.nextPeriodEnd).toEqual(MARCH);+ expect(result.closingPeriodStart).toEqual(JANUARY);});});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-transition-boundary.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-transition-boundary.util.spec.tsnew file mode 100644index 00000000000..c936da342a1--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-transition-boundary.util.spec.ts@@ -0,0 +1,109 @@+/* @license Enterprise */++import { resolveBillingTransitionBoundary } from 'src/engine/core-modules/billing/utils/resolve-billing-transition-boundary.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('resolveBillingTransitionBoundary', () => {+ it('takes the period end while the subscription still holds the closing period', () => {+ const boundary = resolveBillingTransitionBoundary({+ invoiceCreatedAt: FEBRUARY,+ subscriptionCurrentPeriodStart: JANUARY,+ subscriptionCurrentPeriodEnd: FEBRUARY,+ });++ expect(boundary).toEqual(FEBRUARY);+ });++ it('takes the period start once the subscription has advanced', () => {+ const boundary = resolveBillingTransitionBoundary({+ invoiceCreatedAt: FEBRUARY,+ subscriptionCurrentPeriodStart: FEBRUARY,+ subscriptionCurrentPeriodEnd: MARCH,+ });++ expect(boundary).toEqual(FEBRUARY);+ });++ // Stripe stamps an invoice carrying metered items with the period that just+ // closed, so reading the boundary off invoicePeriodStart used to settle the+ // period before the one that ended and carry its grants into a window that+ // was already over. The subscription pins the handover whatever the stamp.+ it('does not move to the start of the period that just closed', () => {+ const boundary = resolveBillingTransitionBoundary({+ invoiceCreatedAt: new Date('2026-02-01T00:04:00.000Z'),+ subscriptionCurrentPeriodStart: JANUARY,+ subscriptionCurrentPeriodEnd: FEBRUARY,+ });++ expect(boundary).toEqual(FEBRUARY);+ });++ // invoice.created is stamped when Stripe raised the invoice, not when we got+ // to it, so a redelivery days later resolves exactly as the first attempt did.+ // Reading our own clock here used to drag the observation point with the+ // delay and pick the period end still in the future.+ it('resolves a redelivery days later to the same handover', () => {+ const boundary = resolveBillingTransitionBoundary({+ invoiceCreatedAt: FEBRUARY,+ subscriptionCurrentPeriodStart: FEBRUARY,+ subscriptionCurrentPeriodEnd: MARCH,+ });++ expect(boundary).toEqual(FEBRUARY);+ });++ // Settling March here would run on partial usage and reserve the idempotency+ // key the real March transition then needs. The invoice was raised at the+ // February handover, so that is the boundary it announces however far into+ // the period we happen to process it.+ it('never settles a period that has not ended yet', () => {+ const boundary = resolveBillingTransitionBoundary({+ invoiceCreatedAt: FEBRUARY,+ subscriptionCurrentPeriodStart: FEBRUARY,+ subscriptionCurrentPeriodEnd: MARCH,+ });++ expect(boundary).toEqual(FEBRUARY);+ });++ it('takes the period end for a redelivery long after it closed', () => {+ const boundary = resolveBillingTransitionBoundary({+ invoiceCreatedAt: new Date('2026-02-20T00:00:00.000Z'),+ subscriptionCurrentPeriodStart: JANUARY,+ subscriptionCurrentPeriodEnd: FEBRUARY,+ });++ expect(boundary).toEqual(FEBRUARY);+ });++ // Stripe can raise the invoice a moment before it rolls the subscription's+ // period end. Rejecting the boundary outright here would hand back the period+ // start, and on a first cycle there is no spent idempotency key to make that+ // a no-op: the transition would reconstruct a pre-subscription window and+ // write carry-forward rows into the period still open.+ it('still reads a boundary the invoice was raised a moment before', () => {+ const boundary = resolveBillingTransitionBoundary({+ invoiceCreatedAt: new Date('2026-01-31T23:59:59.000Z'),+ subscriptionCurrentPeriodStart: JANUARY,+ subscriptionCurrentPeriodEnd: FEBRUARY,+ });++ expect(boundary).toEqual(FEBRUARY);+ });++ // The handover is a whole period away from the other candidate, so nothing+ // realistic reaches the midpoint. An invoice raised nearer the period start+ // than its end is announcing that start, not a period end still to come.+ it('does not reach forward to a period end the invoice predates by most of a period', () => {+ const boundary = resolveBillingTransitionBoundary({+ invoiceCreatedAt: new Date('2026-01-05T00:00:00.000Z'),+ subscriptionCurrentPeriodStart: JANUARY,+ subscriptionCurrentPeriodEnd: FEBRUARY,+ });++ expect(boundary).toEqual(JANUARY);+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/shift-utc-months.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/shift-utc-months.util.spec.tsnew file mode 100644index 00000000000..188cf3b0e67--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/shift-utc-months.util.spec.ts@@ -0,0 +1,117 @@+/* @license Enterprise */++import { shiftUtcMonths } from 'src/engine/core-modules/billing/utils/shift-utc-months.util';++describe('shiftUtcMonths', () => {+ it('keeps the day the date already carries', () => {+ expect(+ shiftUtcMonths({ date: new Date('2026-01-15T00:00:00.000Z'), months: 1 }),+ ).toEqual(new Date('2026-02-15T00:00:00.000Z'));+ });++ it('clamps a day the target month does not have', () => {+ expect(+ shiftUtcMonths({ date: new Date('2026-01-31T00:00:00.000Z'), months: 1 }),+ ).toEqual(new Date('2026-02-28T00:00:00.000Z'));+ });++ it('clamps to the leap day when the target February has one', () => {+ expect(+ shiftUtcMonths({ date: new Date('2024-01-31T00:00:00.000Z'), months: 1 }),+ ).toEqual(new Date('2024-02-29T00:00:00.000Z'));+ });++ // The stored boundary has already been clamped, so the anchor has to be+ // re-applied rather than read off the date being shifted.+ it('applies an anchor day the date itself no longer carries', () => {+ expect(+ shiftUtcMonths({+ date: new Date('2026-02-28T00:00:00.000Z'),+ months: 1,+ dayOfMonth: 31,+ }),+ ).toEqual(new Date('2026-03-31T00:00:00.000Z'));+ });++ it('clamps the anchor again for a month that cannot hold it', () => {+ expect(+ shiftUtcMonths({+ date: new Date('2026-03-31T00:00:00.000Z'),+ months: 1,+ dayOfMonth: 31,+ }),+ ).toEqual(new Date('2026-04-30T00:00:00.000Z'));+ });++ it('steps backwards', () => {+ expect(+ shiftUtcMonths({+ date: new Date('2026-03-31T00:00:00.000Z'),+ months: -1,+ }),+ ).toEqual(new Date('2026-02-28T00:00:00.000Z'));+ });++ it('rolls a month index past either end of the year', () => {+ expect(+ shiftUtcMonths({ date: new Date('2026-12-15T00:00:00.000Z'), months: 1 }),+ ).toEqual(new Date('2027-01-15T00:00:00.000Z'));+ expect(+ shiftUtcMonths({+ date: new Date('2026-01-15T00:00:00.000Z'),+ months: -1,+ }),+ ).toEqual(new Date('2025-12-15T00:00:00.000Z'));+ });++ it('shifts a year as twelve months', () => {+ expect(+ shiftUtcMonths({+ date: new Date('2026-06-15T00:00:00.000Z'),+ months: 12,+ }),+ ).toEqual(new Date('2027-06-15T00:00:00.000Z'));+ expect(+ shiftUtcMonths({+ date: new Date('2024-02-29T00:00:00.000Z'),+ months: -12,+ }),+ ).toEqual(new Date('2023-02-28T00:00:00.000Z'));+ });++ // Stripe's boundaries are instants, not dates, and a subscription anchored+ // mid-day hands over at that time of day in every period.+ it('carries the time of day through the shift', () => {+ expect(+ shiftUtcMonths({ date: new Date('2026-01-15T09:41:07.123Z'), months: 1 }),+ ).toEqual(new Date('2026-02-15T09:41:07.123Z'));+ });++ describe.each(['Europe/Paris', 'Pacific/Kiritimati'])(+ 'with the server in %s',+ (timeZone) => {+ const originalTimeZone = process.env.TZ;++ beforeAll(() => {+ process.env.TZ = timeZone;+ });++ afterAll(() => {+ if (originalTimeZone === undefined) {+ delete process.env.TZ;+ } else {+ process.env.TZ = originalTimeZone;+ }+ });++ it('answers in UTC regardless', () => {+ expect(+ shiftUtcMonths({+ date: new Date('2026-01-01T00:00:00.000Z'),+ months: 3,+ }),+ ).toEqual(new Date('2026-04-01T00:00:00.000Z'));+ });+ },+ );+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util.tsnew file mode 100644index 00000000000..36b25905be7--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util.ts@@ -0,0 +1,116 @@+/* @license Enterprise */++import { isDefined } from 'twenty-shared/utils';++import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';+import { shiftUtcMonths } from 'src/engine/core-modules/billing/utils/shift-utc-months.util';++// Bounds the walk so it cannot run away. Must stay above what the longest+// accepted validity needs on the shortest interval: a year of monthly periods+// is thirteen, so this leaves room to spare. Walking out of it returns a date+// short of the one asked for, so the accepted validity and this bound have to+// move together.+const MAX_PERIODS_AHEAD = 24;++// Stripe keeps the day a subscription was anchored on and clamps it to each+// short month, so a subscription anchored on the 31st renews Jan 31, Feb 28,+// Mar 31. Neither stored boundary is reliably the anchor once it has renewed+// into a short month, so take the later day of the two: for monthly periods+// that is always the anchor, since no two consecutive months are short enough+// to clamp the same one.+//+// Yearly periods have one case the two dates cannot settle, a Feb 29 anchor+// read between leap years, where both say 28. Reading it as 28 leaves a+// deadline a day short of a leap-year boundary; reading it as 29 would push it+// past a common-year one and buy a whole extra period, so the low reading is+// the one worth keeping. Recovering the anchor this way avoids having to+// persist Stripe's billing_cycle_anchor.+const resolveAnchorDayOfMonth = ({+ periodStart,+ periodEnd,+}: {+ periodStart: Date;+ periodEnd: Date;+}): number => Math.max(periodStart.getUTCDate(), periodEnd.getUTCDate());++const projectPeriodEnd = ({+ periodStart,+ anchorDayOfMonth,+ periodsAhead,+ interval,+}: {+ periodStart: Date;+ anchorDayOfMonth: number;+ periodsAhead: number;+ interval: SubscriptionInterval;+}): Date => {+ const monthsAhead =+ interval === SubscriptionInterval.Year ? periodsAhead * 12 : periodsAhead;++ return shiftUtcMonths({+ date: periodStart,+ months: monthsAhead,+ dayOfMonth: anchorDayOfMonth,+ });+};++// A grant's expiry is always a period end. Both mechanisms that spend credits+// work a whole period at a time: the available credit count is cached until the+// period ends, and the carry-forward settles a period's usage against the+// grants that were live for it. A deadline inside a period is invisible to+// both, so the counter would keep spending credits that had lapsed and the+// settlement would let them absorb usage incurred after they died. Asking for+// thirty days therefore buys the period that day falls in, never less.+export const alignGrantExpiryToPeriodEnd = ({+ requestedExpiresAt,+ currentPeriodStart,+ currentPeriodEnd,+ interval,+}: {+ requestedExpiresAt: Date;+ currentPeriodStart: Date;+ currentPeriodEnd: Date;+ // Nullable on the subscription, and only needed to project past the current+ // period. Without it the current period end is the last boundary that can be+ // named, which is short of what was asked for but still a real one.+ interval: SubscriptionInterval | null | undefined;+}): Date => {+ // Known exactly, and the only boundary that survives a period whose length+ // was changed by a plan switch rather than by the schedule.+ if (+ currentPeriodEnd.getTime() >= requestedExpiresAt.getTime() ||+ !isDefined(interval)+ ) {+ return currentPeriodEnd;+ }++ const anchorDayOfMonth = resolveAnchorDayOfMonth({+ periodStart: currentPeriodStart,+ periodEnd: currentPeriodEnd,+ });++ // Every later boundary is projected from the period start rather than by+ // stepping off the previous result, which would walk a month-end anchor down+ // to the 28th and stamp the grant with days the subscription never renews on,+ // putting the deadline back inside a period.+ let periodEnd = currentPeriodEnd;++ for (+ let periodsAhead = 2;+ periodsAhead <= MAX_PERIODS_AHEAD;+ periodsAhead+++ ) {+ periodEnd = projectPeriodEnd({+ periodStart: currentPeriodStart,+ anchorDayOfMonth,+ periodsAhead,+ interval,+ });++ if (periodEnd.getTime() >= requestedExpiresAt.getTime()) {+ break;+ }+ }++ return periodEnd;+};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.tsindex be59a647308..65925732a49 100644--- 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@@ -1,5 +1,7 @@/* @license Enterprise */+import { isDefined } from 'twenty-shared/utils';+import {BillingCreditGrantType,CAPPED_BILLING_CREDIT_GRANT_TYPES,@@ -10,12 +12,14 @@ export type CarryForwardGrantInput = {type: BillingCreditGrantType;amountMicro: number;createdAt: Date;+ expiresAt: Date | null;};export type CarryForwardGrantOutput = {type: BillingCreditGrantType;amountMicro: number;sourceGrantId: string | null;+ expiresAt: Date | null;};type CreditBucket = {@@ -23,11 +27,21 @@ type CreditBucket = {type: BillingCreditGrantType;amountMicro: number;createdAt: Date;+ expiresAt: Date | null;};const isCappedType = (type: BillingCreditGrantType): boolean =>CAPPED_BILLING_CREDIT_GRANT_TYPES.includes(type);+const hasLapsedBy = ({+ expiresAt,+ boundary,+}: {+ expiresAt: Date | null;+ boundary: Date;+}): boolean =>+ isDefined(expiresAt) && expiresAt.getTime() <= boundary.getTime();+// 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.@@ -56,17 +70,22 @@ export const computeCarryForwardGrants = ({liveGrants,usageMicro,rolloverCapMicro,+ boundary,}: {allowanceMicro: number;liveGrants: CarryForwardGrantInput[];usageMicro: number;rolloverCapMicro: number;+ // Where the closing period ends, which decides whether a time-boxed grant is+ // still alive on the other side of it.+ boundary: Date;}): CarryForwardGrantOutput[] => {const allowanceBucket: CreditBucket = {grantId: null,type: BillingCreditGrantType.ROLLOVER,amountMicro: Math.max(0, allowanceMicro),createdAt: new Date(0),+ expiresAt: null,};const buckets = [@@ -99,16 +118,30 @@ export const computeCarryForwardGrants = ({type: BillingCreditGrantType.ROLLOVER,amountMicro: rolloverMicro,sourceGrantId: null,+ expiresAt: null,},]: [];+ // A lapsed grant keeps its place in the waterfall above and only loses its+ // remainder: carrying that would hand back credits the deadline took away.+ // The waterfall spends a whole period at once with no event times, so this is+ // only exact because every deadline is a period end, which is the invariant+ // alignGrantExpiryToPeriodEnd holds at the point an expiry is set.const preservedGrants: CarryForwardGrantOutput[] = unspentBuckets- .filter((bucket) => !isCappedType(bucket.type) && bucket.amountMicro >= 1)+ .filter(+ (bucket) =>+ !isCappedType(bucket.type) &&+ bucket.amountMicro >= 1 &&+ !hasLapsedBy({ expiresAt: bucket.expiresAt, boundary }),+ ).map((bucket) => ({type: bucket.type,amountMicro: Math.floor(bucket.amountMicro),sourceGrantId: bucket.grantId,+ // The successor inherits the deadline rather than outliving it, so a+ // time-boxed grant does not become permanent by crossing a renewal.+ expiresAt: bucket.expiresAt,}));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.tsindex 41a0f369547..2cb543c06b1 100644--- 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@@ -1,39 +1,139 @@/* @license Enterprise */-import { subMonths, subYears } from 'date-fns';import { isDefined } from 'twenty-shared/utils';+import {+ BillingException,+ BillingExceptionCode,+} from 'src/engine/core-modules/billing/billing.exception';+import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';+import { shiftUtcMonths } from 'src/engine/core-modules/billing/utils/shift-utc-months.util';export type BillingPeriodTransition = {closingPeriodStart: Date;closingPeriodEnd: Date;nextPeriodStart: Date;- nextPeriodEnd: Date;+ // Whether the period being closed is the trial. Its allowance comes from+ // config rather than the price, which only applies once paid.+ isFirstPeriodAfterTrial: boolean;};-// 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,+// Stripe stamps the trial end and the boundary from the same schedule, so they+// agree to the second; the slack only absorbs rounding.+const TRIAL_END_TOLERANCE_IN_MS = 60 * 1000;++const subtractOneInterval = ({+ date,+ interval,+}: {+ date: Date;+ interval: SubscriptionInterval;+}): Date =>+ shiftUtcMonths({+ date,+ months: interval === SubscriptionInterval.Year ? -12 : -1,+ });++const resolveClosingPeriodStart = ({+ boundary,subscriptionCurrentPeriodStart,- subscriptionCurrentPeriodEnd,subscriptionInterval,trialStart,isFirstPeriodAfterTrial,subscriptionPreviousPeriodStart,ledgerPeriodStart,}: {- invoicePeriodStart: Date;- invoicePeriodEnd: Date;+ boundary: Date;subscriptionCurrentPeriodStart: Date;- subscriptionCurrentPeriodEnd: Date;- subscriptionInterval: SubscriptionInterval;+ // Nullable on the subscription despite its type. Only the calendar fallback+ // below needs it, and that branch refuses rather than assuming a length.+ subscriptionInterval: SubscriptionInterval | null | undefined;trialStart: Date | null | undefined;isFirstPeriodAfterTrial: boolean;+ subscriptionPreviousPeriodStart: Date | null;+ ledgerPeriodStart: Date | null;+}): Date => {+ if (isFirstPeriodAfterTrial && isDefined(trialStart)) {+ return trialStart;+ }++ // Stripe reports one window at a time, so at the instant a cycle invoice is+ // raised the subscription either still holds the period that is closing or+ // has already been moved on to the next one. In the first case it still+ // carries the closing period's exact start and nothing has to be+ // reconstructed.+ if (boundary.getTime() !== subscriptionCurrentPeriodStart.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;+ }++ // Nothing on record says where the closing period began, so the only way+ // left is to step back one interval — and without one there is no honest+ // guess. Treating a missing interval as monthly would settle a yearly+ // subscription against a month of usage and roll eleven months of allowance+ // forward as unspent. Throwing fails the webhook so Stripe redelivers it,+ // and a settlement that is late beats one that is wrong.+ if (!isDefined(subscriptionInterval)) {+ throw new BillingException(+ `Cannot settle the period closing at ${boundary.toISOString()}: the subscription records no interval and neither it nor the ledger says where the period began`,+ BillingExceptionCode.BILLING_SUBSCRIPTION_INVALID,+ );+ }++ // 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 subtractOneInterval({+ date: boundary,+ interval: subscriptionInterval,+ });+};++export const deriveBillingPeriodTransition = ({+ boundary,+ subscriptionCurrentPeriodStart,+ subscriptionInterval,+ trialStart,+ trialEnd,+ subscriptionPreviousPeriodStart,+ ledgerPeriodStart,+}: {+ // Resolved through resolveBillingTransitionBoundary before the ledger is+ // read, since which period start the ledger is asked for depends on it.+ boundary: Date;+ subscriptionCurrentPeriodStart: Date;+ // Nullable on the subscription despite its type. Only the calendar fallback+ // needs it, and that branch refuses rather than assuming a length.+ subscriptionInterval: SubscriptionInterval | null | undefined;+ trialStart: Date | null | undefined;+ // A trial ends at a period handover, so this transition closes the trial+ // exactly when the boundary it settles is the trial end. Compared against+ // that resolved boundary and never against the invoice's stamped period,+ // which on an arrears-stamped invoice reports the window that just closed.+ trialEnd: Date | null | undefined;// 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.@@ -42,57 +142,25 @@ export const deriveBillingPeriodTransition = ({// 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;- }+ const isFirstPeriodAfterTrial =+ isDefined(trialEnd) &&+ Math.abs(boundary.getTime() - trialEnd.getTime()) <=+ TRIAL_END_TOLERANCE_IN_MS;- // 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);- })();+ const closingPeriodStart = resolveClosingPeriodStart({+ boundary,+ subscriptionCurrentPeriodStart,+ subscriptionInterval,+ trialStart,+ isFirstPeriodAfterTrial,+ subscriptionPreviousPeriodStart,+ ledgerPeriodStart,+ });return {closingPeriodStart,closingPeriodEnd: boundary,nextPeriodStart: boundary,- nextPeriodEnd,+ isFirstPeriodAfterTrial,};};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-transition-boundary.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-transition-boundary.util.tsnew file mode 100644index 00000000000..05282d17fde--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-transition-boundary.util.ts@@ -0,0 +1,51 @@+/* @license Enterprise */++// Stripe stamps a subscription_cycle invoice with the period it bills, which is+// the upcoming one for licensed items but the one that just closed for metered+// items. Resource credits are sold as a metered item, so on a subscription+// carrying both the invoice can arrive stamped with either window and its+// period_start is not the handover instant. The subscription is unambiguous+// about where its own periods hand over, so the boundary is read off it: the+// invoice only tells us that a handover happened.+//+// Which of the subscription's two boundaries is the handover depends on whether+// our copy of it has advanced yet, and Stripe raises the invoice at the+// handover itself. So the answer is whichever boundary the invoice was created+// nearest to: it is the period end while the subscription still holds the+// closing window, and the period start once it has moved on.+//+// The two candidates are a whole period apart and the invoice sits on the+// handover, so this resolves with half a period of room on either side. That is+// what makes it safe where comparing against our own wall clock was not: a+// redelivery processed days late used to drag the observation point with it,+// where invoice.created stays pinned to the handover however late we get to it.+// It also cannot drift toward a period end that has not arrived, because the+// nearer boundary to the handover is the handover.+//+// That last part rests on the caller passing only subscription_cycle invoices,+// which Stripe raises at the handover. Given any other invoice, raised at an+// arbitrary point inside the period, nearness would answer with whichever+// boundary happened to be closer and could name a period end still to come.+// Widening what reaches this, or dropping that filter, breaks the guarantee.+export const resolveBillingTransitionBoundary = ({+ invoiceCreatedAt,+ subscriptionCurrentPeriodStart,+ subscriptionCurrentPeriodEnd,+}: {+ invoiceCreatedAt: Date;+ subscriptionCurrentPeriodStart: Date;+ subscriptionCurrentPeriodEnd: Date;+}): Date => {+ const createdAt = invoiceCreatedAt.getTime();++ const distanceToPeriodStart = Math.abs(+ subscriptionCurrentPeriodStart.getTime() - createdAt,+ );+ const distanceToPeriodEnd = Math.abs(+ subscriptionCurrentPeriodEnd.getTime() - createdAt,+ );++ return distanceToPeriodEnd < distanceToPeriodStart+ ? subscriptionCurrentPeriodEnd+ : subscriptionCurrentPeriodStart;+};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/shift-utc-months.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/shift-utc-months.util.tsnew file mode 100644index 00000000000..4b06396db43--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/shift-utc-months.util.ts@@ -0,0 +1,39 @@+/* @license Enterprise */++// Stripe's period boundaries are UTC instants, and date-fns shifts dates in the+// server's local time: that moves each boundary by the offset and, around a+// daylight-saving change, lands it on the wrong side of the period it defines.+// Every billing period projection goes through here so the arithmetic stays in+// UTC in one place.+export const shiftUtcMonths = ({+ date,+ months,+ dayOfMonth,+}: {+ date: Date;+ months: number;+ // Defaults to the day the date already carries. Passed explicitly to re-apply+ // a billing anchor that the stored boundary had clamped away.+ dayOfMonth?: number;+}): Date => {+ const year = date.getUTCFullYear();+ const targetMonth = date.getUTCMonth() + months;++ // Day 0 of the month after the target is the last day of the target itself,+ // and Date.UTC rolls a month index past either end of the year.+ const daysInTargetMonth = new Date(+ Date.UTC(year, targetMonth + 1, 0),+ ).getUTCDate();++ return new Date(+ Date.UTC(+ year,+ targetMonth,+ Math.min(dayOfMonth ?? date.getUTCDate(), daysInTargetMonth),+ date.getUTCHours(),+ date.getUTCMinutes(),+ date.getUTCSeconds(),+ date.getUTCMilliseconds(),+ ),+ );+};diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.tsindex 80a116d6629..c71352d18fd 100644--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts@@ -1,6 +1,6 @@import { randomUUID } from 'node:crypto';-import { addMonths, startOfMonth } from 'date-fns';+import { addDays, addMonths, startOfMonth } from 'date-fns';import request from 'supertest';import {getBillingUsageCacheService,@@ -11,9 +11,13 @@ import {resetBillingCreditState,setupResourceCreditSubscription,warmAllowanceCounter,+ setSubscriptionStatus,} from 'test/integration/billing/utils/billing-credit-fixtures.util';import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';+import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';+import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';+import { alignGrantExpiryToPeriodEnd } from 'src/engine/core-modules/billing/utils/align-grant-expiry-to-period-end.util';import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'src/engine/core-modules/usage/utils/to-display-credits.util';const client = request(`http://localhost:${APP_PORT}`);@@ -28,6 +32,7 @@ const GRANT_MUTATION = `$amount: Float!$type: BillingCreditGrantType!$reason: String+ $expiresInDays: Int$clientOperationId: UUID!) {grantWorkspaceCredits(@@ -35,12 +40,14 @@ const GRANT_MUTATION = `amount: $amounttype: $typereason: $reason+ expiresInDays: $expiresInDaysclientOperationId: $clientOperationId) {idamounttypereason+ expiresAtisActive}}@@ -117,6 +124,68 @@ describe('Admin credit grant and revoke (integration)', () => {});});+ it('leaves a granted amount without an expiry so no missed transition can drop it', async () => {+ const response = await grantCredits({+ workspaceId,+ amount: 2,+ type: BillingCreditGrantType.COMPENSATION,+ reason: null,+ });++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.grantWorkspaceCredits.expiresAt).toBeNull();++ const grants = await listCreditGrants(workspaceId);++ expect(grants[0].expiresAt).toBeNull();+ });++ // Rounded up to a period end rather than the exact day: credits are spent and+ // settled a period at a time, so a deadline inside one would be invisible to+ // both the cached counter and the carry-forward.+ it('expires a time-boxed grant at the end of the period the requested day falls in', async () => {+ const response = await grantCredits({+ workspaceId,+ amount: 2,+ type: BillingCreditGrantType.SALES,+ reason: 'Pilot credits',+ expiresInDays: 30,+ });++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.grantWorkspaceCredits.isActive).toBe(true);++ const [storedGrant] = await listCreditGrants(workspaceId);++ // Which period the thirtieth day lands in depends on when the suite runs,+ // so the boundary is derived the same way the server derives it rather+ // than listed.+ const expectedExpiresAt = alignGrantExpiryToPeriodEnd({+ requestedExpiresAt: addDays(new Date(), 30),+ currentPeriodStart: PERIOD_START,+ currentPeriodEnd: PERIOD_END,+ interval: SubscriptionInterval.Month,+ });++ expect(storedGrant.expiresAt).toEqual(expectedExpiresAt);+ expect(expectedExpiresAt.getTime()).toBeGreaterThanOrEqual(+ addDays(new Date(), 30).getTime(),+ );+ });++ it('refuses an expiry beyond the accepted range', async () => {+ const response = await grantCredits({+ workspaceId,+ amount: 2,+ type: BillingCreditGrantType.COMPENSATION,+ reason: null,+ expiresInDays: 100_000,+ });++ expect(response.body.errors).toBeDefined();+ expect(await listCreditGrants(workspaceId)).toHaveLength(0);+ });+it('adds the granted amount to a warm available-credits counter', async () => {const cache = getBillingUsageCacheService();@@ -139,6 +208,31 @@ describe('Admin credit grant and revoke (integration)', () => {);});+ // The aligned deadline lands on the period end the counter already expires+ // with, so the cached balance stays valid and can simply be incremented.+ it('keeps a warm available-credits counter usable for a time-boxed grant', async () => {+ const cache = getBillingUsageCacheService();++ await cache.warmAvailableCredits(+ workspaceId,+ PERIOD_START,+ PERIOD_END,+ 500_000,+ );++ await grantCredits({+ workspaceId,+ amount: 2,+ type: BillingCreditGrantType.SALES,+ reason: null,+ expiresInDays: 1,+ });++ 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 available-credits counter', async () => {const cache = getBillingUsageCacheService();@@ -287,4 +381,33 @@ describe('Admin credit grant and revoke (integration)', () => {);expect(await listCreditGrants(workspaceId)).toHaveLength(1);});++ // The refusal to time-box a grant with no billing period must not reach a+ // replay: the subscription that anchored the original deadline can be gone by+ // the time the client retries, and the operation already succeeded.+ it('answers a retried time-boxed grant after the subscription is canceled', async () => {+ const clientOperationId = randomUUID();+ const variables = {+ workspaceId,+ amount: 25,+ type: BillingCreditGrantType.SALES,+ reason: 'Retried after cancellation',+ clientOperationId,+ expiresInDays: 30,+ };++ const first = await callAdminGraphql(GRANT_MUTATION, variables);++ expect(first.body.errors).toBeUndefined();++ await setSubscriptionStatus(workspaceId, SubscriptionStatus.Canceled);++ const second = await callAdminGraphql(GRANT_MUTATION, variables);++ expect(second.body.errors).toBeUndefined();+ expect(second.body.data.grantWorkspaceCredits.id).toBe(+ first.body.data.grantWorkspaceCredits.id,+ );+ expect(await listCreditGrants(workspaceId)).toHaveLength(1);+ });});diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.tsindex f3305537e77..882f50c8481 100644--- a/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts+++ b/packages/twenty-server/test/integration/billing/suites/billing-credit-rollover.integration-spec.ts@@ -100,7 +100,9 @@ describe('Billing credit rollover (integration)', () => {revokedAt: null,});expect(new Date(grants[0].effectiveAt)).toEqual(CLOSING_PERIOD_END);- expect(new Date(grants[0].expiresAt)).toEqual(NEXT_PERIOD_END);+ // Successors carry no deadline: stamping the next period end would put the+ // balance back at the mercy of the transition after this one running.+ expect(grants[0].expiresAt).toBeNull();});it('reads usage over the closing period, not the one just opened', async () => {@@ -146,7 +148,7 @@ describe('Billing credit rollover (integration)', () => {// 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(compensation?.expiresAt).toEqual(CLOSING_PERIOD_END);expect(grants.some((grant) =>@@ -322,7 +324,7 @@ describe('Billing credit rollover (integration)', () => {amountMicro: 250_000,type: BillingCreditGrantType.ONBOARDING_REWARD,effectiveAt: CLOSING_PERIOD_START,- expiresAt: CLOSING_PERIOD_END,+ expiresAt: null,});await postInvoiceFinalized('in_test_trial').expect(200);@@ -334,8 +336,8 @@ describe('Billing credit rollover (integration)', () => {);expect(reward).toBeDefined();- expect(reward!.amountMicro).toBe(250_000);- expect(new Date(reward!.expiresAt)).toEqual(NEXT_PERIOD_END);+ expect(reward?.amountMicro).toBe(250_000);+ expect(reward?.expiresAt).toBeNull();});});});diff --git a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.tsindex c0398d4c7b8..86d27df8894 100644--- a/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts+++ b/packages/twenty-server/test/integration/billing/utils/billing-credit-fixtures.util.ts@@ -2,6 +2,7 @@ import { createClient, type RedisClientType } from 'redis';import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';import { type BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/billing-credit-grant-type.enum';+import { type SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';import { type BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';@@ -25,7 +26,7 @@ export type CreditGrantRow = {amountMicro: number;type: BillingCreditGrantType;effectiveAt: Date;- expiresAt: Date;+ expiresAt: Date | null;revokedAt: Date | null;reason: string | null;idempotencyKey: string | null;@@ -145,7 +146,7 @@ export const insertCreditGrant = async ({amountMicro: number;type: BillingCreditGrantType;effectiveAt: Date;- expiresAt: Date;+ expiresAt: Date | null;idempotencyKey?: string | null;}): Promise<string> => {const [row] = await query<{ id: string }>(@@ -248,3 +249,16 @@ export const getBillingUsageCacheService = (): BillingUsageCacheService =>getAppProviderByClassName<BillingUsageCacheService>('BillingUsageCacheService',);++// Cancelling is what makes getCurrentBillingSubscription stop returning it, so+// this is how a test reaches the no-subscription path without deleting rows the+// rest of the suite shares.+export const setSubscriptionStatus = async (+ workspaceId: string,+ status: SubscriptionStatus,+): Promise<void> => {+ await query(+ `UPDATE "core"."billingSubscription" SET status = $2 WHERE "workspaceId" = $1`,+ [workspaceId, status],+ );+};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.tsindex 2bfbbba70ab..431b4c0e221 100644--- 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@@ -6,6 +6,7 @@ export type MockStripeInvoiceFinalizedData = {id: string;object: 'invoice';billing_reason: string;+ created: number;customer: string;period_start: number;period_end: number;@@ -26,9 +27,15 @@ export const createMockStripeInvoiceFinalizedData = ({stripeSubscriptionId = 'sub_default0',billingReason = 'subscription_cycle',invoiceId = 'in_test_default',+ // Stripe raises a cycle invoice at the handover, which for an advance-stamped+ // one is the period it opens. The boundary is resolved off this rather than+ // off our own clock, so a fixture that leaves it out no longer models the+ // handover at all.+ createdAt = periodStart,}: {periodStart: Date;periodEnd: Date;+ createdAt?: Date;stripeCustomerId?: string;stripeSubscriptionId?: string;billingReason?: string;@@ -38,6 +45,7 @@ export const createMockStripeInvoiceFinalizedData = ({id: invoiceId,object: 'invoice',billing_reason: billingReason,+ created: toUnixSeconds(createdAt),customer: stripeCustomerId,// The invoice for a subscription_cycle bills the period it opens, so its// period_start is the instant the previous period closed.