Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage-limit): expose usage limits over the metadata API (#25740)

Etienne1dd8bad5a9d6
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index d2431749c41..222f47c2f87 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -1793,20 +1793,11 @@ type UsageAnalytics {
userDailyUsage: UsageUserDaily
}
-type UsageLimit {
- id: UUID!
+type UsageQuotaDefinition {
resourceType: UsageResourceType!
- operationType: UsageOperationType!
- spenderType: String!
- spenderId: String
- limitKind: String!
- periodCount: Int!
- periodUnit: String!
- meter: String!
- limitValue: BigInt!
- burstValue: BigInt
- createdAt: DateTime!
- updatedAt: DateTime!
+ allowedOperationTypes: [UsageOperationType!]!
+ allowedSpenderTypes: [String!]!
+ allowedMeters: [String!]!
}
enum UsageResourceType {
@@ -1834,11 +1825,56 @@ enum UsageOperationType {
SUBSCRIPTION
}
+type UsageQuotaDefinitions {
+ definitions: [UsageQuotaDefinition!]!
+ isIntraWorkspaceLimitEntitled: Boolean!
+ hasAllowancePeriod: Boolean!
+}
+
+type UsageQuotaWithConsumption {
+ id: UUID!
+ resourceType: UsageResourceType!
+ operationType: UsageOperationType!
+ spenderType: String!
+ spenderId: String
+ spenderLabel: String
+ periodUnit: String!
+ meter: String!
+ limitValue: BigInt!
+ isEnforced: Boolean!
+ consumedValue: BigInt
+ remainingValue: BigInt
+ periodStart: DateTime
+ periodEnd: DateTime
+}
+
"""
The `BigInt` scalar type represents non-fractional signed whole numeric values.
"""
scalar BigInt
+type UsageQuotaScopeConsumption {
+ consumedValue: BigInt
+ periodStart: DateTime!
+ periodEnd: DateTime!
+}
+
+type UsageLimit {
+ id: UUID!
+ resourceType: UsageResourceType!
+ operationType: UsageOperationType!
+ spenderType: String!
+ spenderId: String
+ limitKind: String!
+ periodCount: Int!
+ periodUnit: String!
+ meter: String!
+ limitValue: BigInt!
+ burstValue: BigInt
+ createdAt: DateTime!
+ updatedAt: DateTime!
+}
+
type ApprovedAccessDomain {
id: UUID!
domain: String!
@@ -3580,6 +3616,9 @@ type Query {
enterpriseSubscriptionStatus: EnterpriseSubscriptionStatusDTO
getUsageAnalytics(input: UsageAnalyticsInput): UsageAnalytics!
usageLimits: [UsageLimit!]!
+ usageQuotasWithConsumption: [UsageQuotaWithConsumption!]!
+ usageQuotaDefinitions: UsageQuotaDefinitions!
+ usageQuotaScopeConsumption(input: UsageQuotaScopeInput!): UsageQuotaScopeConsumption
getViewFilterGroups(viewId: String): [ViewFilterGroup!]!
getViewFilterGroup(id: String!): ViewFilterGroup
getViewFilters(viewId: String): [ViewFilter!]!
@@ -3723,6 +3762,15 @@ input UsageAnalyticsInput {
operationTypes: [UsageOperationType!]
}
+input UsageQuotaScopeInput {
+ resourceType: UsageResourceType!
+ operationType: UsageOperationType!
+ spenderType: String!
+ spenderId: String
+ periodUnit: String!
+ meter: String!
+}
+
input GetApiKeyInput {
id: UUID!
}
@@ -3836,7 +3884,8 @@ type Mutation {
uploadWorkspaceLogo(file: Upload!): FileWithSignedUrl!
uploadWorkspaceMemberProfilePicture(file: Upload!): FileWithSignedUrl!
uploadFilesFieldFileByUniversalIdentifier(file: Upload!, fieldMetadataUniversalIdentifier: String!): FileWithSignedUrl!
- upsertUsageLimit(input: UpsertUsageLimitInput!): UsageLimit!
+ createUsageLimit(input: CreateUsageLimitInput!): UsageLimit!
+ updateUsageLimit(input: UpdateUsageLimitInput!): UsageLimit!
deleteUsageLimit(usageLimitId: UUID!): Boolean!
createViewFilterGroup(input: CreateViewFilterGroupInput!): ViewFilterGroup!
updateViewFilterGroup(id: String!, input: UpdateViewFilterGroupInput!): ViewFilterGroup!
@@ -4121,7 +4170,7 @@ input UpdateNavigationMenuItemInput {
"""The `Upload` scalar type represents a file upload."""
scalar Upload
-input UpsertUsageLimitInput {
+input CreateUsageLimitInput {
resourceType: UsageResourceType!
operationType: UsageOperationType!
spenderType: String!
@@ -4134,6 +4183,11 @@ input UpsertUsageLimitInput {
burstValue: BigInt
}
+input UpdateUsageLimitInput {
+ id: UUID!
+ payload: CreateUsageLimitInput!
+}
+
input CreateViewFilterGroupInput {
id: UUID
parentViewFilterGroupId: UUID
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 0d4914f5a33..fa36c2be56a 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1432,6 +1432,50 @@ export interface UsageAnalytics {
__typename: 'UsageAnalytics'
}
+export interface UsageQuotaDefinition {
+ resourceType: UsageResourceType
+ allowedOperationTypes: UsageOperationType[]
+ allowedSpenderTypes: Scalars['String'][]
+ allowedMeters: Scalars['String'][]
+ __typename: 'UsageQuotaDefinition'
+}
+
+export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL' | 'WEBHOOK'
+
+export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'WEBHOOK_CALL' | 'SUBSCRIPTION'
+
+export interface UsageQuotaDefinitions {
+ definitions: UsageQuotaDefinition[]
+ isIntraWorkspaceLimitEntitled: Scalars['Boolean']
+ hasAllowancePeriod: Scalars['Boolean']
+ __typename: 'UsageQuotaDefinitions'
+}
+
+export interface UsageQuotaWithConsumption {
+ id: Scalars['UUID']
+ resourceType: UsageResourceType
+ operationType: UsageOperationType
+ spenderType: Scalars['String']
+ spenderId?: Scalars['String']
+ spenderLabel?: Scalars['String']
+ periodUnit: Scalars['String']
+ meter: Scalars['String']
+ limitValue: Scalars['BigInt']
+ isEnforced: Scalars['Boolean']
+ consumedValue?: Scalars['BigInt']
+ remainingValue?: Scalars['BigInt']
+ periodStart?: Scalars['DateTime']
+ periodEnd?: Scalars['DateTime']
+ __typename: 'UsageQuotaWithConsumption'
+}
+
+export interface UsageQuotaScopeConsumption {
+ consumedValue?: Scalars['BigInt']
+ periodStart: Scalars['DateTime']
+ periodEnd: Scalars['DateTime']
+ __typename: 'UsageQuotaScopeConsumption'
+}
+
export interface UsageLimit {
id: Scalars['UUID']
resourceType: UsageResourceType
@@ -1449,10 +1493,6 @@ export interface UsageLimit {
__typename: 'UsageLimit'
}
-export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL' | 'WEBHOOK'
-
-export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'WEBHOOK_CALL' | 'SUBSCRIPTION'
-
export interface ApprovedAccessDomain {
id: Scalars['UUID']
domain: Scalars['String']
@@ -3131,6 +3171,9 @@ export interface Query {
enterpriseSubscriptionStatus?: EnterpriseSubscriptionStatusDTO
getUsageAnalytics: UsageAnalytics
usageLimits: UsageLimit[]
+ usageQuotasWithConsumption: UsageQuotaWithConsumption[]
+ usageQuotaDefinitions: UsageQuotaDefinitions
+ usageQuotaScopeConsumption?: UsageQuotaScopeConsumption
getViewFilterGroups: ViewFilterGroup[]
getViewFilterGroup?: ViewFilterGroup
getViewFilters: ViewFilter[]
@@ -3269,7 +3312,8 @@ export interface Mutation {
uploadWorkspaceLogo: FileWithSignedUrl
uploadWorkspaceMemberProfilePicture: FileWithSignedUrl
uploadFilesFieldFileByUniversalIdentifier: FileWithSignedUrl
- upsertUsageLimit: UsageLimit
+ createUsageLimit: UsageLimit
+ updateUsageLimit: UsageLimit
deleteUsageLimit: Scalars['Boolean']
createViewFilterGroup: ViewFilterGroup
updateViewFilterGroup: ViewFilterGroup
@@ -4989,6 +5033,50 @@ export interface UsageAnalyticsGenqlSelection{
__scalar?: boolean | number
}
+export interface UsageQuotaDefinitionGenqlSelection{
+ resourceType?: boolean | number
+ allowedOperationTypes?: boolean | number
+ allowedSpenderTypes?: boolean | number
+ allowedMeters?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface UsageQuotaDefinitionsGenqlSelection{
+ definitions?: UsageQuotaDefinitionGenqlSelection
+ isIntraWorkspaceLimitEntitled?: boolean | number
+ hasAllowancePeriod?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface UsageQuotaWithConsumptionGenqlSelection{
+ id?: boolean | number
+ resourceType?: boolean | number
+ operationType?: boolean | number
+ spenderType?: boolean | number
+ spenderId?: boolean | number
+ spenderLabel?: boolean | number
+ periodUnit?: boolean | number
+ meter?: boolean | number
+ limitValue?: boolean | number
+ isEnforced?: boolean | number
+ consumedValue?: boolean | number
+ remainingValue?: boolean | number
+ periodStart?: boolean | number
+ periodEnd?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface UsageQuotaScopeConsumptionGenqlSelection{
+ consumedValue?: boolean | number
+ periodStart?: boolean | number
+ periodEnd?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface UsageLimitGenqlSelection{
id?: boolean | number
resourceType?: boolean | number
@@ -6777,6 +6865,9 @@ export interface QueryGenqlSelection{
enterpriseSubscriptionStatus?: EnterpriseSubscriptionStatusDTOGenqlSelection
getUsageAnalytics?: (UsageAnalyticsGenqlSelection & { __args?: {input?: (UsageAnalyticsInput | null)} })
usageLimits?: UsageLimitGenqlSelection
+ usageQuotasWithConsumption?: UsageQuotaWithConsumptionGenqlSelection
+ usageQuotaDefinitions?: UsageQuotaDefinitionsGenqlSelection
+ usageQuotaScopeConsumption?: (UsageQuotaScopeConsumptionGenqlSelection & { __args: {input: UsageQuotaScopeInput} })
getViewFilterGroups?: (ViewFilterGroupGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
getViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {id: Scalars['String']} })
getViewFilters?: (ViewFilterGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
@@ -6911,6 +7002,8 @@ export interface QueryGenqlSelection{
export interface UsageAnalyticsInput {periodStart?: (Scalars['DateTime'] | null),periodEnd?: (Scalars['DateTime'] | null),userWorkspaceId?: (Scalars['String'] | null),operationTypes?: (UsageOperationType[] | null)}
+export interface UsageQuotaScopeInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),periodUnit: Scalars['String'],meter: Scalars['String']}
+
export interface GetApiKeyInput {id: Scalars['UUID']}
export interface AgentIdInput {
@@ -6960,7 +7053,8 @@ export interface MutationGenqlSelection{
uploadWorkspaceLogo?: (FileWithSignedUrlGenqlSelection & { __args: {file: Scalars['Upload']} })
uploadWorkspaceMemberProfilePicture?: (FileWithSignedUrlGenqlSelection & { __args: {file: Scalars['Upload']} })
uploadFilesFieldFileByUniversalIdentifier?: (FileWithSignedUrlGenqlSelection & { __args: {file: Scalars['Upload'], fieldMetadataUniversalIdentifier: Scalars['String']} })
- upsertUsageLimit?: (UsageLimitGenqlSelection & { __args: {input: UpsertUsageLimitInput} })
+ createUsageLimit?: (UsageLimitGenqlSelection & { __args: {input: CreateUsageLimitInput} })
+ updateUsageLimit?: (UsageLimitGenqlSelection & { __args: {input: UpdateUsageLimitInput} })
deleteUsageLimit?: { __args: {usageLimitId: Scalars['UUID']} }
createViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {input: CreateViewFilterGroupInput} })
updateViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {id: Scalars['String'], input: UpdateViewFilterGroupInput} })
@@ -7215,7 +7309,9 @@ update: UpdateNavigationMenuItemInput}
export interface UpdateNavigationMenuItemInput {folderId?: (Scalars['UUID'] | null),position?: (Scalars['Float'] | null),name?: (Scalars['String'] | null),link?: (Scalars['String'] | null),icon?: (Scalars['String'] | null),color?: (Scalars['String'] | null),pageLayoutId?: (Scalars['UUID'] | null)}
-export interface UpsertUsageLimitInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),limitKind: Scalars['String'],periodCount: Scalars['Int'],periodUnit: Scalars['String'],meter: Scalars['String'],limitValue: Scalars['BigInt'],burstValue?: (Scalars['BigInt'] | null)}
+export interface CreateUsageLimitInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),limitKind: Scalars['String'],periodCount: Scalars['Int'],periodUnit: Scalars['String'],meter: Scalars['String'],limitValue: Scalars['BigInt'],burstValue?: (Scalars['BigInt'] | null)}
+
+export interface UpdateUsageLimitInput {id: Scalars['UUID'],payload: CreateUsageLimitInput}
export interface CreateViewFilterGroupInput {id?: (Scalars['UUID'] | null),parentViewFilterGroupId?: (Scalars['UUID'] | null),logicalOperator?: (ViewFilterGroupLogicalOperator | null),positionInViewFilterGroup?: (Scalars['Float'] | null),viewId: Scalars['UUID']}
@@ -8539,6 +8635,38 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
+ const UsageQuotaDefinition_possibleTypes: string[] = ['UsageQuotaDefinition']
+ export const isUsageQuotaDefinition = (obj?: { __typename?: any } | null): obj is UsageQuotaDefinition => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaDefinition"')
+ return UsageQuotaDefinition_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const UsageQuotaDefinitions_possibleTypes: string[] = ['UsageQuotaDefinitions']
+ export const isUsageQuotaDefinitions = (obj?: { __typename?: any } | null): obj is UsageQuotaDefinitions => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaDefinitions"')
+ return UsageQuotaDefinitions_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const UsageQuotaWithConsumption_possibleTypes: string[] = ['UsageQuotaWithConsumption']
+ export const isUsageQuotaWithConsumption = (obj?: { __typename?: any } | null): obj is UsageQuotaWithConsumption => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaWithConsumption"')
+ return UsageQuotaWithConsumption_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const UsageQuotaScopeConsumption_possibleTypes: string[] = ['UsageQuotaScopeConsumption']
+ export const isUsageQuotaScopeConsumption = (obj?: { __typename?: any } | null): obj is UsageQuotaScopeConsumption => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageQuotaScopeConsumption"')
+ return UsageQuotaScopeConsumption_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const UsageLimit_possibleTypes: string[] = ['UsageLimit']
export const isUsageLimit = (obj?: { __typename?: any } | null): obj is UsageLimit => {
if (!obj?.__typename) throw new Error('__typename is missing in "isUsageLimit"')
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 937df831166..ac09542fe09 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -60,49 +60,49 @@ export default {
162,
177,
178,
- 179,
- 187,
- 192,
- 199,
- 200,
- 207,
+ 181,
+ 191,
+ 196,
+ 203,
+ 204,
211,
- 214,
- 225,
- 244,
- 245,
- 247,
- 252,
- 255,
- 264,
- 295,
- 302,
- 310,
- 311,
- 312,
+ 215,
+ 218,
+ 229,
+ 248,
+ 249,
+ 251,
+ 256,
+ 259,
+ 268,
+ 299,
+ 306,
314,
315,
316,
- 317,
318,
319,
320,
- 328,
- 329,
+ 321,
+ 322,
+ 323,
+ 324,
332,
- 369,
- 376,
- 378,
- 379,
+ 333,
+ 336,
+ 373,
380,
- 381,
+ 382,
383,
+ 384,
385,
- 390,
- 405,
- 417,
- 534,
- 560
+ 387,
+ 389,
+ 394,
+ 410,
+ 422,
+ 540,
+ 566
],
"types": {
"BillingProductDTO": {
@@ -578,7 +578,7 @@ export default {
1
],
"fields": [
- 259,
+ 263,
{
"paging": [
27,
@@ -591,7 +591,7 @@ export default {
}
],
"indexMetadatas": [
- 260,
+ 264,
{
"paging": [
27,
@@ -604,13 +604,13 @@ export default {
}
],
"fieldsList": [
- 246
+ 250
],
"indexMetadataList": [
- 254
+ 258
],
"searchFieldMetadataList": [
- 262
+ 266
],
"__typename": [
1
@@ -1647,7 +1647,7 @@ export default {
49
],
"featureFlags": [
- 191
+ 195
],
"billingSubscriptions": [
145
@@ -1662,7 +1662,7 @@ export default {
144
],
"billingEntitlements": [
- 263
+ 267
],
"hasValidSignedEnterpriseKey": [
8
@@ -1671,7 +1671,7 @@ export default {
8
],
"workspaceUrls": [
- 193
+ 197
],
"workspaceCustomApplicationId": [
1
@@ -1745,7 +1745,7 @@ export default {
35
],
"deletedWorkspaceMembers": [
- 235
+ 239
],
"hasPassword": [
8
@@ -1760,7 +1760,7 @@ export default {
51
],
"availableWorkspaces": [
- 234
+ 238
],
"__typename": [
1
@@ -3446,6 +3446,101 @@ export default {
1
]
},
+ "UsageQuotaDefinition": {
+ "resourceType": [
+ 177
+ ],
+ "allowedOperationTypes": [
+ 178
+ ],
+ "allowedSpenderTypes": [
+ 1
+ ],
+ "allowedMeters": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageResourceType": {},
+ "UsageOperationType": {},
+ "UsageQuotaDefinitions": {
+ "definitions": [
+ 176
+ ],
+ "isIntraWorkspaceLimitEntitled": [
+ 8
+ ],
+ "hasAllowancePeriod": [
+ 8
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageQuotaWithConsumption": {
+ "id": [
+ 3
+ ],
+ "resourceType": [
+ 177
+ ],
+ "operationType": [
+ 178
+ ],
+ "spenderType": [
+ 1
+ ],
+ "spenderId": [
+ 1
+ ],
+ "spenderLabel": [
+ 1
+ ],
+ "periodUnit": [
+ 1
+ ],
+ "meter": [
+ 1
+ ],
+ "limitValue": [
+ 181
+ ],
+ "isEnforced": [
+ 8
+ ],
+ "consumedValue": [
+ 181
+ ],
+ "remainingValue": [
+ 181
+ ],
+ "periodStart": [
+ 4
+ ],
+ "periodEnd": [
+ 4
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "BigInt": {},
+ "UsageQuotaScopeConsumption": {
+ "consumedValue": [
+ 181
+ ],
+ "periodStart": [
+ 4
+ ],
+ "periodEnd": [
+ 4
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"UsageLimit": {
"id": [
3
@@ -3475,10 +3570,10 @@ export default {
1
],
"limitValue": [
- 179
+ 181
],
"burstValue": [
- 179
+ 181
],
"createdAt": [
4
@@ -3490,9 +3585,6 @@ export default {
1
]
},
- "UsageResourceType": {},
- "UsageOperationType": {},
- "BigInt": {},
"ApprovedAccessDomain": {
"id": [
3
@@ -3565,7 +3657,7 @@ export default {
1
],
"result": [
- 184
+ 188
],
"__typename": [
1
@@ -3582,7 +3674,7 @@ export default {
1
],
"connectionSecurity": [
- 187
+ 191
],
"__typename": [
1
@@ -3591,13 +3683,13 @@ export default {
"EmailConnectionSecurity": {},
"PublicImapSmtpCaldavConnectionParameters": {
"IMAP": [
- 186
+ 190
],
"SMTP": [
- 186
+ 190
],
"CALDAV": [
- 186
+ 190
],
"__typename": [
1
@@ -3656,7 +3748,7 @@ export default {
4
],
"connectionParameters": [
- 188
+ 192
],
"__typename": [
1
@@ -3715,7 +3807,7 @@ export default {
4
],
"connectionParameters": [
- 188
+ 192
],
"isOwnedByCurrentUser": [
8
@@ -3726,7 +3818,7 @@ export default {
},
"FeatureFlag": {
"key": [
- 192
+ 196
],
"value": [
8
@@ -3810,7 +3902,7 @@ export default {
1
],
"versionDistribution": [
- 195
+ 199
],
"__typename": [
1
@@ -3835,10 +3927,10 @@ export default {
1
],
"type": [
- 199
+ 203
],
"status": [
- 200
+ 204
],
"issuer": [
1
@@ -3851,7 +3943,7 @@ export default {
"SSOIdentityProviderStatus": {},
"AuthProviders": {
"sso": [
- 198
+ 202
],
"google": [
8
@@ -3888,10 +3980,10 @@ export default {
3
],
"authProviders": [
- 201
+ 205
],
"authBypassProviders": [
- 202
+ 206
],
"logo": [
1
@@ -3900,7 +3992,7 @@ export default {
1
],
"workspaceUrls": [
- 193
+ 197
],
"__typename": [
1
@@ -3939,7 +4031,7 @@ export default {
1
],
"modelFamily": [
- 207
+ 211
],
"modelFamilyLabel": [
1
@@ -3954,7 +4046,7 @@ export default {
15
],
"nativeCapabilities": [
- 205
+ 209
],
"isDeprecated": [
8
@@ -4019,7 +4111,7 @@ export default {
1
],
"trialPeriods": [
- 197
+ 201
],
"__typename": [
1
@@ -4027,7 +4119,7 @@ export default {
},
"Support": {
"supportDriver": [
- 211
+ 215
],
"supportFrontChatId": [
1
@@ -4056,7 +4148,7 @@ export default {
},
"Captcha": {
"provider": [
- 214
+ 218
],
"siteKey": [
1
@@ -4093,10 +4185,10 @@ export default {
},
"PublicFeatureFlag": {
"key": [
- 192
+ 196
],
"metadata": [
- 216
+ 220
],
"__typename": [
1
@@ -4121,16 +4213,16 @@ export default {
1
],
"authProviders": [
- 201
+ 205
],
"billing": [
- 209
+ 213
],
"aiModels": [
- 206
+ 210
],
"aiModelTiers": [
- 208
+ 212
],
"signInPrefilled": [
8
@@ -4154,25 +4246,25 @@ export default {
8
],
"support": [
- 210
+ 214
],
"isAttachmentPreviewEnabled": [
8
],
"sentry": [
- 212
+ 216
],
"captcha": [
- 213
+ 217
],
"api": [
- 215
+ 219
],
"canManageFeatureFlags": [
8
],
"publicFeatureFlags": [
- 217
+ 221
],
"isCookieSessionEnabled": [
8
@@ -4226,7 +4318,7 @@ export default {
1
],
"maintenance": [
- 218
+ 222
],
"__typename": [
1
@@ -4302,7 +4394,7 @@ export default {
},
"AppConnection": {
"id": [
- 225
+ 229
],
"providerName": [
1
@@ -4360,7 +4452,7 @@ export default {
3
],
"type": [
- 199
+ 203
],
"issuer": [
1
@@ -4369,7 +4461,7 @@ export default {
1
],
"status": [
- 200
+ 204
],
"__typename": [
1
@@ -4388,7 +4480,7 @@ export default {
},
"FindAvailableSSOIDP": {
"type": [
- 199
+ 203
],
"id": [
3
@@ -4400,10 +4492,10 @@ export default {
1
],
"status": [
- 200
+ 204
],
"workspace": [
- 229
+ 233
],
"__typename": [
1
@@ -4414,7 +4506,7 @@ export default {
3
],
"type": [
- 199
+ 203
],
"issuer": [
1
@@ -4423,7 +4515,7 @@ export default {
1
],
"status": [
- 200
+ 204
],
"__typename": [
1
@@ -4431,7 +4523,7 @@ export default {
},
"SSOConnection": {
"type": [
- 199
+ 203
],
"id": [
3
@@ -4443,7 +4535,7 @@ export default {
1
],
"status": [
- 200
+ 204
],
"__typename": [
1
@@ -4466,13 +4558,13 @@ export default {
1
],
"workspaceUrls": [
- 193
+ 197
],
"logo": [
1
],
"sso": [
- 232
+ 236
],
"__typename": [
1
@@ -4480,10 +4572,10 @@ export default {
},
"AvailableWorkspaces": {
"availableWorkspacesForSignIn": [
- 233
+ 237
],
"availableWorkspacesForSignUp": [
- 233
+ 237
],
"__typename": [
1
@@ -4616,10 +4708,10 @@ export default {
1
],
"objectPermissions": [
- 237
+ 241
],
"fieldPermissions": [
- 238
+ 242
],
"__typename": [
1
@@ -4690,7 +4782,7 @@ export default {
1
],
"roles": [
- 239
+ 243
],
"manifest": [
9
@@ -4717,13 +4809,13 @@ export default {
},
"WorkspaceCompanyEnrichmentResult": {
"outcome": [
- 244
+ 248
],
"enrichment": [
9
],
"personOutcome": [
- 245
+ 249
],
"personEnrichment": [
9
@@ -4745,7 +4837,7 @@ export default {
1
],
"type": [
- 247
+ 251
],
"name": [
1
@@ -4817,10 +4909,10 @@ export default {
23
],
"relation": [
- 251
+ 255
],
"morphRelations": [
- 251
+ 255
],
"__typename": [
1
@@ -4846,7 +4938,7 @@ export default {
},
"FieldEdge": {
"node": [
- 246
+ 250
],
"cursor": [
29
@@ -4857,10 +4949,10 @@ export default {
},
"FieldConnection": {
"pageInfo": [
- 248
+ 252
],
"edges": [
- 249
+ 253
],
"__typename": [
1
@@ -4868,7 +4960,7 @@ export default {
},
"Relation": {
"type": [
- 252
+ 256
],
"sourceObjectMetadata": [
23
@@ -4877,10 +4969,10 @@ export default {
23
],
"sourceFieldMetadata": [
- 246
+ 250
],
"targetFieldMetadata": [
- 246
+ 250
],
"__typename": [
1
@@ -4927,7 +5019,7 @@ export default {
1
],
"indexType": [
- 255
+ 259
],
"createdAt": [
4
@@ -4936,7 +5028,7 @@ export default {
4
],
"indexFieldMetadataList": [
- 253
+ 257
],
"__typename": [
1
@@ -4945,7 +5037,7 @@ export default {
"IndexType": {},
"IndexEdge": {
"node": [
- 254
+ 258
],
"cursor": [
29
@@ -4967,10 +5059,10 @@ export default {
},
"ObjectConnection": {
"pageInfo": [
- 248
+ 252
],
"edges": [
- 257
+ 261
],
"__typename": [
1
@@ -4978,10 +5070,10 @@ export default {
},
"ObjectFieldsConnection": {
"pageInfo": [
- 248
+ 252
],
"edges": [
- 249
+ 253
],
"__typename": [
1
@@ -4989,10 +5081,10 @@ export default {
},
"ObjectIndexMetadatasConnection": {
"pageInfo": [
- 248
+ 252
],
"edges": [
- 256
+ 260
],
"__typename": [
1
@@ -5034,7 +5126,7 @@ export default {
},
"BillingEntitlement": {
"key": [
- 264
+ 268
],
"value": [
8
@@ -5072,7 +5164,7 @@ export default {
1
],
"records": [
- 265
+ 269
],
"isCustomDomainEnabled": [
8
@@ -5145,10 +5237,10 @@ export default {
},
"AvailableWorkspacesAndAccessTokens": {
"tokens": [
- 273
+ 277
],
"availableWorkspaces": [
- 234
+ 238
],
"__typename": [
1
@@ -5186,7 +5278,7 @@ export default {
},
"WorkspaceUrlsAndId": {
"workspaceUrls": [
- 193
+ 197
],
"id": [
3
@@ -5200,7 +5292,7 @@ export default {
11
],
"workspace": [
- 278
+ 282
],
"__typename": [
1
@@ -5233,7 +5325,7 @@ export default {
11
],
"workspaceUrls": [
- 193
+ 197
],
"__typename": [
1
@@ -5277,7 +5369,7 @@ export default {
},
"AuthTokens": {
"tokens": [
- 273
+ 277
],
"__typename": [
1
@@ -5318,7 +5410,7 @@ export default {
11
],
"workspace": [
- 278
+ 282
],
"__typename": [
1
@@ -5386,7 +5478,7 @@ export default {
1
],
"status": [
- 295
+ 299
],
"reason": [
1
@@ -5412,16 +5504,16 @@ export default {
},
"ApplicationExport": {
"application": [
- 293
+ 297
],
"manifest": [
9
],
"coverage": [
- 294
+ 298
],
"files": [
- 296
+ 300
],
"__typename": [
1
@@ -5457,10 +5549,10 @@ export default {
},
"CompleteApplicationFileUploadsResult": {
"files": [
- 298
+ 302
],
"errors": [
- 299
+ 303
],
"__typename": [
1
@@ -5471,7 +5563,7 @@ export default {
3
],
"fileFolder": [
- 302
+ 306
],
"filePath": [
1
@@ -5492,7 +5584,7 @@ export default {
"FileFolder": {},
"ApplicationFileUploadError": {
"fileFolder": [
- 302
+ 306
],
"filePath": [
1
@@ -5506,10 +5598,10 @@ export default {
},
"CreateApplicationFileUploadsResult": {
"targets": [
- 301
+ 305
],
"errors": [
- 303
+ 307
],
"__typename": [
1
@@ -5591,16 +5683,16 @@ export default {
1
],
"status": [
- 310
+ 314
],
"tenantStatus": [
- 311
+ 315
],
"unsubscribeHostnameStatus": [
- 312
+ 316
],
"verificationRecords": [
- 308
+ 312
],
"verifiedAt": [
4
@@ -5617,7 +5709,7 @@ export default {
3
],
"visibility": [
- 314
+ 318
],
"handle": [
1
@@ -5626,16 +5718,16 @@ export default {
1
],
"type": [
- 315
+ 319
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 316
+ 320
],
"messageFolderImportPolicy": [
- 317
+ 321
],
"excludeNonProfessionalEmails": [
8
@@ -5644,7 +5736,7 @@ export default {
8
],
"pendingGroupEmailsAction": [
- 318
+ 322
],
"isSyncEnabled": [
8
@@ -5653,10 +5745,10 @@ export default {
4
],
"syncStatus": [
- 319
+ 323
],
"syncStage": [
- 320
+ 324
],
"syncStageStartedAt": [
4
@@ -5677,7 +5769,7 @@ export default {
4
],
"connectedAccount": [
- 189
+ 193
],
"__typename": [
1
@@ -5692,7 +5784,7 @@ export default {
"MessageChannelSyncStage": {},
"CreateEmailGroupChannelOutput": {
"messageChannel": [
- 313
+ 317
],
"forwardingAddress": [
1
@@ -5757,7 +5849,7 @@ export default {
28
],
"audience": [
- 322
+ 326
],
"__typename": [
1
@@ -5800,10 +5892,10 @@ export default {
1
],
"reason": [
- 328
+ 332
],
"source": [
- 329
+ 333
],
"unsubscribeTopicId": [
3
@@ -5816,7 +5908,7 @@ export default {
"MessageSuppressionSource": {},
"MessageSuppressionList": {
"records": [
- 327
+ 331
],
"totalCount": [
28
@@ -5842,7 +5934,7 @@ export default {
1
],
"visibility": [
- 332
+ 336
],
"__typename": [
1
@@ -5888,7 +5980,7 @@ export default {
1
],
"location": [
- 334
+ 338
],
"__typename": [
1
@@ -5905,7 +5997,7 @@ export default {
1
],
"connectionSecurity": [
- 187
+ 191
],
"__typename": [
1
@@ -5916,13 +6008,13 @@ export default {
1
],
"IMAP": [
- 336
+ 340
],
"SMTP": [
- 336
+ 340
],
"CALDAV": [
- 336
+ 340
],
"__typename": [
1
@@ -5942,7 +6034,7 @@ export default {
3
],
"connectionParameters": [
- 337
+ 341
],
"__typename": [
1
@@ -6167,7 +6259,7 @@ export default {
1
],
"series": [
- 346
+ 350
],
"xAxisLabel": [
1
@@ -6216,7 +6308,7 @@ export default {
1
],
"data": [
- 348
+ 352
],
"__typename": [
1
@@ -6224,7 +6316,7 @@ export default {
},
"LineChartData": {
"series": [
- 349
+ 353
],
"xAxisLabel": [
1
@@ -6261,7 +6353,7 @@ export default {
},
"PieChartData": {
"data": [
- 351
+ 355
],
"showLegend": [
8
@@ -6366,13 +6458,13 @@ export default {
},
"EventLogQueryResult": {
"records": [
- 356
+ 360
],
"totalCount": [
28
],
"pageInfo": [
- 357
+ 361
],
"__typename": [
1
@@ -6439,7 +6531,7 @@ export default {
1
],
"parts": [
- 342
+ 346
],
"processedAt": [
4
@@ -6453,7 +6545,7 @@ export default {
},
"AgentChatThread": {
"id": [
- 225
+ 229
],
"title": [
1
@@ -6508,7 +6600,7 @@ export default {
},
"AiSystemPromptPreview": {
"sections": [
- 362
+ 366
],
"estimatedTokenCount": [
28
@@ -6536,7 +6628,7 @@ export default {
28
],
"error": [
- 364
+ 368
],
"__typename": [
1
@@ -6569,10 +6661,10 @@ export default {
},
"StartWorkspaceSetupChatResult": {
"outcome": [
- 369
+ 373
],
"thread": [
- 361
+ 365
],
"__typename": [
1
@@ -6610,10 +6702,10 @@ export default {
3
],
"evaluations": [
- 370
+ 374
],
"messages": [
- 360
+ 364
],
"createdAt": [
4
@@ -6675,7 +6767,7 @@ export default {
9
],
"scope": [
- 376
+ 380
],
"__typename": [
1
@@ -6690,19 +6782,19 @@ export default {
1
],
"syncStatus": [
- 378
+ 382
],
"syncStage": [
- 379
+ 383
],
"visibility": [
- 380
+ 384
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 381
+ 385
],
"isSyncEnabled": [
8
@@ -6753,7 +6845,7 @@ export default {
1
],
"pendingSyncAction": [
- 383
+ 387
],
"messageChannelId": [
3
@@ -6795,7 +6887,7 @@ export default {
1
],
"provenance": [
- 385
+ 389
],
"__typename": [
1
@@ -6824,7 +6916,7 @@ export default {
3
],
"through": [
- 386
+ 390
],
"__typename": [
1
@@ -6844,7 +6936,7 @@ export default {
1
],
"emit": [
- 387
+ 391
],
"action": [
1
@@ -6879,7 +6971,7 @@ export default {
},
"CollectionHash": {
"collectionName": [
- 390
+ 394
],
"hash": [
1
@@ -6943,13 +7035,13 @@ export default {
},
"MinimalMetadata": {
"objectMetadataItems": [
- 391
+ 395
],
"views": [
- 392
+ 396
],
"collectionHashes": [
- 389
+ 393
],
"__typename": [
1
@@ -7009,12 +7101,27 @@ export default {
175,
{
"input": [
- 395
+ 399
]
}
],
"usageLimits": [
- 176
+ 183
+ ],
+ "usageQuotasWithConsumption": [
+ 180
+ ],
+ "usageQuotaDefinitions": [
+ 179
+ ],
+ "usageQuotaScopeConsumption": [
+ 182,
+ {
+ "input": [
+ 400,
+ "UsageQuotaScopeInput!"
+ ]
+ }
],
"getViewFilterGroups": [
55,
@@ -7134,7 +7241,7 @@ export default {
2,
{
"input": [
- 396,
+ 401,
"GetApiKeyInput!"
]
}
@@ -7143,10 +7250,10 @@ export default {
165
],
"myConnectedAccounts": [
- 189
+ 193
],
"applicationConnectedAccounts": [
- 190,
+ 194,
{
"applicationId": [
3,
@@ -7181,13 +7288,13 @@ export default {
167
],
"getInviteSuggestions": [
- 181
+ 185
],
"findWorkspaceInvitations": [
- 184
+ 188
],
"getApprovedAccessDomains": [
- 180
+ 184
],
"getPageLayoutTabs": [
125,
@@ -7252,20 +7359,20 @@ export default {
10,
{
"input": [
- 397,
+ 402,
"AgentIdInput!"
]
}
],
"objects": [
- 258,
+ 262,
{
"paging": [
27,
"CursorPaging!"
],
"filter": [
- 398,
+ 403,
"ObjectFilter!"
]
}
@@ -7280,7 +7387,7 @@ export default {
}
],
"objectRecordCounts": [
- 261
+ 265
],
"mostlyEmptyFieldMetadataIds": [
3,
@@ -7295,7 +7402,7 @@ export default {
21,
{
"input": [
- 399,
+ 404,
"LogicFunctionIdInput!"
]
}
@@ -7307,7 +7414,7 @@ export default {
9,
{
"input": [
- 399,
+ 404,
"LogicFunctionIdInput!"
]
}
@@ -7316,7 +7423,7 @@ export default {
1,
{
"input": [
- 399,
+ 404,
"LogicFunctionIdInput!"
]
}
@@ -7349,7 +7456,7 @@ export default {
69
],
"getPublicWorkspaceDataByDomain": [
- 203,
+ 207,
{
"origin": [
1
@@ -7357,7 +7464,7 @@ export default {
}
],
"getPublicWorkspaceDataById": [
- 204,
+ 208,
{
"id": [
3,
@@ -7366,7 +7473,7 @@ export default {
}
],
"findApplicationRegistrationByClientId": [
- 222,
+ 226,
{
"clientId": [
1,
@@ -7396,7 +7503,7 @@ export default {
}
],
"findApplicationRegistrationStats": [
- 196,
+ 200,
{
"id": [
1,
@@ -7405,7 +7512,7 @@ export default {
}
],
"findApplicationRegistrationVariables": [
- 194,
+ 198,
{
"applicationRegistrationId": [
1,
@@ -7423,7 +7530,7 @@ export default {
}
],
"findClaimableApplicationRegistration": [
- 220,
+ 224,
{
"sourcePackage": [
1
@@ -7475,7 +7582,7 @@ export default {
}
],
"findManyMarketplaceApps": [
- 236,
+ 240,
{
"universalIdentifiers": [
1,
@@ -7484,7 +7591,7 @@ export default {
}
],
"findMarketplaceAppDetail": [
- 240,
+ 244,
{
"universalIdentifier": [
1,
@@ -7493,7 +7600,7 @@ export default {
}
],
"publicMarketplaceApps": [
- 236,
+ 240,
{
"isVetted": [
8,
@@ -7502,7 +7609,7 @@ export default {
}
],
"publicMarketplaceAppDetail": [
- 240,
+ 244,
{
"universalIdentifier": [
1,
@@ -7511,7 +7618,7 @@ export default {
}
],
"fields": [
- 250,
+ 254,
{
"paging": [
27,
@@ -7524,7 +7631,7 @@ export default {
}
],
"field": [
- 246,
+ 250,
{
"id": [
3,
@@ -7553,28 +7660,28 @@ export default {
48
],
"previewMessageCampaignAudience": [
- 322,
+ 326,
{
"input": [
- 400,
+ 405,
"PreviewMessageCampaignAudienceInput!"
]
}
],
"messageSuppressions": [
- 330,
+ 334,
{
"input": [
- 401,
+ 406,
"FindMessageSuppressionsInput!"
]
}
],
"unsubscribeTopics": [
- 331
+ 335
],
"myMessageChannels": [
- 313,
+ 317,
{
"connectedAccountId": [
3
@@ -7582,10 +7689,10 @@ export default {
}
],
"getEmailingDomains": [
- 309
+ 313
],
"getToolIndex": [
- 341
+ 345
],
"getToolInputSchema": [
9,
@@ -7597,10 +7704,10 @@ export default {
}
],
"webhooks": [
- 340
+ 344
],
"webhook": [
- 340,
+ 344,
{
"id": [
3,
@@ -7609,7 +7716,7 @@ export default {
}
],
"myMessageFolders": [
- 382,
+ 386,
{
"messageChannelId": [
3
@@ -7617,7 +7724,7 @@ export default {
}
],
"myCalendarChannels": [
- 377,
+ 381,
{
"connectedAccountId": [
3
@@ -7625,17 +7732,17 @@ export default {
}
],
"minimalMetadata": [
- 393
+ 397
],
"appKeyValue": [
- 375,
+ 379,
{
"key": [
1,
"String!"
],
"scope": [
- 376
+ 380
]
}
],
@@ -7649,30 +7756,30 @@ export default {
}
],
"appConnections": [
- 224,
+ 228,
{
"filter": [
- 402
+ 407
]
}
],
"appConnection": [
- 224,
+ 228,
{
"id": [
- 225,
+ 229,
"ID!"
]
}
],
"findWorkspaceAiStats": [
- 372
+ 376
],
"chatThreads": [
- 361
+ 365
],
"chatThread": [
- 361,
+ 365,
{
"id": [
3,
@@ -7681,7 +7788,7 @@ export default {
}
],
"chatMessages": [
- 360,
+ 364,
{
"threadId": [
3,
@@ -7690,7 +7797,7 @@ export default {
}
],
"chatStreamCatchupChunks": [
- 365,
+ 369,
{
"threadId": [
3,
@@ -7699,13 +7806,13 @@ export default {
}
],
"getAiSystemPromptPreview": [
- 363
+ 367
],
"skills": [
- 359
+ 363
],
"skill": [
- 359,
+ 363,
{
"id": [
3,
@@ -7714,7 +7821,7 @@ export default {
}
],
"agentTurns": [
- 371,
+ 375,
{
"agentId": [
3,
@@ -7723,19 +7830,19 @@ export default {
}
],
"timelineActivityTypes": [
- 388
+ 392
],
"metadataTranslations": [
- 384,
+ 388,
{
"input": [
- 403,
+ 408,
"MetadataTranslationsInput!"
]
}
],
"checkUserExists": [
- 288,
+ 292,
{
"email": [
1,
@@ -7747,7 +7854,7 @@ export default {
}
],
"checkWorkspaceInviteHashIsValid": [
- 289,
+ 293,
{
"inviteHash": [
1,
@@ -7765,7 +7872,7 @@ export default {
}
],
"checkWorkspaceSubdomainAvailability": [
- 283,
+ 287,
{
"subdomain": [
1,
@@ -7774,10 +7881,10 @@ export default {
}
],
"getWorkspaceCreationDefaults": [
- 284
+ 288
],
"validatePasswordResetToken": [
- 281,
+ 285,
{
"passwordResetToken": [
1,
@@ -7789,40 +7896,40 @@ export default {
73
],
"getSSOIdentityProviders": [
- 230
+ 234
],
"eventLogs": [
- 358,
+ 362,
{
"input": [
- 404,
+ 409,
"EventLogQueryInput!"
]
}
],
"pieChartData": [
- 352,
+ 356,
{
"input": [
- 408,
+ 413,
"PieChartDataInput!"
]
}
],
"lineChartData": [
- 350,
+ 354,
{
"input": [
- 409,
+ 414,
"LineChartDataInput!"
]
}
],
"barChartData": [
- 347,
+ 351,
{
"input": [
- 410,
+ 415,
"BarChartDataInput!"
]
}
@@ -7837,7 +7944,7 @@ export default {
}
],
"getConnectedImapSmtpCaldavAccount": [
- 338,
+ 342,
{
"id": [
3,
@@ -7846,7 +7953,7 @@ export default {
}
],
"getAutoCompleteAddress": [
- 333,
+ 337,
{
"address": [
1,
@@ -7865,7 +7972,7 @@ export default {
}
],
"getAddressDetails": [
- 335,
+ 339,
{
"placeId": [
1,
@@ -7878,10 +7985,10 @@ export default {
}
],
"findManyPublicDomains": [
- 307
+ 311
],
"exportApplication": [
- 297,
+ 301,
{
"universalIdentifier": [
3,
@@ -7890,7 +7997,7 @@ export default {
}
],
"currentUserApplicationAuthorizations": [
- 292
+ 296
],
"__typename": [
1
@@ -7913,6 +8020,29 @@ export default {
1
]
},
+ "UsageQuotaScopeInput": {
+ "resourceType": [
+ 177
+ ],
+ "operationType": [
+ 178
+ ],
+ "spenderType": [
+ 1
+ ],
+ "spenderId": [
+ 1
+ ],
+ "periodUnit": [
+ 1
+ ],
+ "meter": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"GetApiKeyInput": {
"id": [
3
@@ -7931,10 +8061,10 @@ export default {
},
"ObjectFilter": {
"and": [
- 398
+ 403
],
"or": [
- 398
+ 403
],
"id": [
31
@@ -7969,7 +8099,7 @@ export default {
},
"LogicFunctionIdInput": {
"id": [
- 225
+ 229
],
"__typename": [
1
@@ -7988,7 +8118,7 @@ export default {
},
"FindMessageSuppressionsInput": {
"reason": [
- 328
+ 332
],
"searchTerm": [
1
@@ -8036,10 +8166,10 @@ export default {
},
"EventLogQueryInput": {
"table": [
- 405
+ 410
],
"filters": [
- 406
+ 411
],
"first": [
28
@@ -8060,7 +8190,7 @@ export default {
1
],
"dateRange": [
- 407
+ 412
],
"recordId": [
1
@@ -8121,7 +8251,7 @@ export default {
8,
{
"input": [
- 412,
+ 417,
"AddQuerySubscriptionInput!"
]
}
@@ -8130,7 +8260,7 @@ export default {
8,
{
"input": [
- 413,
+ 418,
"RemoveQueryFromEventStreamInput!"
]
}
@@ -8139,7 +8269,7 @@ export default {
154,
{
"inputs": [
- 414,
+ 419,
"[CreateNavigationMenuItemInput!]!"
]
}
@@ -8148,7 +8278,7 @@ export default {
154,
{
"input": [
- 414,
+ 419,
"CreateNavigationMenuItemInput!"
]
}
@@ -8157,7 +8287,7 @@ export default {
154,
{
"inputs": [
- 415,
+ 420,
"[UpdateOneNavigationMenuItemInput!]!"
]
}
@@ -8166,7 +8296,7 @@ export default {
154,
{
"input": [
- 415,
+ 420,
"UpdateOneNavigationMenuItemInput!"
]
}
@@ -8201,7 +8331,7 @@ export default {
"Float!"
],
"fileFolder": [
- 302,
+ 306,
"FileFolder!"
],
"fieldMetadataId": [
@@ -8240,7 +8370,7 @@ export default {
151,
{
"file": [
- 417,
+ 422,
"Upload!"
]
}
@@ -8249,7 +8379,7 @@ export default {
151,
{
"file": [
- 417,
+ 422,
"Upload!"
]
}
@@ -8258,7 +8388,7 @@ export default {
151,
{
"file": [
- 417,
+ 422,
"Upload!"
],
"fieldMetadataUniversalIdentifier": [
@@ -8267,12 +8397,21 @@ export default {
]
}
],
- "upsertUsageLimit": [
- 176,
+ "createUsageLimit": [
+ 183,
{
"input": [
- 418,
- "UpsertUsageLimitInput!"
+ 423,
+ "CreateUsageLimitInput!"
+ ]
+ }
+ ],
+ "updateUsageLimit": [
+ 183,
+ {
+ "input": [
+ 424,
+ "UpdateUsageLimitInput!"
]
}
],
@@ -8289,7 +8428,7 @@ export default {
55,
{
"input": [
- 419,
+ 425,
"CreateViewFilterGroupInput!"
]
}
@@ -8302,7 +8441,7 @@ export default {
"String!"
],
"input": [
- 420,
+ 426,
"UpdateViewFilterGroupInput!"
]
}
@@ -8329,7 +8468,7 @@ export default {
57,
{
"input": [
- 421,
+ 427,
"CreateViewFilterInput!"
]
}
@@ -8338,7 +8477,7 @@ export default {
57,
{
"input": [
- 422,
+ 428,
"UpdateViewFilterInput!"
]
}
@@ -8347,7 +8486,7 @@ export default {
57,
{
"input": [
- 424,
+ 430,
"DeleteViewFilterInput!"
]
}
@@ -8356,7 +8495,7 @@ export default {
57,
{
"input": [
- 425,
+ 431,
"DestroyViewFilterInput!"
]
}
@@ -8365,7 +8504,7 @@ export default {
63,
{
"input": [
- 426,
+ 432,
"CreateViewInput!"
]
}
@@ -8378,7 +8517,7 @@ export default {
"String!"
],
"input": [
- 427,
+ 433,
"UpdateViewInput!"
]
}
@@ -8405,7 +8544,7 @@ export default {
63,
{
"input": [
- 428,
+ 434,
"UpsertViewWidgetInput!"
]
}
@@ -8414,7 +8553,7 @@ export default {
60,
{
"input": [
- 434,
+ 440,
"CreateViewSortInput!"
]
}
@@ -8423,7 +8562,7 @@ export default {
60,
{
"input": [
- 435,
+ 441,
"UpdateViewSortInput!"
]
}
@@ -8432,7 +8571,7 @@ export default {
8,
{
"input": [
- 437,
+ 443,
"DeleteViewSortInput!"
]
}
@@ -8441,7 +8580,7 @@ export default {
8,
{
"input": [
- 438,
+ 444,
"DestroyViewSortInput!"
]
}
@@ -8450,7 +8589,7 @@ export default {
53,
{
"input": [
- 439,
+ 445,
"UpdateViewFieldInput!"
]
}
@@ -8459,7 +8598,7 @@ export default {
53,
{
"input": [
- 441,
+ 447,
"CreateViewFieldInput!"
]
}
@@ -8468,7 +8607,7 @@ export default {
53,
{
"inputs": [
- 441,
+ 447,
"[CreateViewFieldInput!]!"
]
}
@@ -8477,7 +8616,7 @@ export default {
53,
{
"input": [
- 442,
+ 448,
"DeleteViewFieldInput!"
]
}
@@ -8486,7 +8625,7 @@ export default {
53,
{
"input": [
- 443,
+ 449,
"DestroyViewFieldInput!"
]
}
@@ -8495,7 +8634,7 @@ export default {
62,
{
"input": [
- 444,
+ 450,
"UpdateViewFieldGroupInput!"
]
}
@@ -8504,7 +8643,7 @@ export default {
62,
{
"input": [
- 446,
+ 452,
"CreateViewFieldGroupInput!"
]
}
@@ -8513,7 +8652,7 @@ export default {
62,
{
"inputs": [
- 446,
+ 452,
"[CreateViewFieldGroupInput!]!"
]
}
@@ -8522,7 +8661,7 @@ export default {
62,
{
"input": [
- 447,
+ 453,
"DeleteViewFieldGroupInput!"
]
}
@@ -8531,7 +8670,7 @@ export default {
62,
{
"input": [
- 448,
+ 454,
"DestroyViewFieldGroupInput!"
]
}
@@ -8540,7 +8679,7 @@ export default {
63,
{
"input": [
- 449,
+ 455,
"UpsertFieldsWidgetInput!"
]
}
@@ -8549,7 +8688,7 @@ export default {
2,
{
"input": [
- 452,
+ 458,
"CreateApiKeyInput!"
]
}
@@ -8558,7 +8697,7 @@ export default {
2,
{
"input": [
- 453,
+ 459,
"UpdateApiKeyInput!"
]
}
@@ -8567,7 +8706,7 @@ export default {
2,
{
"input": [
- 454,
+ 460,
"RevokeApiKeyInput!"
]
}
@@ -8598,7 +8737,7 @@ export default {
28
],
"deleteConnectedAccount": [
- 189,
+ 193,
{
"id": [
3,
@@ -8698,7 +8837,7 @@ export default {
171
],
"skipSyncEmailOnboardingStep": [
- 183,
+ 187,
{
"isAutoSkipped": [
8,
@@ -8707,7 +8846,7 @@ export default {
}
],
"completeBookCallOnboardingStep": [
- 183,
+ 187,
{
"hasBookedCall": [
8,
@@ -8720,7 +8859,7 @@ export default {
}
],
"triggerInstallAppsOnboardingStep": [
- 183,
+ 187,
{
"universalIdentifiers": [
1,
@@ -8733,7 +8872,7 @@ export default {
}
],
"goBackToPreviousOnboardingStep": [
- 182
+ 186
],
"deleteWorkspaceInvitation": [
1,
@@ -8745,7 +8884,7 @@ export default {
}
],
"resendWorkspaceInvitation": [
- 185,
+ 189,
{
"appTokenId": [
1,
@@ -8754,7 +8893,7 @@ export default {
}
],
"sendInvitations": [
- 185,
+ 189,
{
"emails": [
1,
@@ -8766,10 +8905,10 @@ export default {
}
],
"createApprovedAccessDomain": [
- 180,
+ 184,
{
"input": [
- 455,
+ 461,
"CreateApprovedAccessDomainInput!"
]
}
@@ -8778,16 +8917,16 @@ export default {
8,
{
"input": [
- 456,
+ 462,
"DeleteApprovedAccessDomainInput!"
]
}
],
"validateApprovedAccessDomain": [
- 180,
+ 184,
{
"input": [
- 457,
+ 463,
"ValidateApprovedAccessDomainInput!"
]
}
@@ -8796,7 +8935,7 @@ export default {
125,
{
"input": [
- 458,
+ 464,
"CreatePageLayoutTabInput!"
]
}
@@ -8809,7 +8948,7 @@ export default {
"String!"
],
"input": [
- 459,
+ 465,
"UpdatePageLayoutTabInput!"
]
}
@@ -8827,7 +8966,7 @@ export default {
126,
{
"input": [
- 460,
+ 466,
"CreatePageLayoutInput!"
]
}
@@ -8840,7 +8979,7 @@ export default {
"String!"
],
"input": [
- 461,
+ 467,
"UpdatePageLayoutInput!"
]
}
@@ -8862,7 +9001,7 @@ export default {
"String!"
],
"input": [
- 462,
+ 468,
"UpdatePageLayoutWithTabsInput!"
]
}
@@ -8898,7 +9037,7 @@ export default {
81,
{
"input": [
- 465,
+ 471,
"CreatePageLayoutWidgetInput!"
]
}
@@ -8911,7 +9050,7 @@ export default {
"String!"
],
"input": [
- 466,
+ 472,
"UpdatePageLayoutWidgetInput!"
]
}
@@ -8929,7 +9068,7 @@ export default {
10,
{
"input": [
- 467,
+ 473,
"CreateAgentInput!"
]
}
@@ -8938,7 +9077,7 @@ export default {
10,
{
"input": [
- 468,
+ 474,
"UpdateAgentInput!"
]
}
@@ -8947,7 +9086,7 @@ export default {
10,
{
"input": [
- 397,
+ 402,
"AgentIdInput!"
]
}
@@ -8956,7 +9095,7 @@ export default {
23,
{
"input": [
- 469,
+ 475,
"CreateOneObjectInput!"
]
}
@@ -8965,7 +9104,7 @@ export default {
23,
{
"input": [
- 471,
+ 477,
"DeleteOneObjectInput!"
]
}
@@ -8974,25 +9113,25 @@ export default {
23,
{
"input": [
- 472,
+ 478,
"UpdateOneObjectInput!"
]
}
],
"createOneIndex": [
- 254,
+ 258,
{
"input": [
- 475,
+ 481,
"CreateOneIndexInput!"
]
}
],
"deleteOneIndex": [
- 254,
+ 258,
{
"input": [
- 478,
+ 484,
"DeleteOneIndexInput!"
]
}
@@ -9001,7 +9140,7 @@ export default {
21,
{
"input": [
- 399,
+ 404,
"LogicFunctionIdInput!"
]
}
@@ -9010,7 +9149,7 @@ export default {
21,
{
"input": [
- 479,
+ 485,
"CreateLogicFunctionFromSourceInput!"
]
}
@@ -9019,7 +9158,7 @@ export default {
147,
{
"input": [
- 480,
+ 486,
"ExecuteOneLogicFunctionInput!"
]
}
@@ -9028,7 +9167,7 @@ export default {
8,
{
"input": [
- 481,
+ 487,
"UpdateLogicFunctionFromSourceInput!"
]
}
@@ -9037,7 +9176,7 @@ export default {
14,
{
"input": [
- 483,
+ 489,
"CreateCommandMenuItemInput!"
]
}
@@ -9046,7 +9185,7 @@ export default {
14,
{
"input": [
- 484,
+ 490,
"UpdateCommandMenuItemInput!"
]
}
@@ -9073,7 +9212,7 @@ export default {
13,
{
"input": [
- 485,
+ 491,
"CreateFrontComponentInput!"
]
}
@@ -9082,7 +9221,7 @@ export default {
13,
{
"input": [
- 486,
+ 492,
"UpdateFrontComponentInput!"
]
}
@@ -9100,7 +9239,7 @@ export default {
69,
{
"data": [
- 488,
+ 494,
"ActivateWorkspaceInput!"
]
}
@@ -9109,7 +9248,7 @@ export default {
69,
{
"data": [
- 489,
+ 495,
"UpdateWorkspaceInput!"
]
}
@@ -9118,10 +9257,10 @@ export default {
69
],
"checkCustomDomainValidRecords": [
- 266
+ 270
],
"enrichWorkspaceCompany": [
- 243
+ 247
],
"upgradeApplication": [
8,
@@ -9137,10 +9276,10 @@ export default {
}
],
"createApplicationRegistration": [
- 221,
+ 225,
{
"input": [
- 490,
+ 496,
"CreateApplicationRegistrationInput!"
]
}
@@ -9149,7 +9288,7 @@ export default {
76,
{
"input": [
- 491,
+ 497,
"UpdateApplicationRegistrationInput!"
]
}
@@ -9164,7 +9303,7 @@ export default {
}
],
"rotateApplicationRegistrationClientSecret": [
- 223,
+ 227,
{
"id": [
1,
@@ -9173,19 +9312,19 @@ export default {
}
],
"createApplicationRegistrationVariable": [
- 194,
+ 198,
{
"input": [
- 493,
+ 499,
"CreateApplicationRegistrationVariableInput!"
]
}
],
"updateApplicationRegistrationVariable": [
- 194,
+ 198,
{
"input": [
- 494,
+ 500,
"UpdateApplicationRegistrationVariableInput!"
]
}
@@ -9203,7 +9342,7 @@ export default {
76,
{
"file": [
- 417,
+ 422,
"Upload!"
],
"universalIdentifier": [
@@ -9258,19 +9397,19 @@ export default {
}
],
"triggerInstallApplicationJob": [
- 241,
+ 245,
{
"input": [
- 496,
+ 502,
"TriggerInstallApplicationJobInput!"
]
}
],
"triggerUninstallApplicationJob": [
- 242,
+ 246,
{
"input": [
- 497,
+ 503,
"TriggerUninstallApplicationJobInput!"
]
}
@@ -9283,7 +9422,7 @@ export default {
"UUID!"
],
"input": [
- 498,
+ 504,
"UpdateApplicationInput!"
]
}
@@ -9301,28 +9440,28 @@ export default {
8
],
"createOneField": [
- 246,
+ 250,
{
"input": [
- 499,
+ 505,
"CreateOneFieldMetadataInput!"
]
}
],
"updateOneField": [
- 246,
+ 250,
{
"input": [
- 501,
+ 507,
"UpdateOneFieldMetadataInput!"
]
}
],
"deleteOneField": [
- 246,
+ 250,
{
"input": [
- 503,
+ 509,
"DeleteOneFieldInput!"
]
}
@@ -9331,7 +9470,7 @@ export default {
59,
{
"input": [
- 504,
+ 510,
"CreateViewGroupInput!"
]
}
@@ -9340,7 +9479,7 @@ export default {
59,
{
"inputs": [
- 504,
+ 510,
"[CreateViewGroupInput!]!"
]
}
@@ -9349,7 +9488,7 @@ export default {
59,
{
"input": [
- 505,
+ 511,
"UpdateViewGroupInput!"
]
}
@@ -9358,7 +9497,7 @@ export default {
59,
{
"inputs": [
- 505,
+ 511,
"[UpdateViewGroupInput!]!"
]
}
@@ -9367,7 +9506,7 @@ export default {
59,
{
"input": [
- 507,
+ 513,
"DeleteViewGroupInput!"
]
}
@@ -9376,7 +9515,7 @@ export default {
59,
{
"input": [
- 508,
+ 514,
"DestroyViewGroupInput!"
]
}
@@ -9398,7 +9537,7 @@ export default {
48,
{
"createRoleInput": [
- 509,
+ 515,
"CreateRoleInput!"
]
}
@@ -9407,7 +9546,7 @@ export default {
48,
{
"updateRoleInput": [
- 510,
+ 516,
"UpdateRoleInput!"
]
}
@@ -9425,7 +9564,7 @@ export default {
45,
{
"upsertObjectPermissionsInput": [
- 512,
+ 518,
"UpsertObjectPermissionsInput!"
]
}
@@ -9434,7 +9573,7 @@ export default {
46,
{
"upsertPermissionFlagsInput": [
- 514,
+ 520,
"UpsertPermissionFlagsInput!"
]
}
@@ -9443,16 +9582,16 @@ export default {
40,
{
"upsertFieldPermissionsInput": [
- 515,
+ 521,
"UpsertFieldPermissionsInput!"
]
}
],
"upsertRowLevelPermissionPredicates": [
- 267,
+ 271,
{
"input": [
- 517,
+ 523,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
@@ -9480,43 +9619,43 @@ export default {
}
],
"sendEmailViaEmailingDomain": [
- 324,
+ 328,
{
"input": [
- 520,
+ 526,
"SendEmailViaDomainInput!"
]
}
],
"sendMessageCampaign": [
- 325,
+ 329,
{
"input": [
- 521,
+ 527,
"SendMessageCampaignInput!"
]
}
],
"cancelMessageCampaign": [
- 323,
+ 327,
{
"input": [
- 522,
+ 528,
"CancelMessageCampaignInput!"
]
}
],
"sendMessageCampaignTest": [
- 324,
+ 328,
{
"input": [
- 523,
+ 529,
"SendMessageCampaignTestInput!"
]
}
],
"duplicateMessageList": [
- 326,
+ 330,
{
"id": [
3,
@@ -9525,10 +9664,10 @@ export default {
}
],
"createMessageSuppression": [
- 327,
+ 331,
{
"input": [
- 524,
+ 530,
"CreateMessageSuppressionInput!"
]
}
@@ -9543,19 +9682,19 @@ export default {
}
],
"createUnsubscribeTopic": [
- 331,
+ 335,
{
"input": [
- 525,
+ 531,
"CreateUnsubscribeTopicInput!"
]
}
],
"updateUnsubscribeTopic": [
- 331,
+ 335,
{
"input": [
- 526,
+ 532,
"UpdateUnsubscribeTopicInput!"
]
}
@@ -9570,34 +9709,34 @@ export default {
}
],
"updateMessageChannel": [
- 313,
+ 317,
{
"input": [
- 527,
+ 533,
"UpdateMessageChannelInput!"
]
}
],
"createEmailGroupChannel": [
- 321,
+ 325,
{
"input": [
- 529,
+ 535,
"CreateEmailGroupChannelInput!"
]
}
],
"updateEmailGroupChannel": [
- 313,
+ 317,
{
"input": [
- 530,
+ 536,
"UpdateEmailGroupChannelInput!"
]
}
],
"deleteEmailGroupChannel": [
- 313,
+ 317,
{
"id": [
3,
@@ -9606,10 +9745,10 @@ export default {
}
],
"createEmailingDomain": [
- 309,
+ 313,
{
"input": [
- 531,
+ 537,
"CreateEmailingDomainInput!"
]
}
@@ -9624,7 +9763,7 @@ export default {
}
],
"verifyEmailingDomain": [
- 309,
+ 313,
{
"id": [
1,
@@ -9633,34 +9772,34 @@ export default {
}
],
"runAgent": [
- 343,
+ 347,
{
"input": [
- 532,
+ 538,
"RunAgentInput!"
]
}
],
"createWebhook": [
- 340,
+ 344,
{
"input": [
- 535,
+ 541,
"CreateWebhookInput!"
]
}
],
"updateWebhook": [
- 340,
+ 344,
{
"input": [
- 536,
+ 542,
"UpdateWebhookInput!"
]
}
],
"deleteWebhook": [
- 340,
+ 344,
{
"id": [
3,
@@ -9669,37 +9808,37 @@ export default {
}
],
"updateMessageFolder": [
- 382,
+ 386,
{
"input": [
- 538,
+ 544,
"UpdateMessageFolderInput!"
]
}
],
"updateMessageFolders": [
- 382,
+ 386,
{
"input": [
- 540,
+ 546,
"UpdateMessageFoldersInput!"
]
}
],
"updateCalendarChannel": [
- 377,
+ 381,
{
"input": [
- 541,
+ 547,
"UpdateCalendarChannelInput!"
]
}
],
"setAppKeyValue": [
- 375,
+ 379,
{
"input": [
- 543,
+ 549,
"SetAppKeyValueInput!"
]
}
@@ -9712,24 +9851,24 @@ export default {
"String!"
],
"scope": [
- 376
+ 380
]
}
],
"enqueueJob": [
- 373,
+ 377,
{
"input": [
- 544,
+ 550,
"EnqueueJobInput!"
]
}
],
"enqueueJobs": [
- 374,
+ 378,
{
"input": [
- 545,
+ 551,
"EnqueueJobsInput!"
]
}
@@ -9738,16 +9877,16 @@ export default {
8,
{
"input": [
- 547,
+ 553,
"ReportAppConnectionAuthFailureInput!"
]
}
],
"createChatThread": [
- 361
+ 365
],
"sendChatMessage": [
- 366,
+ 370,
{
"threadId": [
3,
@@ -9768,13 +9907,13 @@ export default {
1
],
"fileAttachments": [
- 548,
+ 554,
"[FileAttachmentInput!]"
]
}
],
"retryChatMessage": [
- 366,
+ 370,
{
"threadId": [
3,
@@ -9786,7 +9925,7 @@ export default {
}
],
"answerAgentChatQuestion": [
- 366,
+ 370,
{
"threadId": [
3,
@@ -9797,14 +9936,14 @@ export default {
"UUID!"
],
"answers": [
- 549,
+ 555,
"[AgentChatQuestionAnswerInput!]!"
],
"modelId": [
1
],
"fileAttachments": [
- 548,
+ 554,
"[FileAttachmentInput!]"
]
}
@@ -9819,7 +9958,7 @@ export default {
}
],
"renameChatThread": [
- 361,
+ 365,
{
"id": [
3,
@@ -9832,7 +9971,7 @@ export default {
}
],
"archiveChatThread": [
- 361,
+ 365,
{
"id": [
3,
@@ -9841,7 +9980,7 @@ export default {
}
],
"unarchiveChatThread": [
- 361,
+ 365,
{
"id": [
3,
@@ -9868,7 +10007,7 @@ export default {
}
],
"startWorkspaceSetupChat": [
- 368,
+ 372,
{
"companyContext": [
9
@@ -9879,25 +10018,25 @@ export default {
}
],
"createSkill": [
- 359,
+ 363,
{
"input": [
- 550,
+ 556,
"CreateSkillInput!"
]
}
],
"updateSkill": [
- 359,
+ 363,
{
"input": [
- 551,
+ 557,
"UpdateSkillInput!"
]
}
],
"deleteSkill": [
- 359,
+ 363,
{
"id": [
3,
@@ -9906,7 +10045,7 @@ export default {
}
],
"activateSkill": [
- 359,
+ 363,
{
"id": [
3,
@@ -9915,7 +10054,7 @@ export default {
}
],
"deactivateSkill": [
- 359,
+ 363,
{
"id": [
3,
@@ -9924,7 +10063,7 @@ export default {
}
],
"evaluateAgentTurn": [
- 370,
+ 374,
{
"turnId": [
3,
@@ -9933,7 +10072,7 @@ export default {
}
],
"runEvaluationInput": [
- 371,
+ 375,
{
"agentId": [
3,
@@ -9946,16 +10085,16 @@ export default {
}
],
"updateTimelineActivityType": [
- 388,
+ 392,
{
"input": [
- 552,
+ 558,
"UpdateTimelineActivityTypeInput!"
]
}
],
"resetTimelineActivityType": [
- 388,
+ 392,
{
"id": [
3,
@@ -9964,16 +10103,16 @@ export default {
}
],
"getAuthorizationUrlForSSO": [
- 276,
+ 280,
{
"input": [
- 553,
+ 559,
"GetAuthorizationUrlForSSOInput!"
]
}
],
"getLoginTokenFromCredentials": [
- 287,
+ 291,
{
"email": [
1,
@@ -9999,7 +10138,7 @@ export default {
}
],
"signIn": [
- 274,
+ 278,
{
"email": [
1,
@@ -10021,7 +10160,7 @@ export default {
}
],
"verifyEmailAndGetLoginToken": [
- 282,
+ 286,
{
"emailVerificationToken": [
1,
@@ -10041,7 +10180,7 @@ export default {
}
],
"verifyEmailAndGetWorkspaceAgnosticToken": [
- 274,
+ 278,
{
"emailVerificationToken": [
1,
@@ -10057,7 +10196,7 @@ export default {
}
],
"getAuthTokensFromOTP": [
- 286,
+ 290,
{
"otp": [
1,
@@ -10077,7 +10216,7 @@ export default {
}
],
"signUp": [
- 274,
+ 278,
{
"email": [
1,
@@ -10099,7 +10238,7 @@ export default {
}
],
"signUpInWorkspace": [
- 279,
+ 283,
{
"email": [
1,
@@ -10130,10 +10269,10 @@ export default {
}
],
"signUpInNewWorkspace": [
- 279,
+ 283,
{
"input": [
- 554
+ 560
]
}
],
@@ -10145,16 +10284,16 @@ export default {
"String!"
],
"file": [
- 417,
+ 422,
"Upload!"
]
}
],
"generateTransientToken": [
- 280
+ 284
],
"getAuthTokensFromLoginToken": [
- 286,
+ 290,
{
"loginToken": [
1,
@@ -10167,7 +10306,7 @@ export default {
}
],
"getAuthTokensFromSSOExchangeToken": [
- 286,
+ 290,
{
"ssoExchangeToken": [
1,
@@ -10176,7 +10315,7 @@ export default {
}
],
"authorizeApp": [
- 272,
+ 276,
{
"clientId": [
1,
@@ -10201,7 +10340,7 @@ export default {
}
],
"renewToken": [
- 286,
+ 290,
{
"appToken": [
1,
@@ -10218,7 +10357,7 @@ export default {
}
],
"generateApiKeyToken": [
- 285,
+ 289,
{
"apiKeyId": [
3,
@@ -10234,7 +10373,7 @@ export default {
11
],
"emailPasswordResetLink": [
- 275,
+ 279,
{
"email": [
1,
@@ -10249,7 +10388,7 @@ export default {
}
],
"updatePasswordViaResetToken": [
- 277,
+ 281,
{
"passwordResetToken": [
1,
@@ -10262,7 +10401,7 @@ export default {
}
],
"initiateOTPProvisioning": [
- 270,
+ 274,
{
"loginToken": [
1,
@@ -10275,10 +10414,10 @@ export default {
}
],
"initiateOTPProvisioningForAuthenticatedUser": [
- 270
+ 274
],
"deleteTwoFactorAuthenticationMethod": [
- 269,
+ 273,
{
"twoFactorAuthenticationMethodId": [
3,
@@ -10287,7 +10426,7 @@ export default {
}
],
"verifyTwoFactorAuthenticationMethodForAuthenticatedUser": [
- 271,
+ 275,
{
"otp": [
1,
@@ -10311,7 +10450,7 @@ export default {
8,
{
"input": [
- 555,
+ 561,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -10329,7 +10468,7 @@ export default {
}
],
"resendEmailVerificationToken": [
- 226,
+ 230,
{
"email": [
1,
@@ -10342,43 +10481,43 @@ export default {
}
],
"createOIDCIdentityProvider": [
- 231,
+ 235,
{
"input": [
- 556,
+ 562,
"SetupOIDCSsoInput!"
]
}
],
"createSAMLIdentityProvider": [
- 231,
+ 235,
{
"input": [
- 557,
+ 563,
"SetupSAMLSsoInput!"
]
}
],
"deleteSSOIdentityProvider": [
- 227,
+ 231,
{
"input": [
- 558,
+ 564,
"DeleteSsoInput!"
]
}
],
"editSSOIdentityProvider": [
- 228,
+ 232,
{
"input": [
- 559,
+ 565,
"EditSsoInput!"
]
}
],
"createObjectEvent": [
- 355,
+ 359,
{
"event": [
1,
@@ -10398,10 +10537,10 @@ export default {
}
],
"trackAnalytics": [
- 355,
+ 359,
{
"type": [
- 560,
+ 566,
"AnalyticsType!"
],
"name": [
@@ -10416,7 +10555,7 @@ export default {
}
],
"duplicateDashboard": [
- 353,
+ 357,
{
"id": [
3,
@@ -10425,7 +10564,7 @@ export default {
}
],
"impersonate": [
- 290,
+ 294,
{
"userId": [
3,
@@ -10438,28 +10577,28 @@ export default {
}
],
"stopImpersonation": [
- 291
+ 295
],
"createCalendarEvent": [
- 345,
+ 349,
{
"input": [
- 561,
+ 567,
"CreateCalendarEventInput!"
]
}
],
"sendEmail": [
- 354,
+ 358,
{
"input": [
- 562,
+ 568,
"SendEmailInput!"
]
}
],
"startChannelSync": [
- 344,
+ 348,
{
"connectedAccountId": [
3,
@@ -10468,14 +10607,14 @@ export default {
}
],
"saveImapSmtpCaldavAccount": [
- 339,
+ 343,
{
"handle": [
1,
"String!"
],
"connectionParameters": [
- 564,
+ 570,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -10484,16 +10623,16 @@ export default {
}
],
"updateLabPublicFeatureFlag": [
- 191,
+ 195,
{
"input": [
- 566,
+ 572,
"UpdateLabPublicFeatureFlagInput!"
]
}
],
"createPublicDomain": [
- 307,
+ 311,
{
"domain": [
1,
@@ -10515,7 +10654,7 @@ export default {
}
],
"checkPublicDomainValidRecords": [
- 266,
+ 270,
{
"domain": [
1,
@@ -10524,7 +10663,7 @@ export default {
}
],
"createDevelopmentApplication": [
- 305,
+ 309,
{
"universalIdentifier": [
1,
@@ -10537,7 +10676,7 @@ export default {
}
],
"syncApplication": [
- 306,
+ 310,
{
"manifest": [
9,
@@ -10552,10 +10691,10 @@ export default {
}
],
"uploadApplicationFile": [
- 298,
+ 302,
{
"file": [
- 417,
+ 422,
"Upload!"
],
"applicationUniversalIdentifier": [
@@ -10563,7 +10702,7 @@ export default {
"String!"
],
"fileFolder": [
- 302,
+ 306,
"FileFolder!"
],
"filePath": [
@@ -10573,20 +10712,20 @@ export default {
}
],
"createApplicationFileUploads": [
- 304,
+ 308,
{
"applicationUniversalIdentifier": [
1,
"String!"
],
"files": [
- 567,
+ 573,
"[ApplicationFileUploadRequestInput!]!"
]
}
],
"completeApplicationFileUploads": [
- 300,
+ 304,
{
"applicationUniversalIdentifier": [
1,
@@ -10703,7 +10842,7 @@ export default {
3
],
"update": [
- 416
+ 421
],
"__typename": [
1
@@ -10736,7 +10875,7 @@ export default {
]
},
"Upload": {},
- "UpsertUsageLimitInput": {
+ "CreateUsageLimitInput": {
"resourceType": [
177
],
@@ -10762,10 +10901,21 @@ export default {
1
],
"limitValue": [
- 179
+ 181
],
"burstValue": [
- 179
+ 181
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateUsageLimitInput": {
+ "id": [
+ 3
+ ],
+ "payload": [
+ 423
],
"__typename": [
1
@@ -10848,7 +10998,7 @@ export default {
3
],
"update": [
- 423
+ 429
],
"__typename": [
1
@@ -11019,19 +11169,19 @@ export default {
3
],
"view": [
- 429
+ 435
],
"viewFields": [
- 430
+ 436
],
"viewFilters": [
- 431
+ 437
],
"viewFilterGroups": [
- 432
+ 438
],
"viewSorts": [
- 433
+ 439
],
"__typename": [
1
@@ -11180,7 +11330,7 @@ export default {
3
],
"update": [
- 436
+ 442
],
"__typename": [
1
@@ -11218,7 +11368,7 @@ export default {
3
],
"update": [
- 440
+ 446
],
"__typename": [
1
@@ -11294,7 +11444,7 @@ export default {
3
],
"update": [
- 445
+ 451
],
"__typename": [
1
@@ -11358,10 +11508,10 @@ export default {
3
],
"groups": [
- 450
+ 456
],
"fields": [
- 451
+ 457
],
"__typename": [
1
@@ -11381,7 +11531,7 @@ export default {
8
],
"fields": [
- 451
+ 457
],
"__typename": [
1
@@ -11552,7 +11702,7 @@ export default {
8
],
"tabs": [
- 463
+ 469
],
"__typename": [
1
@@ -11575,7 +11725,7 @@ export default {
85
],
"widgets": [
- 464
+ 470
],
"__typename": [
1
@@ -11740,7 +11890,7 @@ export default {
},
"CreateOneObjectInput": {
"object": [
- 470
+ 476
],
"__typename": [
1
@@ -11800,7 +11950,7 @@ export default {
},
"UpdateOneObjectInput": {
"update": [
- 473
+ 479
],
"id": [
3
@@ -11853,7 +12003,7 @@ export default {
24
],
"translations": [
- 474
+ 480
],
"__typename": [
1
@@ -11875,7 +12025,7 @@ export default {
},
"CreateOneIndexInput": {
"index": [
- 476
+ 482
],
"__typename": [
1
@@ -11886,10 +12036,10 @@ export default {
3
],
"fields": [
- 477
+ 483
],
"indexType": [
- 255
+ 259
],
"__typename": [
1
@@ -11971,7 +12121,7 @@ export default {
3
],
"update": [
- 482
+ 488
],
"__typename": [
1
@@ -12137,7 +12287,7 @@ export default {
3
],
"update": [
- 487
+ 493
],
"__typename": [
1
@@ -12264,7 +12414,7 @@ export default {
1
],
"update": [
- 492
+ 498
],
"__typename": [
1
@@ -12318,7 +12468,7 @@ export default {
1
],
"update": [
- 495
+ 501
],
"__typename": [
1
@@ -12364,7 +12514,7 @@ export default {
},
"CreateOneFieldMetadataInput": {
"field": [
- 500
+ 506
],
"__typename": [
1
@@ -12372,7 +12522,7 @@ export default {
},
"CreateFieldInput": {
"type": [
- 247
+ 251
],
"name": [
1
@@ -12443,7 +12593,7 @@ export default {
3
],
"update": [
- 502
+ 508
],
"__typename": [
1
@@ -12508,7 +12658,7 @@ export default {
9
],
"translations": [
- 474
+ 480
],
"__typename": [
1
@@ -12547,7 +12697,7 @@ export default {
3
],
"update": [
- 506
+ 512
],
"__typename": [
1
@@ -12632,7 +12782,7 @@ export default {
},
"UpdateRoleInput": {
"update": [
- 511
+ 517
],
"id": [
3
@@ -12687,7 +12837,7 @@ export default {
3
],
"objectPermissions": [
- 513
+ 519
],
"__typename": [
1
@@ -12729,7 +12879,7 @@ export default {
3
],
"fieldPermissions": [
- 516
+ 522
],
"__typename": [
1
@@ -12760,10 +12910,10 @@ export default {
3
],
"predicates": [
- 518
+ 524
],
"predicateGroups": [
- 519
+ 525
],
"__typename": [
1
@@ -12911,7 +13061,7 @@ export default {
1
],
"visibility": [
- 332
+ 336
],
"__typename": [
1
@@ -12928,7 +13078,7 @@ export default {
1
],
"visibility": [
- 332
+ 336
],
"__typename": [
1
@@ -12939,7 +13089,7 @@ export default {
3
],
"update": [
- 528
+ 534
],
"__typename": [
1
@@ -12947,16 +13097,16 @@ export default {
},
"UpdateMessageChannelInputUpdates": {
"visibility": [
- 314
+ 318
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 316
+ 320
],
"messageFolderImportPolicy": [
- 317
+ 321
],
"isSyncEnabled": [
8
@@ -13012,7 +13162,7 @@ export default {
3
],
"messages": [
- 533
+ 539
],
"__typename": [
1
@@ -13020,7 +13170,7 @@ export default {
},
"RunAgentMessageInput": {
"role": [
- 534
+ 540
],
"content": [
1
@@ -13055,7 +13205,7 @@ export default {
3
],
"update": [
- 537
+ 543
],
"__typename": [
1
@@ -13083,7 +13233,7 @@ export default {
3
],
"update": [
- 539
+ 545
],
"__typename": [
1
@@ -13102,7 +13252,7 @@ export default {
3
],
"update": [
- 539
+ 545
],
"__typename": [
1
@@ -13113,7 +13263,7 @@ export default {
3
],
"update": [
- 542
+ 548
],
"__typename": [
1
@@ -13121,13 +13271,13 @@ export default {
},
"UpdateCalendarChannelInputUpdates": {
"visibility": [
- 380
+ 384
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 381
+ 385
],
"isSyncEnabled": [
8
@@ -13144,7 +13294,7 @@ export default {
9
],
"scope": [
- 376
+ 380
],
"__typename": [
1
@@ -13178,7 +13328,7 @@ export default {
9
],
"jobs": [
- 546
+ 552
],
"retryLimit": [
28
@@ -13203,7 +13353,7 @@ export default {
},
"ReportAppConnectionAuthFailureInput": {
"id": [
- 225
+ 229
],
"reason": [
1
@@ -13300,7 +13450,7 @@ export default {
8
],
"translations": [
- 474
+ 480
],
"__typename": [
1
@@ -13392,7 +13542,7 @@ export default {
3
],
"status": [
- 200
+ 204
],
"__typename": [
1
@@ -13466,7 +13616,7 @@ export default {
1
],
"files": [
- 563
+ 569
],
"__typename": [
1
@@ -13488,13 +13638,13 @@ export default {
1
],
"IMAP": [
- 565
+ 571
],
"SMTP": [
- 565
+ 571
],
"CALDAV": [
- 565
+ 571
],
"__typename": [
1
@@ -13514,7 +13664,7 @@ export default {
1
],
"connectionSecurity": [
- 187
+ 191
],
"__typename": [
1
@@ -13533,7 +13683,7 @@ export default {
},
"ApplicationFileUploadRequestInput": {
"fileFolder": [
- 302
+ 306
],
"filePath": [
1
@@ -13556,16 +13706,16 @@ export default {
}
],
"logicFunctionLogs": [
- 268,
+ 272,
{
"input": [
- 569,
+ 575,
"LogicFunctionLogsInput!"
]
}
],
"onAgentChatEvent": [
- 367,
+ 371,
{
"threadId": [
3,
@@ -13574,10 +13724,10 @@ export default {
}
],
"eventLogsLive": [
- 356,
+ 360,
{
"table": [
- 405,
+ 410,
"EventLogTable!"
]
}
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index c3ee1f065b4..2d468badd5a 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -1479,6 +1479,19 @@ export type CreateUnsubscribeTopicInput = {
visibility?: InputMaybe<UnsubscribeTopicVisibility>;
};
+export type CreateUsageLimitInput = {
+ burstValue?: InputMaybe<Scalars['BigInt']['input']>;
+ limitKind: Scalars['String']['input'];
+ limitValue: Scalars['BigInt']['input'];
+ meter: Scalars['String']['input'];
+ operationType: UsageOperationType;
+ periodCount: Scalars['Int']['input'];
+ periodUnit: Scalars['String']['input'];
+ resourceType: UsageResourceType;
+ spenderId?: InputMaybe<Scalars['String']['input']>;
+ spenderType: Scalars['String']['input'];
+};
+
export type CreateViewFieldGroupInput = {
id?: InputMaybe<Scalars['UUID']['input']>;
isVisible?: InputMaybe<Scalars['Boolean']['input']>;
@@ -2925,6 +2938,7 @@ export type Mutation = {
createSkill: Skill;
createSubscriptionPaymentIntent: BillingPaymentIntent;
createUnsubscribeTopic: UnsubscribeTopic;
+ createUsageLimit: UsageLimit;
createView: View;
createViewField: ViewField;
createViewFieldGroup: ViewFieldGroup;
@@ -3092,6 +3106,7 @@ export type Mutation = {
updateSkill: Skill;
updateTimelineActivityType: TimelineActivityType;
updateUnsubscribeTopic: UnsubscribeTopic;
+ updateUsageLimit: UsageLimit;
updateUserEmail: Scalars['Boolean']['output'];
updateView: View;
updateViewField: ViewField;
@@ -3116,7 +3131,6 @@ export type Mutation = {
upsertObjectPermissions: Array<ObjectPermission>;
upsertPermissionFlags: Array<RolePermissionFlag>;
upsertRowLevelPermissionPredicates: UpsertRowLevelPermissionPredicatesResult;
- upsertUsageLimit: UsageLimit;
upsertViewWidget: View;
validateApprovedAccessDomain: ApprovedAccessDomain;
verifyEmailAndGetLoginToken: VerifyEmailAndGetLoginToken;
@@ -3401,6 +3415,11 @@ export type MutationCreateUnsubscribeTopicArgs = {
};
+export type MutationCreateUsageLimitArgs = {
+ input: CreateUsageLimitInput;
+};
+
+
export type MutationCreateViewArgs = {
input: CreateViewInput;
};
@@ -4211,6 +4230,11 @@ export type MutationUpdateUnsubscribeTopicArgs = {
};
+export type MutationUpdateUsageLimitArgs = {
+ input: UpdateUsageLimitInput;
+};
+
+
export type MutationUpdateUserEmailArgs = {
newEmail: Scalars['String']['input'];
verifyEmailRedirectPath?: InputMaybe<Scalars['String']['input']>;
@@ -4342,11 +4366,6 @@ export type MutationUpsertRowLevelPermissionPredicatesArgs = {
};
-export type MutationUpsertUsageLimitArgs = {
- input: UpsertUsageLimitInput;
-};
-
-
export type MutationUpsertViewWidgetArgs = {
input: UpsertViewWidgetInput;
};
@@ -5020,6 +5039,9 @@ export type Query = {
timelineActivityTypes: Array<TimelineActivityType>;
unsubscribeTopics: Array<UnsubscribeTopic>;
usageLimits: Array<UsageLimit>;
+ usageQuotaDefinitions: UsageQuotaDefinitions;
+ usageQuotaScopeConsumption?: Maybe<UsageQuotaScopeConsumption>;
+ usageQuotasWithConsumption: Array<UsageQuotaWithConsumption>;
validatePasswordResetToken: ValidatePasswordResetToken;
webhook?: Maybe<Webhook>;
webhooks: Array<Webhook>;
@@ -5474,6 +5496,11 @@ export type QuerySkillArgs = {
};
+export type QueryUsageQuotaScopeConsumptionArgs = {
+ input: UsageQuotaScopeInput;
+};
+
+
export type QueryValidatePasswordResetTokenArgs = {
passwordResetToken: Scalars['String']['input'];
};
@@ -6380,6 +6407,11 @@ export type UpdateUnsubscribeTopicInput = {
visibility?: InputMaybe<UnsubscribeTopicVisibility>;
};
+export type UpdateUsageLimitInput = {
+ id: Scalars['UUID']['input'];
+ payload: CreateUsageLimitInput;
+};
+
export type UpdateViewFieldGroupInput = {
/** The id of the view field group to update */
id: Scalars['UUID']['input'];
@@ -6582,19 +6614,6 @@ export type UpsertRowLevelPermissionPredicatesResult = {
predicates: Array<RowLevelPermissionPredicate>;
};
-export type UpsertUsageLimitInput = {
- burstValue?: InputMaybe<Scalars['BigInt']['input']>;
- limitKind: Scalars['String']['input'];
- limitValue: Scalars['BigInt']['input'];
- meter: Scalars['String']['input'];
- operationType: UsageOperationType;
- periodCount: Scalars['Int']['input'];
- periodUnit: Scalars['String']['input'];
- resourceType: UsageResourceType;
- spenderId?: InputMaybe<Scalars['String']['input']>;
- spenderType: Scalars['String']['input'];
-};
-
export type UpsertViewWidgetInput = {
/** View-level settings (layout type, group by, kanban and calendar settings) to apply to the widget view. */
view?: InputMaybe<UpsertViewWidgetViewSettingsInput>;
@@ -6717,6 +6736,55 @@ export enum UsageOperationType {
WORKFLOW_EXECUTION = 'WORKFLOW_EXECUTION'
}
+export type UsageQuotaDefinition = {
+ __typename?: 'UsageQuotaDefinition';
+ allowedMeters: Array<Scalars['String']['output']>;
+ allowedOperationTypes: Array<UsageOperationType>;
+ allowedSpenderTypes: Array<Scalars['String']['output']>;
+ resourceType: UsageResourceType;
+};
+
+export type UsageQuotaDefinitions = {
+ __typename?: 'UsageQuotaDefinitions';
+ definitions: Array<UsageQuotaDefinition>;
+ hasAllowancePeriod: Scalars['Boolean']['output'];
+ isIntraWorkspaceLimitEntitled: Scalars['Boolean']['output'];
+};
+
+export type UsageQuotaScopeConsumption = {
+ __typename?: 'UsageQuotaScopeConsumption';
+ consumedValue?: Maybe<Scalars['BigInt']['output']>;
+ periodEnd: Scalars['DateTime']['output'];
+ periodStart: Scalars['DateTime']['output'];
+};
+
+export type UsageQuotaScopeInput = {
+ meter: Scalars['String']['input'];
+ operationType: UsageOperationType;
+ periodUnit: Scalars['String']['input'];
+ resourceType: UsageResourceType;
+ spenderId?: InputMaybe<Scalars['String']['input']>;
+ spenderType: Scalars['String']['input'];
+};
+
+export type UsageQuotaWithConsumption = {
+ __typename?: 'UsageQuotaWithConsumption';
+ consumedValue?: Maybe<Scalars['BigInt']['output']>;
+ id: Scalars['UUID']['output'];
+ isEnforced: Scalars['Boolean']['output'];
+ limitValue: Scalars['BigInt']['output'];
+ meter: Scalars['String']['output'];
+ operationType: UsageOperationType;
+ periodEnd?: Maybe<Scalars['DateTime']['output']>;
+ periodStart?: Maybe<Scalars['DateTime']['output']>;
+ periodUnit: Scalars['String']['output'];
+ remainingValue?: Maybe<Scalars['BigInt']['output']>;
+ resourceType: UsageResourceType;
+ spenderId?: Maybe<Scalars['String']['output']>;
+ spenderLabel?: Maybe<Scalars['String']['output']>;
+ spenderType: Scalars['String']['output'];
+};
+
export enum UsageResourceType {
AI = 'AI',
API = 'API',
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts
index 585a404556a..afd83dc72df 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-billing.service.ts
@@ -1,6 +1,7 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
+import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
import { In, type Repository } from 'typeorm';
@@ -24,10 +25,7 @@ import { BillingCreditService } from 'src/engine/core-modules/billing/services/b
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import {
- INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
- toDisplayCredits,
-} from 'src/engine/core-modules/usage/utils/to-display-credits.util';
+import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts
index 9f5f9f40cdf..8b04bb56adc 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts
@@ -3,7 +3,10 @@
import { UseFilters, UseGuards, UsePipes } from '@nestjs/common';
import { Args, Mutation, Query } from '@nestjs/graphql';
-import { PermissionFlagType } from 'twenty-shared/constants';
+import {
+ INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
+ PermissionFlagType,
+} from 'twenty-shared/constants';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
@@ -28,10 +31,7 @@ import { BillingService } from 'src/engine/core-modules/billing/services/billing
import { formatBillingDatabaseProductToGraphqlDTO } from 'src/engine/core-modules/billing/utils/format-database-product-to-graphql-dto.util';
import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';
import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
-import {
- INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
- toDisplayCredits,
-} from 'src/engine/core-modules/usage/utils/to-display-credits.util';
+import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AuthApiKey } from 'src/engine/decorators/auth/auth-api-key.decorator';
import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/format-database-product-to-graphql-dto.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/format-database-product-to-graphql-dto.util.ts
index ae29555e293..d083aeef5c1 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/utils/format-database-product-to-graphql-dto.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/format-database-product-to-graphql-dto.util.ts
@@ -1,5 +1,6 @@
/* @license Enterprise */
+import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
import { isDefined } from 'class-validator';
import { type BillingPlanDTO } from 'src/engine/core-modules/billing/dtos/billing-plan.dto';
import { type BillingPriceLicensedDTO } from 'src/engine/core-modules/billing/dtos/billing-price-licensed.dto';
@@ -9,10 +10,7 @@ import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/bill
import { BillingUsageType } from 'src/engine/core-modules/billing/enums/billing-usage-type.enum';
import { type BillingGetPlanResult } from 'src/engine/core-modules/billing/types/billing-get-plan-result.type';
import { isSellableBillingPrice } from 'src/engine/core-modules/billing/utils/is-sellable-billing-price.util';
-import {
- INTERNAL_CREDITS_PER_DISPLAY_CREDIT,
- toDisplayCredits,
-} from 'src/engine/core-modules/usage/utils/to-display-credits.util';
+import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
export const formatBillingDatabaseProductToGraphqlDTO = (
plan: BillingGetPlanResult,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
index e78bfb4f08c..20a7d3a05a8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant.ts
@@ -47,7 +47,6 @@ export const USAGE_LIMIT_DEFINITIONS: Record<
'userWorkspace',
'apiKey',
'application',
- 'agent',
],
allowedMeters: ['creditsUsedMicro', 'quantity'],
},
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-spender-column-by-spender-type.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-spender-column-by-spender-type.constant.ts
new file mode 100644
index 00000000000..5275268814c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-spender-column-by-spender-type.constant.ts
@@ -0,0 +1,14 @@
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
+
+export const USAGE_SPENDER_COLUMN_BY_SPENDER_TYPE: Record<
+ Exclude<SpenderType, 'workspace'>,
+ keyof UsageSpenders
+> = {
+ userWorkspace: 'userWorkspaceId',
+ apiKey: 'apiKeyId',
+ application: 'applicationId',
+ agent: 'agentId',
+ workflow: 'workflowId',
+ logicFunction: 'logicFunctionId',
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/create-usage-limit.input.ts
similarity index 98%
rename from packages/twenty-server/src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input.ts
rename to packages/twenty-server/src/engine/core-modules/usage-limit/dtos/create-usage-limit.input.ts
index 3a1acc3c239..f0e4530fbcb 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/create-usage-limit.input.ts
@@ -23,7 +23,7 @@ import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-op
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
@InputType()
-export class UpsertUsageLimitInput {
+export class CreateUsageLimitInput {
@Field(() => UsageResourceType)
@IsEnum(UsageResourceType)
resourceType: UsageResourceType;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/update-usage-limit.input.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/update-usage-limit.input.ts
new file mode 100644
index 00000000000..8370eb4def1
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/update-usage-limit.input.ts
@@ -0,0 +1,19 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { Type } from 'class-transformer';
+import { IsUUID, ValidateNested } from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
+
+@InputType()
+export class UpdateUsageLimitInput {
+ @Field(() => UUIDScalarType)
+ @IsUUID()
+ id: string;
+
+ @Field(() => CreateUsageLimitInput)
+ @Type(() => CreateUsageLimitInput)
+ @ValidateNested()
+ payload: CreateUsageLimitInput;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto.ts
new file mode 100644
index 00000000000..b133580197f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto.ts
@@ -0,0 +1,21 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+@ObjectType('UsageQuotaDefinition')
+export class UsageQuotaDefinitionDTO {
+ @Field(() => UsageResourceType)
+ resourceType: UsageResourceType;
+
+ @Field(() => [UsageOperationType])
+ allowedOperationTypes: UsageOperationType[];
+
+ @Field(() => [String])
+ allowedSpenderTypes: SpenderType[];
+
+ @Field(() => [String])
+ allowedMeters: UsageMeter[];
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-definitions.dto.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-definitions.dto.ts
new file mode 100644
index 00000000000..014f8e64b5b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-definitions.dto.ts
@@ -0,0 +1,15 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { UsageQuotaDefinitionDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto';
+
+@ObjectType('UsageQuotaDefinitions')
+export class UsageQuotaDefinitionsDTO {
+ @Field(() => [UsageQuotaDefinitionDTO])
+ definitions: UsageQuotaDefinitionDTO[];
+
+ @Field(() => Boolean)
+ isIntraWorkspaceLimitEntitled: boolean;
+
+ @Field(() => Boolean)
+ hasAllowancePeriod: boolean;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-scope-consumption.dto.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-scope-consumption.dto.ts
new file mode 100644
index 00000000000..de69c01dbbd
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-scope-consumption.dto.ts
@@ -0,0 +1,15 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { GraphQLBigInt } from 'graphql-scalars';
+
+@ObjectType('UsageQuotaScopeConsumption')
+export class UsageQuotaScopeConsumptionDTO {
+ @Field(() => GraphQLBigInt, { nullable: true })
+ consumedValue: number | null;
+
+ @Field(() => Date)
+ periodStart: Date;
+
+ @Field(() => Date)
+ periodEnd: Date;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-scope.input.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-scope.input.ts
new file mode 100644
index 00000000000..75592223781
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-scope.input.ts
@@ -0,0 +1,11 @@
+import { InputType, OmitType } from '@nestjs/graphql';
+
+import { CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
+
+@InputType()
+export class UsageQuotaScopeInput extends OmitType(CreateUsageLimitInput, [
+ 'limitValue',
+ 'burstValue',
+ 'limitKind',
+ 'periodCount',
+] as const) {}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-with-consumption.dto.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-with-consumption.dto.ts
new file mode 100644
index 00000000000..a71baec3e8b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-quota-with-consumption.dto.ts
@@ -0,0 +1,55 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { GraphQLBigInt } from 'graphql-scalars';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+@ObjectType('UsageQuotaWithConsumption')
+export class UsageQuotaWithConsumptionDTO {
+ @Field(() => UUIDScalarType)
+ id: string;
+
+ @Field(() => UsageResourceType)
+ resourceType: UsageResourceType;
+
+ @Field(() => UsageOperationType)
+ operationType: UsageOperationType;
+
+ @Field(() => String)
+ spenderType: SpenderType;
+
+ @Field(() => String, { nullable: true })
+ spenderId: string | null;
+
+ @Field(() => String, { nullable: true })
+ spenderLabel: string | null;
+
+ @Field(() => String)
+ periodUnit: PeriodUnit;
+
+ @Field(() => String)
+ meter: UsageMeter;
+
+ @Field(() => GraphQLBigInt)
+ limitValue: number;
+
+ @Field(() => Boolean)
+ isEnforced: boolean;
+
+ @Field(() => GraphQLBigInt, { nullable: true })
+ consumedValue: number | null;
+
+ @Field(() => GraphQLBigInt, { nullable: true })
+ remainingValue: number | null;
+
+ @Field(() => Date, { nullable: true })
+ periodStart: Date | null;
+
+ @Field(() => Date, { nullable: true })
+ periodEnd: Date | null;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts
index bf6b52cab5f..ff53ba1d5a1 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts
@@ -1,7 +1,6 @@
import { DiscoveryService } from '@nestjs/core';
import { Test, type TestingModule } from '@nestjs/testing';
-import { ClickHouseService } from 'src/database/clickhouse/clickhouse.service';
import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
import {
CacheLockException,
@@ -21,6 +20,7 @@ import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/serv
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
import { type UsageLimitCounterScope } from 'src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type';
import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';
import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util';
@@ -28,6 +28,7 @@ import { buildQuotaWarmLockKey } from 'src/engine/core-modules/usage-limit/utils
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
+import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
const MONTH_PERIOD = {
@@ -106,8 +107,9 @@ describe('UsageLimitQuotaService', () => {
withLock: jest.fn((fn: () => Promise<unknown>) => fn()),
};
- const clickHouseService = {
- selectOrThrow: jest.fn().mockResolvedValue([]),
+ const usageAnalyticsService = {
+ getConsumptionRowsForAllScopes: jest.fn().mockResolvedValue([]),
+ getCreditsUsedMicroForBillingPeriod: jest.fn().mockResolvedValue(0),
};
const usagePeriodService = {
@@ -165,7 +167,10 @@ describe('UsageLimitQuotaService', () => {
);
cacheStorage.mget.mockResolvedValue([]);
cacheStorage.runScript.mockResolvedValue([]);
- clickHouseService.selectOrThrow.mockResolvedValue([]);
+ usageAnalyticsService.getConsumptionRowsForAllScopes.mockResolvedValue([]);
+ usageAnalyticsService.getCreditsUsedMicroForBillingPeriod.mockResolvedValue(
+ 0,
+ );
periodByUnit = { month: MONTH_PERIOD, week: WEEK_PERIOD };
usagePeriodService.findCurrentPeriod.mockImplementation(
async ({ periodUnit }: { periodUnit: PeriodUnit }) =>
@@ -188,7 +193,7 @@ describe('UsageLimitQuotaService', () => {
},
{ provide: WorkspaceCacheService, useValue: workspaceCacheService },
{ provide: CacheLockService, useValue: cacheLockService },
- { provide: ClickHouseService, useValue: clickHouseService },
+ { provide: UsageAnalyticsService, useValue: usageAnalyticsService },
{ provide: UsagePeriodService, useValue: usagePeriodService },
{ provide: MetricsService, useValue: metricsService },
{
@@ -213,7 +218,9 @@ describe('UsageLimitQuotaService', () => {
cacheStorage.mget.mockResolvedValue([250]);
await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();
- expect(clickHouseService.selectOrThrow).not.toHaveBeenCalled();
+ expect(
+ usageAnalyticsService.getConsumptionRowsForAllScopes,
+ ).not.toHaveBeenCalled();
});
it('denies on an exhausted warm counter', async () => {
@@ -235,11 +242,13 @@ describe('UsageLimitQuotaService', () => {
cacheStorage.mget.mockResolvedValue([undefined]);
await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();
- expect(clickHouseService.selectOrThrow).toHaveBeenCalledWith(
- expect.stringContaining(
- "toStartOfDay(timestamp, 'UTC') >= {periodStart:DateTime64(3)}",
- ),
- expect.anything(),
+ expect(
+ usageAnalyticsService.getConsumptionRowsForAllScopes,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({
+ periodAnchor: 'calendar',
+ periodStart: MONTH_PERIOD.periodStart,
+ }),
);
});
@@ -252,21 +261,27 @@ describe('UsageLimitQuotaService', () => {
await assertQuotaNotExhausted();
- expect(clickHouseService.selectOrThrow).toHaveBeenCalledTimes(2);
+ expect(
+ usageAnalyticsService.getConsumptionRowsForAllScopes,
+ ).toHaveBeenCalledTimes(2);
});
it('warms a cold allowance counter from the live allowance minus the stamped consumption', async () => {
setAllowance(100);
cacheStorage.mget.mockResolvedValue([undefined]);
- clickHouseService.selectOrThrow.mockResolvedValue([{ total: '150' }]);
+ usageAnalyticsService.getCreditsUsedMicroForBillingPeriod.mockResolvedValue(
+ 150,
+ );
await expect(assertQuotaNotExhausted()).rejects.toThrow(
UsageLimitException,
);
- expect(clickHouseService.selectOrThrow).toHaveBeenCalledWith(
- expect.stringContaining('periodStart = {periodStart:DateTime64(3)}'),
- expect.anything(),
- );
+ expect(
+ usageAnalyticsService.getCreditsUsedMicroForBillingPeriod,
+ ).toHaveBeenCalledWith({
+ workspaceId: 'workspace-1',
+ periodStart: ALLOWANCE_PERIOD.periodStart,
+ });
expect(cacheStorage.mset).toHaveBeenCalledWith([
expect.objectContaining({ value: -50 }),
]);
@@ -336,7 +351,7 @@ describe('UsageLimitQuotaService', () => {
setAllowance(2_000);
creditAllowanceProvider.isCreditAllowanceEnabled.mockResolvedValue(false);
cacheStorage.mget.mockResolvedValue([undefined]);
- clickHouseService.selectOrThrow.mockResolvedValue([
+ usageAnalyticsService.getConsumptionRowsForAllScopes.mockResolvedValue([
{
operationType: UsageOperationType.AI_CHAT_TOKEN,
userWorkspaceId: 'user-1',
@@ -352,20 +367,15 @@ describe('UsageLimitQuotaService', () => {
await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();
- expect(clickHouseService.selectOrThrow).toHaveBeenCalledWith(
- expect.stringContaining(
- 'AND periodStart = {periodStart:DateTime64(3)}',
- ),
+ expect(
+ usageAnalyticsService.getConsumptionRowsForAllScopes,
+ ).toHaveBeenCalledWith(
expect.objectContaining({
- periodStart: expect.stringContaining('2026-08-15'),
+ periodAnchor: 'billing',
+ periodStart: ALLOWANCE_PERIOD.periodStart,
+ periodEnd: ALLOWANCE_PERIOD.periodEnd,
}),
);
- expect(clickHouseService.selectOrThrow).toHaveBeenCalledWith(
- expect.stringContaining(
- 'AND timestamp >= {periodStart:DateTime64(3)} - INTERVAL 1 DAY',
- ),
- expect.anything(),
- );
expect(cacheStorage.mset).toHaveBeenCalledWith([
expect.objectContaining({ value: 650 }),
]);
@@ -413,7 +423,7 @@ describe('UsageLimitQuotaService', () => {
it('admits when the warm query fails instead of granting a fresh budget', async () => {
setLimits([buildLimit({})]);
cacheStorage.mget.mockResolvedValue([undefined]);
- clickHouseService.selectOrThrow.mockRejectedValue(
+ usageAnalyticsService.getConsumptionRowsForAllScopes.mockRejectedValue(
new Error('clickhouse unreachable'),
);
@@ -693,4 +703,157 @@ describe('UsageLimitQuotaService', () => {
expect(metricsService.incrementCounterBy).not.toHaveBeenCalled();
});
});
+
+ describe('readLimitConsumptions', () => {
+ const readLimitConsumptions = (limits: FlatUsageLimit[]) =>
+ service.readLimitConsumptions({ workspaceId: 'workspace-1', limits });
+
+ const buildConsumptionRow = (
+ overrides: Partial<UsageConsumptionRow> = {},
+ ): UsageConsumptionRow => ({
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ userWorkspaceId: '',
+ apiKeyId: '',
+ applicationId: '',
+ agentId: '',
+ workflowId: '',
+ logicFunctionId: '',
+ creditsUsedMicro: '0',
+ quantity: '0',
+ ...overrides,
+ });
+
+ it('reads the consumption of each warm counter', async () => {
+ cacheStorage.mget.mockResolvedValue([700]);
+
+ await expect(
+ readLimitConsumptions([buildLimit({ limitValue: 1_000 })]),
+ ).resolves.toEqual(
+ new Map([
+ [
+ 'limit-1',
+ {
+ consumedValue: 300,
+ remainingValue: 700,
+ periodStart: MONTH_PERIOD.periodStart,
+ periodEnd: MONTH_PERIOD.periodEnd,
+ },
+ ],
+ ]),
+ );
+ });
+
+ it('answers a null consumption when the counters cannot be read', async () => {
+ cacheStorage.mget.mockRejectedValue(new Error('Socket closed'));
+
+ await expect(
+ readLimitConsumptions([buildLimit({ limitValue: 1_000 })]),
+ ).resolves.toEqual(
+ new Map([
+ [
+ 'limit-1',
+ {
+ consumedValue: null,
+ remainingValue: null,
+ periodStart: MONTH_PERIOD.periodStart,
+ periodEnd: MONTH_PERIOD.periodEnd,
+ },
+ ],
+ ]),
+ );
+ expect(metricsService.incrementCounterBy).not.toHaveBeenCalled();
+ });
+
+ it('reads a cold counter from the consumption rows without warming it', async () => {
+ cacheStorage.mget.mockResolvedValue([undefined]);
+ usageAnalyticsService.getConsumptionRowsForAllScopes.mockResolvedValue([
+ buildConsumptionRow({ creditsUsedMicro: '150' }),
+ buildConsumptionRow({ creditsUsedMicro: '90' }),
+ ]);
+
+ await expect(
+ readLimitConsumptions([buildLimit({ limitValue: 1_000 })]),
+ ).resolves.toEqual(
+ new Map([
+ [
+ 'limit-1',
+ {
+ consumedValue: 240,
+ remainingValue: 760,
+ periodStart: MONTH_PERIOD.periodStart,
+ periodEnd: MONTH_PERIOD.periodEnd,
+ },
+ ],
+ ]),
+ );
+ expect(cacheStorage.mset).not.toHaveBeenCalled();
+ expect(cacheLockService.withLock).not.toHaveBeenCalled();
+ });
+
+ it('reads the warm counters from the cache and only the cold ones from ClickHouse', async () => {
+ cacheStorage.mget.mockResolvedValue([700, undefined]);
+ usageAnalyticsService.getConsumptionRowsForAllScopes.mockResolvedValue([
+ buildConsumptionRow({ creditsUsedMicro: '120' }),
+ ]);
+
+ await expect(
+ readLimitConsumptions([
+ buildLimit({ id: 'monthly', limitValue: 1_000 }),
+ buildLimit({ id: 'weekly', periodUnit: 'week', limitValue: 500 }),
+ ]),
+ ).resolves.toEqual(
+ new Map([
+ [
+ 'monthly',
+ {
+ consumedValue: 300,
+ remainingValue: 700,
+ periodStart: MONTH_PERIOD.periodStart,
+ periodEnd: MONTH_PERIOD.periodEnd,
+ },
+ ],
+ [
+ 'weekly',
+ {
+ consumedValue: 120,
+ remainingValue: 380,
+ periodStart: WEEK_PERIOD.periodStart,
+ periodEnd: WEEK_PERIOD.periodEnd,
+ },
+ ],
+ ]),
+ );
+ expect(
+ usageAnalyticsService.getConsumptionRowsForAllScopes,
+ ).toHaveBeenCalledTimes(1);
+ expect(
+ usageAnalyticsService.getConsumptionRowsForAllScopes,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({ periodStart: WEEK_PERIOD.periodStart }),
+ );
+ });
+
+ it('answers a null consumption when ClickHouse cannot be read', async () => {
+ cacheStorage.mget.mockResolvedValue([undefined]);
+ usageAnalyticsService.getConsumptionRowsForAllScopes.mockRejectedValue(
+ new Error('ClickHouse unreachable'),
+ );
+
+ await expect(
+ readLimitConsumptions([buildLimit({ limitValue: 1_000 })]),
+ ).resolves.toEqual(
+ new Map([
+ [
+ 'limit-1',
+ {
+ consumedValue: null,
+ remainingValue: null,
+ periodStart: MONTH_PERIOD.periodStart,
+ periodEnd: MONTH_PERIOD.periodEnd,
+ },
+ ],
+ ]),
+ );
+ });
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
index ca8f5607186..ffa090e8045 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
@@ -4,8 +4,6 @@ import { DiscoveryService } from '@nestjs/core';
import { msg } from '@lingui/core/macro';
import { isDefined } from 'twenty-shared/utils';
-import { ClickHouseService } from 'src/database/clickhouse/clickhouse.service';
-import { formatDateTimeForClickHouse } from 'src/database/clickhouse/utils/format-date-time-for-clickhouse.util';
import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
import {
CacheLockException,
@@ -23,16 +21,18 @@ import {
} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';
import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
+import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
+import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
-import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type LimitConsumption } from 'src/engine/core-modules/usage-limit/types/limit-consumption.type';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
-import { type QuotaConsumptionRow } from 'src/engine/core-modules/usage-limit/types/quota-consumption-row.type';
import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';
import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';
import { type UsageLimitCounterScope } from 'src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type';
import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';
import { buildIntraWorkspaceLimitCounterKeys } from 'src/engine/core-modules/usage-limit/utils/build-intra-workspace-limit-counter-keys.util';
+import { buildLimitQuotaCounter } from 'src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util';
import { buildLimitWarmedEntries } from 'src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util';
import { buildPeriodGroupKey } from 'src/engine/core-modules/usage-limit/utils/build-period-group-key.util';
import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util';
@@ -40,23 +40,21 @@ import { buildQuotaCounters } from 'src/engine/core-modules/usage-limit/utils/bu
import { buildQuotaExhaustedScope } from 'src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util';
import { buildQuotaWarmLockKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-warm-lock-key.util';
import { clampQuotaCost } from 'src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util';
+import { computeQuotaConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
import { findCreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util';
import { findExhaustedCounters } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util';
import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
import { fromConsumeResultsToRemainings } from 'src/engine/core-modules/usage-limit/utils/from-consume-results-to-remainings.util';
+import { getPeriodAnchor } from 'src/engine/core-modules/usage-limit/utils/get-period-anchor.util';
import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
-import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
+import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
+import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { WorkspaceCacheException } from 'src/engine/workspace-cache/exceptions/workspace-cache.exception';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
const QUOTA_WARM_LOCK_OPTIONS = { ms: 50, maxRetries: 20, ttl: 10_000 };
-const ALLOWANCE_PERIOD_STAMP_SLACK = 'INTERVAL 1 DAY';
-
-type AllowanceSumRow = {
- total: string | number | null;
-};
type QuotaEnforcement = {
operation: 'assert' | 'consume';
@@ -82,8 +80,8 @@ export class UsageLimitQuotaService implements OnModuleInit {
private readonly cacheStorage: CacheStorageService,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly cacheLockService: CacheLockService,
- private readonly clickHouseService: ClickHouseService,
private readonly usagePeriodService: UsagePeriodService,
+ private readonly usageAnalyticsService: UsageAnalyticsService,
private readonly discoveryService: DiscoveryService,
private readonly usageLimitEntitlementService: UsageLimitEntitlementService,
private readonly metricsService: MetricsService,
@@ -228,6 +226,62 @@ export class UsageLimitQuotaService implements OnModuleInit {
}
}
+ async readLimitConsumptions({
+ workspaceId,
+ limits,
+ }: {
+ workspaceId: string;
+ limits: FlatUsageLimit[];
+ }): Promise<Map<string, LimitConsumption>> {
+ if (limits.length === 0) {
+ return new Map();
+ }
+
+ const periodByUnit = await this.usagePeriodService.findCurrentPeriodsByUnit(
+ { workspaceId, limits },
+ );
+
+ const entries = limits.flatMap((limit) => {
+ const period = periodByUnit[limit.periodUnit];
+
+ return isDefined(period)
+ ? [
+ {
+ limit,
+ counter: buildLimitQuotaCounter({ workspaceId, limit, period }),
+ },
+ ]
+ : [];
+ });
+
+ if (entries.length === 0) {
+ return new Map();
+ }
+
+ const consumedValues = await this.readConsumedValuesAdmittingOnFailure({
+ workspaceId,
+ counters: entries.map(({ counter }) => counter),
+ });
+
+ return new Map(
+ entries.map(({ limit, counter }, index) => {
+ const consumedValue = consumedValues[index] ?? null;
+
+ return [
+ limit.id,
+ {
+ consumedValue,
+ remainingValue: isDefined(consumedValue)
+ ? limit.limitValue - consumedValue
+ : null,
+ periodStart: counter.periodStart,
+ periodEnd: counter.periodEnd,
+ },
+ ] as const;
+ }),
+ );
+ }
+
private async delUnderWarmLock({
workspaceId,
keys,
@@ -480,7 +534,6 @@ export class UsageLimitQuotaService implements OnModuleInit {
limits: quotaLimits,
usageSpenders: spenders,
workspaceId,
- resourceType,
operationType,
periodByUnit: await this.usagePeriodService.findCurrentPeriodsByUnit({
workspaceId,
@@ -543,6 +596,62 @@ export class UsageLimitQuotaService implements OnModuleInit {
});
}
+ private async readConsumedValuesAdmittingOnFailure({
+ workspaceId,
+ counters,
+ }: {
+ workspaceId: string;
+ counters: LimitQuotaCounter[];
+ }): Promise<(number | null)[]> {
+ try {
+ return await this.readConsumedValues({ workspaceId, counters });
+ } catch (error) {
+ return this.admitOnFailure<(number | null)[]>({
+ error,
+ workspaceId,
+ admitted: [],
+ });
+ }
+ }
+
+ private async readConsumedValues({
+ workspaceId,
+ counters,
+ }: {
+ workspaceId: string;
+ counters: LimitQuotaCounter[];
+ }): Promise<(number | null)[]> {
+ const remainings = await this.cacheStorage.mget<number>(
+ counters.map((counter) => counter.key),
+ );
+
+ const coldLimitCounters = counters.filter(
+ (_, index) => !isDefined(remainings[index]),
+ );
+
+ const rowsByPeriod =
+ coldLimitCounters.length > 0
+ ? await this.fetchConsumptionRowsByPeriod({
+ workspaceId,
+ coldLimitCounters,
+ })
+ : new Map<string, UsageConsumptionRow[]>();
+
+ return counters.map((counter, index) => {
+ const remaining = remainings[index];
+
+ if (isDefined(remaining)) {
+ return counter.limitValue - remaining;
+ }
+
+ const rows = rowsByPeriod.get(buildPeriodGroupKey(counter));
+
+ return isDefined(rows)
+ ? computeQuotaConsumed({ rows, scope: counter })
+ : null;
+ });
+ }
+
private async readRemainings({
workspaceId,
counters,
@@ -671,10 +780,11 @@ export class UsageLimitQuotaService implements OnModuleInit {
return [];
}
- const consumedMicro = await this.fetchAllowanceConsumedMicro({
- workspaceId,
- periodStart: counter.periodStart,
- });
+ const consumedMicro =
+ await this.usageAnalyticsService.getCreditsUsedMicroForBillingPeriod({
+ workspaceId,
+ periodStart: counter.periodStart,
+ });
return [
{
@@ -685,41 +795,20 @@ export class UsageLimitQuotaService implements OnModuleInit {
];
}
- private async fetchAllowanceConsumedMicro({
- workspaceId,
- periodStart,
- }: {
- workspaceId: string;
- periodStart: Date;
- }): Promise<number> {
- const rows = await this.clickHouseService.selectOrThrow<AllowanceSumRow>(
- `SELECT sum(creditsUsedMicro) AS total
- FROM usageEvent
- WHERE workspaceId = {workspaceId:String}
- AND periodStart = {periodStart:DateTime64(3)}`,
- {
- workspaceId,
- periodStart: formatDateTimeForClickHouse(periodStart),
- },
- );
-
- return Number(rows[0]?.total ?? 0);
- }
-
private async fetchConsumptionRowsByPeriod({
workspaceId,
coldLimitCounters,
}: {
workspaceId: string;
coldLimitCounters: LimitQuotaCounter[];
- }): Promise<Map<string, QuotaConsumptionRow[]>> {
+ }): Promise<Map<string, UsageConsumptionRow[]>> {
const countersByPeriod = new Map<string, LimitQuotaCounter>();
for (const counter of coldLimitCounters) {
countersByPeriod.set(buildPeriodGroupKey(counter), counter);
}
- const rowsByPeriod = new Map<string, QuotaConsumptionRow[]>();
+ const rowsByPeriod = new Map<string, UsageConsumptionRow[]>();
await Promise.all(
[...countersByPeriod.entries()].map(async ([periodGroupKey, counter]) => {
@@ -733,39 +822,19 @@ export class UsageLimitQuotaService implements OnModuleInit {
return rowsByPeriod;
}
- private async fetchConsumptionRows({
+ private fetchConsumptionRows({
workspaceId,
counter,
}: {
workspaceId: string;
counter: LimitQuotaCounter;
- }): Promise<QuotaConsumptionRow[]> {
- // Events carry a period only once the cache holds it, so the bound only helps the primary key prune
- const periodClause =
- counter.periodUnit === 'allowancePeriod'
- ? `AND periodStart = {periodStart:DateTime64(3)}
- AND timestamp >= {periodStart:DateTime64(3)} - ${ALLOWANCE_PERIOD_STAMP_SLACK}
- AND timestamp < {periodEnd:DateTime64(3)} + ${ALLOWANCE_PERIOD_STAMP_SLACK}`
- : `AND toStartOfDay(timestamp, 'UTC') >= {periodStart:DateTime64(3)}
- AND toStartOfDay(timestamp, 'UTC') < {periodEnd:DateTime64(3)}`;
-
- return this.clickHouseService.selectOrThrow<QuotaConsumptionRow>(
- `SELECT operationType, userWorkspaceId, apiKeyId, applicationId, agentId,
- workflowId, logicFunctionId,
- sum(creditsUsedMicro) AS creditsUsedMicro,
- sum(quantity) AS quantity
- FROM usageEvent
- WHERE workspaceId = {workspaceId:String}
- AND resourceType = {resourceType:String}
- ${periodClause}
- GROUP BY operationType, userWorkspaceId, apiKeyId, applicationId, agentId,
- workflowId, logicFunctionId`,
- {
- workspaceId,
- resourceType: counter.resourceType,
- periodStart: formatDateTimeForClickHouse(counter.periodStart),
- periodEnd: formatDateTimeForClickHouse(counter.periodEnd),
- },
- );
+ }): Promise<UsageConsumptionRow[]> {
+ return this.usageAnalyticsService.getConsumptionRowsForAllScopes({
+ workspaceId,
+ resourceType: counter.resourceType,
+ periodStart: counter.periodStart,
+ periodEnd: counter.periodEnd,
+ periodAnchor: getPeriodAnchor(counter.periodUnit),
+ });
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts
index af3ca11dc94..b23757af0a1 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts
@@ -5,7 +5,8 @@ import { isDefined } from 'twenty-shared/utils';
import { ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
-import { type UpsertUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input';
+import { type CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
+import { type UpdateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/update-usage-limit.input';
import {
UsageLimitException,
UsageLimitExceptionCode,
@@ -15,6 +16,7 @@ import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/serv
import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
import { UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+import { buildUsageLimitScope } from 'src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util';
import { isIntraWorkspaceScoped } from 'src/engine/core-modules/usage-limit/utils/is-intra-workspace-scoped.util';
import { validateUsageLimitAgainstDefinition } from 'src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
@@ -49,13 +51,126 @@ export class UsageLimitService {
return this.usageLimitRepository.find(workspaceId);
}
- async upsert({
+ async create({
workspaceId,
input,
}: {
workspaceId: string;
- input: UpsertUsageLimitInput;
+ input: CreateUsageLimitInput;
}): Promise<UsageLimitEntity> {
+ await this.validateInput({ workspaceId, input });
+
+ const scope = buildUsageLimitScope(input);
+
+ await this.assertScopeIsFree({ workspaceId, scope });
+
+ await this.usageLimitRepository.insert(workspaceId, {
+ workspaceId,
+ ...scope,
+ limitValue: input.limitValue,
+ burstValue: input.burstValue ?? null,
+ });
+
+ await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
+ 'usageLimits',
+ ]);
+
+ const usageLimit = await this.usageLimitRepository.findOneOrFail(
+ workspaceId,
+ { where: scope },
+ );
+
+ await this.usageLimitQuotaService.dropLimitCounter(usageLimit);
+
+ return usageLimit;
+ }
+
+ async update({
+ workspaceId,
+ input,
+ }: {
+ workspaceId: string;
+ input: UpdateUsageLimitInput;
+ }): Promise<UsageLimitEntity> {
+ await this.validateInput({ workspaceId, input: input.payload });
+
+ const usageLimit = await this.usageLimitRepository.findOne(workspaceId, {
+ where: { id: input.id },
+ });
+
+ if (!isDefined(usageLimit)) {
+ throw new UsageLimitException(
+ `No usage limit ${input.id} in this workspace`,
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+
+ const scope = buildUsageLimitScope(input.payload);
+
+ await this.assertScopeIsFree({
+ workspaceId,
+ scope,
+ allowedUsageLimitId: usageLimit.id,
+ });
+
+ await this.usageLimitRepository.update(
+ workspaceId,
+ { id: usageLimit.id },
+ {
+ ...scope,
+ limitValue: input.payload.limitValue,
+ burstValue: input.payload.burstValue ?? null,
+ },
+ );
+
+ await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
+ 'usageLimits',
+ ]);
+
+ const updatedUsageLimit = await this.usageLimitRepository.findOneOrFail(
+ workspaceId,
+ { where: { id: usageLimit.id } },
+ );
+
+ // counters are keyed by scope, so a scope change leaves two of them to rewarm
+ await this.usageLimitQuotaService.dropLimitCounter(usageLimit);
+ await this.usageLimitQuotaService.dropLimitCounter(updatedUsageLimit);
+
+ return updatedUsageLimit;
+ }
+
+ private async assertScopeIsFree({
+ workspaceId,
+ scope,
+ allowedUsageLimitId,
+ }: {
+ workspaceId: string;
+ scope: ReturnType<typeof buildUsageLimitScope>;
+ allowedUsageLimitId?: string;
+ }): Promise<void> {
+ const usageLimitHoldingScope = await this.usageLimitRepository.findOne(
+ workspaceId,
+ { where: scope },
+ );
+
+ if (
+ isDefined(usageLimitHoldingScope) &&
+ usageLimitHoldingScope.id !== allowedUsageLimitId
+ ) {
+ throw new UsageLimitException(
+ 'Another usage limit already covers this scope',
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
+ }
+ }
+
+ private async validateInput({
+ workspaceId,
+ input,
+ }: {
+ workspaceId: string;
+ input: CreateUsageLimitInput;
+ }): Promise<void> {
validateUsageLimitAgainstDefinition(input);
if (
@@ -87,43 +202,6 @@ export class UsageLimitService {
spenderId: input.spenderId,
});
}
-
- const scope = {
- resourceType: input.resourceType,
- operationType: input.operationType,
- spenderType: input.spenderType,
- spenderId: input.spenderId ?? '',
- limitKind: input.limitKind,
- periodCount: input.periodCount,
- periodUnit: input.periodUnit,
- meter: input.meter,
- };
-
- await this.usageLimitRepository.upsert(
- workspaceId,
- {
- workspaceId,
- ...scope,
- limitValue: input.limitValue,
- burstValue: input.burstValue ?? null,
- },
- { conflictPaths: ['workspaceId', ...Object.keys(scope)] },
- );
-
- await this.workspaceCacheService.invalidateAndRecompute(workspaceId, [
- 'usageLimits',
- ]);
-
- const usageLimit = await this.usageLimitRepository.findOneOrFail(
- workspaceId,
- {
- where: scope,
- },
- );
-
- await this.usageLimitQuotaService.dropLimitCounter(usageLimit);
-
- return usageLimit;
}
async delete({
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts
new file mode 100644
index 00000000000..d63b3270a3c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-consumption.service.ts
@@ -0,0 +1,208 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+import { In } from 'typeorm';
+
+import { ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
+import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
+import { type UsageQuotaScopeInput } from 'src/engine/core-modules/usage-limit/dtos/usage-quota-scope.input';
+import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
+import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
+import { UsageLimitService } from 'src/engine/core-modules/usage-limit/services/usage-limit.service';
+import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageQuotaScopeConsumption } from 'src/engine/core-modules/usage-limit/types/usage-quota-scope-consumption.type';
+import { type UsageQuotaWithConsumption } from 'src/engine/core-modules/usage-limit/types/usage-quota-with-consumption.type';
+import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+import { buildCustomQuota } from 'src/engine/core-modules/usage-limit/utils/build-custom-quota.util';
+import { getPeriodAnchor } from 'src/engine/core-modules/usage-limit/utils/get-period-anchor.util';
+import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
+import { groupSpenderIdsByType } from 'src/engine/core-modules/usage-limit/utils/group-spender-ids-by-type.util';
+import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
+import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+
+@Injectable()
+export class UsageQuotaConsumptionService {
+ private readonly logger = new Logger(UsageQuotaConsumptionService.name);
+
+ constructor(
+ @InjectWorkspaceScopedRepository(ApiKeyEntity)
+ private readonly apiKeyRepository: WorkspaceScopedRepository<ApiKeyEntity>,
+ @InjectWorkspaceScopedRepository(ApplicationEntity)
+ private readonly applicationRepository: WorkspaceScopedRepository<ApplicationEntity>,
+ @InjectWorkspaceScopedRepository(UserWorkspaceEntity)
+ private readonly userWorkspaceRepository: WorkspaceScopedRepository<UserWorkspaceEntity>,
+ @InjectWorkspaceScopedRepository(AgentEntity)
+ private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,
+ @InjectWorkspaceScopedRepository(LogicFunctionEntity)
+ private readonly logicFunctionRepository: WorkspaceScopedRepository<LogicFunctionEntity>,
+ private readonly usageLimitService: UsageLimitService,
+ private readonly usageLimitQuotaService: UsageLimitQuotaService,
+ private readonly usageLimitEntitlementService: UsageLimitEntitlementService,
+ private readonly usagePeriodService: UsagePeriodService,
+ private readonly usageAnalyticsService: UsageAnalyticsService,
+ ) {}
+
+ async findQuotasWithConsumption(
+ workspaceId: string,
+ ): Promise<UsageQuotaWithConsumption[]> {
+ return this.buildCustomQuotas(workspaceId);
+ }
+
+ async findConsumptionForScope({
+ workspaceId,
+ scope,
+ }: {
+ workspaceId: string;
+ scope: UsageQuotaScopeInput;
+ }): Promise<UsageQuotaScopeConsumption | null> {
+ const periodUnit = scope.periodUnit;
+
+ if (periodUnit === 'second') {
+ return null;
+ }
+
+ const period = await this.usagePeriodService.findCurrentPeriod({
+ workspaceId,
+ periodUnit,
+ });
+
+ if (!isDefined(period)) {
+ return null;
+ }
+
+ try {
+ const totals =
+ await this.usageAnalyticsService.getConsumptionTotalsForScope({
+ workspaceId,
+ resourceType: scope.resourceType,
+ operationType: scope.operationType,
+ spenderType: scope.spenderType,
+ spenderId: normalizeSpenderId(scope.spenderId ?? ''),
+ periodStart: period.periodStart,
+ periodEnd: period.periodEnd,
+ periodAnchor: getPeriodAnchor(periodUnit),
+ });
+
+ return {
+ consumedValue: Number(totals[scope.meter]),
+ periodStart: period.periodStart,
+ periodEnd: period.periodEnd,
+ };
+ } catch (error) {
+ this.logger.error(
+ `Could not read the scope consumption for workspace ${workspaceId}: ${error instanceof Error ? error.message : 'unknown error'}`,
+ );
+
+ return {
+ consumedValue: null,
+ periodStart: period.periodStart,
+ periodEnd: period.periodEnd,
+ };
+ }
+ }
+
+ private async buildCustomQuotas(
+ workspaceId: string,
+ ): Promise<UsageQuotaWithConsumption[]> {
+ const usageLimits = (
+ await this.usageLimitService.findAll(workspaceId)
+ ).filter((usageLimit) => usageLimit.limitKind === 'quota');
+
+ if (usageLimits.length === 0) {
+ return [];
+ }
+
+ const enforceableLimits =
+ await this.usageLimitEntitlementService.findEnforceableLimits({
+ workspaceId,
+ limits: usageLimits,
+ });
+
+ const enforceableIds = new Set(enforceableLimits.map((limit) => limit.id));
+
+ const [consumptionById, spenderLabelById] = await Promise.all([
+ this.usageLimitQuotaService.readLimitConsumptions({
+ workspaceId,
+ limits: enforceableLimits,
+ }),
+ this.findSpenderLabels({ workspaceId, usageLimits }),
+ ]);
+
+ return usageLimits.map((usageLimit) =>
+ buildCustomQuota({
+ usageLimit,
+ isEnforced: enforceableIds.has(usageLimit.id),
+ consumption: consumptionById.get(usageLimit.id),
+ spenderLabel: spenderLabelById.get(usageLimit.spenderId) ?? null,
+ }),
+ );
+ }
+
+ private async findSpenderLabels({
+ workspaceId,
+ usageLimits,
+ }: {
+ workspaceId: string;
+ usageLimits: UsageLimitEntity[];
+ }): Promise<Map<string, string>> {
+ const idsByType = groupSpenderIdsByType(usageLimits);
+
+ const labelEntries = await Promise.all(
+ [...idsByType.entries()].map(([spenderType, ids]) =>
+ this.findSpenderLabelsByType({ workspaceId, spenderType, ids }),
+ ),
+ );
+
+ return new Map(labelEntries.flat());
+ }
+
+ private async findSpenderLabelsByType({
+ workspaceId,
+ spenderType,
+ ids,
+ }: {
+ workspaceId: string;
+ spenderType: SpenderType;
+ ids: string[];
+ }): Promise<[string, string][]> {
+ const where = { id: In(ids) };
+
+ switch (spenderType) {
+ case 'userWorkspace': {
+ const userWorkspaces = await this.userWorkspaceRepository.find(
+ workspaceId,
+ { where, relations: ['user'] },
+ );
+
+ return userWorkspaces.map((userWorkspace) => [
+ userWorkspace.id,
+ `${userWorkspace.user.firstName} ${userWorkspace.user.lastName}`.trim() ||
+ userWorkspace.user.email,
+ ]);
+ }
+ case 'apiKey':
+ return (await this.apiKeyRepository.find(workspaceId, { where })).map(
+ (apiKey) => [apiKey.id, apiKey.name],
+ );
+ case 'application':
+ return (
+ await this.applicationRepository.find(workspaceId, { where })
+ ).map((application) => [application.id, application.name]);
+ case 'agent':
+ return (await this.agentRepository.find(workspaceId, { where })).map(
+ (agent) => [agent.id, agent.label],
+ );
+ case 'logicFunction':
+ return (
+ await this.logicFunctionRepository.find(workspaceId, { where })
+ ).map((logicFunction) => [logicFunction.id, logicFunction.name]);
+ default:
+ return [];
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-definition.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-definition.service.ts
new file mode 100644
index 00000000000..9d97bbe9f48
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-quota-definition.service.ts
@@ -0,0 +1,32 @@
+import { Injectable } from '@nestjs/common';
+
+import { type UsageQuotaDefinitionsDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-quota-definitions.dto';
+import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
+import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
+import { buildQuotaDefinitions } from 'src/engine/core-modules/usage-limit/utils/build-quota-definitions.util';
+
+@Injectable()
+export class UsageQuotaDefinitionService {
+ constructor(
+ private readonly usageLimitEntitlementService: UsageLimitEntitlementService,
+ private readonly usagePeriodService: UsagePeriodService,
+ ) {}
+
+ async findDefinitions(
+ workspaceId: string,
+ ): Promise<UsageQuotaDefinitionsDTO> {
+ const [isIntraWorkspaceLimitEntitled, hasAllowancePeriod] =
+ await Promise.all([
+ this.usageLimitEntitlementService.isIntraWorkspaceLimitEntitled(
+ workspaceId,
+ ),
+ this.usagePeriodService.hasAllowancePeriod(workspaceId),
+ ]);
+
+ return {
+ definitions: buildQuotaDefinitions(),
+ isIntraWorkspaceLimitEntitled,
+ hasAllowancePeriod,
+ };
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-consumption.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-consumption.type.ts
new file mode 100644
index 00000000000..f3c0d397522
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-consumption.type.ts
@@ -0,0 +1,6 @@
+export type LimitConsumption = {
+ consumedValue: number | null;
+ remainingValue: number | null;
+ periodStart: Date;
+ periodEnd: Date;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-quota-scope-consumption.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-quota-scope-consumption.type.ts
new file mode 100644
index 00000000000..81ca7dfa0da
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-quota-scope-consumption.type.ts
@@ -0,0 +1,5 @@
+export type UsageQuotaScopeConsumption = {
+ consumedValue: number | null;
+ periodStart: Date;
+ periodEnd: Date;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-quota-with-consumption.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-quota-with-consumption.type.ts
new file mode 100644
index 00000000000..3cc8fda7012
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-quota-with-consumption.type.ts
@@ -0,0 +1,22 @@
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+export type UsageQuotaWithConsumption = {
+ id: string;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ spenderType: SpenderType;
+ spenderId: string | null;
+ spenderLabel: string | null;
+ periodUnit: PeriodUnit;
+ meter: UsageMeter;
+ limitValue: number;
+ isEnforced: boolean;
+ consumedValue: number | null;
+ remainingValue: number | null;
+ periodStart: Date | null;
+ periodEnd: Date | null;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
index 40ea9bb1e5d..54b8474b5d4 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
@@ -2,7 +2,6 @@ import { Module } from '@nestjs/common';
import { DiscoveryModule } from '@nestjs/core';
import { TypeOrmModule } from '@nestjs/typeorm';
-import { ClickHouseModule } from 'src/database/clickhouse/clickhouse.module';
import { ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
@@ -13,6 +12,8 @@ import { ApplicationEntity } from 'src/engine/core-modules/application/applicati
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
import { LogicFunctionEntity } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
+import { UsageQuotaConsumptionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-consumption.service';
+import { UsageQuotaDefinitionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-definition.service';
import { UsageLimitEntitlementService } from 'src/engine/core-modules/usage-limit/services/usage-limit-entitlement.service';
import { UsageLimitSpeedService } from 'src/engine/core-modules/usage-limit/services/usage-limit-speed.service';
import { UsageLimitResolver } from 'src/engine/core-modules/usage-limit/usage-limit.resolver';
@@ -37,7 +38,6 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
PermissionsModule,
DiscoveryModule,
CacheLockModule,
- ClickHouseModule,
MetricsModule,
UsageModule,
],
@@ -48,6 +48,8 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
UsageLimitsCacheService,
UsagePeriodService,
UsageLimitService,
+ UsageQuotaConsumptionService,
+ UsageQuotaDefinitionService,
UsageLimitResolver,
provideWorkspaceScopedRepository(UsageLimitEntity),
provideWorkspaceScopedRepository(ApiKeyEntity),
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.resolver.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.resolver.ts
index 8640271d2bb..e85cfdfdb63 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.resolver.ts
@@ -7,9 +7,16 @@ import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';
import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
-import { UpsertUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input';
+import { UpdateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/update-usage-limit.input';
+import { CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
+import { UsageQuotaDefinitionsDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-quota-definitions.dto';
+import { UsageQuotaWithConsumptionDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-quota-with-consumption.dto';
+import { UsageQuotaScopeConsumptionDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-quota-scope-consumption.dto';
+import { UsageQuotaScopeInput } from 'src/engine/core-modules/usage-limit/dtos/usage-quota-scope.input';
import { UsageLimitDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-limit.dto';
import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
+import { UsageQuotaConsumptionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-consumption.service';
+import { UsageQuotaDefinitionService } from 'src/engine/core-modules/usage-limit/services/usage-quota-definition.service';
import { UsageLimitService } from 'src/engine/core-modules/usage-limit/services/usage-limit.service';
import { fromUsageLimitEntityToDto } from 'src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -28,7 +35,11 @@ import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
SettingsPermissionGuard(PermissionFlagType.WORKSPACE),
)
export class UsageLimitResolver {
- constructor(private readonly usageLimitService: UsageLimitService) {}
+ constructor(
+ private readonly usageLimitService: UsageLimitService,
+ private readonly usageQuotaConsumptionService: UsageQuotaConsumptionService,
+ private readonly usageQuotaDefinitionService: UsageQuotaDefinitionService,
+ ) {}
@Query(() => [UsageLimitDTO])
async usageLimits(
@@ -39,12 +50,52 @@ export class UsageLimitResolver {
return usageLimits.map(fromUsageLimitEntityToDto);
}
+ @Query(() => [UsageQuotaWithConsumptionDTO])
+ async usageQuotasWithConsumption(
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ ): Promise<UsageQuotaWithConsumptionDTO[]> {
+ return this.usageQuotaConsumptionService.findQuotasWithConsumption(
+ workspace.id,
+ );
+ }
+
+ @Query(() => UsageQuotaDefinitionsDTO)
+ async usageQuotaDefinitions(
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ ): Promise<UsageQuotaDefinitionsDTO> {
+ return this.usageQuotaDefinitionService.findDefinitions(workspace.id);
+ }
+
+ @Query(() => UsageQuotaScopeConsumptionDTO, { nullable: true })
+ async usageQuotaScopeConsumption(
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ @Args('input') input: UsageQuotaScopeInput,
+ ): Promise<UsageQuotaScopeConsumptionDTO | null> {
+ return this.usageQuotaConsumptionService.findConsumptionForScope({
+ workspaceId: workspace.id,
+ scope: input,
+ });
+ }
+
+ @Mutation(() => UsageLimitDTO)
+ async createUsageLimit(
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ @Args('input') input: CreateUsageLimitInput,
+ ): Promise<UsageLimitDTO> {
+ const usageLimit = await this.usageLimitService.create({
+ workspaceId: workspace.id,
+ input,
+ });
+
+ return fromUsageLimitEntityToDto(usageLimit);
+ }
+
@Mutation(() => UsageLimitDTO)
- async upsertUsageLimit(
+ async updateUsageLimit(
@AuthWorkspace() workspace: WorkspaceEntity,
- @Args('input') input: UpsertUsageLimitInput,
+ @Args('input') input: UpdateUsageLimitInput,
): Promise<UsageLimitDTO> {
- const usageLimit = await this.usageLimitService.upsert({
+ const usageLimit = await this.usageLimitService.update({
workspaceId: workspace.id,
input,
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-custom-quota.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-custom-quota.util.spec.ts
new file mode 100644
index 00000000000..f0fa043846d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-custom-quota.util.spec.ts
@@ -0,0 +1,85 @@
+import { buildCustomQuota } from 'src/engine/core-modules/usage-limit/utils/build-custom-quota.util';
+import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const MONTH_PERIOD = {
+ periodStart: new Date('2026-09-01T00:00:00.000Z'),
+ periodEnd: new Date('2026-10-01T00:00:00.000Z'),
+};
+
+const buildUsageLimit = (overrides: Partial<UsageLimitEntity> = {}) => ({
+ id: 'limit-1',
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace' as const,
+ spenderId: '',
+ periodUnit: 'month' as const,
+ meter: 'creditsUsedMicro' as const,
+ limitValue: 1_000_000,
+ ...overrides,
+});
+
+describe('buildCustomQuota', () => {
+ it('carries the consumption and the period of the counter', () => {
+ expect(
+ buildCustomQuota({
+ usageLimit: buildUsageLimit(),
+ isEnforced: true,
+ consumption: {
+ consumedValue: 250_000,
+ remainingValue: 750_000,
+ ...MONTH_PERIOD,
+ },
+ spenderLabel: null,
+ }),
+ ).toEqual(
+ expect.objectContaining({
+ id: 'limit-1',
+ spenderId: null,
+ consumedValue: 250_000,
+ remainingValue: 750_000,
+ periodEnd: MONTH_PERIOD.periodEnd,
+ isEnforced: true,
+ }),
+ );
+ });
+
+ it('leaves consumption and period empty when the counter was not read', () => {
+ const item = buildCustomQuota({
+ usageLimit: buildUsageLimit(),
+ isEnforced: false,
+ consumption: undefined,
+ spenderLabel: null,
+ });
+
+ expect(item).toEqual(
+ expect.objectContaining({
+ isEnforced: false,
+ consumedValue: null,
+ remainingValue: null,
+ periodStart: null,
+ periodEnd: null,
+ }),
+ );
+ });
+
+ it('exposes the spender id and its label when the limit targets one spender', () => {
+ expect(
+ buildCustomQuota({
+ usageLimit: buildUsageLimit({
+ spenderType: 'userWorkspace',
+ spenderId: 'user-1',
+ }),
+ isEnforced: true,
+ consumption: undefined,
+ spenderLabel: 'Tim Apple',
+ }),
+ ).toEqual(
+ expect.objectContaining({
+ spenderId: 'user-1',
+ spenderLabel: 'Tim Apple',
+ }),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-limit-warmed-entries.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-limit-warmed-entries.util.spec.ts
index 5edfe115321..b0aca173fb7 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-limit-warmed-entries.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-limit-warmed-entries.util.spec.ts
@@ -1,5 +1,5 @@
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
-import { type QuotaConsumptionRow } from 'src/engine/core-modules/usage-limit/types/quota-consumption-row.type';
+import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
import { buildLimitWarmedEntries } from 'src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util';
import { buildPeriodGroupKey } from 'src/engine/core-modules/usage-limit/utils/build-period-group-key.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
@@ -25,8 +25,8 @@ const buildCounter = (
});
const buildRow = (
- overrides: Partial<QuotaConsumptionRow> = {},
-): QuotaConsumptionRow => ({
+ overrides: Partial<UsageConsumptionRow> = {},
+): UsageConsumptionRow => ({
operationType: UsageOperationType.AI_CHAT_TOKEN,
userWorkspaceId: 'user-1',
apiKeyId: '',
@@ -41,7 +41,7 @@ const buildRow = (
const buildRowsByPeriod = (
counter: LimitQuotaCounter,
- rows: QuotaConsumptionRow[],
+ rows: UsageConsumptionRow[],
) => new Map([[buildPeriodGroupKey(counter), rows]]);
describe('buildLimitWarmedEntries', () => {
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
index 1b6f91a140d..6bf0da131c6 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
@@ -33,7 +33,6 @@ const buildCounters = ({ limits }: { limits: FlatUsageLimit[] }) =>
limits,
usageSpenders: { userWorkspaceId: 'user-1' },
workspaceId: 'workspace-1',
- resourceType: UsageResourceType.AI,
operationType: UsageOperationType.AI_CHAT_TOKEN,
periodByUnit: { month: MONTH_PERIOD, week: WEEK_PERIOD },
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
new file mode 100644
index 00000000000..0d07a21925c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-definitions.util.spec.ts
@@ -0,0 +1,20 @@
+import { buildQuotaDefinitions } from 'src/engine/core-modules/usage-limit/utils/build-quota-definitions.util';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+describe('buildQuotaDefinitions', () => {
+ it('exposes only the resources that define a quota', () => {
+ const resourceTypes = buildQuotaDefinitions().map(
+ (definition) => definition.resourceType,
+ );
+
+ expect(resourceTypes).toEqual([UsageResourceType.AI]);
+ });
+
+ it('carries the allow lists a form needs to offer a scope', () => {
+ const [definition] = buildQuotaDefinitions();
+
+ expect(definition.allowedOperationTypes.length).toBeGreaterThan(0);
+ expect(definition.allowedSpenderTypes).toContain('workspace');
+ expect(definition.allowedMeters).toContain('creditsUsedMicro');
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-usage-limit-scope.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-usage-limit-scope.util.spec.ts
new file mode 100644
index 00000000000..49d36289973
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-usage-limit-scope.util.spec.ts
@@ -0,0 +1,42 @@
+import { type CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
+import { buildUsageLimitScope } from 'src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const buildInput = (
+ overrides: Partial<CreateUsageLimitInput> = {},
+): CreateUsageLimitInput => ({
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace',
+ spenderId: null,
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ meter: 'creditsUsedMicro',
+ limitValue: 1_000_000,
+ burstValue: null,
+ ...overrides,
+});
+
+describe('buildUsageLimitScope', () => {
+ it('keeps the columns the unique index covers, and drops the values', () => {
+ expect(buildUsageLimitScope(buildInput())).toEqual({
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace',
+ spenderId: '',
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ meter: 'creditsUsedMicro',
+ });
+ });
+
+ it('stores an absent spender id as the empty string the index matches on', () => {
+ expect(buildUsageLimitScope(buildInput()).spenderId).toBe('');
+ expect(
+ buildUsageLimitScope(buildInput({ spenderId: 'user-1' })).spenderId,
+ ).toBe('user-1');
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts
index f56d5195689..c68aad76103 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts
@@ -1,12 +1,12 @@
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
-import { type QuotaConsumptionRow } from 'src/engine/core-modules/usage-limit/types/quota-consumption-row.type';
+import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
import { computeQuotaConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
const buildRow = (
- overrides: Partial<QuotaConsumptionRow>,
-): QuotaConsumptionRow => ({
+ overrides: Partial<UsageConsumptionRow>,
+): UsageConsumptionRow => ({
operationType: UsageOperationType.AI_CHAT_TOKEN,
userWorkspaceId: 'user-1',
apiKeyId: '',
@@ -53,15 +53,15 @@ const rows = [
];
describe('computeQuotaConsumed', () => {
- it('sums every row for a workspace counter with no operation', () => {
- expect(computeQuotaConsumed({ rows, counter: buildCounter({}) })).toBe(147);
+ it('sums every row for a workspace scope with no operation', () => {
+ expect(computeQuotaConsumed({ rows, scope: buildCounter({}) })).toBe(147);
});
- it('cuts by operation when the counter names one', () => {
+ it('cuts by operation when the scope names one', () => {
expect(
computeQuotaConsumed({
rows,
- counter: buildCounter({
+ scope: buildCounter({
operationType: UsageOperationType.AI_CHAT_TOKEN,
}),
}),
@@ -72,7 +72,7 @@ describe('computeQuotaConsumed', () => {
expect(
computeQuotaConsumed({
rows,
- counter: buildCounter({
+ scope: buildCounter({
spenderType: 'userWorkspace',
spenderId: 'user-2',
}),
@@ -84,7 +84,7 @@ describe('computeQuotaConsumed', () => {
expect(
computeQuotaConsumed({
rows,
- counter: buildCounter({
+ scope: buildCounter({
spenderType: 'userWorkspace',
spenderId: null,
}),
@@ -96,7 +96,7 @@ describe('computeQuotaConsumed', () => {
expect(
computeQuotaConsumed({
rows,
- counter: buildCounter({ meter: 'quantity' }),
+ scope: buildCounter({ meter: 'quantity' }),
}),
).toBe(23);
});
@@ -105,7 +105,7 @@ describe('computeQuotaConsumed', () => {
expect(
computeQuotaConsumed({
rows,
- counter: buildCounter({ spenderType: 'agent', spenderId: 'agent-1' }),
+ scope: buildCounter({ spenderType: 'agent', spenderId: 'agent-1' }),
}),
).toBe(100);
});
@@ -114,7 +114,7 @@ describe('computeQuotaConsumed', () => {
expect(
computeQuotaConsumed({
rows,
- counter: buildCounter({
+ scope: buildCounter({
spenderType: 'workflow',
spenderId: 'workflow-1',
}),
@@ -126,7 +126,7 @@ describe('computeQuotaConsumed', () => {
expect(
computeQuotaConsumed({
rows,
- counter: buildCounter({
+ scope: buildCounter({
spenderType: 'logicFunction',
spenderId: 'logic-function-1',
}),
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/group-spender-ids-by-type.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/group-spender-ids-by-type.util.spec.ts
new file mode 100644
index 00000000000..41a0e987c7b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/group-spender-ids-by-type.util.spec.ts
@@ -0,0 +1,27 @@
+import { groupSpenderIdsByType } from 'src/engine/core-modules/usage-limit/utils/group-spender-ids-by-type.util';
+
+describe('groupSpenderIdsByType', () => {
+ it('groups the spender ids of every scoped limit by spender type', () => {
+ expect(
+ groupSpenderIdsByType([
+ { spenderType: 'userWorkspace', spenderId: 'user-1' },
+ { spenderType: 'userWorkspace', spenderId: 'user-2' },
+ { spenderType: 'apiKey', spenderId: 'key-1' },
+ ]),
+ ).toEqual(
+ new Map([
+ ['userWorkspace', ['user-1', 'user-2']],
+ ['apiKey', ['key-1']],
+ ]),
+ );
+ });
+
+ it('skips limits shared by every spender of their type', () => {
+ expect(
+ groupSpenderIdsByType([
+ { spenderType: 'workspace', spenderId: '' },
+ { spenderType: 'agent', spenderId: '' },
+ ]),
+ ).toEqual(new Map());
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts
index 61c8c4d958f..e9aad332040 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-definition.util.spec.ts
@@ -1,10 +1,10 @@
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
-import { type UpsertUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input';
+import { type CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
import { UsageLimitExceptionCode } from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
import { validateUsageLimitAgainstDefinition } from 'src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util';
-const validSpeedLimit: UpsertUsageLimitInput = {
+const validSpeedLimit: CreateUsageLimitInput = {
resourceType: UsageResourceType.API,
operationType: UsageOperationType.API_REQUEST,
spenderType: 'apiKey',
@@ -16,7 +16,7 @@ const validSpeedLimit: UpsertUsageLimitInput = {
limitValue: 100,
};
-const validQuotaLimit: UpsertUsageLimitInput = {
+const validQuotaLimit: CreateUsageLimitInput = {
resourceType: UsageResourceType.AI,
operationType: UsageOperationType.AI_CHAT_TOKEN,
spenderType: 'workspace',
@@ -142,16 +142,26 @@ describe('validateUsageLimitAgainstDefinition', () => {
).not.toThrow();
});
- it('accepts a quota scoped to one agent', () => {
+ it('accepts a quota scoped to one application', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
...validQuotaLimit,
- spenderType: 'agent',
+ spenderType: 'application',
spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
}),
).not.toThrow();
});
+ it('rejects a quota scoped to an agent, which spends through its workflow', () => {
+ expect(() =>
+ validateUsageLimitAgainstDefinition({
+ ...validQuotaLimit,
+ spenderType: 'agent',
+ spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
+ }),
+ ).toThrow();
+ });
+
it('accepts a quota covering every operation of the resource', () => {
expect(() =>
validateUsageLimitAgainstDefinition({
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-custom-quota.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-custom-quota.util.ts
new file mode 100644
index 00000000000..0e70d2c30ea
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-custom-quota.util.ts
@@ -0,0 +1,45 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type LimitConsumption } from 'src/engine/core-modules/usage-limit/types/limit-consumption.type';
+import { type UsageQuotaWithConsumption } from 'src/engine/core-modules/usage-limit/types/usage-quota-with-consumption.type';
+import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
+
+type CustomQuotaScope = Pick<
+ UsageLimitEntity,
+ | 'id'
+ | 'resourceType'
+ | 'operationType'
+ | 'spenderType'
+ | 'spenderId'
+ | 'periodUnit'
+ | 'meter'
+ | 'limitValue'
+>;
+
+export const buildCustomQuota = ({
+ usageLimit,
+ isEnforced,
+ consumption,
+ spenderLabel,
+}: {
+ usageLimit: CustomQuotaScope;
+ isEnforced: boolean;
+ consumption: LimitConsumption | undefined;
+ spenderLabel: string | null;
+}): UsageQuotaWithConsumption => ({
+ id: usageLimit.id,
+ resourceType: usageLimit.resourceType,
+ operationType: usageLimit.operationType,
+ spenderType: usageLimit.spenderType,
+ spenderId: normalizeSpenderId(usageLimit.spenderId),
+ spenderLabel,
+ periodUnit: usageLimit.periodUnit,
+ meter: usageLimit.meter,
+ limitValue: usageLimit.limitValue,
+ isEnforced,
+ consumedValue: consumption?.consumedValue ?? null,
+ remainingValue: consumption?.remainingValue ?? null,
+ periodStart: isDefined(consumption) ? consumption.periodStart : null,
+ periodEnd: isDefined(consumption) ? consumption.periodEnd : null,
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts
new file mode 100644
index 00000000000..106eca34d7c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util.ts
@@ -0,0 +1,39 @@
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util';
+import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
+
+export const buildLimitQuotaCounter = ({
+ workspaceId,
+ limit,
+ period,
+}: {
+ workspaceId: string;
+ limit: Omit<
+ FlatUsageLimit,
+ 'id' | 'limitKind' | 'periodCount' | 'burstValue'
+ >;
+ period: UsagePeriod;
+}): LimitQuotaCounter => ({
+ kind: 'limit',
+ key: buildQuotaCounterKey({
+ workspaceId,
+ resourceType: limit.resourceType,
+ operationType: limit.operationType,
+ spenderType: limit.spenderType,
+ spenderId: limit.spenderId,
+ meter: limit.meter,
+ periodUnit: limit.periodUnit,
+ periodStart: period.periodStart,
+ }),
+ limitValue: limit.limitValue,
+ meter: limit.meter,
+ resourceType: limit.resourceType,
+ periodUnit: limit.periodUnit,
+ periodStart: period.periodStart,
+ periodEnd: period.periodEnd,
+ spenderType: limit.spenderType,
+ spenderId: normalizeSpenderId(limit.spenderId),
+ operationType: limit.operationType,
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util.ts
index baf609fbefe..14e13f82bc1 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util.ts
@@ -1,7 +1,7 @@
import { isDefined } from 'twenty-shared/utils';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
-import { type QuotaConsumptionRow } from 'src/engine/core-modules/usage-limit/types/quota-consumption-row.type';
+import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
import { buildPeriodGroupKey } from 'src/engine/core-modules/usage-limit/utils/build-period-group-key.util';
import { computeQuotaConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
@@ -11,7 +11,7 @@ export const buildLimitWarmedEntries = ({
now,
}: {
coldLimitCounters: LimitQuotaCounter[];
- rowsByPeriod: Map<string, QuotaConsumptionRow[]>;
+ rowsByPeriod: Map<string, UsageConsumptionRow[]>;
now: number;
}): { key: string; value: number; ttl: number }[] =>
coldLimitCounters.flatMap((counter) => {
@@ -25,7 +25,8 @@ export const buildLimitWarmedEntries = ({
return [
{
key: counter.key,
- value: counter.limitValue - computeQuotaConsumed({ rows, counter }),
+ value:
+ counter.limitValue - computeQuotaConsumed({ rows, scope: counter }),
ttl,
},
];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
index 2786698c9fe..b56e5d488dd 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
@@ -4,12 +4,10 @@ import { SPENDER_TYPE_SPECIFICITY } from 'src/engine/core-modules/usage-limit/co
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
-import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util';
+import { buildLimitQuotaCounter } from 'src/engine/core-modules/usage-limit/utils/build-limit-quota-counter.util';
import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util';
import { findLimitsForSpender } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util';
-import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
-import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
@@ -22,14 +20,12 @@ export const buildQuotaCounters = ({
limits,
usageSpenders,
workspaceId,
- resourceType,
operationType,
periodByUnit,
}: {
limits: FlatUsageLimit[];
usageSpenders: UsageSpenders;
workspaceId: string;
- resourceType: UsageResourceType;
operationType: UsageOperationType;
periodByUnit: Partial<Record<PeriodUnit, UsagePeriod>>;
}): LimitQuotaCounter[] => {
@@ -44,30 +40,7 @@ export const buildQuotaCounters = ({
return [];
}
- return [
- {
- kind: 'limit' as const,
- key: buildQuotaCounterKey({
- workspaceId,
- resourceType,
- operationType: limit.operationType,
- spenderType: limit.spenderType,
- spenderId: limit.spenderId,
- meter: limit.meter,
- periodUnit: limit.periodUnit,
- periodStart: period.periodStart,
- }),
- limitValue: limit.limitValue,
- meter: limit.meter,
- resourceType,
- periodUnit: limit.periodUnit,
- periodStart: period.periodStart,
- periodEnd: period.periodEnd,
- spenderType: limit.spenderType,
- spenderId: normalizeSpenderId(limit.spenderId),
- operationType: limit.operationType,
- },
- ];
+ return [buildLimitQuotaCounter({ workspaceId, limit, period })];
},
),
);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts
new file mode 100644
index 00000000000..633746dee18
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-definitions.util.ts
@@ -0,0 +1,21 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { USAGE_LIMIT_DEFINITIONS } from 'src/engine/core-modules/usage-limit/constants/usage-limit-definitions.constant';
+import { type UsageQuotaDefinitionDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+export const buildQuotaDefinitions = (): UsageQuotaDefinitionDTO[] =>
+ Object.values(UsageResourceType).flatMap((resourceType) => {
+ const { quota } = USAGE_LIMIT_DEFINITIONS[resourceType];
+
+ return isDefined(quota)
+ ? [
+ {
+ resourceType,
+ allowedOperationTypes: quota.allowedOperationTypes,
+ allowedSpenderTypes: quota.allowedSpenderTypes,
+ allowedMeters: quota.allowedMeters,
+ },
+ ]
+ : [];
+ });
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util.ts
new file mode 100644
index 00000000000..6640684551f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-scope.util.ts
@@ -0,0 +1,27 @@
+import { type CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
+import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+
+type UsageLimitScope = Pick<
+ UsageLimitEntity,
+ | 'resourceType'
+ | 'operationType'
+ | 'spenderType'
+ | 'spenderId'
+ | 'limitKind'
+ | 'periodCount'
+ | 'periodUnit'
+ | 'meter'
+>;
+
+export const buildUsageLimitScope = (
+ input: CreateUsageLimitInput,
+): UsageLimitScope => ({
+ resourceType: input.resourceType,
+ operationType: input.operationType,
+ spenderType: input.spenderType,
+ spenderId: input.spenderId ?? '',
+ limitKind: input.limitKind,
+ periodCount: input.periodCount,
+ periodUnit: input.periodUnit,
+ meter: input.meter,
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts
index 6f5888a440b..5b86f8d39eb 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts
@@ -2,9 +2,10 @@ import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { USAGE_SPENDER_COLUMN_BY_SPENDER_TYPE } from 'src/engine/core-modules/usage-limit/constants/usage-spender-column-by-spender-type.constant';
import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
-import { type QuotaConsumptionRow } from 'src/engine/core-modules/usage-limit/types/quota-consumption-row.type';
+import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
const spenderColumnMatches = (
rowValue: string,
@@ -12,42 +13,39 @@ const spenderColumnMatches = (
): boolean =>
isDefined(spenderId) ? rowValue === spenderId : isNonEmptyString(rowValue);
-const rowMatchesCounter = (
- row: QuotaConsumptionRow,
- counter: LimitQuotaCounter,
+export type QuotaConsumptionScope = Pick<
+ LimitQuotaCounter,
+ 'operationType' | 'spenderType' | 'spenderId' | 'meter'
+>;
+
+const rowMatchesScope = (
+ row: UsageConsumptionRow,
+ scope: QuotaConsumptionScope,
): boolean => {
if (
- counter.operationType !== UsageOperationType.ALL &&
- row.operationType !== counter.operationType
+ scope.operationType !== UsageOperationType.ALL &&
+ row.operationType !== scope.operationType
) {
return false;
}
- switch (counter.spenderType) {
- case 'workspace':
- return true;
- case 'userWorkspace':
- return spenderColumnMatches(row.userWorkspaceId, counter.spenderId);
- case 'apiKey':
- return spenderColumnMatches(row.apiKeyId, counter.spenderId);
- case 'application':
- return spenderColumnMatches(row.applicationId, counter.spenderId);
- case 'agent':
- return spenderColumnMatches(row.agentId, counter.spenderId);
- case 'workflow':
- return spenderColumnMatches(row.workflowId, counter.spenderId);
- case 'logicFunction':
- return spenderColumnMatches(row.logicFunctionId, counter.spenderId);
+ if (scope.spenderType === 'workspace') {
+ return true;
}
+
+ return spenderColumnMatches(
+ row[USAGE_SPENDER_COLUMN_BY_SPENDER_TYPE[scope.spenderType]],
+ scope.spenderId,
+ );
};
export const computeQuotaConsumed = ({
rows,
- counter,
+ scope,
}: {
- rows: QuotaConsumptionRow[];
- counter: LimitQuotaCounter;
+ rows: UsageConsumptionRow[];
+ scope: QuotaConsumptionScope;
}): number =>
rows
- .filter((row) => rowMatchesCounter(row, counter))
- .reduce((total, row) => total + Number(row[counter.meter]), 0);
+ .filter((row) => rowMatchesScope(row, scope))
+ .reduce((total, row) => total + Number(row[scope.meter]), 0);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-period-anchor.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-period-anchor.util.ts
new file mode 100644
index 00000000000..c1eb8725d78
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-period-anchor.util.ts
@@ -0,0 +1,5 @@
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type UsagePeriodAnchor } from 'src/engine/core-modules/usage/types/usage-period-anchor.type';
+
+export const getPeriodAnchor = (periodUnit: PeriodUnit): UsagePeriodAnchor =>
+ periodUnit === 'allowancePeriod' ? 'billing' : 'calendar';
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/group-spender-ids-by-type.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/group-spender-ids-by-type.util.ts
new file mode 100644
index 00000000000..358bf753ef0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/group-spender-ids-by-type.util.ts
@@ -0,0 +1,26 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
+
+export const groupSpenderIdsByType = (
+ usageLimits: Pick<UsageLimitEntity, 'spenderType' | 'spenderId'>[],
+): Map<SpenderType, string[]> => {
+ const idsByType = new Map<SpenderType, string[]>();
+
+ for (const usageLimit of usageLimits) {
+ const spenderId = normalizeSpenderId(usageLimit.spenderId);
+
+ if (!isDefined(spenderId)) {
+ continue;
+ }
+
+ idsByType.set(usageLimit.spenderType, [
+ ...(idsByType.get(usageLimit.spenderType) ?? []),
+ spenderId,
+ ]);
+ }
+
+ return idsByType;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util.ts
index b3048d5142f..eeb9e9af7c8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util.ts
@@ -1,7 +1,7 @@
import { isNonEmptyString } from '@sniptt/guards';
import { isDefined, isValidUuid } from 'twenty-shared/utils';
-import { type UpsertUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/upsert-usage-limit.input';
+import { type CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
import {
UsageLimitException,
UsageLimitExceptionCode,
@@ -10,7 +10,7 @@ import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/ut
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
export const validateUsageLimitAgainstDefinition = (
- input: UpsertUsageLimitInput,
+ input: CreateUsageLimitInput,
): void => {
const definition = findUsageLimitDefinition({
resourceType: input.resourceType,
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts b/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
index d1ae1bc9756..7cbca7f9584 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
@@ -8,9 +8,15 @@ import { isNonEmptyArray } from 'twenty-shared/utils';
import { ClickHouseService } from 'src/database/clickhouse/clickhouse.service';
import { formatDateTimeForClickHouse } from 'src/database/clickhouse/utils/format-date-time-for-clickhouse.util';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
+import { type UsageConsumptionTotals } from 'src/engine/core-modules/usage/types/usage-consumption-totals.type';
+import { type UsagePeriodAnchor } from 'src/engine/core-modules/usage/types/usage-period-anchor.type';
import { buildRecurringChargeKey } from 'src/engine/core-modules/usage/utils/build-recurring-charge-key.util';
+import { buildUsagePeriodClause } from 'src/engine/core-modules/usage/utils/build-usage-period-clause.util';
+import { buildUsageScopeFilter } from 'src/engine/core-modules/usage/utils/build-usage-scope-filter.util';
import { fillUsageTimeSeriesGaps } from 'src/engine/core-modules/usage/utils/fill-usage-time-series-gaps.util';
import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
import { toDollars } from 'src/engine/core-modules/usage/utils/to-dollars.util';
@@ -69,6 +75,115 @@ const DECLARED_OPERATION_KEY_SEPARATOR = ':';
export class UsageAnalyticsService {
constructor(private readonly clickHouseService: ClickHouseService) {}
+ async getConsumptionRowsForAllScopes({
+ workspaceId,
+ resourceType,
+ periodStart,
+ periodEnd,
+ periodAnchor,
+ }: {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ periodStart: Date;
+ periodEnd: Date;
+ periodAnchor: UsagePeriodAnchor;
+ }): Promise<UsageConsumptionRow[]> {
+ const periodClause = buildUsagePeriodClause(periodAnchor);
+
+ // The filtered keys are grouped again so the shape matches the
+ // consumption_by_scope projection, which is only picked on a full key match.
+ return this.clickHouseService.selectOrThrow<UsageConsumptionRow>(
+ `SELECT operationType, userWorkspaceId, apiKeyId, applicationId, agentId,
+ workflowId, logicFunctionId,
+ sum(creditsUsedMicro) AS creditsUsedMicro,
+ sum(quantity) AS quantity
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND resourceType = {resourceType:String}
+ ${periodClause}
+ GROUP BY operationType, userWorkspaceId, apiKeyId, applicationId,
+ agentId, workflowId, logicFunctionId`,
+ {
+ workspaceId,
+ resourceType,
+ periodStart: formatDateTimeForClickHouse(periodStart),
+ periodEnd: formatDateTimeForClickHouse(periodEnd),
+ },
+ );
+ }
+
+ async getConsumptionTotalsForScope({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenderType,
+ spenderId,
+ periodStart,
+ periodEnd,
+ periodAnchor,
+ }: {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ spenderType: SpenderType;
+ spenderId: string | null;
+ periodStart: Date;
+ periodEnd: Date;
+ periodAnchor: UsagePeriodAnchor;
+ }): Promise<UsageConsumptionTotals> {
+ const scopeFilter = buildUsageScopeFilter({
+ operationType,
+ spenderType,
+ spenderId,
+ });
+
+ const rows =
+ await this.clickHouseService.selectOrThrow<UsageConsumptionTotals>(
+ `SELECT sum(creditsUsedMicro) AS creditsUsedMicro,
+ sum(quantity) AS quantity
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND resourceType = {resourceType:String}
+ ${buildUsagePeriodClause(periodAnchor)}
+ ${scopeFilter.clause}`,
+ {
+ workspaceId,
+ resourceType,
+ periodStart: formatDateTimeForClickHouse(periodStart),
+ periodEnd: formatDateTimeForClickHouse(periodEnd),
+ ...scopeFilter.params,
+ },
+ );
+
+ return {
+ creditsUsedMicro: rows[0]?.creditsUsedMicro ?? 0,
+ quantity: rows[0]?.quantity ?? 0,
+ };
+ }
+
+ async getCreditsUsedMicroForBillingPeriod({
+ workspaceId,
+ periodStart,
+ }: {
+ workspaceId: string;
+ periodStart: Date;
+ }): Promise<number> {
+ // Both keys are pinned, so the grouping only exists to match the
+ // billing_by_workspace_period projection; it still returns a single row.
+ const rows = await this.clickHouseService.selectOrThrow<{
+ total: string | number | null;
+ }>(
+ `SELECT sum(creditsUsedMicro) AS total
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND periodStart = {periodStart:DateTime64(3)}
+ GROUP BY workspaceId, periodStart`,
+ { workspaceId, periodStart: formatDateTimeForClickHouse(periodStart) },
+ );
+
+ return Number(rows[0]?.total ?? 0);
+ }
+
async getAdminAiUsageByWorkspace(params: {
periodStart: Date;
periodEnd: Date;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-consumption-row.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-row.type.ts
similarity index 86%
rename from packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-consumption-row.type.ts
rename to packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-row.type.ts
index ca036cdc2dd..af06c62fa55 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-consumption-row.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-row.type.ts
@@ -1,4 +1,4 @@
-export type QuotaConsumptionRow = {
+export type UsageConsumptionRow = {
operationType: string;
userWorkspaceId: string;
apiKeyId: string;
diff --git a/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-totals.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-totals.type.ts
new file mode 100644
index 00000000000..9545c146e0e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/usage-consumption-totals.type.ts
@@ -0,0 +1,6 @@
+import { type UsageConsumptionRow } from 'src/engine/core-modules/usage/types/usage-consumption-row.type';
+
+export type UsageConsumptionTotals = Pick<
+ UsageConsumptionRow,
+ 'creditsUsedMicro' | 'quantity'
+>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage/types/usage-period-anchor.type.ts b/packages/twenty-server/src/engine/core-modules/usage/types/usage-period-anchor.type.ts
new file mode 100644
index 00000000000..45737558165
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/types/usage-period-anchor.type.ts
@@ -0,0 +1 @@
+export type UsagePeriodAnchor = 'billing' | 'calendar';
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/build-usage-period-clause.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/build-usage-period-clause.util.spec.ts
new file mode 100644
index 00000000000..c471db428f8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/build-usage-period-clause.util.spec.ts
@@ -0,0 +1,27 @@
+import { buildUsagePeriodClause } from 'src/engine/core-modules/usage/utils/build-usage-period-clause.util';
+
+describe('buildUsagePeriodClause', () => {
+ it('matches a billing period on the period stamped on the event', () => {
+ const clause = buildUsagePeriodClause('billing');
+
+ expect(clause).toContain('AND periodStart = {periodStart:DateTime64(3)}');
+ expect(clause).toContain(
+ 'AND timestamp >= {periodStart:DateTime64(3)} - INTERVAL 1 DAY',
+ );
+ expect(clause).toContain(
+ 'AND timestamp < {periodEnd:DateTime64(3)} + INTERVAL 1 DAY',
+ );
+ });
+
+ it('matches a calendar period on UTC day buckets', () => {
+ const clause = buildUsagePeriodClause('calendar');
+
+ expect(clause).toContain(
+ "AND toStartOfDay(timestamp, 'UTC') >= {periodStart:DateTime64(3)}",
+ );
+ expect(clause).toContain(
+ "AND toStartOfDay(timestamp, 'UTC') < {periodEnd:DateTime64(3)}",
+ );
+ expect(clause).not.toContain('periodStart =');
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/build-usage-scope-filter.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/build-usage-scope-filter.util.spec.ts
new file mode 100644
index 00000000000..38230880a57
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/build-usage-scope-filter.util.spec.ts
@@ -0,0 +1,68 @@
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { buildUsageScopeFilter } from 'src/engine/core-modules/usage/utils/build-usage-scope-filter.util';
+
+describe('buildUsageScopeFilter', () => {
+ it('narrows nothing for a workspace scope over every operation', () => {
+ const filter = buildUsageScopeFilter({
+ operationType: UsageOperationType.ALL,
+ spenderType: 'workspace',
+ spenderId: null,
+ });
+
+ expect(filter).toEqual({ clause: '', params: {} });
+ });
+
+ it('pins the operation when the scope names one', () => {
+ const filter = buildUsageScopeFilter({
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace',
+ spenderId: null,
+ });
+
+ expect(filter.clause).toContain(
+ 'AND operationType = {operationType:String}',
+ );
+ expect(filter.params).toEqual({
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ });
+ });
+
+ it('pins the spender id on the column of its type', () => {
+ const filter = buildUsageScopeFilter({
+ operationType: UsageOperationType.ALL,
+ spenderType: 'apiKey',
+ spenderId: 'api-key-1',
+ });
+
+ expect(filter.clause).toContain('AND apiKeyId = {spenderId:String}');
+ expect(filter.params).toEqual({ spenderId: 'api-key-1' });
+ });
+
+ it('sums every spender of the type when the scope carries no id', () => {
+ const filter = buildUsageScopeFilter({
+ operationType: UsageOperationType.ALL,
+ spenderType: 'userWorkspace',
+ spenderId: null,
+ });
+
+ expect(filter.clause).toContain("AND userWorkspaceId != ''");
+ expect(filter.params).toEqual({});
+ });
+
+ it.each([
+ ['userWorkspace', 'userWorkspaceId'],
+ ['apiKey', 'apiKeyId'],
+ ['application', 'applicationId'],
+ ['agent', 'agentId'],
+ ['workflow', 'workflowId'],
+ ['logicFunction', 'logicFunctionId'],
+ ] as const)('scopes a %s on %s', (spenderType, column) => {
+ const filter = buildUsageScopeFilter({
+ operationType: UsageOperationType.ALL,
+ spenderType,
+ spenderId: 'spender-1',
+ });
+
+ expect(filter.clause).toBe(`AND ${column} = {spenderId:String}`);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-period-clause.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-period-clause.util.ts
new file mode 100644
index 00000000000..29380abaf06
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-period-clause.util.ts
@@ -0,0 +1,13 @@
+import { type UsagePeriodAnchor } from 'src/engine/core-modules/usage/types/usage-period-anchor.type';
+
+const BILLING_PERIOD_STAMP_SLACK = 'INTERVAL 1 DAY';
+
+export const buildUsagePeriodClause = (
+ periodAnchor: UsagePeriodAnchor,
+): string =>
+ periodAnchor === 'billing'
+ ? `AND periodStart = {periodStart:DateTime64(3)}
+ AND timestamp >= {periodStart:DateTime64(3)} - ${BILLING_PERIOD_STAMP_SLACK}
+ AND timestamp < {periodEnd:DateTime64(3)} + ${BILLING_PERIOD_STAMP_SLACK}`
+ : `AND toStartOfDay(timestamp, 'UTC') >= {periodStart:DateTime64(3)}
+ AND toStartOfDay(timestamp, 'UTC') < {periodEnd:DateTime64(3)}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-scope-filter.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-scope-filter.util.ts
new file mode 100644
index 00000000000..74fabfadcf0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/build-usage-scope-filter.util.ts
@@ -0,0 +1,41 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { USAGE_SPENDER_COLUMN_BY_SPENDER_TYPE } from 'src/engine/core-modules/usage-limit/constants/usage-spender-column-by-spender-type.constant';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+export type UsageScopeFilter = {
+ clause: string;
+ params: Record<string, string>;
+};
+
+export const buildUsageScopeFilter = ({
+ operationType,
+ spenderType,
+ spenderId,
+}: {
+ operationType: UsageOperationType;
+ spenderType: SpenderType;
+ spenderId: string | null;
+}): UsageScopeFilter => {
+ const clauses: string[] = [];
+ const params: Record<string, string> = {};
+
+ if (operationType !== UsageOperationType.ALL) {
+ clauses.push('AND operationType = {operationType:String}');
+ params.operationType = operationType;
+ }
+
+ if (spenderType !== 'workspace') {
+ const spenderColumn = USAGE_SPENDER_COLUMN_BY_SPENDER_TYPE[spenderType];
+
+ if (isDefined(spenderId)) {
+ clauses.push(`AND ${spenderColumn} = {spenderId:String}`);
+ params.spenderId = spenderId;
+ } else {
+ clauses.push(`AND ${spenderColumn} != ''`);
+ }
+ }
+
+ return { clause: clauses.join('\n'), params };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/to-display-credits.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/to-display-credits.util.ts
index d9d97d3b04a..b7d48b199d9 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/utils/to-display-credits.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/to-display-credits.util.ts
@@ -1,6 +1,4 @@
-// Internal credits use micro-precision: $1 = 1,000,000 internal credits
-// This mirrors the "micro" pattern in payment systems (e.g. microdollars → dollars)
-export const INTERNAL_CREDITS_PER_DISPLAY_CREDIT = 1_000_000;
+import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
export const toDisplayCredits = (internalCredits: number): number =>
internalCredits / INTERNAL_CREDITS_PER_DISPLAY_CREDIT;
diff --git a/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts b/packages/twenty-server/test/integration/billing/suites/billing-credit-grant-admin.integration-spec.ts
index c71352d18fd..432e9a8cedf 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,3 +1,4 @@
+import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
import { randomUUID } from 'node:crypto';
import { addDays, addMonths, startOfMonth } from 'date-fns';
@@ -18,7 +19,6 @@ import { BillingCreditGrantType } from 'src/engine/core-modules/billing/enums/bi
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}`);
diff --git a/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts
new file mode 100644
index 00000000000..e439831bd3f
--- /dev/null
+++ b/packages/twenty-server/test/integration/usage-limit/usage-limit-mutations.integration-spec.ts
@@ -0,0 +1,245 @@
+import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
+
+import { gql } from 'graphql-tag';
+import { createClient } from 'redis';
+import { type Repository } from 'typeorm';
+
+import { UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const CREATE_USAGE_LIMIT = gql`
+ mutation CreateUsageLimit($input: CreateUsageLimitInput!) {
+ createUsageLimit(input: $input) {
+ id
+ limitValue
+ periodUnit
+ }
+ }
+`;
+
+const UPDATE_USAGE_LIMIT = gql`
+ mutation UpdateUsageLimit($input: UpdateUsageLimitInput!) {
+ updateUsageLimit(input: $input) {
+ id
+ limitValue
+ periodUnit
+ }
+ }
+`;
+
+const DELETE_USAGE_LIMIT = gql`
+ mutation DeleteUsageLimit($usageLimitId: UUID!) {
+ deleteUsageLimit(usageLimitId: $usageLimitId)
+ }
+`;
+
+const USAGE_QUOTAS_WITH_CONSUMPTION = gql`
+ query UsageQuotasWithConsumption {
+ usageQuotasWithConsumption {
+ id
+ limitValue
+ periodUnit
+ spenderType
+ }
+ }
+`;
+
+const buildPayload = (
+ overrides: Record<string, unknown> = {},
+): Record<string, unknown> => ({
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace',
+ spenderId: null,
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ meter: 'creditsUsedMicro',
+ limitValue: 1_000_000,
+ burstValue: null,
+ ...overrides,
+});
+
+describe('Usage limit mutations', () => {
+ let usageLimitRepository: Repository<UsageLimitEntity>;
+ let redis: Awaited<ReturnType<typeof createClient>>;
+
+ const createUsageLimitRequest = (overrides: Record<string, unknown> = {}) =>
+ makeMetadataAPIRequest({
+ query: CREATE_USAGE_LIMIT,
+ variables: { input: buildPayload(overrides) },
+ });
+
+ const updateUsageLimit = (
+ id: string,
+ overrides: Record<string, unknown> = {},
+ ) =>
+ makeMetadataAPIRequest({
+ query: UPDATE_USAGE_LIMIT,
+ variables: { input: { id, payload: buildPayload(overrides) } },
+ });
+
+ const findQuotasWithConsumption = async () => {
+ const response = await makeMetadataAPIRequest({
+ query: USAGE_QUOTAS_WITH_CONSUMPTION,
+ });
+
+ return response.body.data?.usageQuotasWithConsumption ?? [];
+ };
+
+ const createUsageLimit = async (overrides: Record<string, unknown> = {}) => {
+ const response = await createUsageLimitRequest(overrides);
+ const usageLimitId = response.body.data?.createUsageLimit?.id;
+
+ jestExpectToBeDefined(usageLimitId);
+
+ return usageLimitId as string;
+ };
+
+ beforeAll(async () => {
+ usageLimitRepository =
+ getCoreRepository<UsageLimitEntity>(UsageLimitEntity);
+ redis = await createClient({ url: process.env.REDIS_URL }).connect();
+ });
+
+ afterEach(async () => {
+ await usageLimitRepository.delete({ workspaceId: SEED_APPLE_WORKSPACE_ID });
+
+ const keys = await redis.keys(`*usageLimits:${SEED_APPLE_WORKSPACE_ID}*`);
+
+ if (keys.length > 0) {
+ await redis.del(keys);
+ }
+ });
+
+ afterAll(async () => {
+ await redis.quit();
+ });
+
+ describe('createUsageLimit', () => {
+ it('creates a limit and lists it with its consumption', async () => {
+ const usageLimitId = await createUsageLimit();
+
+ const quotas = await findQuotasWithConsumption();
+
+ expect(quotas).toContainEqual(
+ expect.objectContaining({
+ id: usageLimitId,
+ limitValue: 1_000_000,
+ periodUnit: 'month',
+ spenderType: 'workspace',
+ }),
+ );
+ });
+
+ it('refuses a scope another limit already covers', async () => {
+ await createUsageLimit();
+
+ const response = await createUsageLimitRequest({ limitValue: 2_000_000 });
+
+ expect(response.body.errors?.[0]?.message).toBe(
+ 'Another usage limit already covers this scope',
+ );
+ expect(
+ await usageLimitRepository.countBy({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ }),
+ ).toBe(1);
+ });
+
+ it('refuses a quota carrying a burst value', async () => {
+ const response = await createUsageLimitRequest({ burstValue: 10 });
+
+ expect(response.body.errors?.[0]?.message).toBe(
+ 'A quota cannot hold a burst value',
+ );
+ });
+ });
+
+ describe('updateUsageLimit', () => {
+ it('changes the amount without moving the row', async () => {
+ const usageLimitId = await createUsageLimit();
+
+ const response = await updateUsageLimit(usageLimitId, {
+ limitValue: 5_000_000,
+ });
+
+ expect(response.body.data?.updateUsageLimit).toEqual(
+ expect.objectContaining({ id: usageLimitId, limitValue: 5_000_000 }),
+ );
+ expect(await findQuotasWithConsumption()).toHaveLength(1);
+ });
+
+ it('moves the limit to another scope, keeping its id', async () => {
+ const usageLimitId = await createUsageLimit();
+
+ const response = await updateUsageLimit(usageLimitId, {
+ periodUnit: 'week',
+ });
+
+ expect(response.body.data?.updateUsageLimit).toEqual(
+ expect.objectContaining({ id: usageLimitId, periodUnit: 'week' }),
+ );
+
+ const quotas = await findQuotasWithConsumption();
+
+ expect(quotas).toHaveLength(1);
+ expect(quotas[0]).toEqual(
+ expect.objectContaining({ id: usageLimitId, periodUnit: 'week' }),
+ );
+ });
+
+ it('refuses a scope another limit already covers', async () => {
+ await createUsageLimit();
+ const weeklyUsageLimitId = await createUsageLimit({
+ periodUnit: 'week',
+ });
+
+ const response = await updateUsageLimit(weeklyUsageLimitId, {
+ periodUnit: 'month',
+ });
+
+ expect(response.body.errors?.[0]?.message).toBe(
+ 'Another usage limit already covers this scope',
+ );
+ expect(await findQuotasWithConsumption()).toHaveLength(2);
+ });
+
+ it('refuses an id that belongs to no limit of this workspace', async () => {
+ const response = await updateUsageLimit(
+ '20202020-0000-4000-8000-000000000000',
+ );
+
+ expect(response.body.errors?.[0]?.message).toBe(
+ 'No usage limit 20202020-0000-4000-8000-000000000000 in this workspace',
+ );
+ });
+ });
+
+ describe('deleteUsageLimit', () => {
+ it('removes the limit from the list', async () => {
+ const usageLimitId = await createUsageLimit();
+
+ const response = await makeMetadataAPIRequest({
+ query: DELETE_USAGE_LIMIT,
+ variables: { usageLimitId },
+ });
+
+ expect(response.body.data?.deleteUsageLimit).toBe(true);
+ expect(await findQuotasWithConsumption()).toEqual([]);
+ });
+
+ it('reports nothing deleted for an unknown id', async () => {
+ const response = await makeMetadataAPIRequest({
+ query: DELETE_USAGE_LIMIT,
+ variables: { usageLimitId: '20202020-0000-4000-8000-000000000000' },
+ });
+
+ expect(response.body.data?.deleteUsageLimit).toBe(false);
+ });
+ });
+});
diff --git a/packages/twenty-shared/src/constants/InternalCreditsPerDisplayCredit.ts b/packages/twenty-shared/src/constants/InternalCreditsPerDisplayCredit.ts
new file mode 100644
index 00000000000..03e161e07da
--- /dev/null
+++ b/packages/twenty-shared/src/constants/InternalCreditsPerDisplayCredit.ts
@@ -0,0 +1 @@
+export const INTERNAL_CREDITS_PER_DISPLAY_CREDIT = 1_000_000;
diff --git a/packages/twenty-shared/src/constants/index.ts b/packages/twenty-shared/src/constants/index.ts
index 340ad485915..b47366d62bc 100644
--- a/packages/twenty-shared/src/constants/index.ts
+++ b/packages/twenty-shared/src/constants/index.ts
@@ -43,6 +43,7 @@ export { GIN_COMPATIBLE_FIELD_TYPES } from './GinCompatibleFieldTypes';
export { GROUP_BY_DATE_GRANULARITY_THAT_REQUIRE_TIME_ZONE } from './GroupByDateGranularityThatRequireTimeZone';
export { IANA_TIME_ZONES } from './IanaTimeZones';
export { IMAGE_IDENTIFIER_FIELD_METADATA_TYPES } from './ImageIdentifierFieldMetadataTypes';
+export { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from './InternalCreditsPerDisplayCredit';
export { LABEL_IDENTIFIER_FIELD_METADATA_TYPES } from './LabelIdentifierFieldMetadataTypes';
export { MAX_CORE_WORKFLOW_FILTER_RULES } from './MaxCoreWorkflowFilterRules';
export { MAX_CUSTOM_INDEXES_PER_OBJECT } from './MaxCustomIndexesPerObject';
diff --git a/packages/twenty-shared/src/types/SettingsPath.ts b/packages/twenty-shared/src/types/SettingsPath.ts
index d898e7e9e87..43b50cea4b0 100644
--- a/packages/twenty-shared/src/types/SettingsPath.ts
+++ b/packages/twenty-shared/src/types/SettingsPath.ts
@@ -13,6 +13,9 @@ export enum SettingsPath {
BillingPlans = 'billing/plans',
Usage = 'billing/usage',
UsageUserDetail = 'billing/usage/user/:userWorkspaceId',
+ BillingLimits = 'billing/limits',
+ BillingNewLimit = 'billing/limits/new',
+ BillingLimitEdit = 'billing/limits/:usageLimitId/edit',
Enterprise = 'enterprise',
Objects = 'objects',
ObjectOverview = 'objects/overview',