Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage-limit): replace the limit meter with a usage unit (#27124)

Etienneb6abd0605adb
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 7ad840a7149..7d35e12cea1 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -1634,24 +1634,9 @@ enum LogicFunctionExecutionStatus {
ERROR
}
-type UsageQuotaDefinition {
- resourceType: UsageResourceType!
- limitKind: String!
- allowedOperationTypes: [UsageOperationType!]!
- allowedSpenderTypes: [String!]!
- allowedMeters: [String!]!
-}
-
-enum UsageResourceType {
- AI
- WORKFLOW
- APP
- STORAGE
- API
- LOGIC_FUNCTION
- EMAIL
- WEBHOOK
- RECORD
+type UsageLimitOperationDefinition {
+ operationType: UsageOperationType!
+ allowedUnits: [UsageUnit!]!
}
enum UsageOperationType {
@@ -1671,6 +1656,39 @@ enum UsageOperationType {
SUBSCRIPTION
}
+enum UsageUnit {
+ CREDIT
+ TOKEN
+ INVOCATION
+ MINUTE
+ MILLISECOND
+ BYTE
+ FILE
+ REQUEST
+ SEAT
+ RECORD
+ COMPLEXITY
+}
+
+type UsageQuotaDefinition {
+ resourceType: UsageResourceType!
+ limitKind: String!
+ allowedOperations: [UsageLimitOperationDefinition!]!
+ allowedSpenderTypes: [String!]!
+}
+
+enum UsageResourceType {
+ AI
+ WORKFLOW
+ APP
+ STORAGE
+ API
+ LOGIC_FUNCTION
+ EMAIL
+ WEBHOOK
+ RECORD
+}
+
type UsageQuotaDefinitions {
definitions: [UsageQuotaDefinition!]!
isIntraWorkspaceLimitEntitled: Boolean!
@@ -1685,7 +1703,7 @@ type UsageQuotaWithConsumption {
spenderId: String
spenderLabel: String
periodUnit: String!
- meter: String!
+ unit: UsageUnit!
limitValue: BigInt!
isEnforced: Boolean!
consumedValue: BigInt
@@ -1714,7 +1732,7 @@ type UsageLimit {
limitKind: String!
periodCount: Int!
periodUnit: String!
- meter: String!
+ unit: UsageUnit!
limitValue: BigInt!
burstValue: BigInt
createdAt: DateTime!
@@ -4034,7 +4052,7 @@ input UsageQuotaScopeInput {
spenderType: String!
spenderId: String
periodUnit: String!
- meter: String!
+ unit: UsageUnit!
}
input AgentIdInput {
@@ -4491,7 +4509,7 @@ input CreateUsageLimitInput {
limitKind: String!
periodCount: Int!
periodUnit: String!
- meter: String!
+ unit: UsageUnit!
limitValue: BigInt!
burstValue: BigInt
}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index fdf9045ae85..4893ed7aa4a 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1268,19 +1268,26 @@ export interface LogicFunctionExecutionResult {
/** Status of the logic function execution */
export type LogicFunctionExecutionStatus = 'IDLE' | 'SUCCESS' | 'ERROR'
+export interface UsageLimitOperationDefinition {
+ operationType: UsageOperationType
+ allowedUnits: UsageUnit[]
+ __typename: 'UsageLimitOperationDefinition'
+}
+
+export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'MESSAGE_CAMPAIGN_SEND' | 'API_REQUEST' | 'WEBHOOK_CALL' | 'STORAGE_FILE' | 'RECORD_WRITE' | 'SUBSCRIPTION'
+
+export type UsageUnit = 'CREDIT' | 'TOKEN' | 'INVOCATION' | 'MINUTE' | 'MILLISECOND' | 'BYTE' | 'FILE' | 'REQUEST' | 'SEAT' | 'RECORD' | 'COMPLEXITY'
+
export interface UsageQuotaDefinition {
resourceType: UsageResourceType
limitKind: Scalars['String']
- allowedOperationTypes: UsageOperationType[]
+ allowedOperations: UsageLimitOperationDefinition[]
allowedSpenderTypes: Scalars['String'][]
- allowedMeters: Scalars['String'][]
__typename: 'UsageQuotaDefinition'
}
export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL' | 'WEBHOOK' | 'RECORD'
-export type UsageOperationType = 'ALL' | 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'MESSAGE_CAMPAIGN_SEND' | 'API_REQUEST' | 'WEBHOOK_CALL' | 'STORAGE_FILE' | 'RECORD_WRITE' | 'SUBSCRIPTION'
-
export interface UsageQuotaDefinitions {
definitions: UsageQuotaDefinition[]
isIntraWorkspaceLimitEntitled: Scalars['Boolean']
@@ -1296,7 +1303,7 @@ export interface UsageQuotaWithConsumption {
spenderId?: Scalars['String']
spenderLabel?: Scalars['String']
periodUnit: Scalars['String']
- meter: Scalars['String']
+ unit: UsageUnit
limitValue: Scalars['BigInt']
isEnforced: Scalars['Boolean']
consumedValue?: Scalars['BigInt']
@@ -1322,7 +1329,7 @@ export interface UsageLimit {
limitKind: Scalars['String']
periodCount: Scalars['Int']
periodUnit: Scalars['String']
- meter: Scalars['String']
+ unit: UsageUnit
limitValue: Scalars['BigInt']
burstValue?: Scalars['BigInt']
createdAt: Scalars['DateTime']
@@ -5119,12 +5126,18 @@ export interface LogicFunctionExecutionResultGenqlSelection{
__scalar?: boolean | number
}
+export interface UsageLimitOperationDefinitionGenqlSelection{
+ operationType?: boolean | number
+ allowedUnits?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface UsageQuotaDefinitionGenqlSelection{
resourceType?: boolean | number
limitKind?: boolean | number
- allowedOperationTypes?: boolean | number
+ allowedOperations?: UsageLimitOperationDefinitionGenqlSelection
allowedSpenderTypes?: boolean | number
- allowedMeters?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
@@ -5145,7 +5158,7 @@ export interface UsageQuotaWithConsumptionGenqlSelection{
spenderId?: boolean | number
spenderLabel?: boolean | number
periodUnit?: boolean | number
- meter?: boolean | number
+ unit?: boolean | number
limitValue?: boolean | number
isEnforced?: boolean | number
consumedValue?: boolean | number
@@ -5173,7 +5186,7 @@ export interface UsageLimitGenqlSelection{
limitKind?: boolean | number
periodCount?: boolean | number
periodUnit?: boolean | number
- meter?: boolean | number
+ unit?: boolean | number
limitValue?: boolean | number
burstValue?: boolean | number
createdAt?: boolean | number
@@ -7490,7 +7503,7 @@ export interface QueryGenqlSelection{
export interface RecordTargetInput {objectMetadataId: Scalars['UUID'],recordId: Scalars['UUID']}
-export interface UsageQuotaScopeInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),periodUnit: Scalars['String'],meter: Scalars['String']}
+export interface UsageQuotaScopeInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),periodUnit: Scalars['String'],unit: UsageUnit}
export interface AgentIdInput {
/** The id of the agent. */
@@ -7830,7 +7843,7 @@ 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 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 CreateUsageLimitInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),limitKind: Scalars['String'],periodCount: Scalars['Int'],periodUnit: Scalars['String'],unit: UsageUnit,limitValue: Scalars['BigInt'],burstValue?: (Scalars['BigInt'] | null)}
export interface UpdateUsageLimitInput {id: Scalars['UUID'],payload: CreateUsageLimitInput}
@@ -9035,6 +9048,14 @@ export interface CreateRecordExportInput {objectMetadataId: Scalars['UUID'],fiel
+ const UsageLimitOperationDefinition_possibleTypes: string[] = ['UsageLimitOperationDefinition']
+ export const isUsageLimitOperationDefinition = (obj?: { __typename?: any } | null): obj is UsageLimitOperationDefinition => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isUsageLimitOperationDefinition"')
+ return UsageLimitOperationDefinition_possibleTypes.includes(obj.__typename)
+ }
+
+
+
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"')
@@ -11303,18 +11324,6 @@ export const enumLogicFunctionExecutionStatus = {
ERROR: 'ERROR' as const
}
-export const enumUsageResourceType = {
- AI: 'AI' as const,
- WORKFLOW: 'WORKFLOW' as const,
- APP: 'APP' as const,
- STORAGE: 'STORAGE' as const,
- API: 'API' as const,
- LOGIC_FUNCTION: 'LOGIC_FUNCTION' as const,
- EMAIL: 'EMAIL' as const,
- WEBHOOK: 'WEBHOOK' as const,
- RECORD: 'RECORD' as const
-}
-
export const enumUsageOperationType = {
ALL: 'ALL' as const,
AI_CHAT_TOKEN: 'AI_CHAT_TOKEN' as const,
@@ -11332,6 +11341,32 @@ export const enumUsageOperationType = {
SUBSCRIPTION: 'SUBSCRIPTION' as const
}
+export const enumUsageUnit = {
+ CREDIT: 'CREDIT' as const,
+ TOKEN: 'TOKEN' as const,
+ INVOCATION: 'INVOCATION' as const,
+ MINUTE: 'MINUTE' as const,
+ MILLISECOND: 'MILLISECOND' as const,
+ BYTE: 'BYTE' as const,
+ FILE: 'FILE' as const,
+ REQUEST: 'REQUEST' as const,
+ SEAT: 'SEAT' as const,
+ RECORD: 'RECORD' as const,
+ COMPLEXITY: 'COMPLEXITY' as const
+}
+
+export const enumUsageResourceType = {
+ AI: 'AI' as const,
+ WORKFLOW: 'WORKFLOW' as const,
+ APP: 'APP' as const,
+ STORAGE: 'STORAGE' as const,
+ API: 'API' as const,
+ LOGIC_FUNCTION: 'LOGIC_FUNCTION' as const,
+ EMAIL: 'EMAIL' as const,
+ WEBHOOK: 'WEBHOOK' as const,
+ RECORD: 'RECORD' as const
+}
+
export const enumNavigationMenuItemType = {
VIEW: 'VIEW' as const,
FOLDER: 'FOLDER' as const,
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index f08f4737a3b..a951eae700a 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -58,60 +58,61 @@ export default {
155,
157,
158,
- 161,
- 168,
- 171,
- 172,
+ 160,
+ 163,
+ 170,
173,
174,
- 177,
- 180,
- 183,
+ 175,
+ 176,
+ 179,
+ 182,
185,
- 206,
- 211,
- 218,
- 219,
- 226,
- 231,
- 234,
- 257,
- 267,
- 268,
+ 187,
+ 208,
+ 213,
+ 220,
+ 221,
+ 228,
+ 233,
+ 236,
+ 259,
+ 269,
270,
- 275,
- 278,
- 287,
- 320,
- 327,
- 333,
- 334,
+ 272,
+ 277,
+ 280,
+ 289,
+ 322,
+ 329,
335,
+ 336,
337,
- 338,
339,
340,
341,
342,
343,
- 353,
- 354,
- 357,
- 392,
- 405,
+ 344,
+ 345,
+ 355,
+ 356,
+ 359,
+ 394,
407,
- 408,
409,
410,
+ 411,
412,
414,
- 421,
- 439,
- 443,
- 454,
- 574,
- 581,
- 609
+ 416,
+ 423,
+ 441,
+ 445,
+ 456,
+ 576,
+ 583,
+ 611
],
"types": {
"BillingProductDTO": {
@@ -647,7 +648,7 @@ export default {
1
],
"fields": [
- 282,
+ 284,
{
"paging": [
30,
@@ -660,7 +661,7 @@ export default {
}
],
"indexMetadatas": [
- 283,
+ 285,
{
"paging": [
30,
@@ -673,13 +674,13 @@ export default {
}
],
"fieldsList": [
- 269
+ 271
],
"indexMetadataList": [
- 277
+ 279
],
"searchFieldMetadataList": [
- 285
+ 287
],
"__typename": [
1
@@ -1741,7 +1742,7 @@ export default {
52
],
"featureFlags": [
- 210
+ 212
],
"billingSubscriptions": [
94
@@ -1756,7 +1757,7 @@ export default {
96
],
"billingEntitlements": [
- 286
+ 288
],
"hasValidSignedEnterpriseKey": [
8
@@ -1765,7 +1766,7 @@ export default {
8
],
"workspaceUrls": [
- 212
+ 214
],
"workspaceCustomApplicationId": [
1
@@ -1839,7 +1840,7 @@ export default {
38
],
"deletedWorkspaceMembers": [
- 254
+ 256
],
"hasPassword": [
8
@@ -1854,7 +1855,7 @@ export default {
54
],
"availableWorkspaces": [
- 253
+ 255
],
"__typename": [
1
@@ -3141,31 +3142,40 @@ export default {
]
},
"LogicFunctionExecutionStatus": {},
+ "UsageLimitOperationDefinition": {
+ "operationType": [
+ 157
+ ],
+ "allowedUnits": [
+ 158
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UsageOperationType": {},
+ "UsageUnit": {},
"UsageQuotaDefinition": {
"resourceType": [
- 157
+ 160
],
"limitKind": [
1
],
- "allowedOperationTypes": [
- 158
+ "allowedOperations": [
+ 156
],
"allowedSpenderTypes": [
1
],
- "allowedMeters": [
- 1
- ],
"__typename": [
1
]
},
"UsageResourceType": {},
- "UsageOperationType": {},
"UsageQuotaDefinitions": {
"definitions": [
- 156
+ 159
],
"isIntraWorkspaceLimitEntitled": [
8
@@ -3182,10 +3192,10 @@ export default {
3
],
"resourceType": [
- 157
+ 160
],
"operationType": [
- 158
+ 157
],
"spenderType": [
1
@@ -3199,20 +3209,20 @@ export default {
"periodUnit": [
1
],
- "meter": [
- 1
+ "unit": [
+ 158
],
"limitValue": [
- 161
+ 163
],
"isEnforced": [
8
],
"consumedValue": [
- 161
+ 163
],
"remainingValue": [
- 161
+ 163
],
"periodStart": [
4
@@ -3227,7 +3237,7 @@ export default {
"BigInt": {},
"UsageQuotaScopeConsumption": {
"consumedValue": [
- 161
+ 163
],
"periodStart": [
4
@@ -3244,10 +3254,10 @@ export default {
3
],
"resourceType": [
- 157
+ 160
],
"operationType": [
- 158
+ 157
],
"spenderType": [
1
@@ -3264,14 +3274,14 @@ export default {
"periodUnit": [
1
],
- "meter": [
- 1
+ "unit": [
+ 158
],
"limitValue": [
- 161
+ 163
],
"burstValue": [
- 161
+ 163
],
"createdAt": [
4
@@ -3351,7 +3361,7 @@ export default {
3
],
"type": [
- 168
+ 170
],
"name": [
1
@@ -3384,7 +3394,7 @@ export default {
4
],
"targetRecordIdentifier": [
- 166
+ 168
],
"__typename": [
1
@@ -3410,10 +3420,10 @@ export default {
},
"RecordSharingGrantDTO": {
"id": [
- 171
+ 173
],
"principalType": [
- 172
+ 174
],
"principalId": [
3
@@ -3422,10 +3432,10 @@ export default {
3
],
"accessLevel": [
- 173
+ 175
],
"rowCause": [
- 174
+ 176
],
"__typename": [
1
@@ -3454,28 +3464,28 @@ export default {
},
"RecordSharingDTO": {
"sharingMode": [
- 177
+ 179
],
"canManageSharing": [
8
],
"permissions": [
- 169
+ 171
],
"generalAccessLevel": [
- 173
+ 175
],
"defaultGeneralAccessLevel": [
- 173
+ 175
],
"hasManagedGeneralAccess": [
8
],
"roles": [
- 175
+ 177
],
"shares": [
- 170
+ 172
],
"__typename": [
1
@@ -3490,7 +3500,7 @@ export default {
3
],
"permissions": [
- 169
+ 171
],
"__typename": [
1
@@ -3501,7 +3511,7 @@ export default {
1
],
"state": [
- 180
+ 182
],
"attemptsMade": [
31
@@ -3542,7 +3552,7 @@ export default {
},
"MetadataEvent": {
"type": [
- 183
+ 185
],
"metadataName": [
1
@@ -3551,7 +3561,7 @@ export default {
1
],
"properties": [
- 181
+ 183
],
"updatedCollectionHash": [
1
@@ -3563,7 +3573,7 @@ export default {
"MetadataEventAction": {},
"ObjectRecordEvent": {
"action": [
- 185
+ 187
],
"objectNameSingular": [
1
@@ -3578,7 +3588,7 @@ export default {
1
],
"properties": [
- 181
+ 183
],
"__typename": [
1
@@ -3590,7 +3600,7 @@ export default {
1
],
"objectRecordEvent": [
- 184
+ 186
],
"__typename": [
1
@@ -3601,13 +3611,13 @@ export default {
1
],
"objectRecordEventsWithQueryIds": [
- 186
+ 188
],
"metadataEvents": [
- 182
+ 184
],
"queueJobEvents": [
- 179
+ 181
],
"__typename": [
1
@@ -3774,7 +3784,7 @@ export default {
1
],
"dailyUsage": [
- 196
+ 198
],
"__typename": [
1
@@ -3782,19 +3792,19 @@ export default {
},
"UsageAnalytics": {
"usageByUser": [
- 195
+ 197
],
"usageByOperationType": [
- 195
+ 197
],
"usageByApplication": [
- 195
+ 197
],
"usageByModel": [
- 195
+ 197
],
"timeSeries": [
- 196
+ 198
],
"periodStart": [
4
@@ -3803,7 +3813,7 @@ export default {
4
],
"userDailyUsage": [
- 197
+ 199
],
"__typename": [
1
@@ -3881,7 +3891,7 @@ export default {
1
],
"result": [
- 203
+ 205
],
"__typename": [
1
@@ -3898,7 +3908,7 @@ export default {
1
],
"connectionSecurity": [
- 206
+ 208
],
"__typename": [
1
@@ -3907,13 +3917,13 @@ export default {
"EmailConnectionSecurity": {},
"PublicImapSmtpCaldavConnectionParameters": {
"IMAP": [
- 205
+ 207
],
"SMTP": [
- 205
+ 207
],
"CALDAV": [
- 205
+ 207
],
"__typename": [
1
@@ -3972,7 +3982,7 @@ export default {
4
],
"connectionParameters": [
- 207
+ 209
],
"__typename": [
1
@@ -4031,7 +4041,7 @@ export default {
4
],
"connectionParameters": [
- 207
+ 209
],
"isOwnedByCurrentUser": [
8
@@ -4042,7 +4052,7 @@ export default {
},
"FeatureFlag": {
"key": [
- 211
+ 213
],
"value": [
8
@@ -4126,7 +4136,7 @@ export default {
1
],
"versionDistribution": [
- 214
+ 216
],
"__typename": [
1
@@ -4151,10 +4161,10 @@ export default {
1
],
"type": [
- 218
+ 220
],
"status": [
- 219
+ 221
],
"issuer": [
1
@@ -4167,7 +4177,7 @@ export default {
"SSOIdentityProviderStatus": {},
"AuthProviders": {
"sso": [
- 217
+ 219
],
"google": [
8
@@ -4204,10 +4214,10 @@ export default {
3
],
"authProviders": [
- 220
+ 222
],
"authBypassProviders": [
- 221
+ 223
],
"logo": [
1
@@ -4216,7 +4226,7 @@ export default {
1
],
"workspaceUrls": [
- 212
+ 214
],
"__typename": [
1
@@ -4255,7 +4265,7 @@ export default {
1
],
"modelFamily": [
- 226
+ 228
],
"modelFamilyLabel": [
1
@@ -4270,7 +4280,7 @@ export default {
15
],
"nativeCapabilities": [
- 224
+ 226
],
"isDeprecated": [
8
@@ -4376,7 +4386,7 @@ export default {
1
],
"trialPeriods": [
- 216
+ 218
],
"__typename": [
1
@@ -4384,7 +4394,7 @@ export default {
},
"Support": {
"supportDriver": [
- 231
+ 233
],
"supportFrontChatId": [
1
@@ -4413,7 +4423,7 @@ export default {
},
"Captcha": {
"provider": [
- 234
+ 236
],
"siteKey": [
1
@@ -4450,10 +4460,10 @@ export default {
},
"PublicFeatureFlag": {
"key": [
- 211
+ 213
],
"metadata": [
- 236
+ 238
],
"__typename": [
1
@@ -4478,19 +4488,19 @@ export default {
1
],
"authProviders": [
- 220
+ 222
],
"billing": [
- 229
+ 231
],
"aiModels": [
- 225
+ 227
],
"aiEvaluationModels": [
- 227
+ 229
],
"aiModelTiers": [
- 228
+ 230
],
"signInPrefilled": [
8
@@ -4514,25 +4524,25 @@ export default {
8
],
"support": [
- 230
+ 232
],
"isAttachmentPreviewEnabled": [
8
],
"sentry": [
- 232
+ 234
],
"captcha": [
- 233
+ 235
],
"api": [
- 235
+ 237
],
"canManageFeatureFlags": [
8
],
"publicFeatureFlags": [
- 237
+ 239
],
"isCookieSessionEnabled": [
8
@@ -4586,7 +4596,7 @@ export default {
1
],
"maintenance": [
- 238
+ 240
],
"__typename": [
1
@@ -4662,7 +4672,7 @@ export default {
},
"AppConnection": {
"id": [
- 171
+ 173
],
"providerName": [
1
@@ -4719,7 +4729,7 @@ export default {
3
],
"type": [
- 218
+ 220
],
"issuer": [
1
@@ -4728,7 +4738,7 @@ export default {
1
],
"status": [
- 219
+ 221
],
"__typename": [
1
@@ -4747,7 +4757,7 @@ export default {
},
"FindAvailableSSOIDP": {
"type": [
- 218
+ 220
],
"id": [
3
@@ -4759,10 +4769,10 @@ export default {
1
],
"status": [
- 219
+ 221
],
"workspace": [
- 248
+ 250
],
"__typename": [
1
@@ -4773,7 +4783,7 @@ export default {
3
],
"type": [
- 218
+ 220
],
"issuer": [
1
@@ -4782,7 +4792,7 @@ export default {
1
],
"status": [
- 219
+ 221
],
"__typename": [
1
@@ -4790,7 +4800,7 @@ export default {
},
"SSOConnection": {
"type": [
- 218
+ 220
],
"id": [
3
@@ -4802,7 +4812,7 @@ export default {
1
],
"status": [
- 219
+ 221
],
"__typename": [
1
@@ -4825,13 +4835,13 @@ export default {
1
],
"workspaceUrls": [
- 212
+ 214
],
"logo": [
1
],
"sso": [
- 251
+ 253
],
"__typename": [
1
@@ -4839,10 +4849,10 @@ export default {
},
"AvailableWorkspaces": {
"availableWorkspacesForSignIn": [
- 252
+ 254
],
"availableWorkspacesForSignUp": [
- 252
+ 254
],
"__typename": [
1
@@ -4881,7 +4891,7 @@ export default {
},
"ApplicationHealthCheckResult": {
"status": [
- 257
+ 259
],
"title": [
1
@@ -4890,7 +4900,7 @@ export default {
1
],
"action": [
- 255
+ 257
],
"__typename": [
1
@@ -5004,10 +5014,10 @@ export default {
1
],
"objectPermissions": [
- 259
+ 261
],
"fieldPermissions": [
- 260
+ 262
],
"__typename": [
1
@@ -5081,7 +5091,7 @@ export default {
1
],
"roles": [
- 261
+ 263
],
"requestedCapabilities": [
1
@@ -5122,13 +5132,13 @@ export default {
},
"WorkspaceCompanyEnrichmentResult": {
"outcome": [
- 267
+ 269
],
"enrichment": [
9
],
"personOutcome": [
- 268
+ 270
],
"personEnrichment": [
9
@@ -5150,7 +5160,7 @@ export default {
1
],
"type": [
- 270
+ 272
],
"name": [
1
@@ -5222,10 +5232,10 @@ export default {
25
],
"relation": [
- 274
+ 276
],
"morphRelations": [
- 274
+ 276
],
"__typename": [
1
@@ -5251,7 +5261,7 @@ export default {
},
"FieldEdge": {
"node": [
- 269
+ 271
],
"cursor": [
32
@@ -5262,10 +5272,10 @@ export default {
},
"FieldConnection": {
"pageInfo": [
- 271
+ 273
],
"edges": [
- 272
+ 274
],
"__typename": [
1
@@ -5273,7 +5283,7 @@ export default {
},
"Relation": {
"type": [
- 275
+ 277
],
"sourceObjectMetadata": [
25
@@ -5282,10 +5292,10 @@ export default {
25
],
"sourceFieldMetadata": [
- 269
+ 271
],
"targetFieldMetadata": [
- 269
+ 271
],
"__typename": [
1
@@ -5332,7 +5342,7 @@ export default {
1
],
"indexType": [
- 278
+ 280
],
"createdAt": [
4
@@ -5341,7 +5351,7 @@ export default {
4
],
"indexFieldMetadataList": [
- 276
+ 278
],
"__typename": [
1
@@ -5350,7 +5360,7 @@ export default {
"IndexType": {},
"IndexEdge": {
"node": [
- 277
+ 279
],
"cursor": [
32
@@ -5372,10 +5382,10 @@ export default {
},
"ObjectConnection": {
"pageInfo": [
- 271
+ 273
],
"edges": [
- 280
+ 282
],
"__typename": [
1
@@ -5383,10 +5393,10 @@ export default {
},
"ObjectFieldsConnection": {
"pageInfo": [
- 271
+ 273
],
"edges": [
- 272
+ 274
],
"__typename": [
1
@@ -5394,10 +5404,10 @@ export default {
},
"ObjectIndexMetadatasConnection": {
"pageInfo": [
- 271
+ 273
],
"edges": [
- 279
+ 281
],
"__typename": [
1
@@ -5439,7 +5449,7 @@ export default {
},
"BillingEntitlement": {
"key": [
- 287
+ 289
],
"value": [
8
@@ -5477,7 +5487,7 @@ export default {
1
],
"records": [
- 288
+ 290
],
"isCustomDomainEnabled": [
8
@@ -5556,10 +5566,10 @@ export default {
},
"AvailableWorkspacesAndAccessTokens": {
"tokens": [
- 296
+ 298
],
"availableWorkspaces": [
- 253
+ 255
],
"__typename": [
1
@@ -5597,7 +5607,7 @@ export default {
},
"WorkspaceUrlsAndId": {
"workspaceUrls": [
- 212
+ 214
],
"id": [
3
@@ -5611,7 +5621,7 @@ export default {
11
],
"workspace": [
- 301
+ 303
],
"__typename": [
1
@@ -5644,7 +5654,7 @@ export default {
11
],
"workspaceUrls": [
- 212
+ 214
],
"__typename": [
1
@@ -5688,7 +5698,7 @@ export default {
},
"AuthTokens": {
"tokens": [
- 296
+ 298
],
"__typename": [
1
@@ -5729,7 +5739,7 @@ export default {
11
],
"workspace": [
- 301
+ 303
],
"__typename": [
1
@@ -5805,10 +5815,10 @@ export default {
},
"CompleteApplicationFileUploadsResult": {
"files": [
- 316
+ 318
],
"errors": [
- 317
+ 319
],
"__typename": [
1
@@ -5819,7 +5829,7 @@ export default {
3
],
"fileFolder": [
- 320
+ 322
],
"filePath": [
1
@@ -5840,7 +5850,7 @@ export default {
"FileFolder": {},
"ApplicationFileUploadError": {
"fileFolder": [
- 320
+ 322
],
"filePath": [
1
@@ -5854,10 +5864,10 @@ export default {
},
"CreateApplicationFileUploadsResult": {
"targets": [
- 319
+ 321
],
"errors": [
- 321
+ 323
],
"__typename": [
1
@@ -5907,7 +5917,7 @@ export default {
1
],
"status": [
- 327
+ 329
],
"reason": [
1
@@ -5933,16 +5943,16 @@ export default {
},
"ApplicationExport": {
"application": [
- 325
+ 327
],
"manifest": [
9
],
"coverage": [
- 326
+ 328
],
"files": [
- 328
+ 330
],
"__typename": [
1
@@ -6002,16 +6012,16 @@ export default {
1
],
"status": [
- 333
+ 335
],
"tenantStatus": [
- 334
+ 336
],
"unsubscribeHostnameStatus": [
- 335
+ 337
],
"verificationRecords": [
- 331
+ 333
],
"verifiedAt": [
4
@@ -6028,7 +6038,7 @@ export default {
3
],
"visibility": [
- 337
+ 339
],
"handle": [
1
@@ -6037,16 +6047,16 @@ export default {
1
],
"type": [
- 338
+ 340
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 339
+ 341
],
"messageFolderImportPolicy": [
- 340
+ 342
],
"excludeNonProfessionalEmails": [
8
@@ -6055,7 +6065,7 @@ export default {
8
],
"pendingGroupEmailsAction": [
- 341
+ 343
],
"isSyncEnabled": [
8
@@ -6064,10 +6074,10 @@ export default {
4
],
"syncStatus": [
- 342
+ 344
],
"syncStage": [
- 343
+ 345
],
"syncStageStartedAt": [
4
@@ -6088,7 +6098,7 @@ export default {
4
],
"connectedAccount": [
- 208
+ 210
],
"__typename": [
1
@@ -6117,7 +6127,7 @@ export default {
},
"IngestAppMessagesOutput": {
"messages": [
- 344
+ 346
],
"__typename": [
1
@@ -6125,7 +6135,7 @@ export default {
},
"CreateEmailGroupChannelOutput": {
"messageChannel": [
- 336
+ 338
],
"forwardingAddress": [
1
@@ -6190,7 +6200,7 @@ export default {
31
],
"audience": [
- 347
+ 349
],
"__typename": [
1
@@ -6233,10 +6243,10 @@ export default {
1
],
"reason": [
- 353
+ 355
],
"source": [
- 354
+ 356
],
"unsubscribeTopicId": [
3
@@ -6249,7 +6259,7 @@ export default {
"MessageSuppressionSource": {},
"MessageSuppressionList": {
"records": [
- 352
+ 354
],
"totalCount": [
31
@@ -6275,7 +6285,7 @@ export default {
1
],
"visibility": [
- 357
+ 359
],
"__typename": [
1
@@ -6321,7 +6331,7 @@ export default {
1
],
"location": [
- 359
+ 361
],
"__typename": [
1
@@ -6338,7 +6348,7 @@ export default {
1
],
"connectionSecurity": [
- 206
+ 208
],
"__typename": [
1
@@ -6349,13 +6359,13 @@ export default {
1
],
"IMAP": [
- 361
+ 363
],
"SMTP": [
- 361
+ 363
],
"CALDAV": [
- 361
+ 363
],
"__typename": [
1
@@ -6375,7 +6385,7 @@ export default {
3
],
"connectionParameters": [
- 362
+ 364
],
"__typename": [
1
@@ -6562,7 +6572,7 @@ export default {
1
],
"parts": [
- 367
+ 369
],
"processedAt": [
4
@@ -6641,7 +6651,7 @@ export default {
1
],
"series": [
- 372
+ 374
],
"xAxisLabel": [
1
@@ -6690,7 +6700,7 @@ export default {
1
],
"data": [
- 374
+ 376
],
"__typename": [
1
@@ -6698,7 +6708,7 @@ export default {
},
"LineChartData": {
"series": [
- 375
+ 377
],
"xAxisLabel": [
1
@@ -6735,7 +6745,7 @@ export default {
},
"PieChartData": {
"data": [
- 377
+ 379
],
"showLegend": [
8
@@ -6781,10 +6791,10 @@ export default {
},
"AiChatUsage": {
"limitValue": [
- 161
+ 163
],
"consumedValue": [
- 161
+ 163
],
"periodEnd": [
4
@@ -6839,7 +6849,7 @@ export default {
},
"AgentChatThread": {
"id": [
- 171
+ 173
],
"title": [
1
@@ -6894,7 +6904,7 @@ export default {
},
"AiSystemPromptPreview": {
"sections": [
- 383
+ 385
],
"estimatedTokenCount": [
31
@@ -6922,7 +6932,7 @@ export default {
31
],
"error": [
- 385
+ 387
],
"__typename": [
1
@@ -6986,10 +6996,10 @@ export default {
},
"StartWorkspaceSetupChatResult": {
"outcome": [
- 392
+ 394
],
"thread": [
- 382
+ 384
],
"__typename": [
1
@@ -7057,13 +7067,13 @@ export default {
},
"EventLogQueryResult": {
"records": [
- 395
+ 397
],
"totalCount": [
31
],
"pageInfo": [
- 396
+ 398
],
"__typename": [
1
@@ -7120,10 +7130,10 @@ export default {
3
],
"evaluations": [
- 399
+ 401
],
"messages": [
- 368
+ 370
],
"createdAt": [
4
@@ -7185,7 +7195,7 @@ export default {
9
],
"scope": [
- 405
+ 407
],
"__typename": [
1
@@ -7200,19 +7210,19 @@ export default {
1
],
"syncStatus": [
- 407
+ 409
],
"syncStage": [
- 408
+ 410
],
"visibility": [
- 409
+ 411
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 410
+ 412
],
"isSyncEnabled": [
8
@@ -7263,7 +7273,7 @@ export default {
1
],
"pendingSyncAction": [
- 412
+ 414
],
"messageChannelId": [
3
@@ -7305,7 +7315,7 @@ export default {
1
],
"provenance": [
- 414
+ 416
],
"__typename": [
1
@@ -7334,7 +7344,7 @@ export default {
3
],
"through": [
- 415
+ 417
],
"__typename": [
1
@@ -7354,7 +7364,7 @@ export default {
1
],
"emit": [
- 416
+ 418
],
"action": [
1
@@ -7456,7 +7466,7 @@ export default {
},
"CollectionHash": {
"collectionName": [
- 421
+ 423
],
"hash": [
1
@@ -7520,13 +7530,13 @@ export default {
},
"MinimalMetadata": {
"objectMetadataItems": [
- 422
+ 424
],
"views": [
- 423
+ 425
],
"collectionHashes": [
- 420
+ 422
],
"__typename": [
1
@@ -7534,28 +7544,28 @@ export default {
},
"Query": {
"recordSharing": [
- 176,
+ 178,
{
"target": [
- 426,
+ 428,
"RecordTargetInput!"
]
}
],
"recordPermissions": [
- 178,
+ 180,
{
"targets": [
- 426,
+ 428,
"[RecordTargetInput!]!"
]
}
],
"navigationMenuItems": [
- 167
+ 169
],
"navigationMenuItem": [
- 167,
+ 169,
{
"id": [
3,
@@ -7601,19 +7611,19 @@ export default {
}
],
"usageLimits": [
- 163
+ 165
],
"usageQuotasWithConsumption": [
- 160
+ 162
],
"usageQuotaDefinitions": [
- 159
+ 161
],
"usageQuotaScopeConsumption": [
- 162,
+ 164,
{
"input": [
- 427,
+ 429,
"UsageQuotaScopeInput!"
]
}
@@ -7772,20 +7782,20 @@ export default {
10,
{
"input": [
- 428,
+ 430,
"AgentIdInput!"
]
}
],
"objects": [
- 281,
+ 283,
{
"paging": [
30,
"CursorPaging!"
],
"filter": [
- 429,
+ 431,
"ObjectFilter!"
]
}
@@ -7800,7 +7810,7 @@ export default {
}
],
"objectRecordCounts": [
- 284
+ 286
],
"mostlyEmptyFieldMetadataIds": [
3,
@@ -7812,13 +7822,13 @@ export default {
}
],
"currentUserSessions": [
- 188
+ 190
],
"findOneLogicFunction": [
23,
{
"input": [
- 430,
+ 432,
"LogicFunctionIdInput!"
]
}
@@ -7830,7 +7840,7 @@ export default {
9,
{
"input": [
- 430,
+ 432,
"LogicFunctionIdInput!"
]
}
@@ -7839,7 +7849,7 @@ export default {
1,
{
"input": [
- 430,
+ 432,
"LogicFunctionIdInput!"
]
}
@@ -7869,7 +7879,7 @@ export default {
}
],
"getInviteSuggestions": [
- 200
+ 202
],
"applicationConnectionProviders": [
153,
@@ -7881,15 +7891,15 @@ export default {
}
],
"getUsageAnalytics": [
- 198,
+ 200,
{
"input": [
- 431
+ 433
]
}
],
"billingPortalSession": [
- 193,
+ 195,
{
"returnUrlPath": [
1
@@ -7900,16 +7910,16 @@ export default {
}
],
"listPlans": [
- 191
+ 193
],
"getResourceCreditUsage": [
- 190
+ 192
],
"findWorkspaceInvitations": [
- 203
+ 205
],
"getApprovedAccessDomains": [
- 199
+ 201
],
"getRoles": [
51
@@ -7933,7 +7943,7 @@ export default {
2,
{
"input": [
- 432,
+ 434,
"GetApiKeyInput!"
]
}
@@ -7956,10 +7966,10 @@ export default {
}
],
"myConnectedAccounts": [
- 208
+ 210
],
"applicationConnectedAccounts": [
- 209,
+ 211,
{
"applicationId": [
3,
@@ -7971,7 +7981,7 @@ export default {
72
],
"getPublicWorkspaceDataByDomain": [
- 222,
+ 224,
{
"origin": [
1
@@ -7979,7 +7989,7 @@ export default {
}
],
"getPublicWorkspaceDataById": [
- 223,
+ 225,
{
"id": [
3,
@@ -7988,7 +7998,7 @@ export default {
}
],
"findApplicationRegistrationByClientId": [
- 242,
+ 244,
{
"clientId": [
1,
@@ -8018,7 +8028,7 @@ export default {
}
],
"findApplicationRegistrationStats": [
- 215,
+ 217,
{
"id": [
1,
@@ -8027,7 +8037,7 @@ export default {
}
],
"findApplicationRegistrationVariables": [
- 213,
+ 215,
{
"applicationRegistrationId": [
1,
@@ -8045,7 +8055,7 @@ export default {
}
],
"findClaimableApplicationRegistration": [
- 240,
+ 242,
{
"sourcePackage": [
1
@@ -8079,7 +8089,7 @@ export default {
}
],
"findInstallApplicationJobStatus": [
- 179,
+ 181,
{
"universalIdentifier": [
1,
@@ -8088,7 +8098,7 @@ export default {
}
],
"findUninstallApplicationJobStatus": [
- 179,
+ 181,
{
"universalIdentifier": [
1,
@@ -8097,7 +8107,7 @@ export default {
}
],
"findManyMarketplaceApps": [
- 258,
+ 260,
{
"universalIdentifiers": [
1,
@@ -8106,7 +8116,7 @@ export default {
}
],
"findMarketplaceAppDetail": [
- 262,
+ 264,
{
"universalIdentifier": [
1,
@@ -8115,7 +8125,7 @@ export default {
}
],
"publicMarketplaceApps": [
- 258,
+ 260,
{
"isVetted": [
8,
@@ -8124,7 +8134,7 @@ export default {
}
],
"publicMarketplaceAppDetail": [
- 262,
+ 264,
{
"universalIdentifier": [
1,
@@ -8133,7 +8143,7 @@ export default {
}
],
"fields": [
- 273,
+ 275,
{
"paging": [
30,
@@ -8146,7 +8156,7 @@ export default {
}
],
"field": [
- 269,
+ 271,
{
"id": [
3,
@@ -8172,28 +8182,28 @@ export default {
}
],
"previewMessageCampaignAudience": [
- 347,
+ 349,
{
"input": [
- 433,
+ 435,
"PreviewMessageCampaignAudienceInput!"
]
}
],
"messageSuppressions": [
- 355,
+ 357,
{
"input": [
- 434,
+ 436,
"FindMessageSuppressionsInput!"
]
}
],
"unsubscribeTopics": [
- 356
+ 358
],
"myMessageChannels": [
- 336,
+ 338,
{
"connectedAccountId": [
3
@@ -8201,18 +8211,18 @@ export default {
}
],
"appMessageChannels": [
- 336,
+ 338,
{
"filter": [
- 435
+ 437
]
}
],
"getEmailingDomains": [
- 332
+ 334
],
"getToolIndex": [
- 366
+ 368
],
"getToolInputSchema": [
9,
@@ -8224,10 +8234,10 @@ export default {
}
],
"webhooks": [
- 365
+ 367
],
"webhook": [
- 365,
+ 367,
{
"id": [
3,
@@ -8236,7 +8246,7 @@ export default {
}
],
"myMessageFolders": [
- 411,
+ 413,
{
"messageChannelId": [
3
@@ -8244,7 +8254,7 @@ export default {
}
],
"myCalendarChannels": [
- 406,
+ 408,
{
"connectedAccountId": [
3
@@ -8252,25 +8262,25 @@ export default {
}
],
"getPermissionFlags": [
- 419
+ 421
],
"minimalMetadata": [
- 424
+ 426
],
"appKeyValue": [
- 404,
+ 406,
{
"key": [
1,
"String!"
],
"scope": [
- 405
+ 407
]
}
],
"getJobs": [
- 179,
+ 181,
{
"jobIds": [
1,
@@ -8279,30 +8289,30 @@ export default {
}
],
"appConnections": [
- 244,
+ 246,
{
"filter": [
- 436
+ 438
]
}
],
"appConnection": [
- 244,
+ 246,
{
"id": [
- 171,
+ 173,
"ID!"
]
}
],
"findWorkspaceAiStats": [
- 401
+ 403
],
"aiChatUsage": [
- 380
+ 382
],
"chatThread": [
- 382,
+ 384,
{
"id": [
3,
@@ -8311,7 +8321,7 @@ export default {
}
],
"chatMessages": [
- 368,
+ 370,
{
"threadId": [
3,
@@ -8320,7 +8330,7 @@ export default {
}
],
"chatStreamCatchupChunks": [
- 386,
+ 388,
{
"threadId": [
3,
@@ -8329,13 +8339,13 @@ export default {
}
],
"getAiSystemPromptPreview": [
- 384
+ 386
],
"skills": [
- 381
+ 383
],
"skill": [
- 381,
+ 383,
{
"id": [
3,
@@ -8344,7 +8354,7 @@ export default {
}
],
"agentTurns": [
- 400,
+ 402,
{
"agentId": [
3,
@@ -8353,7 +8363,7 @@ export default {
}
],
"validationRules": [
- 418,
+ 420,
{
"objectMetadataId": [
3,
@@ -8362,19 +8372,19 @@ export default {
}
],
"timelineActivityTypes": [
- 417
+ 419
],
"metadataTranslations": [
- 413,
+ 415,
{
"input": [
- 437,
+ 439,
"MetadataTranslationsInput!"
]
}
],
"checkUserExists": [
- 311,
+ 313,
{
"email": [
1,
@@ -8386,7 +8396,7 @@ export default {
}
],
"checkWorkspaceInviteHashIsValid": [
- 312,
+ 314,
{
"inviteHash": [
1,
@@ -8404,7 +8414,7 @@ export default {
}
],
"checkWorkspaceSubdomainAvailability": [
- 306,
+ 308,
{
"subdomain": [
1,
@@ -8413,10 +8423,10 @@ export default {
}
],
"getWorkspaceCreationDefaults": [
- 307
+ 309
],
"validatePasswordResetToken": [
- 304,
+ 306,
{
"passwordResetToken": [
1,
@@ -8428,40 +8438,40 @@ export default {
76
],
"getSSOIdentityProviders": [
- 249
+ 251
],
"eventLogs": [
- 397,
+ 399,
{
"input": [
- 438,
+ 440,
"EventLogQueryInput!"
]
}
],
"pieChartData": [
- 378,
+ 380,
{
"input": [
- 444,
+ 446,
"PieChartDataInput!"
]
}
],
"lineChartData": [
- 376,
+ 378,
{
"input": [
- 445,
+ 447,
"LineChartDataInput!"
]
}
],
"barChartData": [
- 373,
+ 375,
{
"input": [
- 446,
+ 448,
"BarChartDataInput!"
]
}
@@ -8476,7 +8486,7 @@ export default {
}
],
"getConnectedImapSmtpCaldavAccount": [
- 363,
+ 365,
{
"id": [
3,
@@ -8485,7 +8495,7 @@ export default {
}
],
"getAutoCompleteAddress": [
- 358,
+ 360,
{
"address": [
1,
@@ -8504,7 +8514,7 @@ export default {
}
],
"getAddressDetails": [
- 360,
+ 362,
{
"placeId": [
1,
@@ -8517,10 +8527,10 @@ export default {
}
],
"findManyPublicDomains": [
- 330
+ 332
],
"exportApplication": [
- 329,
+ 331,
{
"universalIdentifier": [
3,
@@ -8538,7 +8548,7 @@ export default {
}
],
"currentUserApplicationAuthorizations": [
- 315
+ 317
],
"__typename": [
1
@@ -8557,10 +8567,10 @@ export default {
},
"UsageQuotaScopeInput": {
"resourceType": [
- 157
+ 160
],
"operationType": [
- 158
+ 157
],
"spenderType": [
1
@@ -8571,8 +8581,8 @@ export default {
"periodUnit": [
1
],
- "meter": [
- 1
+ "unit": [
+ 158
],
"__typename": [
1
@@ -8588,10 +8598,10 @@ export default {
},
"ObjectFilter": {
"and": [
- 429
+ 431
],
"or": [
- 429
+ 431
],
"id": [
34
@@ -8626,7 +8636,7 @@ export default {
},
"LogicFunctionIdInput": {
"id": [
- 171
+ 173
],
"__typename": [
1
@@ -8643,7 +8653,7 @@ export default {
1
],
"operationTypes": [
- 158
+ 157
],
"__typename": [
1
@@ -8670,7 +8680,7 @@ export default {
},
"FindMessageSuppressionsInput": {
"reason": [
- 353
+ 355
],
"searchTerm": [
1
@@ -8726,10 +8736,10 @@ export default {
},
"EventLogQueryInput": {
"table": [
- 439
+ 441
],
"filters": [
- 440
+ 442
],
"first": [
31
@@ -8750,7 +8760,7 @@ export default {
1
],
"dateRange": [
- 441
+ 443
],
"recordId": [
1
@@ -8759,7 +8769,7 @@ export default {
1
],
"fieldFilters": [
- 442
+ 444
],
"__typename": [
1
@@ -8781,7 +8791,7 @@ export default {
1
],
"operand": [
- 443
+ 445
],
"values": [
1
@@ -8829,7 +8839,7 @@ export default {
8,
{
"input": [
- 448,
+ 450,
"AddQuerySubscriptionInput!"
]
}
@@ -8838,92 +8848,92 @@ export default {
8,
{
"input": [
- 449,
+ 451,
"RemoveQueryFromEventStreamInput!"
]
}
],
"setRecordGeneralAccess": [
- 176,
+ 178,
{
"target": [
- 426,
+ 428,
"RecordTargetInput!"
],
"accessLevel": [
- 173,
+ 175,
"RecordShareAccessLevel!"
]
}
],
"setRecordShare": [
- 176,
+ 178,
{
"target": [
- 426,
+ 428,
"RecordTargetInput!"
],
"principal": [
- 450,
+ 452,
"RecordSharePrincipalInput!"
],
"accessLevel": [
- 173,
+ 175,
"RecordShareAccessLevel!"
]
}
],
"removeRecordShare": [
- 176,
+ 178,
{
"target": [
- 426,
+ 428,
"RecordTargetInput!"
],
"principal": [
- 450,
+ 452,
"RecordSharePrincipalInput!"
]
}
],
"createManyNavigationMenuItems": [
- 167,
+ 169,
{
"inputs": [
- 451,
+ 453,
"[CreateNavigationMenuItemInput!]!"
]
}
],
"createNavigationMenuItem": [
- 167,
+ 169,
{
"input": [
- 451,
+ 453,
"CreateNavigationMenuItemInput!"
]
}
],
"updateManyNavigationMenuItems": [
- 167,
+ 169,
{
"inputs": [
- 452,
+ 454,
"[UpdateOneNavigationMenuItemInput!]!"
]
}
],
"updateNavigationMenuItem": [
- 167,
+ 169,
{
"input": [
- 452,
+ 454,
"UpdateOneNavigationMenuItemInput!"
]
}
],
"deleteManyNavigationMenuItems": [
- 167,
+ 169,
{
"ids": [
3,
@@ -8932,7 +8942,7 @@ export default {
}
],
"deleteNavigationMenuItem": [
- 167,
+ 169,
{
"id": [
3,
@@ -8941,7 +8951,7 @@ export default {
}
],
"createFileUpload": [
- 165,
+ 167,
{
"filename": [
1,
@@ -8952,7 +8962,7 @@ export default {
"Float!"
],
"fileFolder": [
- 320,
+ 322,
"FileFolder!"
],
"fieldMetadataId": [
@@ -8964,7 +8974,7 @@ export default {
}
],
"completeFileUpload": [
- 164,
+ 166,
{
"fileId": [
1,
@@ -8988,25 +8998,25 @@ export default {
}
],
"uploadWorkspaceLogo": [
- 164,
+ 166,
{
"file": [
- 454,
+ 456,
"Upload!"
]
}
],
"uploadWorkspaceMemberProfilePicture": [
- 164,
+ 166,
{
"file": [
- 454,
+ 456,
"Upload!"
]
}
],
"completeWorkspaceLogoUpload": [
- 164,
+ 166,
{
"fileId": [
1,
@@ -9015,7 +9025,7 @@ export default {
}
],
"completeWorkspaceMemberProfilePictureUpload": [
- 164,
+ 166,
{
"fileId": [
1,
@@ -9024,10 +9034,10 @@ export default {
}
],
"uploadFilesFieldFileByUniversalIdentifier": [
- 164,
+ 166,
{
"file": [
- 454,
+ 456,
"Upload!"
],
"fieldMetadataUniversalIdentifier": [
@@ -9037,19 +9047,19 @@ export default {
}
],
"createUsageLimit": [
- 163,
+ 165,
{
"input": [
- 455,
+ 457,
"CreateUsageLimitInput!"
]
}
],
"updateUsageLimit": [
- 163,
+ 165,
{
"input": [
- 456,
+ 458,
"UpdateUsageLimitInput!"
]
}
@@ -9067,7 +9077,7 @@ export default {
103,
{
"input": [
- 457,
+ 459,
"CreatePageLayoutWidgetInput!"
]
}
@@ -9080,7 +9090,7 @@ export default {
"String!"
],
"input": [
- 458,
+ 460,
"UpdatePageLayoutWidgetInput!"
]
}
@@ -9098,7 +9108,7 @@ export default {
149,
{
"input": [
- 459,
+ 461,
"CreatePageLayoutTabInput!"
]
}
@@ -9111,7 +9121,7 @@ export default {
"String!"
],
"input": [
- 460,
+ 462,
"UpdatePageLayoutTabInput!"
]
}
@@ -9129,7 +9139,7 @@ export default {
150,
{
"input": [
- 461,
+ 463,
"CreatePageLayoutInput!"
]
}
@@ -9142,7 +9152,7 @@ export default {
"String!"
],
"input": [
- 462,
+ 464,
"UpdatePageLayoutInput!"
]
}
@@ -9164,7 +9174,7 @@ export default {
"String!"
],
"input": [
- 463,
+ 465,
"UpdatePageLayoutWithTabsInput!"
]
}
@@ -9200,7 +9210,7 @@ export default {
66,
{
"input": [
- 466,
+ 468,
"CreateViewInput!"
]
}
@@ -9213,7 +9223,7 @@ export default {
"String!"
],
"input": [
- 467,
+ 469,
"UpdateViewInput!"
]
}
@@ -9240,7 +9250,7 @@ export default {
66,
{
"input": [
- 468,
+ 470,
"UpsertViewWidgetInput!"
]
}
@@ -9249,7 +9259,7 @@ export default {
63,
{
"input": [
- 474,
+ 476,
"CreateViewSortInput!"
]
}
@@ -9258,7 +9268,7 @@ export default {
63,
{
"input": [
- 475,
+ 477,
"UpdateViewSortInput!"
]
}
@@ -9267,7 +9277,7 @@ export default {
8,
{
"input": [
- 477,
+ 479,
"DeleteViewSortInput!"
]
}
@@ -9276,7 +9286,7 @@ export default {
8,
{
"input": [
- 478,
+ 480,
"DestroyViewSortInput!"
]
}
@@ -9285,7 +9295,7 @@ export default {
60,
{
"input": [
- 479,
+ 481,
"CreateViewFilterInput!"
]
}
@@ -9294,7 +9304,7 @@ export default {
60,
{
"input": [
- 480,
+ 482,
"UpdateViewFilterInput!"
]
}
@@ -9303,7 +9313,7 @@ export default {
60,
{
"input": [
- 482,
+ 484,
"DeleteViewFilterInput!"
]
}
@@ -9312,7 +9322,7 @@ export default {
60,
{
"input": [
- 483,
+ 485,
"DestroyViewFilterInput!"
]
}
@@ -9321,7 +9331,7 @@ export default {
56,
{
"input": [
- 484,
+ 486,
"UpdateViewFieldInput!"
]
}
@@ -9330,7 +9340,7 @@ export default {
56,
{
"input": [
- 486,
+ 488,
"CreateViewFieldInput!"
]
}
@@ -9339,7 +9349,7 @@ export default {
56,
{
"inputs": [
- 486,
+ 488,
"[CreateViewFieldInput!]!"
]
}
@@ -9348,7 +9358,7 @@ export default {
56,
{
"input": [
- 487,
+ 489,
"DeleteViewFieldInput!"
]
}
@@ -9357,7 +9367,7 @@ export default {
56,
{
"input": [
- 488,
+ 490,
"DestroyViewFieldInput!"
]
}
@@ -9366,7 +9376,7 @@ export default {
65,
{
"input": [
- 489,
+ 491,
"UpdateViewFieldGroupInput!"
]
}
@@ -9375,7 +9385,7 @@ export default {
65,
{
"input": [
- 491,
+ 493,
"CreateViewFieldGroupInput!"
]
}
@@ -9384,7 +9394,7 @@ export default {
65,
{
"inputs": [
- 491,
+ 493,
"[CreateViewFieldGroupInput!]!"
]
}
@@ -9393,7 +9403,7 @@ export default {
65,
{
"input": [
- 492,
+ 494,
"DeleteViewFieldGroupInput!"
]
}
@@ -9402,7 +9412,7 @@ export default {
65,
{
"input": [
- 493,
+ 495,
"DestroyViewFieldGroupInput!"
]
}
@@ -9411,7 +9421,7 @@ export default {
66,
{
"input": [
- 494,
+ 496,
"UpsertFieldsWidgetInput!"
]
}
@@ -9420,7 +9430,7 @@ export default {
10,
{
"input": [
- 497,
+ 499,
"CreateAgentInput!"
]
}
@@ -9429,7 +9439,7 @@ export default {
10,
{
"input": [
- 498,
+ 500,
"UpdateAgentInput!"
]
}
@@ -9438,7 +9448,7 @@ export default {
10,
{
"input": [
- 428,
+ 430,
"AgentIdInput!"
]
}
@@ -9447,7 +9457,7 @@ export default {
25,
{
"input": [
- 499,
+ 501,
"CreateOneObjectInput!"
]
}
@@ -9456,7 +9466,7 @@ export default {
25,
{
"input": [
- 501,
+ 503,
"DeleteOneObjectInput!"
]
}
@@ -9465,7 +9475,7 @@ export default {
25,
{
"input": [
- 502,
+ 504,
"UpdateOneObjectInput!"
]
}
@@ -9474,25 +9484,25 @@ export default {
25,
{
"inputs": [
- 502,
+ 504,
"[UpdateOneObjectInput!]!"
]
}
],
"createOneIndex": [
- 277,
+ 279,
{
"input": [
- 505,
+ 507,
"CreateOneIndexInput!"
]
}
],
"deleteOneIndex": [
- 277,
+ 279,
{
"input": [
- 508,
+ 510,
"DeleteOneIndexInput!"
]
}
@@ -9513,7 +9523,7 @@ export default {
23,
{
"input": [
- 430,
+ 432,
"LogicFunctionIdInput!"
]
}
@@ -9522,7 +9532,7 @@ export default {
23,
{
"input": [
- 509,
+ 511,
"CreateLogicFunctionFromSourceInput!"
]
}
@@ -9531,7 +9541,7 @@ export default {
154,
{
"input": [
- 510,
+ 512,
"ExecuteOneLogicFunctionInput!"
]
}
@@ -9540,7 +9550,7 @@ export default {
8,
{
"input": [
- 511,
+ 513,
"UpdateLogicFunctionFromSourceInput!"
]
}
@@ -9549,7 +9559,7 @@ export default {
14,
{
"input": [
- 513,
+ 515,
"CreateCommandMenuItemInput!"
]
}
@@ -9558,7 +9568,7 @@ export default {
14,
{
"input": [
- 514,
+ 516,
"UpdateCommandMenuItemInput!"
]
}
@@ -9594,7 +9604,7 @@ export default {
13,
{
"input": [
- 515,
+ 517,
"CreateFrontComponentInput!"
]
}
@@ -9603,7 +9613,7 @@ export default {
13,
{
"input": [
- 516,
+ 518,
"UpdateFrontComponentInput!"
]
}
@@ -9634,7 +9644,7 @@ export default {
}
],
"skipSyncEmailOnboardingStep": [
- 202,
+ 204,
{
"isAutoSkipped": [
8,
@@ -9643,7 +9653,7 @@ export default {
}
],
"completeBookCallOnboardingStep": [
- 202,
+ 204,
{
"hasBookedCall": [
8,
@@ -9656,7 +9666,7 @@ export default {
}
],
"triggerInstallAppsOnboardingStep": [
- 202,
+ 204,
{
"universalIdentifiers": [
1,
@@ -9669,10 +9679,10 @@ export default {
}
],
"goBackToPreviousOnboardingStep": [
- 201
+ 203
],
"checkoutSession": [
- 193,
+ 195,
{
"recurringInterval": [
87,
@@ -9692,7 +9702,7 @@ export default {
}
],
"createSubscriptionPaymentIntent": [
- 192,
+ 194,
{
"recurringInterval": [
87,
@@ -9716,22 +9726,22 @@ export default {
}
],
"createBillingPaymentMethodSetupIntent": [
- 192
+ 194
],
"switchSubscriptionInterval": [
- 194
+ 196
],
"switchBillingPlan": [
- 194
+ 196
],
"cancelSwitchBillingPlan": [
- 194
+ 196
],
"cancelSwitchBillingInterval": [
- 194
+ 196
],
"setResourceCreditSubscriptionPrice": [
- 194,
+ 196,
{
"priceId": [
1,
@@ -9740,10 +9750,10 @@ export default {
}
],
"endSubscriptionTrialPeriod": [
- 189
+ 191
],
"cancelSwitchResourceCreditPrice": [
- 194
+ 196
],
"deleteWorkspaceInvitation": [
1,
@@ -9755,7 +9765,7 @@ export default {
}
],
"resendWorkspaceInvitation": [
- 204,
+ 206,
{
"appTokenId": [
1,
@@ -9764,7 +9774,7 @@ export default {
}
],
"sendInvitations": [
- 204,
+ 206,
{
"emails": [
1,
@@ -9776,10 +9786,10 @@ export default {
}
],
"createApprovedAccessDomain": [
- 199,
+ 201,
{
"input": [
- 518,
+ 520,
"CreateApprovedAccessDomainInput!"
]
}
@@ -9788,16 +9798,16 @@ export default {
8,
{
"input": [
- 519,
+ 521,
"DeleteApprovedAccessDomainInput!"
]
}
],
"validateApprovedAccessDomain": [
- 199,
+ 201,
{
"input": [
- 520,
+ 522,
"ValidateApprovedAccessDomainInput!"
]
}
@@ -9819,7 +9829,7 @@ export default {
51,
{
"createRoleInput": [
- 521,
+ 523,
"CreateRoleInput!"
]
}
@@ -9828,7 +9838,7 @@ export default {
51,
{
"updateRoleInput": [
- 522,
+ 524,
"UpdateRoleInput!"
]
}
@@ -9846,7 +9856,7 @@ export default {
48,
{
"upsertObjectPermissionsInput": [
- 524,
+ 526,
"UpsertObjectPermissionsInput!"
]
}
@@ -9855,7 +9865,7 @@ export default {
49,
{
"upsertPermissionFlagsInput": [
- 526,
+ 528,
"UpsertPermissionFlagsInput!"
]
}
@@ -9864,16 +9874,16 @@ export default {
43,
{
"upsertFieldPermissionsInput": [
- 527,
+ 529,
"UpsertFieldPermissionsInput!"
]
}
],
"upsertRowLevelPermissionPredicates": [
- 290,
+ 292,
{
"input": [
- 529,
+ 531,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
@@ -9904,7 +9914,7 @@ export default {
2,
{
"input": [
- 532,
+ 534,
"CreateApiKeyInput!"
]
}
@@ -9913,7 +9923,7 @@ export default {
2,
{
"input": [
- 533,
+ 535,
"UpdateApiKeyInput!"
]
}
@@ -9922,7 +9932,7 @@ export default {
2,
{
"input": [
- 534,
+ 536,
"RevokeApiKeyInput!"
]
}
@@ -9944,7 +9954,7 @@ export default {
58,
{
"input": [
- 535,
+ 537,
"CreateViewFilterGroupInput!"
]
}
@@ -9957,7 +9967,7 @@ export default {
"String!"
],
"input": [
- 536,
+ 538,
"UpdateViewFilterGroupInput!"
]
}
@@ -9981,7 +9991,7 @@ export default {
}
],
"deleteConnectedAccount": [
- 208,
+ 210,
{
"id": [
3,
@@ -9990,7 +10000,7 @@ export default {
}
],
"disconnectConnectedAccount": [
- 208,
+ 210,
{
"id": [
3,
@@ -10002,7 +10012,7 @@ export default {
72,
{
"data": [
- 537,
+ 539,
"ActivateWorkspaceInput!"
]
}
@@ -10011,7 +10021,7 @@ export default {
72,
{
"data": [
- 538,
+ 540,
"UpdateWorkspaceInput!"
]
}
@@ -10020,7 +10030,7 @@ export default {
72,
{
"data": [
- 539,
+ 541,
"UpdateWorkspaceAllowedIframeOriginsInput!"
]
}
@@ -10029,10 +10039,10 @@ export default {
72
],
"checkCustomDomainValidRecords": [
- 289
+ 291
],
"enrichWorkspaceCompany": [
- 266
+ 268
],
"upgradeApplication": [
8,
@@ -10048,10 +10058,10 @@ export default {
}
],
"createApplicationRegistration": [
- 241,
+ 243,
{
"input": [
- 540,
+ 542,
"CreateApplicationRegistrationInput!"
]
}
@@ -10060,7 +10070,7 @@ export default {
79,
{
"input": [
- 541,
+ 543,
"UpdateApplicationRegistrationInput!"
]
}
@@ -10075,7 +10085,7 @@ export default {
}
],
"rotateApplicationRegistrationClientSecret": [
- 243,
+ 245,
{
"id": [
1,
@@ -10084,10 +10094,10 @@ export default {
}
],
"updateApplicationRegistrationVariable": [
- 213,
+ 215,
{
"input": [
- 543,
+ 545,
"UpdateApplicationRegistrationVariableInput!"
]
}
@@ -10105,7 +10115,7 @@ export default {
79,
{
"file": [
- 454,
+ 456,
"Upload!"
],
"universalIdentifier": [
@@ -10136,10 +10146,10 @@ export default {
}
],
"grantApplicationCapabilities": [
- 265,
+ 267,
{
"input": [
- 545,
+ 547,
"GrantApplicationCapabilitiesInput!"
]
}
@@ -10169,19 +10179,19 @@ export default {
}
],
"triggerInstallApplicationJob": [
- 263,
+ 265,
{
"input": [
- 546,
+ 548,
"TriggerInstallApplicationJobInput!"
]
}
],
"triggerUninstallApplicationJob": [
- 264,
+ 266,
{
"input": [
- 547,
+ 549,
"TriggerUninstallApplicationJobInput!"
]
}
@@ -10194,7 +10204,7 @@ export default {
"UUID!"
],
"input": [
- 548,
+ 550,
"UpdateApplicationInput!"
]
}
@@ -10212,7 +10222,7 @@ export default {
8
],
"runApplicationHealthCheck": [
- 256,
+ 258,
{
"applicationId": [
3,
@@ -10221,28 +10231,28 @@ export default {
}
],
"createOneField": [
- 269,
+ 271,
{
"input": [
- 549,
+ 551,
"CreateOneFieldMetadataInput!"
]
}
],
"updateOneField": [
- 269,
+ 271,
{
"input": [
- 551,
+ 553,
"UpdateOneFieldMetadataInput!"
]
}
],
"deleteOneField": [
- 269,
+ 271,
{
"input": [
- 553,
+ 555,
"DeleteOneFieldInput!"
]
}
@@ -10251,7 +10261,7 @@ export default {
62,
{
"input": [
- 554,
+ 556,
"CreateViewGroupInput!"
]
}
@@ -10260,7 +10270,7 @@ export default {
62,
{
"inputs": [
- 554,
+ 556,
"[CreateViewGroupInput!]!"
]
}
@@ -10269,7 +10279,7 @@ export default {
62,
{
"input": [
- 555,
+ 557,
"UpdateViewGroupInput!"
]
}
@@ -10278,7 +10288,7 @@ export default {
62,
{
"inputs": [
- 555,
+ 557,
"[UpdateViewGroupInput!]!"
]
}
@@ -10287,7 +10297,7 @@ export default {
62,
{
"input": [
- 557,
+ 559,
"DeleteViewGroupInput!"
]
}
@@ -10296,40 +10306,40 @@ export default {
62,
{
"input": [
- 558,
+ 560,
"DestroyViewGroupInput!"
]
}
],
"sendMessageCampaign": [
- 350,
+ 352,
{
"input": [
- 559,
+ 561,
"SendMessageCampaignInput!"
]
}
],
"cancelMessageCampaign": [
- 348,
+ 350,
{
"input": [
- 560,
+ 562,
"CancelMessageCampaignInput!"
]
}
],
"sendMessageCampaignTest": [
- 349,
+ 351,
{
"input": [
- 561,
+ 563,
"SendMessageCampaignTestInput!"
]
}
],
"duplicateMessageList": [
- 351,
+ 353,
{
"id": [
3,
@@ -10338,10 +10348,10 @@ export default {
}
],
"createMessageSuppression": [
- 352,
+ 354,
{
"input": [
- 562,
+ 564,
"CreateMessageSuppressionInput!"
]
}
@@ -10356,19 +10366,19 @@ export default {
}
],
"createUnsubscribeTopic": [
- 356,
+ 358,
{
"input": [
- 563,
+ 565,
"CreateUnsubscribeTopicInput!"
]
}
],
"updateUnsubscribeTopic": [
- 356,
+ 358,
{
"input": [
- 564,
+ 566,
"UpdateUnsubscribeTopicInput!"
]
}
@@ -10383,34 +10393,34 @@ export default {
}
],
"updateMessageChannel": [
- 336,
+ 338,
{
"input": [
- 565,
+ 567,
"UpdateMessageChannelInput!"
]
}
],
"createEmailGroupChannel": [
- 346,
+ 348,
{
"input": [
- 567,
+ 569,
"CreateEmailGroupChannelInput!"
]
}
],
"updateEmailGroupChannel": [
- 336,
+ 338,
{
"input": [
- 568,
+ 570,
"UpdateEmailGroupChannelInput!"
]
}
],
"deleteEmailGroupChannel": [
- 336,
+ 338,
{
"id": [
3,
@@ -10419,25 +10429,25 @@ export default {
}
],
"createAppMessageChannel": [
- 336,
+ 338,
{
"input": [
- 569,
+ 571,
"CreateAppMessageChannelInput!"
]
}
],
"updateAppMessageChannel": [
- 336,
+ 338,
{
"input": [
- 570,
+ 572,
"UpdateAppMessageChannelInput!"
]
}
],
"deleteAppMessageChannel": [
- 336,
+ 338,
{
"id": [
3,
@@ -10446,19 +10456,19 @@ export default {
}
],
"ingestAppMessages": [
- 345,
+ 347,
{
"input": [
- 571,
+ 573,
"IngestAppMessagesInput!"
]
}
],
"createEmailingDomain": [
- 332,
+ 334,
{
"input": [
- 575,
+ 577,
"CreateEmailingDomainInput!"
]
}
@@ -10473,7 +10483,7 @@ export default {
}
],
"verifyEmailingDomain": [
- 332,
+ 334,
{
"id": [
1,
@@ -10482,25 +10492,25 @@ export default {
}
],
"createWebhook": [
- 365,
+ 367,
{
"input": [
- 576,
+ 578,
"CreateWebhookInput!"
]
}
],
"updateWebhook": [
- 365,
+ 367,
{
"input": [
- 577,
+ 579,
"UpdateWebhookInput!"
]
}
],
"deleteWebhook": [
- 365,
+ 367,
{
"id": [
3,
@@ -10509,46 +10519,46 @@ export default {
}
],
"runAgent": [
- 369,
+ 371,
{
"input": [
- 579,
+ 581,
"RunAgentInput!"
]
}
],
"updateMessageFolder": [
- 411,
+ 413,
{
"input": [
- 584,
+ 586,
"UpdateMessageFolderInput!"
]
}
],
"updateMessageFolders": [
- 411,
+ 413,
{
"input": [
- 586,
+ 588,
"UpdateMessageFoldersInput!"
]
}
],
"updateCalendarChannel": [
- 406,
+ 408,
{
"input": [
- 587,
+ 589,
"UpdateCalendarChannelInput!"
]
}
],
"setAppKeyValue": [
- 404,
+ 406,
{
"input": [
- 589,
+ 591,
"SetAppKeyValueInput!"
]
}
@@ -10561,24 +10571,24 @@ export default {
"String!"
],
"scope": [
- 405
+ 407
]
}
],
"enqueueJob": [
- 402,
+ 404,
{
"input": [
- 590,
+ 592,
"EnqueueJobInput!"
]
}
],
"enqueueJobs": [
- 403,
+ 405,
{
"input": [
- 591,
+ 593,
"EnqueueJobsInput!"
]
}
@@ -10587,16 +10597,16 @@ export default {
8,
{
"input": [
- 593,
+ 595,
"ReportAppConnectionAuthFailureInput!"
]
}
],
"createChatThread": [
- 382
+ 384
],
"sendChatMessage": [
- 387,
+ 389,
{
"threadId": [
3,
@@ -10617,13 +10627,13 @@ export default {
1
],
"fileAttachments": [
- 594,
+ 596,
"[FileAttachmentInput!]"
]
}
],
"retryChatMessage": [
- 387,
+ 389,
{
"threadId": [
3,
@@ -10653,7 +10663,7 @@ export default {
}
],
"markAgentChatThreadAsRead": [
- 388,
+ 390,
{
"threadId": [
3,
@@ -10662,7 +10672,7 @@ export default {
}
],
"markAgentChatThreadAsUnread": [
- 388,
+ 390,
{
"threadId": [
3,
@@ -10671,7 +10681,7 @@ export default {
}
],
"archiveAgentChatThread": [
- 388,
+ 390,
{
"threadId": [
3,
@@ -10680,7 +10690,7 @@ export default {
}
],
"snoozeAgentChatThread": [
- 388,
+ 390,
{
"threadId": [
3,
@@ -10693,7 +10703,7 @@ export default {
}
],
"moveAgentChatThreadToInbox": [
- 388,
+ 390,
{
"threadId": [
3,
@@ -10715,7 +10725,7 @@ export default {
}
],
"startWorkspaceSetupChat": [
- 391,
+ 393,
{
"companyContext": [
9
@@ -10726,34 +10736,34 @@ export default {
}
],
"sendInboxMessage": [
- 390,
+ 392,
{
"input": [
- 595,
+ 597,
"SendInboxMessageInput!"
]
}
],
"createSkill": [
- 381,
+ 383,
{
"input": [
- 596,
+ 598,
"CreateSkillInput!"
]
}
],
"updateSkill": [
- 381,
+ 383,
{
"input": [
- 597,
+ 599,
"UpdateSkillInput!"
]
}
],
"deleteSkill": [
- 381,
+ 383,
{
"id": [
3,
@@ -10762,7 +10772,7 @@ export default {
}
],
"activateSkill": [
- 381,
+ 383,
{
"id": [
3,
@@ -10771,7 +10781,7 @@ export default {
}
],
"deactivateSkill": [
- 381,
+ 383,
{
"id": [
3,
@@ -10780,7 +10790,7 @@ export default {
}
],
"evaluateAgentTurn": [
- 399,
+ 401,
{
"turnId": [
3,
@@ -10789,7 +10799,7 @@ export default {
}
],
"runEvaluationInput": [
- 400,
+ 402,
{
"agentId": [
3,
@@ -10802,25 +10812,25 @@ export default {
}
],
"createValidationRule": [
- 418,
+ 420,
{
"input": [
- 598,
+ 600,
"CreateValidationRuleInput!"
]
}
],
"updateValidationRule": [
- 418,
+ 420,
{
"input": [
- 599,
+ 601,
"UpdateValidationRuleInput!"
]
}
],
"deleteValidationRule": [
- 418,
+ 420,
{
"id": [
3,
@@ -10829,16 +10839,16 @@ export default {
}
],
"updateTimelineActivityType": [
- 417,
+ 419,
{
"input": [
- 601,
+ 603,
"UpdateTimelineActivityTypeInput!"
]
}
],
"resetTimelineActivityType": [
- 417,
+ 419,
{
"id": [
3,
@@ -10847,16 +10857,16 @@ export default {
}
],
"getAuthorizationUrlForSSO": [
- 299,
+ 301,
{
"input": [
- 602,
+ 604,
"GetAuthorizationUrlForSSOInput!"
]
}
],
"getLoginTokenFromCredentials": [
- 310,
+ 312,
{
"email": [
1,
@@ -10882,7 +10892,7 @@ export default {
}
],
"signIn": [
- 297,
+ 299,
{
"email": [
1,
@@ -10904,7 +10914,7 @@ export default {
}
],
"verifyEmailAndGetLoginToken": [
- 305,
+ 307,
{
"emailVerificationToken": [
1,
@@ -10924,7 +10934,7 @@ export default {
}
],
"verifyEmailAndGetWorkspaceAgnosticToken": [
- 297,
+ 299,
{
"emailVerificationToken": [
1,
@@ -10940,7 +10950,7 @@ export default {
}
],
"getAuthTokensFromOTP": [
- 309,
+ 311,
{
"otp": [
1,
@@ -10960,7 +10970,7 @@ export default {
}
],
"signUp": [
- 297,
+ 299,
{
"email": [
1,
@@ -10982,7 +10992,7 @@ export default {
}
],
"signUpInWorkspace": [
- 302,
+ 304,
{
"email": [
1,
@@ -11013,28 +11023,28 @@ export default {
}
],
"signUpInNewWorkspace": [
- 302,
+ 304,
{
"input": [
- 603
+ 605
]
}
],
"uploadNewWorkspaceLogo": [
- 164,
+ 166,
{
"workspaceId": [
1,
"String!"
],
"file": [
- 454,
+ 456,
"Upload!"
]
}
],
"createNewWorkspaceLogoUpload": [
- 165,
+ 167,
{
"workspaceId": [
1,
@@ -11051,7 +11061,7 @@ export default {
}
],
"completeNewWorkspaceLogoUpload": [
- 164,
+ 166,
{
"workspaceId": [
1,
@@ -11064,10 +11074,10 @@ export default {
}
],
"generateTransientToken": [
- 303
+ 305
],
"getAuthTokensFromLoginToken": [
- 309,
+ 311,
{
"loginToken": [
1,
@@ -11080,7 +11090,7 @@ export default {
}
],
"getAuthTokensFromSSOExchangeToken": [
- 309,
+ 311,
{
"ssoExchangeToken": [
1,
@@ -11089,7 +11099,7 @@ export default {
}
],
"authorizeApp": [
- 295,
+ 297,
{
"clientId": [
1,
@@ -11114,7 +11124,7 @@ export default {
}
],
"renewToken": [
- 309,
+ 311,
{
"appToken": [
1,
@@ -11131,7 +11141,7 @@ export default {
}
],
"generateApiKeyToken": [
- 308,
+ 310,
{
"apiKeyId": [
3,
@@ -11147,7 +11157,7 @@ export default {
11
],
"emailPasswordResetLink": [
- 298,
+ 300,
{
"email": [
1,
@@ -11162,7 +11172,7 @@ export default {
}
],
"updatePasswordViaResetToken": [
- 300,
+ 302,
{
"passwordResetToken": [
1,
@@ -11175,7 +11185,7 @@ export default {
}
],
"initiateOTPProvisioning": [
- 293,
+ 295,
{
"loginToken": [
1,
@@ -11188,10 +11198,10 @@ export default {
}
],
"initiateOTPProvisioningForAuthenticatedUser": [
- 293
+ 295
],
"deleteTwoFactorAuthenticationMethod": [
- 292,
+ 294,
{
"twoFactorAuthenticationMethodId": [
3,
@@ -11200,7 +11210,7 @@ export default {
}
],
"verifyTwoFactorAuthenticationMethodForAuthenticatedUser": [
- 294,
+ 296,
{
"otp": [
1,
@@ -11224,7 +11234,7 @@ export default {
8,
{
"input": [
- 604,
+ 606,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -11242,7 +11252,7 @@ export default {
}
],
"resendEmailVerificationToken": [
- 245,
+ 247,
{
"email": [
1,
@@ -11255,43 +11265,43 @@ export default {
}
],
"createOIDCIdentityProvider": [
- 250,
+ 252,
{
"input": [
- 605,
+ 607,
"SetupOIDCSsoInput!"
]
}
],
"createSAMLIdentityProvider": [
- 250,
+ 252,
{
"input": [
- 606,
+ 608,
"SetupSAMLSsoInput!"
]
}
],
"deleteSSOIdentityProvider": [
- 246,
+ 248,
{
"input": [
- 607,
+ 609,
"DeleteSsoInput!"
]
}
],
"editSSOIdentityProvider": [
- 247,
+ 249,
{
"input": [
- 608,
+ 610,
"EditSsoInput!"
]
}
],
"createObjectEvent": [
- 394,
+ 396,
{
"event": [
1,
@@ -11311,10 +11321,10 @@ export default {
}
],
"trackAnalytics": [
- 394,
+ 396,
{
"type": [
- 609,
+ 611,
"AnalyticsType!"
],
"name": [
@@ -11329,7 +11339,7 @@ export default {
}
],
"duplicateDashboard": [
- 379,
+ 381,
{
"id": [
3,
@@ -11338,7 +11348,7 @@ export default {
}
],
"impersonate": [
- 313,
+ 315,
{
"userId": [
3,
@@ -11351,28 +11361,28 @@ export default {
}
],
"stopImpersonation": [
- 314
+ 316
],
"createCalendarEvent": [
- 371,
+ 373,
{
"input": [
- 610,
+ 612,
"CreateCalendarEventInput!"
]
}
],
"sendEmail": [
- 393,
+ 395,
{
"input": [
- 611,
+ 613,
"SendEmailInput!"
]
}
],
"startChannelSync": [
- 370,
+ 372,
{
"connectedAccountId": [
3,
@@ -11381,14 +11391,14 @@ export default {
}
],
"saveImapSmtpCaldavAccount": [
- 364,
+ 366,
{
"handle": [
1,
"String!"
],
"connectionParameters": [
- 613,
+ 615,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -11397,16 +11407,16 @@ export default {
}
],
"updateLabPublicFeatureFlag": [
- 210,
+ 212,
{
"input": [
- 615,
+ 617,
"UpdateLabPublicFeatureFlagInput!"
]
}
],
"createPublicDomain": [
- 330,
+ 332,
{
"domain": [
1,
@@ -11428,7 +11438,7 @@ export default {
}
],
"checkPublicDomainValidRecords": [
- 289,
+ 291,
{
"domain": [
1,
@@ -11437,7 +11447,7 @@ export default {
}
],
"createDevelopmentApplication": [
- 323,
+ 325,
{
"universalIdentifier": [
1,
@@ -11450,7 +11460,7 @@ export default {
}
],
"syncApplication": [
- 324,
+ 326,
{
"manifest": [
9,
@@ -11465,10 +11475,10 @@ export default {
}
],
"uploadApplicationFile": [
- 316,
+ 318,
{
"file": [
- 454,
+ 456,
"Upload!"
],
"applicationUniversalIdentifier": [
@@ -11476,7 +11486,7 @@ export default {
"String!"
],
"fileFolder": [
- 320,
+ 322,
"FileFolder!"
],
"filePath": [
@@ -11486,20 +11496,20 @@ export default {
}
],
"createApplicationFileUploads": [
- 322,
+ 324,
{
"applicationUniversalIdentifier": [
1,
"String!"
],
"files": [
- 616,
+ 618,
"[ApplicationFileUploadRequestInput!]!"
]
}
],
"completeApplicationFileUploads": [
- 318,
+ 320,
{
"applicationUniversalIdentifier": [
1,
@@ -11586,7 +11596,7 @@ export default {
3
],
"type": [
- 168
+ 170
],
"name": [
1
@@ -11618,7 +11628,7 @@ export default {
3
],
"update": [
- 453
+ 455
],
"__typename": [
1
@@ -11653,10 +11663,10 @@ export default {
"Upload": {},
"CreateUsageLimitInput": {
"resourceType": [
- 157
+ 160
],
"operationType": [
- 158
+ 157
],
"spenderType": [
1
@@ -11673,14 +11683,14 @@ export default {
"periodUnit": [
1
],
- "meter": [
- 1
+ "unit": [
+ 158
],
"limitValue": [
- 161
+ 163
],
"burstValue": [
- 161
+ 163
],
"__typename": [
1
@@ -11691,7 +11701,7 @@ export default {
3
],
"payload": [
- 455
+ 457
],
"__typename": [
1
@@ -11825,7 +11835,7 @@ export default {
8
],
"tabs": [
- 464
+ 466
],
"__typename": [
1
@@ -11848,7 +11858,7 @@ export default {
107
],
"widgets": [
- 465
+ 467
],
"__typename": [
1
@@ -12015,19 +12025,19 @@ export default {
3
],
"view": [
- 469
+ 471
],
"viewFields": [
- 470
+ 472
],
"viewFilters": [
- 471
+ 473
],
"viewFilterGroups": [
- 472
+ 474
],
"viewSorts": [
- 473
+ 475
],
"__typename": [
1
@@ -12176,7 +12186,7 @@ export default {
3
],
"update": [
- 476
+ 478
],
"__typename": [
1
@@ -12246,7 +12256,7 @@ export default {
3
],
"update": [
- 481
+ 483
],
"__typename": [
1
@@ -12299,7 +12309,7 @@ export default {
3
],
"update": [
- 485
+ 487
],
"__typename": [
1
@@ -12375,7 +12385,7 @@ export default {
3
],
"update": [
- 490
+ 492
],
"__typename": [
1
@@ -12439,10 +12449,10 @@ export default {
3
],
"groups": [
- 495
+ 497
],
"fields": [
- 496
+ 498
],
"__typename": [
1
@@ -12462,7 +12472,7 @@ export default {
8
],
"fields": [
- 496
+ 498
],
"__typename": [
1
@@ -12560,7 +12570,7 @@ export default {
},
"CreateOneObjectInput": {
"object": [
- 500
+ 502
],
"__typename": [
1
@@ -12620,7 +12630,7 @@ export default {
},
"UpdateOneObjectInput": {
"update": [
- 503
+ 505
],
"id": [
3
@@ -12679,7 +12689,7 @@ export default {
28
],
"translations": [
- 504
+ 506
],
"__typename": [
1
@@ -12701,7 +12711,7 @@ export default {
},
"CreateOneIndexInput": {
"index": [
- 506
+ 508
],
"__typename": [
1
@@ -12712,10 +12722,10 @@ export default {
3
],
"fields": [
- 507
+ 509
],
"indexType": [
- 278
+ 280
],
"__typename": [
1
@@ -12797,7 +12807,7 @@ export default {
3
],
"update": [
- 512
+ 514
],
"__typename": [
1
@@ -12966,7 +12976,7 @@ export default {
3
],
"update": [
- 517
+ 519
],
"__typename": [
1
@@ -13059,7 +13069,7 @@ export default {
},
"UpdateRoleInput": {
"update": [
- 523
+ 525
],
"id": [
3
@@ -13114,7 +13124,7 @@ export default {
3
],
"objectPermissions": [
- 525
+ 527
],
"__typename": [
1
@@ -13156,7 +13166,7 @@ export default {
3
],
"fieldPermissions": [
- 528
+ 530
],
"__typename": [
1
@@ -13187,10 +13197,10 @@ export default {
3
],
"predicates": [
- 530
+ 532
],
"predicateGroups": [
- 531
+ 533
],
"__typename": [
1
@@ -13457,7 +13467,7 @@ export default {
1
],
"update": [
- 542
+ 544
],
"__typename": [
1
@@ -13482,7 +13492,7 @@ export default {
1
],
"update": [
- 544
+ 546
],
"__typename": [
1
@@ -13539,7 +13549,7 @@ export default {
},
"CreateOneFieldMetadataInput": {
"field": [
- 550
+ 552
],
"__typename": [
1
@@ -13547,7 +13557,7 @@ export default {
},
"CreateFieldInput": {
"type": [
- 270
+ 272
],
"name": [
1
@@ -13618,7 +13628,7 @@ export default {
3
],
"update": [
- 552
+ 554
],
"__typename": [
1
@@ -13683,7 +13693,7 @@ export default {
9
],
"translations": [
- 504
+ 506
],
"__typename": [
1
@@ -13722,7 +13732,7 @@ export default {
3
],
"update": [
- 556
+ 558
],
"__typename": [
1
@@ -13819,7 +13829,7 @@ export default {
1
],
"visibility": [
- 357
+ 359
],
"__typename": [
1
@@ -13836,7 +13846,7 @@ export default {
1
],
"visibility": [
- 357
+ 359
],
"__typename": [
1
@@ -13847,7 +13857,7 @@ export default {
3
],
"update": [
- 566
+ 568
],
"__typename": [
1
@@ -13855,16 +13865,16 @@ export default {
},
"UpdateMessageChannelInputUpdates": {
"visibility": [
- 337
+ 339
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 339
+ 341
],
"messageFolderImportPolicy": [
- 340
+ 342
],
"isSyncEnabled": [
8
@@ -13912,7 +13922,7 @@ export default {
1
],
"visibility": [
- 337
+ 339
],
"__typename": [
1
@@ -13926,7 +13936,7 @@ export default {
1
],
"visibility": [
- 337
+ 339
],
"isSyncEnabled": [
8
@@ -13940,7 +13950,7 @@ export default {
3
],
"messages": [
- 572
+ 574
],
"__typename": [
1
@@ -13963,7 +13973,7 @@ export default {
4
],
"participants": [
- 573
+ 575
],
"__typename": [
1
@@ -13971,7 +13981,7 @@ export default {
},
"AppMessageParticipantInput": {
"role": [
- 574
+ 576
],
"handle": [
1
@@ -14023,7 +14033,7 @@ export default {
3
],
"update": [
- 578
+ 580
],
"__typename": [
1
@@ -14057,16 +14067,16 @@ export default {
3
],
"messages": [
- 580
+ 582
],
"input": [
- 580
+ 582
],
"additionalInstructions": [
1
],
"thread": [
- 583
+ 585
],
"__typename": [
1
@@ -14074,13 +14084,13 @@ export default {
},
"RunAgentMessageInput": {
"role": [
- 581
+ 583
],
"content": [
1
],
"attachments": [
- 582
+ 584
],
"__typename": [
1
@@ -14114,7 +14124,7 @@ export default {
3
],
"update": [
- 585
+ 587
],
"__typename": [
1
@@ -14133,7 +14143,7 @@ export default {
3
],
"update": [
- 585
+ 587
],
"__typename": [
1
@@ -14144,7 +14154,7 @@ export default {
3
],
"update": [
- 588
+ 590
],
"__typename": [
1
@@ -14152,13 +14162,13 @@ export default {
},
"UpdateCalendarChannelInputUpdates": {
"visibility": [
- 409
+ 411
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 410
+ 412
],
"isSyncEnabled": [
8
@@ -14175,7 +14185,7 @@ export default {
9
],
"scope": [
- 405
+ 407
],
"__typename": [
1
@@ -14209,7 +14219,7 @@ export default {
9
],
"jobs": [
- 592
+ 594
],
"retryLimit": [
31
@@ -14234,7 +14244,7 @@ export default {
},
"ReportAppConnectionAuthFailureInput": {
"id": [
- 171
+ 173
],
"reason": [
1
@@ -14360,7 +14370,7 @@ export default {
3
],
"update": [
- 600
+ 602
],
"__typename": [
1
@@ -14406,7 +14416,7 @@ export default {
8
],
"translations": [
- 504
+ 506
],
"__typename": [
1
@@ -14498,7 +14508,7 @@ export default {
3
],
"status": [
- 219
+ 221
],
"__typename": [
1
@@ -14572,7 +14582,7 @@ export default {
1
],
"files": [
- 612
+ 614
],
"__typename": [
1
@@ -14594,13 +14604,13 @@ export default {
1
],
"IMAP": [
- 614
+ 616
],
"SMTP": [
- 614
+ 616
],
"CALDAV": [
- 614
+ 616
],
"__typename": [
1
@@ -14620,7 +14630,7 @@ export default {
1
],
"connectionSecurity": [
- 206
+ 208
],
"__typename": [
1
@@ -14639,7 +14649,7 @@ export default {
},
"ApplicationFileUploadRequestInput": {
"fileFolder": [
- 320
+ 322
],
"filePath": [
1
@@ -14653,7 +14663,7 @@ export default {
},
"Subscription": {
"onEventSubscription": [
- 187,
+ 189,
{
"eventStreamId": [
1,
@@ -14662,16 +14672,16 @@ export default {
}
],
"logicFunctionLogs": [
- 291,
+ 293,
{
"input": [
- 618,
+ 620,
"LogicFunctionLogsInput!"
]
}
],
"onAgentChatEvent": [
- 389,
+ 391,
{
"threadId": [
3,
@@ -14680,23 +14690,23 @@ export default {
}
],
"eventLogsLive": [
- 395,
+ 397,
{
"table": [
- 439,
+ 441,
"EventLogTable!"
],
"fieldFilters": [
- 442,
+ 444,
"[EventLogFieldFilterInput!]"
]
}
],
"exportRecords": [
- 398,
+ 400,
{
"input": [
- 619,
+ 621,
"CreateRecordExportInput!"
]
}
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index 3ee3376c4da..8660f47f095 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -172,13 +172,13 @@ export type AdminPanelUsageLimit = {
id: Scalars['UUID']['output'];
limitKind: Scalars['String']['output'];
limitValue: Scalars['BigInt']['output'];
- meter: Scalars['String']['output'];
operationType: UsageOperationType;
periodCount: Scalars['Int']['output'];
periodUnit: Scalars['String']['output'];
resourceType: UsageResourceType;
spenderId?: Maybe<Scalars['String']['output']>;
spenderType: Scalars['String']['output'];
+ unit: UsageUnit;
updatedAt: Scalars['DateTime']['output'];
};
@@ -187,13 +187,13 @@ export type AdminPanelUsageLimitDefault = {
isOverridable: Scalars['Boolean']['output'];
limitKind: Scalars['String']['output'];
limitValue: Scalars['BigInt']['output'];
- meter: Scalars['String']['output'];
operationType: UsageOperationType;
overriddenByUsageLimitId?: Maybe<Scalars['UUID']['output']>;
periodCount: Scalars['Int']['output'];
periodUnit: Scalars['String']['output'];
resourceType: UsageResourceType;
spenderType: Scalars['String']['output'];
+ unit: UsageUnit;
};
export type AdminPanelWorkerQueueHealth = {
@@ -446,13 +446,13 @@ 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'];
+ unit: UsageUnit;
};
export type CustomAiProviderAccessDto = {
@@ -1131,6 +1131,20 @@ export enum UsageResourceType {
WORKFLOW = 'WORKFLOW'
}
+export enum UsageUnit {
+ BYTE = 'BYTE',
+ COMPLEXITY = 'COMPLEXITY',
+ CREDIT = 'CREDIT',
+ FILE = 'FILE',
+ INVOCATION = 'INVOCATION',
+ MILLISECOND = 'MILLISECOND',
+ MINUTE = 'MINUTE',
+ RECORD = 'RECORD',
+ REQUEST = 'REQUEST',
+ SEAT = 'SEAT',
+ TOKEN = 'TOKEN'
+}
+
export type UserInfo = {
__typename?: 'UserInfo';
avatarUrl?: Maybe<Scalars['String']['output']>;
@@ -1557,7 +1571,7 @@ export type WorkspaceUsageLimitsQueryVariables = Exact<{
}>;
-export type WorkspaceUsageLimitsQuery = { __typename?: 'Query', workspaceUsageLimits: { __typename?: 'AdminPanelWorkspaceUsageLimits', defaults: Array<{ __typename?: 'AdminPanelUsageLimitDefault', resourceType: UsageResourceType, operationType: UsageOperationType, spenderType: string, limitKind: string, periodCount: number, periodUnit: string, meter: string, limitValue: any, isOverridable: boolean, overriddenByUsageLimitId?: string | null }>, limits: Array<{ __typename?: 'AdminPanelUsageLimit', id: string, periodCount: number, periodUnit: string, limitValue: any, burstValue?: any | null }> } };
+export type WorkspaceUsageLimitsQuery = { __typename?: 'Query', workspaceUsageLimits: { __typename?: 'AdminPanelWorkspaceUsageLimits', defaults: Array<{ __typename?: 'AdminPanelUsageLimitDefault', resourceType: UsageResourceType, operationType: UsageOperationType, spenderType: string, limitKind: string, periodCount: number, periodUnit: string, unit: UsageUnit, limitValue: any, isOverridable: boolean, overriddenByUsageLimitId?: string | null }>, limits: Array<{ __typename?: 'AdminPanelUsageLimit', id: string, periodCount: number, periodUnit: string, limitValue: any, burstValue?: any | null }> } };
export type DeleteJobsMutationVariables = Exact<{
queueName: Scalars['String']['input'];
@@ -1695,7 +1709,7 @@ export const GetVersionInfoDocument = {"kind":"Document","definitions":[{"kind":
export const WorkspaceBillingAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceBillingAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceBillingAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripeCustomerId"}},{"kind":"Field","name":{"kind":"Name","value":"creditBalance"}},{"kind":"Field","name":{"kind":"Name","value":"creditGrants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"amount"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveAt"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"revokedAt"}},{"kind":"Field","name":{"kind":"Name","value":"sourceGrantId"}},{"kind":"Field","name":{"kind":"Name","value":"reason"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"usedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"grantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"rolloverCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalGrantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"remainingCredits"}}]}},{"kind":"Field","name":{"kind":"Name","value":"subscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripeSubscriptionId"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"currency"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodStart"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"trialStart"}},{"kind":"Field","name":{"kind":"Name","value":"trialEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"canceledAt"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAtPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productName"}},{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"includedCredits"}}]}}]}}]}}]}}]} as unknown as DocumentNode<WorkspaceBillingAdminPanelQuery, WorkspaceBillingAdminPanelQueryVariables>;
export const UserLookupAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UserLookupAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userLookupAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userIdentifier"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"UserInfoFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"totalUsers"}},{"kind":"Field","name":{"kind":"Name","value":"activationStatus"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customUrl"}},{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"users"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}}]}},{"kind":"Field","name":{"kind":"Name","value":"featureFlags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"UserInfoFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"UserInfo"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]} as unknown as DocumentNode<UserLookupAdminPanelQuery, UserLookupAdminPanelQueryVariables>;
export const WorkspaceLookupAdminPanelDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceLookupAdminPanel"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceLookupAdminPanel"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"UserInfoFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspaces"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"allowImpersonation"}},{"kind":"Field","name":{"kind":"Name","value":"logo"}},{"kind":"Field","name":{"kind":"Name","value":"totalUsers"}},{"kind":"Field","name":{"kind":"Name","value":"activationStatus"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"customUrl"}},{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"users"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"featureFlags"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"value"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"UserInfoFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"UserInfo"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]} as unknown as DocumentNode<WorkspaceLookupAdminPanelQuery, WorkspaceLookupAdminPanelQueryVariables>;
-export const WorkspaceUsageLimitsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceUsageLimits"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceUsageLimits"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"defaults"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"resourceType"}},{"kind":"Field","name":{"kind":"Name","value":"operationType"}},{"kind":"Field","name":{"kind":"Name","value":"spenderType"}},{"kind":"Field","name":{"kind":"Name","value":"limitKind"}},{"kind":"Field","name":{"kind":"Name","value":"periodCount"}},{"kind":"Field","name":{"kind":"Name","value":"periodUnit"}},{"kind":"Field","name":{"kind":"Name","value":"meter"}},{"kind":"Field","name":{"kind":"Name","value":"limitValue"}},{"kind":"Field","name":{"kind":"Name","value":"isOverridable"}},{"kind":"Field","name":{"kind":"Name","value":"overriddenByUsageLimitId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"limits"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"periodCount"}},{"kind":"Field","name":{"kind":"Name","value":"periodUnit"}},{"kind":"Field","name":{"kind":"Name","value":"limitValue"}},{"kind":"Field","name":{"kind":"Name","value":"burstValue"}}]}}]}}]}}]} as unknown as DocumentNode<WorkspaceUsageLimitsQuery, WorkspaceUsageLimitsQueryVariables>;
+export const WorkspaceUsageLimitsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkspaceUsageLimits"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceUsageLimits"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"defaults"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"resourceType"}},{"kind":"Field","name":{"kind":"Name","value":"operationType"}},{"kind":"Field","name":{"kind":"Name","value":"spenderType"}},{"kind":"Field","name":{"kind":"Name","value":"limitKind"}},{"kind":"Field","name":{"kind":"Name","value":"periodCount"}},{"kind":"Field","name":{"kind":"Name","value":"periodUnit"}},{"kind":"Field","name":{"kind":"Name","value":"unit"}},{"kind":"Field","name":{"kind":"Name","value":"limitValue"}},{"kind":"Field","name":{"kind":"Name","value":"isOverridable"}},{"kind":"Field","name":{"kind":"Name","value":"overriddenByUsageLimitId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"limits"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"periodCount"}},{"kind":"Field","name":{"kind":"Name","value":"periodUnit"}},{"kind":"Field","name":{"kind":"Name","value":"limitValue"}},{"kind":"Field","name":{"kind":"Name","value":"burstValue"}}]}}]}}]}}]} as unknown as DocumentNode<WorkspaceUsageLimitsQuery, WorkspaceUsageLimitsQueryVariables>;
export const DeleteJobsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteJobs"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"queueName"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"jobIds"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteJobs"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"queueName"},"value":{"kind":"Variable","name":{"kind":"Name","value":"queueName"}}},{"kind":"Argument","name":{"kind":"Name","value":"jobIds"},"value":{"kind":"Variable","name":{"kind":"Name","value":"jobIds"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deletedCount"}},{"kind":"Field","name":{"kind":"Name","value":"results"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"jobId"}},{"kind":"Field","name":{"kind":"Name","value":"success"}},{"kind":"Field","name":{"kind":"Name","value":"error"}}]}}]}}]}}]} as unknown as DocumentNode<DeleteJobsMutation, DeleteJobsMutationVariables>;
export const RefreshUpgradeStatusDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RefreshUpgradeStatus"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"refreshUpgradeStatus"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"instanceUpgradeStatus"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"inferredVersion"}},{"kind":"Field","name":{"kind":"Name","value":"health"}},{"kind":"Field","name":{"kind":"Name","value":"latestCommand"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"executedByVersion"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspacesBehind"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"workspacesFailed"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"computedAt"}}]}}]}}]} as unknown as DocumentNode<RefreshUpgradeStatusMutation, RefreshUpgradeStatusMutationVariables>;
export const RetryJobsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RetryJobs"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"queueName"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"jobIds"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"retryJobs"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"queueName"},"value":{"kind":"Variable","name":{"kind":"Name","value":"queueName"}}},{"kind":"Argument","name":{"kind":"Name","value":"jobIds"},"value":{"kind":"Variable","name":{"kind":"Name","value":"jobIds"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"retriedCount"}},{"kind":"Field","name":{"kind":"Name","value":"results"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"jobId"}},{"kind":"Field","name":{"kind":"Name","value":"success"}},{"kind":"Field","name":{"kind":"Name","value":"error"}}]}}]}}]}}]} as unknown as DocumentNode<RetryJobsMutation, RetryJobsMutationVariables>;
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index ee3961a33ef..f321bc28e57 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -1587,13 +1587,13 @@ 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'];
+ unit: UsageUnit;
};
export type CreateValidationRuleInput = {
@@ -7243,16 +7243,22 @@ export type UsageLimit = {
id: Scalars['UUID']['output'];
limitKind: Scalars['String']['output'];
limitValue: Scalars['BigInt']['output'];
- meter: Scalars['String']['output'];
operationType: UsageOperationType;
periodCount: Scalars['Int']['output'];
periodUnit: Scalars['String']['output'];
resourceType: UsageResourceType;
spenderId?: Maybe<Scalars['String']['output']>;
spenderType: Scalars['String']['output'];
+ unit: UsageUnit;
updatedAt: Scalars['DateTime']['output'];
};
+export type UsageLimitOperationDefinition = {
+ __typename?: 'UsageLimitOperationDefinition';
+ allowedUnits: Array<UsageUnit>;
+ operationType: UsageOperationType;
+};
+
export enum UsageOperationType {
AI_CHAT_TOKEN = 'AI_CHAT_TOKEN',
AI_WORKFLOW_TOKEN = 'AI_WORKFLOW_TOKEN',
@@ -7272,8 +7278,7 @@ export enum UsageOperationType {
export type UsageQuotaDefinition = {
__typename?: 'UsageQuotaDefinition';
- allowedMeters: Array<Scalars['String']['output']>;
- allowedOperationTypes: Array<UsageOperationType>;
+ allowedOperations: Array<UsageLimitOperationDefinition>;
allowedSpenderTypes: Array<Scalars['String']['output']>;
limitKind: Scalars['String']['output'];
resourceType: UsageResourceType;
@@ -7294,12 +7299,12 @@ export type UsageQuotaScopeConsumption = {
};
export type UsageQuotaScopeInput = {
- meter: Scalars['String']['input'];
operationType: UsageOperationType;
periodUnit: Scalars['String']['input'];
resourceType: UsageResourceType;
spenderId?: InputMaybe<Scalars['String']['input']>;
spenderType: Scalars['String']['input'];
+ unit: UsageUnit;
};
export type UsageQuotaWithConsumption = {
@@ -7308,7 +7313,6 @@ export type UsageQuotaWithConsumption = {
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']>;
@@ -7318,6 +7322,7 @@ export type UsageQuotaWithConsumption = {
spenderId?: Maybe<Scalars['String']['output']>;
spenderLabel?: Maybe<Scalars['String']['output']>;
spenderType: Scalars['String']['output'];
+ unit: UsageUnit;
};
export enum UsageResourceType {
@@ -7338,6 +7343,20 @@ export type UsageTimeSeries = {
date: Scalars['String']['output'];
};
+export enum UsageUnit {
+ BYTE = 'BYTE',
+ COMPLEXITY = 'COMPLEXITY',
+ CREDIT = 'CREDIT',
+ FILE = 'FILE',
+ INVOCATION = 'INVOCATION',
+ MILLISECOND = 'MILLISECOND',
+ MINUTE = 'MINUTE',
+ RECORD = 'RECORD',
+ REQUEST = 'REQUEST',
+ SEAT = 'SEAT',
+ TOKEN = 'TOKEN'
+}
+
export type UsageUserDaily = {
__typename?: 'UsageUserDaily';
dailyUsage: Array<UsageTimeSeries>;
@@ -9869,7 +9888,7 @@ export type ListPlansQuery = { __typename?: 'Query', listPlans: Array<{ __typena
export type UsageQuotaDefinitionsQueryVariables = Exact<{ [key: string]: never; }>;
-export type UsageQuotaDefinitionsQuery = { __typename?: 'Query', usageQuotaDefinitions: { __typename?: 'UsageQuotaDefinitions', isIntraWorkspaceLimitEntitled: boolean, hasAllowancePeriod: boolean, definitions: Array<{ __typename?: 'UsageQuotaDefinition', resourceType: UsageResourceType, allowedOperationTypes: Array<UsageOperationType>, allowedSpenderTypes: Array<string>, allowedMeters: Array<string> }> } };
+export type UsageQuotaDefinitionsQuery = { __typename?: 'Query', usageQuotaDefinitions: { __typename?: 'UsageQuotaDefinitions', isIntraWorkspaceLimitEntitled: boolean, hasAllowancePeriod: boolean, definitions: Array<{ __typename?: 'UsageQuotaDefinition', resourceType: UsageResourceType, allowedSpenderTypes: Array<string>, allowedOperations: Array<{ __typename?: 'UsageLimitOperationDefinition', operationType: UsageOperationType, allowedUnits: Array<UsageUnit> }> }> } };
export type UsageQuotaScopeConsumptionQueryVariables = Exact<{
input: UsageQuotaScopeInput;
@@ -9881,7 +9900,7 @@ export type UsageQuotaScopeConsumptionQuery = { __typename?: 'Query', usageQuota
export type UsageQuotasWithConsumptionQueryVariables = Exact<{ [key: string]: never; }>;
-export type UsageQuotasWithConsumptionQuery = { __typename?: 'Query', usageQuotasWithConsumption: Array<{ __typename?: 'UsageQuotaWithConsumption', id: string, resourceType: UsageResourceType, operationType: UsageOperationType, spenderType: string, spenderId?: string | null, spenderLabel?: string | null, periodUnit: string, meter: string, limitValue: any, isEnforced: boolean, consumedValue?: any | null, remainingValue?: any | null, periodStart?: string | null, periodEnd?: string | null }> };
+export type UsageQuotasWithConsumptionQuery = { __typename?: 'Query', usageQuotasWithConsumption: Array<{ __typename?: 'UsageQuotaWithConsumption', id: string, resourceType: UsageResourceType, operationType: UsageOperationType, spenderType: string, spenderId?: string | null, spenderLabel?: string | null, periodUnit: string, unit: UsageUnit, limitValue: any, isEnforced: boolean, consumedValue?: any | null, remainingValue?: any | null, periodStart?: string | null, periodEnd?: string | null }> };
export type ApiKeyFragmentFragment = { __typename?: 'ApiKey', id: string, name: string, expiresAt: string, revokedAt?: string | null, role: { __typename?: 'Role', id: string, label: string, icon?: string | null } };
@@ -10910,9 +10929,9 @@ export const UpdateUsageLimitDocument = {"kind":"Document","definitions":[{"kind
export const BillingPortalSessionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"BillingPortalSession"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"returnUrlPath"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"forPaymentMethodUpdate"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"billingPortalSession"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"returnUrlPath"},"value":{"kind":"Variable","name":{"kind":"Name","value":"returnUrlPath"}}},{"kind":"Argument","name":{"kind":"Name","value":"forPaymentMethodUpdate"},"value":{"kind":"Variable","name":{"kind":"Name","value":"forPaymentMethodUpdate"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"url"}}]}}]}}]} as unknown as DocumentNode<BillingPortalSessionQuery, BillingPortalSessionQueryVariables>;
export const GetResourceCreditUsageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetResourceCreditUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getResourceCreditUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"usedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"grantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"rolloverCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalGrantedCredits"}},{"kind":"Field","name":{"kind":"Name","value":"unitPriceCents"}}]}}]}}]} as unknown as DocumentNode<GetResourceCreditUsageQuery, GetResourceCreditUsageQueryVariables>;
export const ListPlansDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"listPlans"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"listPlans"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"baseProducts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingLicensedProduct"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"prices"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingPriceLicensedFragment"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"resourceCreditProducts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingLicensedProduct"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"prices"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingPriceLicensedFragment"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"meteredProducts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingMeteredProduct"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"prices"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingPriceMeteredFragment"}}]}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingPriceLicensedFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingPriceLicensed"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"recurringInterval"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageType"}},{"kind":"Field","name":{"kind":"Name","value":"creditAmount"}},{"kind":"Field","name":{"kind":"Name","value":"isSellable"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingPriceMeteredFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingPriceMetered"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"priceUsageType"}},{"kind":"Field","name":{"kind":"Name","value":"recurringInterval"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"tiers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"flatAmount"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"upTo"}}]}}]}}]} as unknown as DocumentNode<ListPlansQuery, ListPlansQueryVariables>;
-export const UsageQuotaDefinitionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UsageQuotaDefinitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageQuotaDefinitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"definitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"resourceType"}},{"kind":"Field","name":{"kind":"Name","value":"allowedOperationTypes"}},{"kind":"Field","name":{"kind":"Name","value":"allowedSpenderTypes"}},{"kind":"Field","name":{"kind":"Name","value":"allowedMeters"}}]}},{"kind":"Field","name":{"kind":"Name","value":"isIntraWorkspaceLimitEntitled"}},{"kind":"Field","name":{"kind":"Name","value":"hasAllowancePeriod"}}]}}]}}]} as unknown as DocumentNode<UsageQuotaDefinitionsQuery, UsageQuotaDefinitionsQueryVariables>;
+export const UsageQuotaDefinitionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UsageQuotaDefinitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageQuotaDefinitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"definitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"resourceType"}},{"kind":"Field","name":{"kind":"Name","value":"allowedOperations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"operationType"}},{"kind":"Field","name":{"kind":"Name","value":"allowedUnits"}}]}},{"kind":"Field","name":{"kind":"Name","value":"allowedSpenderTypes"}}]}},{"kind":"Field","name":{"kind":"Name","value":"isIntraWorkspaceLimitEntitled"}},{"kind":"Field","name":{"kind":"Name","value":"hasAllowancePeriod"}}]}}]}}]} as unknown as DocumentNode<UsageQuotaDefinitionsQuery, UsageQuotaDefinitionsQueryVariables>;
export const UsageQuotaScopeConsumptionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UsageQuotaScopeConsumption"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UsageQuotaScopeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageQuotaScopeConsumption"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"consumedValue"}},{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}}]}}]}}]} as unknown as DocumentNode<UsageQuotaScopeConsumptionQuery, UsageQuotaScopeConsumptionQueryVariables>;
-export const UsageQuotasWithConsumptionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UsageQuotasWithConsumption"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageQuotasWithConsumption"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"resourceType"}},{"kind":"Field","name":{"kind":"Name","value":"operationType"}},{"kind":"Field","name":{"kind":"Name","value":"spenderType"}},{"kind":"Field","name":{"kind":"Name","value":"spenderId"}},{"kind":"Field","name":{"kind":"Name","value":"spenderLabel"}},{"kind":"Field","name":{"kind":"Name","value":"periodUnit"}},{"kind":"Field","name":{"kind":"Name","value":"meter"}},{"kind":"Field","name":{"kind":"Name","value":"limitValue"}},{"kind":"Field","name":{"kind":"Name","value":"isEnforced"}},{"kind":"Field","name":{"kind":"Name","value":"consumedValue"}},{"kind":"Field","name":{"kind":"Name","value":"remainingValue"}},{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}}]}}]}}]} as unknown as DocumentNode<UsageQuotasWithConsumptionQuery, UsageQuotasWithConsumptionQueryVariables>;
+export const UsageQuotasWithConsumptionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UsageQuotasWithConsumption"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageQuotasWithConsumption"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"resourceType"}},{"kind":"Field","name":{"kind":"Name","value":"operationType"}},{"kind":"Field","name":{"kind":"Name","value":"spenderType"}},{"kind":"Field","name":{"kind":"Name","value":"spenderId"}},{"kind":"Field","name":{"kind":"Name","value":"spenderLabel"}},{"kind":"Field","name":{"kind":"Name","value":"periodUnit"}},{"kind":"Field","name":{"kind":"Name","value":"unit"}},{"kind":"Field","name":{"kind":"Name","value":"limitValue"}},{"kind":"Field","name":{"kind":"Name","value":"isEnforced"}},{"kind":"Field","name":{"kind":"Name","value":"consumedValue"}},{"kind":"Field","name":{"kind":"Name","value":"remainingValue"}},{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}}]}}]}}]} as unknown as DocumentNode<UsageQuotasWithConsumptionQuery, UsageQuotasWithConsumptionQueryVariables>;
export const AssignRoleToApiKeyDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AssignRoleToApiKey"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"apiKeyId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"assignRoleToApiKey"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"apiKeyId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"apiKeyId"}}},{"kind":"Argument","name":{"kind":"Name","value":"roleId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}}}]}]}}]} as unknown as DocumentNode<AssignRoleToApiKeyMutation, AssignRoleToApiKeyMutationVariables>;
export const CreateApiKeyDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateApiKey"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateApiKeyInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createApiKey"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ApiKeyFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ApiKeyFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ApiKey"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"revokedAt"}},{"kind":"Field","name":{"kind":"Name","value":"role"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}}]}}]}}]} as unknown as DocumentNode<CreateApiKeyMutation, CreateApiKeyMutationVariables>;
export const CreateWebhookDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateWebhook"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateWebhookInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createWebhook"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WebhookFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WebhookFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Webhook"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"targetUrl"}},{"kind":"Field","name":{"kind":"Name","value":"operations"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"secret"}}]}}]} as unknown as DocumentNode<CreateWebhookMutation, CreateWebhookMutationVariables>;
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceUsageLimitModal.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceUsageLimitModal.tsx
index 6e27f57369e..fa67fa99a85 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceUsageLimitModal.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceUsageLimitModal.tsx
@@ -15,10 +15,9 @@ import { DELETE_WORKSPACE_USAGE_LIMIT } from '@/settings/admin-panel/graphql/mut
import { UPDATE_WORKSPACE_USAGE_LIMIT } from '@/settings/admin-panel/graphql/mutations/updateWorkspaceUsageLimit';
import { WORKSPACE_USAGE_LIMITS } from '@/settings/admin-panel/graphql/queries/workspaceUsageLimits';
import { type AdminUsageLimitRow } from '@/settings/admin-panel/types/AdminUsageLimitRow';
-import { formatUsageLimitValue } from '@/settings/admin-panel/utils/formatUsageLimitValue';
import { getAdminUsageLimitScopeLabel } from '@/settings/admin-panel/utils/getAdminUsageLimitScopeLabel';
-import { USAGE_LIMIT_METER_LABELS } from '@/settings/billing/constants/UsageLimitMeterLabels';
-import { getUsageLimitLabel } from '@/settings/billing/utils/getUsageLimitLabel';
+import { getUsageLimitUnitLabel } from '@/settings/billing/utils/getUsageLimitUnitLabel';
+import { useUsageLimitFormatter } from '@/settings/billing/hooks/useUsageLimitFormatter';
import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';
import { DialogInstance } from '@/ui/layout/dialog/components/DialogInstance';
import { useDialog } from '@/ui/layout/dialog/hooks/useDialog';
@@ -62,6 +61,7 @@ export const SettingsAdminWorkspaceUsageLimitModal = ({
row,
}: SettingsAdminWorkspaceUsageLimitModalProps) => {
const { t } = useLingui();
+ const { formatLimitValue } = useUsageLimitFormatter();
const { closeDialog } = useDialog();
const { enqueueToast } = useToast();
const apolloAdminClient = useApolloAdminClient();
@@ -120,7 +120,7 @@ export const SettingsAdminWorkspaceUsageLimitModal = ({
limitKind: row.limitKind,
periodCount: row.periodCount,
periodUnit: row.periodUnit,
- meter: row.meter,
+ unit: row.unit,
limitValue: parsedLimitValue,
burstValue: isBurstAllowed ? parsedBurstValue : null,
};
@@ -179,16 +179,16 @@ export const SettingsAdminWorkspaceUsageLimitModal = ({
}
};
- const meterLabel = getUsageLimitLabel(USAGE_LIMIT_METER_LABELS, row.meter);
+ const unitLabel = getUsageLimitUnitLabel({
+ unit: row.unit,
+ operationType: row.operationType,
+ });
const scopeLabel = getAdminUsageLimitScopeLabel(row);
- const defaultText = formatUsageLimitValue({
+ const defaultText = formatLimitValue({
value: row.defaultValue,
- meter: row.meter,
+ unit: row.unit,
+ operationType: row.operationType,
});
- const limitValueAdornment =
- isDefined(parsedLimitValue) && row.meter !== 'quantity'
- ? formatUsageLimitValue({ value: parsedLimitValue, meter: row.meter })
- : undefined;
return (
<DialogInstance
@@ -218,12 +218,11 @@ export const SettingsAdminWorkspaceUsageLimitModal = ({
<StyledFields>
<SettingsTextInput
instanceId={`${dialogId}-limit-value`}
- label={isDefined(meterLabel) ? t(meterLabel) : t`Limit`}
+ label={t(unitLabel.name)}
type="number"
min={1}
value={limitValue}
onChange={setLimitValue}
- rightAdornment={limitValueAdornment}
autoFocusOnMount
fullWidth
/>
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceUsageLimitsSection.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceUsageLimitsSection.tsx
index 64a8712673f..87349095783 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceUsageLimitsSection.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceUsageLimitsSection.tsx
@@ -15,7 +15,6 @@ import { SettingsAdminWorkspaceUsageLimitModal } from '@/settings/admin-panel/co
import { WORKSPACE_USAGE_LIMITS } from '@/settings/admin-panel/graphql/queries/workspaceUsageLimits';
import { type AdminUsageLimitRow } from '@/settings/admin-panel/types/AdminUsageLimitRow';
import { buildAdminUsageLimitRows } from '@/settings/admin-panel/utils/buildAdminUsageLimitRows';
-import { formatUsageLimitValue } from '@/settings/admin-panel/utils/formatUsageLimitValue';
import { getAdminUsageLimitOperationLabel } from '@/settings/admin-panel/utils/getAdminUsageLimitOperationLabel';
import { getAdminUsageLimitPeriodLabel } from '@/settings/admin-panel/utils/getAdminUsageLimitPeriodLabel';
import { getAdminUsageLimitResourceLabel } from '@/settings/admin-panel/utils/getAdminUsageLimitResourceLabel';
@@ -23,6 +22,7 @@ import { getAdminUsageLimitSpenderLabel } from '@/settings/admin-panel/utils/get
import { SettingsEmptyPlaceholder } from '@/settings/components/SettingsEmptyPlaceholder';
import { SettingsSectionSkeletonLoader } from '@/settings/components/SettingsSectionSkeletonLoader';
import { SettingsTableListSection } from '@/settings/components/SettingsTableListSection';
+import { useUsageLimitFormatter } from '@/settings/billing/hooks/useUsageLimitFormatter';
import { useDialog } from '@/ui/layout/dialog/hooks/useDialog';
import { type WorkspaceUsageLimitsQuery } from '~/generated-admin/graphql';
@@ -45,6 +45,7 @@ export const SettingsAdminWorkspaceUsageLimitsSection = ({
workspaceId,
}: SettingsAdminWorkspaceUsageLimitsSectionProps) => {
const { t } = useLingui();
+ const { formatLimitValue } = useUsageLimitFormatter();
const apolloAdminClient = useApolloAdminClient();
const { openDialog } = useDialog();
@@ -111,9 +112,10 @@ export const SettingsAdminWorkspaceUsageLimitsSection = ({
label: t`Limit`,
Cell: ({ item }) => (
<>
- {formatUsageLimitValue({
+ {formatLimitValue({
value: item.limitValue,
- meter: item.meter,
+ unit: item.unit,
+ operationType: item.operationType,
})}
</>
),
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/workspaceUsageLimits.ts b/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/workspaceUsageLimits.ts
index 0b53d631469..0d7e0a01067 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/workspaceUsageLimits.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/graphql/queries/workspaceUsageLimits.ts
@@ -10,7 +10,7 @@ export const WORKSPACE_USAGE_LIMITS = gql`
limitKind
periodCount
periodUnit
- meter
+ unit
limitValue
isOverridable
overriddenByUsageLimitId
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/types/AdminUsageLimitRow.ts b/packages/twenty-front/src/modules/settings/admin-panel/types/AdminUsageLimitRow.ts
index 9844df9cfbf..de9e1f6a970 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/types/AdminUsageLimitRow.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/types/AdminUsageLimitRow.ts
@@ -1,6 +1,7 @@
import {
type UsageOperationType,
type UsageResourceType,
+ type UsageUnit,
} from '~/generated-admin/graphql';
export type AdminUsageLimitRow = {
@@ -11,7 +12,7 @@ export type AdminUsageLimitRow = {
limitKind: string;
periodCount: number;
periodUnit: string;
- meter: string;
+ unit: UsageUnit;
defaultValue: number;
limitValue: number;
burstValue: number | null;
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/buildAdminUsageLimitRows.test.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/buildAdminUsageLimitRows.test.ts
index cd548a23465..a66275b48f9 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/buildAdminUsageLimitRows.test.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/__tests__/buildAdminUsageLimitRows.test.ts
@@ -2,6 +2,7 @@ import { buildAdminUsageLimitRows } from '@/settings/admin-panel/utils/buildAdmi
import {
UsageOperationType,
UsageResourceType,
+ UsageUnit,
type WorkspaceUsageLimitsQuery,
} from '~/generated-admin/graphql';
@@ -17,7 +18,7 @@ const buildDefault = (
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
limitValue: 100,
isOverridable: true,
overriddenByUsageLimitId: null,
@@ -103,7 +104,7 @@ describe('buildAdminUsageLimitRows', () => {
defaults: [
buildDefault({
limitKind: 'speed',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
periodUnit: 'second',
periodCount: 30,
overriddenByUsageLimitId: 'limit-1',
@@ -136,7 +137,7 @@ describe('buildAdminUsageLimitRows', () => {
operationType: UsageOperationType.API_REQUEST,
spenderType: 'apiKey',
limitKind: 'speed',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
periodUnit: 'second',
periodCount: 60,
overriddenByUsageLimitId: 'limit-1',
@@ -157,7 +158,7 @@ describe('buildAdminUsageLimitRows', () => {
resourceType: UsageResourceType.WEBHOOK,
operationType: UsageOperationType.WEBHOOK_CALL,
limitKind: 'speed',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
}),
buildDefault(),
],
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/buildAdminUsageLimitRows.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/buildAdminUsageLimitRows.ts
index 25f44ef1529..42004b6bf15 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/utils/buildAdminUsageLimitRows.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/utils/buildAdminUsageLimitRows.ts
@@ -35,7 +35,7 @@ export const buildAdminUsageLimitRows = (
limitKind: usageLimitDefault.limitKind,
periodCount: override?.periodCount ?? usageLimitDefault.periodCount,
periodUnit: override?.periodUnit ?? usageLimitDefault.periodUnit,
- meter: usageLimitDefault.meter,
+ unit: usageLimitDefault.unit,
defaultValue,
limitValue: isDefined(override)
? Number(override.limitValue)
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/utils/formatUsageLimitValue.ts b/packages/twenty-front/src/modules/settings/admin-panel/utils/formatUsageLimitValue.ts
deleted file mode 100644
index 3e59adb7975..00000000000
--- a/packages/twenty-front/src/modules/settings/admin-panel/utils/formatUsageLimitValue.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { t } from '@lingui/core/macro';
-import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
-import { formatBytes } from 'twenty-shared/utils';
-
-export const formatUsageLimitValue = ({
- value,
- meter,
-}: {
- value: number;
- meter: string;
-}): string => {
- if (meter === 'bytes') {
- return formatBytes(value);
- }
-
- if (meter === 'creditsUsedMicro') {
- const credits = (
- value / INTERNAL_CREDITS_PER_DISPLAY_CREDIT
- ).toLocaleString();
-
- return t`${credits} credits`;
- }
-
- return value.toLocaleString();
-};
diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitForm.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitForm.tsx
index a94ed5ab8df..08afaa5681c 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitForm.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitForm.tsx
@@ -1,6 +1,5 @@
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
-import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
import { ProgressRing } from 'twenty-ui/primitives/feedback';
import { Section } from 'twenty-ui/components';
@@ -11,20 +10,21 @@ import { SettingsBillingLimitUsageSelect } from '@/settings/billing/components/S
import { SettingsBillingLimitAmount } from '@/settings/billing/components/internal/SettingsBillingLimitAmount';
import { StyledSettingsBillingFieldLabel } from '@/settings/billing/components/internal/SettingsBillingFieldLabel';
import { SettingsBillingLimitSpenderSelect } from '@/settings/billing/components/SettingsBillingLimitSpenderSelect';
-import { USAGE_LIMIT_METER_ICONS } from '@/settings/billing/constants/UsageLimitMeterIcons';
-import { USAGE_LIMIT_METER_LABELS } from '@/settings/billing/constants/UsageLimitMeterLabels';
import { USAGE_LIMIT_PERIOD_ICONS } from '@/settings/billing/constants/UsageLimitPeriodIcons';
import { USAGE_LIMIT_PERIOD_SPAN_LABELS } from '@/settings/billing/constants/UsageLimitPeriodSpanLabels';
import { USAGE_LIMIT_PERIOD_UNIT_LABELS } from '@/settings/billing/constants/UsageLimitPeriodUnitLabels';
+import { USAGE_LIMIT_UNIT_ICONS } from '@/settings/billing/constants/UsageLimitUnitIcons';
import { type UsageLimitFormValues } from '@/settings/billing/types/UsageLimitFormValues';
-import { type UsageLimitMeter } from '@/settings/billing/types/UsageLimitMeter';
import { type UsageLimitPeriodUnit } from '@/settings/billing/types/UsageLimitPeriodUnit';
import { useUsageLimitFormatter } from '@/settings/billing/hooks/useUsageLimitFormatter';
import { type UsageQuotaScopeConsumption } from '@/settings/billing/types/UsageQuotaScopeConsumption';
import { computeUsageLimitProgress } from '@/settings/billing/utils/computeUsageLimitProgress';
import { getUsageLimitFormOptions } from '@/settings/billing/utils/getUsageLimitFormOptions';
+import { getUsageLimitInputScale } from '@/settings/billing/utils/getUsageLimitInputScale';
import { getUsageLimitLabel } from '@/settings/billing/utils/getUsageLimitLabel';
+import { getUsageLimitAmountInput } from '@/settings/billing/utils/getUsageLimitAmountInput';
import { getUsageLimitRingColor } from '@/settings/billing/utils/getUsageLimitRingColor';
+import { getUsageLimitUnitLabel } from '@/settings/billing/utils/getUsageLimitUnitLabel';
import { Select } from '@/ui/input/components/Select';
import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';
import { TooltipDelay } from '@/ui/layout/tooltip/constants/TooltipDelay';
@@ -32,6 +32,7 @@ import {
type UsageQuotaDefinitionsQuery,
UsageOperationType,
type UsageResourceType,
+ type UsageUnit,
} from '~/generated-metadata/graphql';
const RING_ANCHOR_ID = 'usage-limit-form-ring';
@@ -49,7 +50,7 @@ const StyledTooltipRow = styled.div`
white-space: nowrap;
`;
-const StyledMeterRow = styled.div`
+const StyledUnitRow = styled.div`
display: grid;
gap: ${themeCssVariables.spacing[2]};
grid-template-columns: 1fr 1fr;
@@ -98,7 +99,7 @@ export const SettingsBillingLimitForm = ({
operationType,
spenderType: null,
spenderId: '',
- meter: null,
+ unit: null,
periodUnit: 'month',
}
: { ...values, operationType };
@@ -113,33 +114,35 @@ export const SettingsBillingLimitForm = ({
spenderType: isNewResource
? (nextOptions.spenderTypes[0] ?? null)
: nextValues.spenderType,
- meter:
- isDefined(nextValues.meter) &&
- nextOptions.meters.includes(nextValues.meter)
- ? nextValues.meter
- : (nextOptions.meters[0] ?? null),
+ unit:
+ isDefined(nextValues.unit) &&
+ nextOptions.units.includes(nextValues.unit)
+ ? nextValues.unit
+ : (nextOptions.units[0] ?? null),
});
};
- const isCreditsMeter = values.meter === 'creditsUsedMicro';
const consumedValue = scopeConsumption?.consumedValue ?? null;
- const limitValue = Number(values.limitValue);
const progress = computeUsageLimitProgress({
- limitValue: isCreditsMeter
- ? limitValue * INTERNAL_CREDITS_PER_DISPLAY_CREDIT
- : limitValue,
+ limitValue:
+ Number(values.limitValue) * getUsageLimitInputScale(values.unit),
consumedValue,
});
const consumedPercentage = progress?.consumedPercentage ?? 0;
const isExhausted = progress?.remainingValue === 0;
const hasConsumption = isDefined(consumedValue) && consumedValue > 0;
- const consumedText = isDefined(consumedValue)
- ? formatLimitValue({
- value: consumedValue,
- meter: values.meter ?? '',
- operationType: values.operationType ?? UsageOperationType.ALL,
- })
- : '';
+ const consumedText =
+ isDefined(consumedValue) && isDefined(values.unit)
+ ? formatLimitValue({
+ value: consumedValue,
+ unit: values.unit,
+ operationType: values.operationType ?? UsageOperationType.ALL,
+ })
+ : '';
+ const amountInput = getUsageLimitAmountInput({
+ unit: values.unit,
+ operationType: values.operationType,
+ });
const periodSpanLabelDescriptor = isDefined(values.periodUnit)
? getUsageLimitLabel(USAGE_LIMIT_PERIOD_SPAN_LABELS, values.periodUnit)
: undefined;
@@ -187,11 +190,11 @@ export const SettingsBillingLimitForm = ({
<StyledRow>
<StyledAmountField>
<StyledSettingsBillingFieldLabel>
- {isCreditsMeter ? t`Credits` : t`Amount`}
+ {t(amountInput.label)}
</StyledSettingsBillingFieldLabel>
<SettingsTextInput
instanceId="usage-limit-value"
- placeholder={isCreditsMeter ? '100' : '1000'}
+ placeholder={amountInput.placeholder}
type="number"
min={0}
value={values.limitValue}
@@ -205,12 +208,12 @@ export const SettingsBillingLimitForm = ({
positionMethod="fixed"
content={
<>
- {hasConsumption ? (
+ {hasConsumption && isDefined(values.unit) ? (
<StyledTooltipRow>
{t`Used`}
<SettingsBillingLimitAmount
text={consumedText}
- isCreditsMeter={isCreditsMeter}
+ unit={values.unit}
/>
{`· ${periodSpanLabel}`}
</StyledTooltipRow>
@@ -234,21 +237,26 @@ export const SettingsBillingLimitForm = ({
)}
/>
</StyledAmountField>
- <StyledMeterRow>
+ <StyledUnitRow>
<Select
- dropdownId="usage-limit-meter"
- label={t`Meter`}
+ dropdownId="usage-limit-unit"
+ label={t`Unit`}
fullWidth
- disabled={options.meters.length <= 1}
- value={values.meter ?? undefined}
- options={options.meters.map((meter: UsageLimitMeter) => ({
- value: meter,
- label: t(USAGE_LIMIT_METER_LABELS[meter]),
- Icon: USAGE_LIMIT_METER_ICONS[meter],
+ disabled={options.units.length <= 1}
+ value={values.unit ?? undefined}
+ options={options.units.map((unit: UsageUnit) => ({
+ value: unit,
+ label: t(
+ getUsageLimitUnitLabel({
+ unit,
+ operationType: values.operationType,
+ }).name,
+ ),
+ Icon: USAGE_LIMIT_UNIT_ICONS[unit],
}))}
emptyOption={placeholderOption}
- onChange={(meter) =>
- isDefined(meter) && onChange({ ...values, meter })
+ onChange={(unit) =>
+ isDefined(unit) && onChange({ ...values, unit })
}
/>
<Select
@@ -269,7 +277,7 @@ export const SettingsBillingLimitForm = ({
isDefined(periodUnit) && onChange({ ...values, periodUnit })
}
/>
- </StyledMeterRow>
+ </StyledUnitRow>
</StyledRow>
</Section.Root>
</>
diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitUsageSelect.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitUsageSelect.tsx
index d66deb3763e..1c0ce49e5c2 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitUsageSelect.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitUsageSelect.tsx
@@ -2,7 +2,6 @@ import { SettingsBillingLimitNestedSelect } from '@/settings/billing/components/
import { USAGE_LIMIT_OPERATION_TYPE_ICONS } from '@/settings/billing/constants/UsageLimitOperationTypeIcons';
import { USAGE_LIMIT_RESOURCE_TYPE_ICONS } from '@/settings/billing/constants/UsageLimitResourceTypeIcons';
import { USAGE_LIMIT_RESOURCE_TYPE_LABELS } from '@/settings/billing/constants/UsageLimitResourceTypeLabels';
-import { getUsageLimitOperationTypes } from '@/settings/billing/utils/getUsageLimitOperationTypes';
import { USAGE_OPERATION_TYPE_LABELS } from '@/settings/usage/constants/UsageOperationTypeLabels';
import { SelectOptionIcon } from '@/ui/input/components/SelectOptionIcon';
import { useLingui } from '@lingui/react/macro';
@@ -81,28 +80,30 @@ export const SettingsBillingLimitUsageSelect = ({
{t(USAGE_LIMIT_RESOURCE_TYPE_LABELS[definition.resourceType])}
</Dropdown.Back>
<Dropdown.Section>
- {getUsageLimitOperationTypes(definition).map((candidate) => (
- <Dropdown.OptionItem
- key={candidate}
- selected={
- resourceType === definition.resourceType &&
- operationType === candidate
- }
- onSelect={() =>
- onChange({
- resourceType: definition.resourceType,
- operationType: candidate,
- })
- }
- startIcon={
- <SelectOptionIcon
- Icon={USAGE_LIMIT_OPERATION_TYPE_ICONS[candidate]}
- />
- }
- >
- {t(USAGE_OPERATION_TYPE_LABELS[candidate])}
- </Dropdown.OptionItem>
- ))}
+ {definition.allowedOperations.map(
+ ({ operationType: candidate }) => (
+ <Dropdown.OptionItem
+ key={candidate}
+ selected={
+ resourceType === definition.resourceType &&
+ operationType === candidate
+ }
+ onSelect={() =>
+ onChange({
+ resourceType: definition.resourceType,
+ operationType: candidate,
+ })
+ }
+ startIcon={
+ <SelectOptionIcon
+ Icon={USAGE_LIMIT_OPERATION_TYPE_ICONS[candidate]}
+ />
+ }
+ >
+ {t(USAGE_OPERATION_TYPE_LABELS[candidate])}
+ </Dropdown.OptionItem>
+ ),
+ )}
</Dropdown.Section>
</Dropdown.Page>
))}
diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitsTable.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitsTable.tsx
index d1199fe2f36..375fe94cf23 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitsTable.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingLimitsTable.tsx
@@ -130,7 +130,7 @@ const UsedCell = ({ item }: { item: UsageLimitRow }) => {
{t`Used`}
<SettingsBillingLimitAmount
text={item.consumedText}
- isCreditsMeter={item.isCreditsMeter}
+ unit={item.unit}
/>
</StyledTooltipRow>
)}
@@ -138,7 +138,7 @@ const UsedCell = ({ item }: { item: UsageLimitRow }) => {
{t`Limit`}
<SettingsBillingLimitAmount
text={item.limitText}
- isCreditsMeter={item.isCreditsMeter}
+ unit={item.unit}
/>
</StyledTooltipRow>
</StyledTooltipRows>
diff --git a/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitForm.stories.tsx b/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitForm.stories.tsx
index 06d2d718927..84263a229bc 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitForm.stories.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitForm.stories.tsx
@@ -6,6 +6,7 @@ import { EMPTY_USAGE_LIMIT_FORM_VALUES } from '@/settings/billing/constants/Empt
import {
UsageOperationType,
UsageResourceType,
+ UsageUnit,
} from '~/generated-metadata/graphql';
import { ComponentWithRouterDecorator } from '~/testing/decorators/ComponentWithRouterDecorator';
@@ -15,13 +16,53 @@ const DEFINITIONS = {
{
__typename: 'UsageQuotaDefinition' as const,
resourceType: UsageResourceType.AI,
- allowedOperationTypes: [
- UsageOperationType.AI_CHAT_TOKEN,
- UsageOperationType.AI_WORKFLOW_TOKEN,
- UsageOperationType.WEB_SEARCH,
+ allowedOperations: [
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.ALL,
+ allowedUnits: [UsageUnit.CREDIT],
+ },
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.TOKEN],
+ },
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.TOKEN],
+ },
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.WEB_SEARCH,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
],
allowedSpenderTypes: ['workspace', 'userWorkspace', 'apiKey'],
- allowedMeters: ['creditsUsedMicro', 'quantity'],
+ },
+ {
+ __typename: 'UsageQuotaDefinition' as const,
+ resourceType: UsageResourceType.WORKFLOW,
+ allowedOperations: [
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.WORKFLOW_EXECUTION,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
+ ],
+ allowedSpenderTypes: ['workspace'],
+ },
+ {
+ __typename: 'UsageQuotaDefinition' as const,
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ allowedOperations: [
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
+ ],
+ allowedSpenderTypes: ['workspace'],
},
],
isIntraWorkspaceLimitEntitled: true,
@@ -33,7 +74,7 @@ const FILLED_VALUES = {
operationType: UsageOperationType.AI_CHAT_TOKEN,
spenderType: 'workspace' as const,
spenderId: '',
- meter: 'creditsUsedMicro' as const,
+ unit: UsageUnit.CREDIT,
periodUnit: 'month' as const,
limitValue: '100',
};
diff --git a/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitUsageSelect.stories.tsx b/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitUsageSelect.stories.tsx
index 881b6dee7c1..e71843f0956 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitUsageSelect.stories.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitUsageSelect.stories.tsx
@@ -6,6 +6,7 @@ import { SettingsBillingLimitUsageSelect } from '@/settings/billing/components/S
import {
UsageOperationType,
UsageResourceType,
+ UsageUnit,
} from '~/generated-metadata/graphql';
const DEFINITIONS = {
@@ -14,13 +15,29 @@ const DEFINITIONS = {
{
__typename: 'UsageQuotaDefinition' as const,
resourceType: UsageResourceType.AI,
- allowedOperationTypes: [
- UsageOperationType.AI_CHAT_TOKEN,
- UsageOperationType.AI_WORKFLOW_TOKEN,
- UsageOperationType.WEB_SEARCH,
+ allowedOperations: [
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.ALL,
+ allowedUnits: [UsageUnit.CREDIT],
+ },
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.TOKEN],
+ },
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.TOKEN],
+ },
+ {
+ __typename: 'UsageLimitOperationDefinition' as const,
+ operationType: UsageOperationType.WEB_SEARCH,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
],
allowedSpenderTypes: ['workspace', 'userWorkspace', 'apiKey'],
- allowedMeters: ['creditsUsedMicro', 'quantity'],
},
],
isIntraWorkspaceLimitEntitled: true,
@@ -44,6 +61,25 @@ type Story = StoryObj<typeof SettingsBillingLimitUsageSelect>;
export const Empty: Story = {};
+export const AllOperationsFromServer: Story = {
+ args: {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ },
+ play: async ({ canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+
+ await userEvent.click(within(canvasElement).getByRole('button'));
+ const popup = await body.findByRole('dialog', { name: 'Usage' });
+
+ await userEvent.click(within(popup).getByRole('button', { name: 'AI' }));
+ expect(
+ await within(popup).findByRole('button', { name: 'All operations' }),
+ ).toBeVisible();
+ await userEvent.keyboard('{Escape}');
+ },
+};
+
export const Chosen: Story = {
args: {
resourceType: UsageResourceType.AI,
diff --git a/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitsTable.stories.tsx b/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitsTable.stories.tsx
index 62135ccafcd..d28664ee366 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitsTable.stories.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/__stories__/SettingsBillingLimitsTable.stories.tsx
@@ -7,6 +7,7 @@ import { type UsageQuotaWithConsumption } from '@/settings/billing/types/UsageQu
import {
UsageOperationType,
UsageResourceType,
+ UsageUnit,
} from '~/generated-metadata/graphql';
import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';
@@ -21,7 +22,7 @@ const buildQuota = (
spenderId: null,
spenderLabel: null,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 100_000_000,
isEnforced: true,
consumedValue: 23_860_000,
@@ -44,15 +45,15 @@ const CUSTOM_USER_QUOTA = buildQuota({
isEnforced: false,
});
-const API_KEY_QUOTA = buildQuota({
+const LOGIC_FUNCTION_RUNS_QUOTA = buildQuota({
id: 'limit-2',
- resourceType: UsageResourceType.API,
- operationType: UsageOperationType.API_REQUEST,
- spenderType: 'apiKey',
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ spenderType: 'logicFunction',
spenderId: 'b1b2c3d4-0000-0000-0000-000000000000',
- spenderLabel: 'Production key',
+ spenderLabel: 'Enrich company',
periodUnit: 'day',
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
limitValue: 10_000,
consumedValue: 9_800,
remainingValue: 200,
@@ -62,7 +63,13 @@ const meta: Meta<typeof SettingsBillingLimitsTable> = {
title: 'Modules/Settings/Billing/SettingsBillingLimitsTable',
component: SettingsBillingLimitsTable,
decorators: [ComponentDecorator, MemoryRouterDecorator],
- args: { quotas: [ALL_OPERATIONS_QUOTA, CUSTOM_USER_QUOTA, API_KEY_QUOTA] },
+ args: {
+ quotas: [
+ ALL_OPERATIONS_QUOTA,
+ CUSTOM_USER_QUOTA,
+ LOGIC_FUNCTION_RUNS_QUOTA,
+ ],
+ },
};
export default meta;
@@ -72,11 +79,11 @@ export const Default: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
- await expect(
- await canvas.findByRole('progressbar', {
- name: /used by Production key$/,
- }),
- ).toHaveAttribute('aria-valuenow', '98');
+ const [logicFunctionRunsRing] = await canvas.findAllByRole('progressbar', {
+ name: /used by Enrich company$/,
+ });
+
+ await expect(logicFunctionRunsRing).toHaveAttribute('aria-valuenow', '98');
await userEvent.hover(await canvas.findByText('Deactivated'));
diff --git a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingLimitAmount.tsx b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingLimitAmount.tsx
index ede28cfd599..3b55dece526 100644
--- a/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingLimitAmount.tsx
+++ b/packages/twenty-front/src/modules/settings/billing/components/internal/SettingsBillingLimitAmount.tsx
@@ -2,6 +2,8 @@ import { styled } from '@linaria/react';
import { IconCoins } from 'twenty-ui/icon';
import { themeCssVariables } from 'twenty-ui/theme';
+import { UsageUnit } from '~/generated-metadata/graphql';
+
const CREDITS_UNIT_ICON_SIZE = 12;
const StyledAmount = styled.span`
@@ -13,15 +15,15 @@ const StyledAmount = styled.span`
type SettingsBillingLimitAmountProps = {
text: string;
- isCreditsMeter: boolean;
+ unit: UsageUnit;
};
export const SettingsBillingLimitAmount = ({
text,
- isCreditsMeter,
+ unit,
}: SettingsBillingLimitAmountProps) => (
<StyledAmount>
{text}
- {isCreditsMeter && <IconCoins size={CREDITS_UNIT_ICON_SIZE} />}
+ {unit === UsageUnit.CREDIT && <IconCoins size={CREDITS_UNIT_ICON_SIZE} />}
</StyledAmount>
);
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/EmptyUsageLimitFormValues.ts b/packages/twenty-front/src/modules/settings/billing/constants/EmptyUsageLimitFormValues.ts
index 445faefa53a..6108b6bb4c4 100644
--- a/packages/twenty-front/src/modules/settings/billing/constants/EmptyUsageLimitFormValues.ts
+++ b/packages/twenty-front/src/modules/settings/billing/constants/EmptyUsageLimitFormValues.ts
@@ -5,7 +5,7 @@ export const EMPTY_USAGE_LIMIT_FORM_VALUES: UsageLimitFormValues = {
operationType: null,
spenderType: 'workspace',
spenderId: '',
- meter: null,
+ unit: null,
periodUnit: null,
limitValue: '',
};
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitInvocationUnitLabels.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitInvocationUnitLabels.ts
new file mode 100644
index 00000000000..402a1e13bd9
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitInvocationUnitLabels.ts
@@ -0,0 +1,23 @@
+import { msg } from '@lingui/core/macro';
+
+import { type UsageLimitUnitLabel } from '@/settings/billing/types/UsageLimitUnitLabel';
+import { UsageOperationType } from '~/generated-metadata/graphql';
+
+export const USAGE_LIMIT_INVOCATION_UNIT_LABELS: Partial<
+ Record<UsageOperationType, UsageLimitUnitLabel>
+> = {
+ [UsageOperationType.WORKFLOW_EXECUTION]: {
+ name: msg`Steps`,
+ suffix: msg`steps`,
+ },
+ [UsageOperationType.CODE_EXECUTION]: { name: msg`Runs`, suffix: msg`runs` },
+ [UsageOperationType.WEB_SEARCH]: {
+ name: msg`Searches`,
+ suffix: msg`searches`,
+ },
+ [UsageOperationType.EMAIL_SEND]: { name: msg`Emails`, suffix: msg`emails` },
+ [UsageOperationType.MESSAGE_CAMPAIGN_SEND]: {
+ name: msg`Emails`,
+ suffix: msg`emails`,
+ },
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitMeterIcons.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitMeterIcons.ts
deleted file mode 100644
index f46a0e1e911..00000000000
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitMeterIcons.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { IconCoins, type IconComponent, IconNumber123 } from 'twenty-ui/icon';
-
-import { type UsageLimitMeter } from '@/settings/billing/types/UsageLimitMeter';
-
-export const USAGE_LIMIT_METER_ICONS: Partial<
- Record<UsageLimitMeter, IconComponent>
-> = {
- creditsUsedMicro: IconCoins,
- quantity: IconNumber123,
-};
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitMeterLabels.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitMeterLabels.ts
deleted file mode 100644
index dce4768485e..00000000000
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitMeterLabels.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { type MessageDescriptor } from '@lingui/core';
-import { msg } from '@lingui/core/macro';
-
-import { type UsageLimitMeter } from '@/settings/billing/types/UsageLimitMeter';
-
-export const USAGE_LIMIT_METER_LABELS: Record<
- UsageLimitMeter,
- MessageDescriptor
-> = {
- creditsUsedMicro: msg`Credits`,
- quantity: msg`Operations`,
- bytes: msg`Bytes`,
-};
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitQuantityUnitLabels.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitQuantityUnitLabels.ts
deleted file mode 100644
index 02677ed52ae..00000000000
--- a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitQuantityUnitLabels.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { type MessageDescriptor } from '@lingui/core';
-import { msg } from '@lingui/core/macro';
-
-import { UsageOperationType } from '~/generated-metadata/graphql';
-
-export const USAGE_LIMIT_QUANTITY_UNIT_LABELS: Partial<
- Record<UsageOperationType, MessageDescriptor>
-> = {
- [UsageOperationType.EMAIL_SEND]: msg`emails`,
- [UsageOperationType.WEB_SEARCH]: msg`searches`,
- [UsageOperationType.WORKFLOW_EXECUTION]: msg`runs`,
- [UsageOperationType.CODE_EXECUTION]: msg`runs`,
-};
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitIcons.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitIcons.ts
new file mode 100644
index 00000000000..e1090b59ef3
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitIcons.ts
@@ -0,0 +1,26 @@
+import {
+ IconAddressBook,
+ IconClock,
+ IconCoins,
+ type IconComponent,
+ IconDatabase,
+ IconFiles,
+ IconNumber123,
+ IconUsers,
+} from 'twenty-ui/icon';
+
+import { UsageUnit } from '~/generated-metadata/graphql';
+
+export const USAGE_LIMIT_UNIT_ICONS: Record<UsageUnit, IconComponent> = {
+ [UsageUnit.CREDIT]: IconCoins,
+ [UsageUnit.TOKEN]: IconNumber123,
+ [UsageUnit.INVOCATION]: IconNumber123,
+ [UsageUnit.MINUTE]: IconClock,
+ [UsageUnit.MILLISECOND]: IconClock,
+ [UsageUnit.BYTE]: IconDatabase,
+ [UsageUnit.FILE]: IconFiles,
+ [UsageUnit.REQUEST]: IconNumber123,
+ [UsageUnit.SEAT]: IconUsers,
+ [UsageUnit.RECORD]: IconAddressBook,
+ [UsageUnit.COMPLEXITY]: IconNumber123,
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitLabels.ts b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitLabels.ts
new file mode 100644
index 00000000000..756605b06f8
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/constants/UsageLimitUnitLabels.ts
@@ -0,0 +1,18 @@
+import { msg } from '@lingui/core/macro';
+
+import { type UsageLimitUnitLabel } from '@/settings/billing/types/UsageLimitUnitLabel';
+import { UsageUnit } from '~/generated-metadata/graphql';
+
+export const USAGE_LIMIT_UNIT_LABELS: Record<UsageUnit, UsageLimitUnitLabel> = {
+ [UsageUnit.CREDIT]: { name: msg`Credits`, suffix: msg`credits` },
+ [UsageUnit.TOKEN]: { name: msg`Tokens`, suffix: msg`tokens` },
+ [UsageUnit.INVOCATION]: { name: msg`Operations`, suffix: msg`operations` },
+ [UsageUnit.MINUTE]: { name: msg`Minutes`, suffix: msg`min` },
+ [UsageUnit.MILLISECOND]: { name: msg`Runtime`, suffix: msg`ms` },
+ [UsageUnit.BYTE]: { name: msg`Bytes`, suffix: msg`bytes` },
+ [UsageUnit.FILE]: { name: msg`Files`, suffix: msg`files` },
+ [UsageUnit.REQUEST]: { name: msg`Requests`, suffix: msg`requests` },
+ [UsageUnit.SEAT]: { name: msg`Seats`, suffix: msg`seats` },
+ [UsageUnit.RECORD]: { name: msg`Records`, suffix: msg`records` },
+ [UsageUnit.COMPLEXITY]: { name: msg`Complexity`, suffix: msg`points` },
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/graphql/queries/usageQuotaDefinitions.ts b/packages/twenty-front/src/modules/settings/billing/graphql/queries/usageQuotaDefinitions.ts
index ca19e72707e..45b3e0a97aa 100644
--- a/packages/twenty-front/src/modules/settings/billing/graphql/queries/usageQuotaDefinitions.ts
+++ b/packages/twenty-front/src/modules/settings/billing/graphql/queries/usageQuotaDefinitions.ts
@@ -5,9 +5,11 @@ export const USAGE_QUOTA_DEFINITIONS = gql`
usageQuotaDefinitions {
definitions {
resourceType
- allowedOperationTypes
+ allowedOperations {
+ operationType
+ allowedUnits
+ }
allowedSpenderTypes
- allowedMeters
}
isIntraWorkspaceLimitEntitled
hasAllowancePeriod
diff --git a/packages/twenty-front/src/modules/settings/billing/graphql/queries/usageQuotasWithConsumption.ts b/packages/twenty-front/src/modules/settings/billing/graphql/queries/usageQuotasWithConsumption.ts
index de5fd84bf99..0c6eae77a41 100644
--- a/packages/twenty-front/src/modules/settings/billing/graphql/queries/usageQuotasWithConsumption.ts
+++ b/packages/twenty-front/src/modules/settings/billing/graphql/queries/usageQuotasWithConsumption.ts
@@ -10,7 +10,7 @@ export const USAGE_QUOTAS_WITH_CONSUMPTION = gql`
spenderId
spenderLabel
periodUnit
- meter
+ unit
limitValue
isEnforced
consumedValue
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitFormatter.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitFormatter.ts
index e1e70ea60b1..576156cffab 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitFormatter.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitFormatter.ts
@@ -1,13 +1,14 @@
import { useLingui } from '@lingui/react/macro';
import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
-import { isDefined } from 'twenty-shared/utils';
+import { formatBytes } from 'twenty-shared/utils';
import { useNumberFormat } from '@/localization/hooks/useNumberFormat';
-import { USAGE_LIMIT_QUANTITY_UNIT_LABELS } from '@/settings/billing/constants/UsageLimitQuantityUnitLabels';
-import { isCreditsMeter } from '@/settings/billing/utils/isCreditsMeter';
-import { getUsageLimitLabel } from '@/settings/billing/utils/getUsageLimitLabel';
+import { getUsageLimitUnitLabel } from '@/settings/billing/utils/getUsageLimitUnitLabel';
import { useUsageValueFormatter } from '@/settings/usage/hooks/useUsageValueFormatter';
-import { type UsageOperationType } from '~/generated-metadata/graphql';
+import {
+ type UsageOperationType,
+ UsageUnit,
+} from '~/generated-metadata/graphql';
export const useUsageLimitFormatter = () => {
const { t } = useLingui();
@@ -16,27 +17,26 @@ export const useUsageLimitFormatter = () => {
const formatLimitValue = ({
value,
- meter,
+ unit,
operationType,
}: {
value: number;
- meter: string;
+ unit: UsageUnit;
operationType: UsageOperationType;
}): string => {
- if (isCreditsMeter(meter)) {
+ if (unit === UsageUnit.CREDIT) {
return formatUsageAmount(value / INTERNAL_CREDITS_PER_DISPLAY_CREDIT, {
abbreviate: true,
});
}
- const unitLabel = getUsageLimitLabel(
- USAGE_LIMIT_QUANTITY_UNIT_LABELS,
- operationType,
- );
+ if (unit === UsageUnit.BYTE) {
+ return formatBytes(value);
+ }
- const unit = isDefined(unitLabel) ? t(unitLabel) : t`operations`;
+ const { suffix } = getUsageLimitUnitLabel({ unit, operationType });
- return `${formatNumber(value, { decimals: 1, abbreviate: true })} ${unit}`;
+ return `${formatNumber(value, { decimals: 1, abbreviate: true })} ${t(suffix)}`;
};
return { formatLimitValue };
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitRows.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitRows.ts
index d794ba30aec..e8afb58b67e 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitRows.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useUsageLimitRows.ts
@@ -14,7 +14,6 @@ import { type UsageQuotaWithConsumption } from '@/settings/billing/types/UsageQu
import { computeUsageLimitProgress } from '@/settings/billing/utils/computeUsageLimitProgress';
import { getUsageLimitLabel } from '@/settings/billing/utils/getUsageLimitLabel';
import { getUsageLimitSpenderName } from '@/settings/billing/utils/getUsageLimitSpenderName';
-import { isCreditsMeter } from '@/settings/billing/utils/isCreditsMeter';
import { isKeyOfRecord } from '@/settings/billing/utils/isKeyOfRecord';
import { getUsageOperationTypeLabel } from '@/settings/usage/utils/getUsageOperationTypeLabel';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
@@ -91,16 +90,16 @@ export const useUsageLimitRows = (
consumedText: isDefined(consumedValue)
? formatLimitValue({
value: consumedValue,
- meter: quota.meter,
+ unit: quota.unit,
operationType: quota.operationType,
})
: null,
limitText: formatLimitValue({
value: limitValue,
- meter: quota.meter,
+ unit: quota.unit,
operationType: quota.operationType,
}),
- isCreditsMeter: isCreditsMeter(quota.meter),
+ unit: quota.unit,
isExhausted: progress?.remainingValue === 0,
periodName: getPeriodName(quota.periodUnit),
};
diff --git a/packages/twenty-front/src/modules/settings/billing/hooks/useUsageQuotaScopeConsumption.ts b/packages/twenty-front/src/modules/settings/billing/hooks/useUsageQuotaScopeConsumption.ts
index 281708338c5..02a6b1e91fb 100644
--- a/packages/twenty-front/src/modules/settings/billing/hooks/useUsageQuotaScopeConsumption.ts
+++ b/packages/twenty-front/src/modules/settings/billing/hooks/useUsageQuotaScopeConsumption.ts
@@ -12,7 +12,7 @@ export const useUsageQuotaScopeConsumption = ({
operationType,
spenderType,
spenderId,
- meter,
+ unit,
periodUnit,
}: Omit<UsageLimitFormValues, 'limitValue'>): {
scopeConsumption: UsageQuotaScopeConsumption | null;
@@ -25,10 +25,10 @@ export const useUsageQuotaScopeConsumption = ({
operationType,
spenderType,
spenderId,
- meter,
+ unit,
periodUnit,
}),
- [resourceType, operationType, spenderType, spenderId, meter, periodUnit],
+ [resourceType, operationType, spenderType, spenderId, unit, periodUnit],
);
const { data, loading } = useQuery(
diff --git a/packages/twenty-front/src/modules/settings/billing/types/UsageLimitAmountInput.ts b/packages/twenty-front/src/modules/settings/billing/types/UsageLimitAmountInput.ts
new file mode 100644
index 00000000000..a728a298420
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/types/UsageLimitAmountInput.ts
@@ -0,0 +1,6 @@
+import { type MessageDescriptor } from '@lingui/core';
+
+export type UsageLimitAmountInput = {
+ label: MessageDescriptor;
+ placeholder: string;
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/types/UsageLimitFormValues.ts b/packages/twenty-front/src/modules/settings/billing/types/UsageLimitFormValues.ts
index 4e74a0f8cc8..a7266ad0363 100644
--- a/packages/twenty-front/src/modules/settings/billing/types/UsageLimitFormValues.ts
+++ b/packages/twenty-front/src/modules/settings/billing/types/UsageLimitFormValues.ts
@@ -1,9 +1,9 @@
-import { type UsageLimitMeter } from '@/settings/billing/types/UsageLimitMeter';
import { type UsageLimitPeriodUnit } from '@/settings/billing/types/UsageLimitPeriodUnit';
import { type UsageLimitSpenderType } from '@/settings/billing/types/UsageLimitSpenderType';
import {
type UsageOperationType,
type UsageResourceType,
+ type UsageUnit,
} from '~/generated-metadata/graphql';
export type UsageLimitFormValues = {
@@ -11,7 +11,7 @@ export type UsageLimitFormValues = {
operationType: UsageOperationType | null;
spenderType: UsageLimitSpenderType | null;
spenderId: string;
- meter: UsageLimitMeter | null;
+ unit: UsageUnit | null;
periodUnit: UsageLimitPeriodUnit | null;
limitValue: string;
};
diff --git a/packages/twenty-front/src/modules/settings/billing/types/UsageLimitMeter.ts b/packages/twenty-front/src/modules/settings/billing/types/UsageLimitMeter.ts
deleted file mode 100644
index 6b1e16dbdb0..00000000000
--- a/packages/twenty-front/src/modules/settings/billing/types/UsageLimitMeter.ts
+++ /dev/null
@@ -1 +0,0 @@
-export type UsageLimitMeter = 'creditsUsedMicro' | 'quantity' | 'bytes';
diff --git a/packages/twenty-front/src/modules/settings/billing/types/UsageLimitRow.ts b/packages/twenty-front/src/modules/settings/billing/types/UsageLimitRow.ts
index 5073d99769b..644806c48e1 100644
--- a/packages/twenty-front/src/modules/settings/billing/types/UsageLimitRow.ts
+++ b/packages/twenty-front/src/modules/settings/billing/types/UsageLimitRow.ts
@@ -1,6 +1,9 @@
import { type IconComponent } from 'twenty-ui/icon';
-import { type UsageResourceType } from '~/generated-metadata/graphql';
+import {
+ type UsageResourceType,
+ type UsageUnit,
+} from '~/generated-metadata/graphql';
export type UsageLimitRow = {
id: string;
@@ -14,7 +17,7 @@ export type UsageLimitRow = {
consumedPercentage: number | null;
consumedText: string | null;
limitText: string;
- isCreditsMeter: boolean;
+ unit: UsageUnit;
isExhausted: boolean;
periodName: string;
};
diff --git a/packages/twenty-front/src/modules/settings/billing/types/UsageLimitUnitLabel.ts b/packages/twenty-front/src/modules/settings/billing/types/UsageLimitUnitLabel.ts
new file mode 100644
index 00000000000..5a5093fcc67
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/types/UsageLimitUnitLabel.ts
@@ -0,0 +1,6 @@
+import { type MessageDescriptor } from '@lingui/core';
+
+export type UsageLimitUnitLabel = {
+ name: MessageDescriptor;
+ suffix: MessageDescriptor;
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildCreateUsageLimitInput.test.ts b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildCreateUsageLimitInput.test.ts
index e661e91369d..4f661271a01 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildCreateUsageLimitInput.test.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildCreateUsageLimitInput.test.ts
@@ -4,6 +4,7 @@ import { buildCreateUsageLimitInput } from '@/settings/billing/utils/buildCreate
import {
UsageOperationType,
UsageResourceType,
+ UsageUnit,
} from '~/generated-metadata/graphql';
const buildValues = (
@@ -13,7 +14,7 @@ const buildValues = (
resourceType: UsageResourceType.AI,
operationType: UsageOperationType.ALL,
spenderType: 'workspace',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
periodUnit: 'month',
limitValue: '100',
...overrides,
@@ -27,6 +28,7 @@ describe('buildCreateUsageLimitInput', () => {
expect(
buildCreateUsageLimitInput(buildValues({ spenderType: null })),
).toBeNull();
+ expect(buildCreateUsageLimitInput(buildValues({ unit: null }))).toBeNull();
});
it('always builds a one-period quota without burst', () => {
@@ -40,26 +42,42 @@ describe('buildCreateUsageLimitInput', () => {
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 12_500_000,
burstValue: null,
});
});
- it('keeps a quantity quota as an integer and rejects fractions', () => {
+ it('rounds a count to a whole number', () => {
expect(
buildCreateUsageLimitInput(
buildValues({
operationType: UsageOperationType.WEB_SEARCH,
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
limitValue: '200',
}),
),
- ).toEqual(expect.objectContaining({ limitValue: 200, meter: 'quantity' }));
+ ).toEqual(
+ expect.objectContaining({ limitValue: 200, unit: UsageUnit.INVOCATION }),
+ );
expect(
buildCreateUsageLimitInput(
- buildValues({ meter: 'quantity', limitValue: '2.5' }),
- ),
+ buildValues({ unit: UsageUnit.INVOCATION, limitValue: '2.4' }),
+ )?.limitValue,
+ ).toBe(2);
+ });
+
+ it('rejects an amount that is not a positive number', () => {
+ for (const limitValue of ['', 'abc', '-5', '0', '1e30']) {
+ expect(
+ buildCreateUsageLimitInput(buildValues({ limitValue })),
+ ).toBeNull();
+ }
+ });
+
+ it('rejects an amount too small to store', () => {
+ expect(
+ buildCreateUsageLimitInput(buildValues({ limitValue: '0.0000001' })),
).toBeNull();
});
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildUsageLimitFormValues.test.ts b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildUsageLimitFormValues.test.ts
index 11302b6ed28..ea5650c7682 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildUsageLimitFormValues.test.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildUsageLimitFormValues.test.ts
@@ -3,6 +3,7 @@ import { type UsageQuotaWithConsumption } from '@/settings/billing/types/UsageQu
import {
UsageOperationType,
UsageResourceType,
+ UsageUnit,
} from '~/generated-metadata/graphql';
const buildItem = (
@@ -16,7 +17,7 @@ const buildItem = (
spenderId: null,
spenderLabel: null,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 100_000_000,
isEnforced: true,
consumedValue: null,
@@ -33,17 +34,17 @@ describe('buildUsageLimitFormValues', () => {
operationType: UsageOperationType.AI_CHAT_TOKEN,
spenderType: 'workspace',
spenderId: '',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
periodUnit: 'month',
limitValue: '100',
});
});
- it('keeps a quantity quota as it is stored and carries the spender id', () => {
+ it('keeps a count as it is stored and carries the spender id', () => {
expect(
buildUsageLimitFormValues(
buildItem({
- meter: 'quantity',
+ unit: UsageUnit.TOKEN,
limitValue: 200,
spenderType: 'userWorkspace',
spenderId: 'user-1',
@@ -51,6 +52,7 @@ describe('buildUsageLimitFormValues', () => {
),
).toEqual(
expect.objectContaining({
+ unit: UsageUnit.TOKEN,
limitValue: '200',
spenderId: 'user-1',
}),
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildUsageQuotaScopeInput.test.ts b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildUsageQuotaScopeInput.test.ts
index 3979a71f0b6..ed1e172f624 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildUsageQuotaScopeInput.test.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/buildUsageQuotaScopeInput.test.ts
@@ -4,6 +4,7 @@ import { buildUsageQuotaScopeInput } from '@/settings/billing/utils/buildUsageQu
import {
UsageOperationType,
UsageResourceType,
+ UsageUnit,
} from '~/generated-metadata/graphql';
const buildValues = (
@@ -13,7 +14,7 @@ const buildValues = (
resourceType: UsageResourceType.AI,
operationType: UsageOperationType.ALL,
spenderType: 'workspace',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
periodUnit: 'month',
limitValue: '100',
...overrides,
@@ -33,7 +34,7 @@ describe('buildUsageQuotaScopeInput', () => {
operationType: UsageOperationType.ALL,
spenderType: 'workspace',
spenderId: null,
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
periodUnit: 'month',
};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/filterUsageLimitRows.test.ts b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/filterUsageLimitRows.test.ts
index ee411179397..54a57adf388 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/filterUsageLimitRows.test.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/filterUsageLimitRows.test.ts
@@ -2,7 +2,7 @@ import { IconCoins } from 'twenty-ui/icon';
import { type UsageLimitRow } from '@/settings/billing/types/UsageLimitRow';
import { filterUsageLimitRows } from '@/settings/billing/utils/filterUsageLimitRows';
-import { UsageResourceType } from '~/generated-metadata/graphql';
+import { UsageResourceType, UsageUnit } from '~/generated-metadata/graphql';
const buildRow = (overrides: Partial<UsageLimitRow> = {}): UsageLimitRow => ({
id: 'row-id',
@@ -16,7 +16,7 @@ const buildRow = (overrides: Partial<UsageLimitRow> = {}): UsageLimitRow => ({
consumedPercentage: 60,
consumedText: '60 credits',
limitText: '100 credits',
- isCreditsMeter: true,
+ unit: UsageUnit.CREDIT,
isExhausted: false,
periodName: 'Monthly',
...overrides,
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/getUsageLimitFormOptions.test.ts b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/getUsageLimitFormOptions.test.ts
index 2ec5c90c210..77ee78971bf 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/getUsageLimitFormOptions.test.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/getUsageLimitFormOptions.test.ts
@@ -3,18 +3,38 @@ import { getUsageLimitFormOptions } from '@/settings/billing/utils/getUsageLimit
import {
UsageOperationType,
UsageResourceType,
+ UsageUnit,
} from '~/generated-metadata/graphql';
const DEFINITIONS = {
definitions: [
{
resourceType: UsageResourceType.AI,
- allowedOperationTypes: [
- UsageOperationType.AI_CHAT_TOKEN,
- UsageOperationType.WEB_SEARCH,
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.ALL,
+ allowedUnits: [UsageUnit.CREDIT],
+ },
+ {
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.TOKEN],
+ },
+ {
+ operationType: UsageOperationType.WEB_SEARCH,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
],
allowedSpenderTypes: ['workspace', 'userWorkspace'],
- allowedMeters: ['creditsUsedMicro', 'quantity'],
+ },
+ {
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.CODE_EXECUTION,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
+ ],
+ allowedSpenderTypes: ['workspace', 'application', 'logicFunction'],
},
],
isIntraWorkspaceLimitEntitled: true,
@@ -28,12 +48,16 @@ describe('getUsageLimitFormOptions', () => {
values: EMPTY_USAGE_LIMIT_FORM_VALUES,
});
- expect(options.resourceTypes).toEqual([UsageResourceType.AI]);
+ expect(options.resourceTypes).toEqual([
+ UsageResourceType.AI,
+ UsageResourceType.LOGIC_FUNCTION,
+ ]);
expect(options.operationTypes).toEqual([]);
+ expect(options.units).toEqual([]);
expect(options.periodUnits).toEqual([]);
});
- it('offers "all operations" to credit quotas and pins their meter', () => {
+ it('offers the operations in the order the server lists them and only credits for all operations', () => {
const options = getUsageLimitFormOptions({
definitions: DEFINITIONS,
values: {
@@ -48,11 +72,37 @@ describe('getUsageLimitFormOptions', () => {
UsageOperationType.AI_CHAT_TOKEN,
UsageOperationType.WEB_SEARCH,
]);
- expect(options.meters).toEqual(['creditsUsedMicro']);
+ expect(options.units).toEqual([UsageUnit.CREDIT]);
expect(options.spenderTypes).toEqual(['workspace', 'userWorkspace']);
expect(options.periodUnits).toEqual(['day', 'week', 'month']);
});
+ it('offers the units the chosen operation records', () => {
+ const options = getUsageLimitFormOptions({
+ definitions: DEFINITIONS,
+ values: {
+ ...EMPTY_USAGE_LIMIT_FORM_VALUES,
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.WEB_SEARCH,
+ },
+ });
+
+ expect(options.units).toEqual([UsageUnit.CREDIT, UsageUnit.INVOCATION]);
+ });
+
+ it('offers credits for an all-operations limit on a resource with a single operation', () => {
+ const options = getUsageLimitFormOptions({
+ definitions: DEFINITIONS,
+ values: {
+ ...EMPTY_USAGE_LIMIT_FORM_VALUES,
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.ALL,
+ },
+ });
+
+ expect(options.units).toEqual([UsageUnit.CREDIT]);
+ });
+
it('adds the billing period once the workspace has one', () => {
const options = getUsageLimitFormOptions({
definitions: { ...DEFINITIONS, hasAllowancePeriod: true },
@@ -69,6 +119,5 @@ describe('getUsageLimitFormOptions', () => {
'month',
'allowancePeriod',
]);
- expect(options.meters).toEqual(['creditsUsedMicro', 'quantity']);
});
});
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/getUsageLimitOperationTypes.test.ts b/packages/twenty-front/src/modules/settings/billing/utils/__tests__/getUsageLimitOperationTypes.test.ts
deleted file mode 100644
index 716510ffc86..00000000000
--- a/packages/twenty-front/src/modules/settings/billing/utils/__tests__/getUsageLimitOperationTypes.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { getUsageLimitOperationTypes } from '@/settings/billing/utils/getUsageLimitOperationTypes';
-import {
- UsageOperationType,
- UsageResourceType,
-} from '~/generated-metadata/graphql';
-
-const buildDefinition = (
- allowedMeters: string[],
- allowedOperationTypes: UsageOperationType[] = [
- UsageOperationType.AI_CHAT_TOKEN,
- UsageOperationType.WEB_SEARCH,
- ],
-) => ({
- __typename: 'UsageQuotaDefinition' as const,
- resourceType: UsageResourceType.AI,
- allowedOperationTypes,
- allowedSpenderTypes: ['workspace'],
- allowedMeters,
-});
-
-describe('getUsageLimitOperationTypes', () => {
- it('offers "all operations" first when the resource is metered in credits', () => {
- expect(
- getUsageLimitOperationTypes(
- buildDefinition(['creditsUsedMicro', 'quantity']),
- ),
- ).toEqual([
- UsageOperationType.ALL,
- UsageOperationType.AI_CHAT_TOKEN,
- UsageOperationType.WEB_SEARCH,
- ]);
- });
-
- it('lists only the real operations without a credits meter', () => {
- expect(getUsageLimitOperationTypes(buildDefinition(['quantity']))).toEqual([
- UsageOperationType.AI_CHAT_TOKEN,
- UsageOperationType.WEB_SEARCH,
- ]);
- });
-
- it('skips "all operations" when the resource has a single operation', () => {
- expect(
- getUsageLimitOperationTypes(
- buildDefinition(
- ['creditsUsedMicro', 'quantity'],
- [UsageOperationType.WEB_SEARCH],
- ),
- ),
- ).toEqual([UsageOperationType.WEB_SEARCH]);
- });
-});
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/buildCreateUsageLimitInput.ts b/packages/twenty-front/src/modules/settings/billing/utils/buildCreateUsageLimitInput.ts
index f82b412ac0d..17f1100d51c 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/buildCreateUsageLimitInput.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/buildCreateUsageLimitInput.ts
@@ -1,22 +1,10 @@
-import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
import { type UsageLimitFormValues } from '@/settings/billing/types/UsageLimitFormValues';
import { buildUsageQuotaScopeInput } from '@/settings/billing/utils/buildUsageQuotaScopeInput';
+import { getUsageLimitInputScale } from '@/settings/billing/utils/getUsageLimitInputScale';
import { type CreateUsageLimitInput } from '~/generated-metadata/graphql';
-const parsePositiveInteger = (value: string): number | null => {
- const parsed = Number(value);
-
- return Number.isInteger(parsed) && parsed >= 1 ? parsed : null;
-};
-
-const parsePositiveNumber = (value: string): number | null => {
- const parsed = Number(value);
-
- return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
-};
-
export const buildCreateUsageLimitInput = (
values: UsageLimitFormValues,
): CreateUsageLimitInput | null => {
@@ -26,13 +14,11 @@ export const buildCreateUsageLimitInput = (
return null;
}
- const isCreditsMeter = scope.meter === 'creditsUsedMicro';
-
- const limitValue = isCreditsMeter
- ? parsePositiveNumber(values.limitValue)
- : parsePositiveInteger(values.limitValue);
+ const limitValue = Math.round(
+ Number(values.limitValue) * getUsageLimitInputScale(scope.unit),
+ );
- if (!isDefined(limitValue)) {
+ if (!Number.isSafeInteger(limitValue) || limitValue < 1) {
return null;
}
@@ -40,9 +26,7 @@ export const buildCreateUsageLimitInput = (
...scope,
limitKind: 'quota',
periodCount: 1,
- limitValue: isCreditsMeter
- ? Math.round(limitValue * INTERNAL_CREDITS_PER_DISPLAY_CREDIT)
- : limitValue,
+ limitValue,
burstValue: null,
};
};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/buildUsageLimitFormValues.ts b/packages/twenty-front/src/modules/settings/billing/utils/buildUsageLimitFormValues.ts
index 34dc4c36063..0ac1b0a2dcd 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/buildUsageLimitFormValues.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/buildUsageLimitFormValues.ts
@@ -1,11 +1,8 @@
-import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
-import { isDefined } from 'twenty-shared/utils';
-
import { type UsageLimitFormValues } from '@/settings/billing/types/UsageLimitFormValues';
import { type UsageQuotaWithConsumption } from '@/settings/billing/types/UsageQuotaWithConsumption';
-import { USAGE_LIMIT_METER_LABELS } from '@/settings/billing/constants/UsageLimitMeterLabels';
import { USAGE_LIMIT_PERIOD_UNIT_LABELS } from '@/settings/billing/constants/UsageLimitPeriodUnitLabels';
import { USAGE_LIMIT_SPENDER_TYPE_LABELS } from '@/settings/billing/constants/UsageLimitSpenderTypeLabels';
+import { getUsageLimitInputScale } from '@/settings/billing/utils/getUsageLimitInputScale';
import { isKeyOfRecord } from '@/settings/billing/utils/isKeyOfRecord';
export const buildUsageLimitFormValues = (
@@ -23,15 +20,10 @@ export const buildUsageLimitFormValues = (
? item.spenderType
: null,
spenderId: item.spenderId ?? '',
- meter: isKeyOfRecord(USAGE_LIMIT_METER_LABELS, item.meter)
- ? item.meter
- : null,
+ unit: item.unit,
periodUnit: isKeyOfRecord(USAGE_LIMIT_PERIOD_UNIT_LABELS, item.periodUnit)
? item.periodUnit
: null,
- limitValue:
- isDefined(item.meter) && item.meter === 'creditsUsedMicro'
- ? String(limitValue / INTERNAL_CREDITS_PER_DISPLAY_CREDIT)
- : String(limitValue),
+ limitValue: String(limitValue / getUsageLimitInputScale(item.unit)),
};
};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/buildUsageQuotaScopeInput.ts b/packages/twenty-front/src/modules/settings/billing/utils/buildUsageQuotaScopeInput.ts
index ef54c4d6016..b55a819f5e9 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/buildUsageQuotaScopeInput.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/buildUsageQuotaScopeInput.ts
@@ -9,14 +9,14 @@ export const buildUsageQuotaScopeInput = ({
operationType,
spenderType,
spenderId,
- meter,
+ unit,
periodUnit,
}: Omit<UsageLimitFormValues, 'limitValue'>): UsageQuotaScopeInput | null => {
if (
!isDefined(resourceType) ||
!isDefined(operationType) ||
!isDefined(spenderType) ||
- !isDefined(meter) ||
+ !isDefined(unit) ||
!isDefined(periodUnit)
) {
return null;
@@ -30,7 +30,7 @@ export const buildUsageQuotaScopeInput = ({
spenderType !== 'workspace' && isNonEmptyString(spenderId.trim())
? spenderId.trim()
: null,
- meter,
+ unit,
periodUnit,
};
};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitAmountInput.ts b/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitAmountInput.ts
new file mode 100644
index 00000000000..f2a3db754dd
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitAmountInput.ts
@@ -0,0 +1,26 @@
+import { msg } from '@lingui/core/macro';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type UsageLimitAmountInput } from '@/settings/billing/types/UsageLimitAmountInput';
+import { getUsageLimitUnitLabel } from '@/settings/billing/utils/getUsageLimitUnitLabel';
+import {
+ type UsageOperationType,
+ UsageUnit,
+} from '~/generated-metadata/graphql';
+
+export const getUsageLimitAmountInput = ({
+ unit,
+ operationType,
+}: {
+ unit: UsageUnit | null;
+ operationType: UsageOperationType | null;
+}): UsageLimitAmountInput => {
+ if (!isDefined(unit)) {
+ return { label: msg`Amount`, placeholder: '1000' };
+ }
+
+ return {
+ label: getUsageLimitUnitLabel({ unit, operationType }).name,
+ placeholder: unit === UsageUnit.CREDIT ? '100' : '1000',
+ };
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitFormOptions.ts b/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitFormOptions.ts
index be30e2400ae..aed259614ee 100644
--- a/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitFormOptions.ts
+++ b/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitFormOptions.ts
@@ -1,18 +1,16 @@
import { isDefined } from 'twenty-shared/utils';
-import { USAGE_LIMIT_METER_LABELS } from '@/settings/billing/constants/UsageLimitMeterLabels';
import { ANCHORED_USAGE_LIMIT_PERIOD_UNITS } from '@/settings/billing/constants/AnchoredUsageLimitPeriodUnits';
import { USAGE_LIMIT_SPENDER_TYPE_LABELS } from '@/settings/billing/constants/UsageLimitSpenderTypeLabels';
import { type UsageLimitFormValues } from '@/settings/billing/types/UsageLimitFormValues';
-import { type UsageLimitMeter } from '@/settings/billing/types/UsageLimitMeter';
import { type UsageLimitPeriodUnit } from '@/settings/billing/types/UsageLimitPeriodUnit';
import { type UsageLimitSpenderType } from '@/settings/billing/types/UsageLimitSpenderType';
-import { getUsageLimitOperationTypes } from '@/settings/billing/utils/getUsageLimitOperationTypes';
import { isKeyOfRecord } from '@/settings/billing/utils/isKeyOfRecord';
import {
UsageOperationType,
type UsageQuotaDefinitionsQuery,
type UsageResourceType,
+ UsageUnit,
} from '~/generated-metadata/graphql';
type UsageLimitDefinitions =
@@ -22,7 +20,7 @@ type UsageLimitFormOptions = {
resourceTypes: UsageResourceType[];
operationTypes: UsageOperationType[];
spenderTypes: UsageLimitSpenderType[];
- meters: UsageLimitMeter[];
+ units: UsageUnit[];
periodUnits: UsageLimitPeriodUnit[];
};
@@ -48,20 +46,21 @@ export const getUsageLimitFormOptions = ({
resourceTypes,
operationTypes: [],
spenderTypes: [],
- meters: [],
+ units: [],
periodUnits: [],
};
}
- const operationTypes = getUsageLimitOperationTypes(definition);
+ const operationTypes = definition.allowedOperations.map(
+ (allowedOperation) => allowedOperation.operationType,
+ );
- const meters = definition.allowedMeters
- .filter((meter) => isKeyOfRecord(USAGE_LIMIT_METER_LABELS, meter))
- .filter(
- (meter) =>
- values.operationType !== UsageOperationType.ALL ||
- meter === 'creditsUsedMicro',
- );
+ const units =
+ definition.allowedOperations.find(
+ (allowedOperation) =>
+ allowedOperation.operationType === values.operationType,
+ )?.allowedUnits ??
+ (values.operationType === UsageOperationType.ALL ? [UsageUnit.CREDIT] : []);
const periodUnits = ANCHORED_USAGE_LIMIT_PERIOD_UNITS.filter(
(periodUnit) =>
@@ -74,7 +73,7 @@ export const getUsageLimitFormOptions = ({
spenderTypes: definition.allowedSpenderTypes.filter((spenderType) =>
isKeyOfRecord(USAGE_LIMIT_SPENDER_TYPE_LABELS, spenderType),
),
- meters,
+ units,
periodUnits,
};
};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitInputScale.ts b/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitInputScale.ts
new file mode 100644
index 00000000000..243a184d7ab
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitInputScale.ts
@@ -0,0 +1,6 @@
+import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';
+
+import { UsageUnit } from '~/generated-metadata/graphql';
+
+export const getUsageLimitInputScale = (unit: UsageUnit | null): number =>
+ unit === UsageUnit.CREDIT ? INTERNAL_CREDITS_PER_DISPLAY_CREDIT : 1;
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitOperationTypes.ts b/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitOperationTypes.ts
deleted file mode 100644
index 8f4fbae37c7..00000000000
--- a/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitOperationTypes.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import {
- UsageOperationType,
- type UsageQuotaDefinitionsQuery,
-} from '~/generated-metadata/graphql';
-
-type UsageLimitDefinition =
- UsageQuotaDefinitionsQuery['usageQuotaDefinitions']['definitions'][number];
-
-export const getUsageLimitOperationTypes = (
- definition: UsageLimitDefinition,
-): UsageOperationType[] =>
- definition.allowedMeters.includes('creditsUsedMicro') &&
- definition.allowedOperationTypes.length > 1
- ? [UsageOperationType.ALL, ...definition.allowedOperationTypes]
- : definition.allowedOperationTypes;
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitUnitLabel.ts b/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitUnitLabel.ts
new file mode 100644
index 00000000000..090d17cea35
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/billing/utils/getUsageLimitUnitLabel.ts
@@ -0,0 +1,24 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { USAGE_LIMIT_INVOCATION_UNIT_LABELS } from '@/settings/billing/constants/UsageLimitInvocationUnitLabels';
+import { USAGE_LIMIT_UNIT_LABELS } from '@/settings/billing/constants/UsageLimitUnitLabels';
+import { type UsageLimitUnitLabel } from '@/settings/billing/types/UsageLimitUnitLabel';
+import {
+ type UsageOperationType,
+ UsageUnit,
+} from '~/generated-metadata/graphql';
+
+export const getUsageLimitUnitLabel = ({
+ unit,
+ operationType,
+}: {
+ unit: UsageUnit;
+ operationType: UsageOperationType | null;
+}): UsageLimitUnitLabel => {
+ const invocationLabel =
+ unit === UsageUnit.INVOCATION && isDefined(operationType)
+ ? USAGE_LIMIT_INVOCATION_UNIT_LABELS[operationType]
+ : undefined;
+
+ return invocationLabel ?? USAGE_LIMIT_UNIT_LABELS[unit];
+};
diff --git a/packages/twenty-front/src/modules/settings/billing/utils/isCreditsMeter.ts b/packages/twenty-front/src/modules/settings/billing/utils/isCreditsMeter.ts
deleted file mode 100644
index 92c713654c3..00000000000
--- a/packages/twenty-front/src/modules/settings/billing/utils/isCreditsMeter.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { type UsageLimitMeter } from '@/settings/billing/types/UsageLimitMeter';
-
-const CREDITS_METER: UsageLimitMeter = 'creditsUsedMicro';
-
-export const isCreditsMeter = (meter: string): boolean =>
- meter === CREDITS_METER;
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791186790123-rename-usage-limit-meter-to-unit.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791186790123-rename-usage-limit-meter-to-unit.ts
new file mode 100644
index 00000000000..5d086365969
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791186790123-rename-usage-limit-meter-to-unit.ts
@@ -0,0 +1,68 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+const QUANTITY_UNIT_BY_OPERATION_SQL = `CASE "operationType"
+ WHEN 'AI_CHAT_TOKEN' THEN 'TOKEN'
+ WHEN 'AI_WORKFLOW_TOKEN' THEN 'TOKEN'
+ WHEN 'WEB_SEARCH' THEN 'INVOCATION'
+ WHEN 'WORKFLOW_EXECUTION' THEN 'INVOCATION'
+ WHEN 'CODE_EXECUTION' THEN 'INVOCATION'
+ WHEN 'EMAIL_SEND' THEN 'INVOCATION'
+ WHEN 'MESSAGE_CAMPAIGN_SEND' THEN 'INVOCATION'
+ WHEN 'API_REQUEST' THEN 'REQUEST'
+ WHEN 'WEBHOOK_CALL' THEN 'REQUEST'
+ WHEN 'STORAGE_FILE' THEN 'FILE'
+ WHEN 'RECORD_WRITE' THEN 'RECORD'
+END`;
+
+const UNIT_FROM_METER_SQL = `CASE "meter"
+ WHEN 'creditsUsedMicro' THEN 'CREDIT'
+ WHEN 'bytes' THEN 'BYTE'
+ WHEN 'quantity' THEN (${QUANTITY_UNIT_BY_OPERATION_SQL})
+END`;
+
+const METER_FROM_UNIT_SQL = `CASE "unit"
+ WHEN 'CREDIT' THEN 'creditsUsedMicro'
+ WHEN 'BYTE' THEN 'bytes'
+ ELSE 'quantity'
+END`;
+
+@RegisteredInstanceCommand('2.46.0', 1791186790123)
+export class RenameUsageLimitMeterToUnitFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" DROP CONSTRAINT "UQ_USAGE_LIMIT_SCOPE"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ALTER COLUMN "meter" TYPE character varying USING (${UNIT_FROM_METER_SQL})`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" RENAME COLUMN "meter" TO "unit"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ADD CONSTRAINT "UQ_USAGE_LIMIT_SCOPE" UNIQUE ("workspaceId", "resourceType", "operationType", "spenderType", "spenderId", "limitKind", "periodCount", "periodUnit", "unit")`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" DROP CONSTRAINT "UQ_USAGE_LIMIT_SCOPE"`,
+ );
+ await queryRunner.query(
+ `DELETE FROM "core"."usageLimit"
+ WHERE "unit" NOT IN ('CREDIT', 'BYTE')
+ AND "unit" IS DISTINCT FROM (${QUANTITY_UNIT_BY_OPERATION_SQL})`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ALTER COLUMN "unit" TYPE character varying USING (${METER_FROM_UNIT_SQL})`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" RENAME COLUMN "unit" TO "meter"`,
+ );
+ await queryRunner.query(
+ `ALTER TABLE "core"."usageLimit" ADD CONSTRAINT "UQ_USAGE_LIMIT_SCOPE" UNIQUE ("workspaceId", "resourceType", "operationType", "spenderType", "spenderId", "limitKind", "periodCount", "periodUnit", "meter")`,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 0f5ff82f0a9..46e784ff69f 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -222,6 +222,7 @@ import { AddSharingReachToObjectMetadataFastInstanceCommand } from 'src/database
import { AddIsSystemToAgentAndWorkflowFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791130291063-add-is-system-to-agent-and-workflow';
import { CreateWorkflowStepWaitTableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791148642493-create-workflow-step-wait-table';
import { DropCoreAgentHistoryTablesFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-47/2-47-instance-command-fast-1791094130961-drop-core-agent-history-tables';
+import { RenameUsageLimitMeterToUnitFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791186790123-rename-usage-limit-meter-to-unit';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -446,4 +447,5 @@ export const INSTANCE_COMMANDS = [
AddIsSystemToAgentAndWorkflowFastInstanceCommand,
CreateWorkflowStepWaitTableFastInstanceCommand,
DropCoreAgentHistoryTablesFastInstanceCommand,
+ RenameUsageLimitMeterToUnitFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-usage-limits.dto.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-usage-limits.dto.ts
index 33ff09aa784..c8439fa0c0d 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-usage-limits.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-panel-workspace-usage-limits.dto.ts
@@ -7,9 +7,9 @@ import { UsageLimitDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-li
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
@ObjectType('AdminPanelUsageLimitDefault')
export class AdminPanelUsageLimitDefaultDTO {
@@ -31,8 +31,8 @@ export class AdminPanelUsageLimitDefaultDTO {
@Field(() => String)
periodUnit: PeriodUnit;
- @Field(() => String)
- meter: UsageMeter;
+ @Field(() => UsageUnit)
+ unit: UsageUnit;
@Field(() => GraphQLBigInt)
limitValue: number;
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-usage-limit.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-usage-limit.service.ts
index d5da38d752f..49ae35b34b5 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-usage-limit.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-usage-limit.service.ts
@@ -53,7 +53,7 @@ export class AdminPanelUsageLimitService {
limitKind: usageLimitDefault.limitKind,
periodCount: usageLimitDefault.periodCount,
periodUnit: usageLimitDefault.periodUnit,
- meter: usageLimitDefault.meter,
+ unit: usageLimitDefault.unit,
limitValue: usageLimitDefault.limitValue,
isOverridable: usageLimitDefault.isOverridable,
overriddenByUsageLimitId: overridingUsageLimit?.id ?? null,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
index 67a22579e76..74c81e7f480 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.service.ts
@@ -86,8 +86,8 @@ export class AppBillingService {
operationType,
spenders,
cost: {
- creditsUsedMicro: charge.creditsUsedMicro,
- quantity: charge.quantity,
+ [UsageUnit.CREDIT]: charge.creditsUsedMicro,
+ [unit]: charge.quantity,
},
});
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts b/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
index 362e7b568b7..3d9bea49943 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/services/file-storage.service.ts
@@ -36,13 +36,12 @@ import { FileSettings } from 'src/engine/core-modules/file/types/file-settings.t
import { FILE_STATUS } from 'src/engine/core-modules/file/types/file-status.type';
import { extractFileInfoOrThrow } from 'src/engine/core-modules/file/utils/extract-file-info-or-throw.utils';
import { removeFileFolderFromFileEntityPath } from 'src/engine/core-modules/file/utils/remove-file-folder-from-file-entity-path.utils';
-import { STOCK_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
import { UsageLimitStockService } from 'src/engine/core-modules/usage-limit/services/usage-limit-stock.service';
import { type StockCost } from 'src/engine/core-modules/usage-limit/types/stock-cost.type';
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
import { type StockScope } from 'src/engine/core-modules/usage-limit/types/stock-scope.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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@@ -79,7 +78,7 @@ export class FileStorageService {
resourceType: UsageResourceType.STORAGE,
operationType: UsageOperationType.STORAGE_FILE,
spenders: { applicationId },
- cost: { bytes, quantity },
+ cost: { [UsageUnit.BYTE]: bytes, [UsageUnit.FILE]: quantity },
});
}
@@ -107,7 +106,7 @@ export class FileStorageService {
applicationId: string;
delta: StockCost;
}): Promise<void> {
- if (STOCK_METERS.every((meter) => (delta[meter] ?? 0) <= 0)) {
+ if (Object.values(delta).every((amount) => (amount ?? 0) <= 0)) {
return;
}
@@ -126,9 +125,7 @@ export class FileStorageService {
workspaceId,
spenderType,
spenderId,
- }: StockScope & { workspaceId: string }): Promise<
- Record<StockMeter, number>
- > {
+ }: StockScope & { workspaceId: string }): Promise<StockCost> {
const query = this.fileRepository
.createQueryBuilder('file')
.select('COUNT(*)::bigint', 'quantity')
@@ -145,8 +142,8 @@ export class FileStorageService {
const used = await query.getRawOne<{ quantity: string; bytes: string }>();
return {
- quantity: Number(used?.quantity ?? 0),
- bytes: Number(used?.bytes ?? 0),
+ [UsageUnit.FILE]: Number(used?.quantity ?? 0),
+ [UsageUnit.BYTE]: Number(used?.bytes ?? 0),
};
}
@@ -240,7 +237,7 @@ export class FileStorageService {
await this.applyStorageStockDelta({
workspaceId: resourceIdentifier.workspaceId,
applicationId,
- delta: { bytes: metadata.size, quantity: 1 },
+ delta: { [UsageUnit.BYTE]: metadata.size, [UsageUnit.FILE]: 1 },
});
}
@@ -263,11 +260,11 @@ export class FileStorageService {
spenders: { applicationId },
};
- if ((delta.bytes ?? 0) < 0) {
+ if ((delta[UsageUnit.BYTE] ?? 0) < 0) {
return this.releaseStorageStock({
workspaceId,
applicationId,
- bytes: -(delta.bytes ?? 0),
+ bytes: -(delta[UsageUnit.BYTE] ?? 0),
quantity: 0,
});
}
@@ -616,7 +613,7 @@ export class FileStorageService {
await this.applyStorageStockDelta({
workspaceId,
applicationId,
- delta: { bytes: size - chargedSize, quantity: 0 },
+ delta: { [UsageUnit.BYTE]: size - chargedSize },
});
return updateResult;
@@ -899,7 +896,7 @@ export class FileStorageService {
settings: FileSettings | null;
}): Promise<FileEntity> {
const { filePath } = this.validateAndBuildFileStoragePathOrThrow(to);
- const delta = { bytes: size, quantity: 1 };
+ const delta = { [UsageUnit.BYTE]: size, [UsageUnit.FILE]: 1 };
await this.assertStorageStockAvailable({
workspaceId: to.workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/utils/__tests__/build-stock-delta.util.spec.ts b/packages/twenty-server/src/engine/core-modules/file-storage/utils/__tests__/build-stock-delta.util.spec.ts
index 0525872ea9c..c57ad07af2d 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/utils/__tests__/build-stock-delta.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/utils/__tests__/build-stock-delta.util.spec.ts
@@ -1,37 +1,38 @@
import { buildStockDelta } from 'src/engine/core-modules/file-storage/utils/build-stock-delta.util';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const existingFile = (size: number) => ({ size });
describe('buildStockDelta', () => {
- it('charges the bytes and the row of a file at a free path', () => {
+ it('charges the bytes and the file of a file at a free path', () => {
expect(buildStockDelta({ existingFile: null, size: 12 })).toEqual({
- bytes: 12,
- quantity: 1,
+ [UsageUnit.BYTE]: 12,
+ [UsageUnit.FILE]: 1,
});
});
- it('charges the row of an empty file, which still occupies one', () => {
+ it('charges the file of an empty file, which still occupies one', () => {
expect(buildStockDelta({ existingFile: null, size: 0 })).toEqual({
- bytes: 0,
- quantity: 1,
+ [UsageUnit.BYTE]: 0,
+ [UsageUnit.FILE]: 1,
});
});
it('moves nothing when a replacement is the same size', () => {
expect(
buildStockDelta({ existingFile: existingFile(500), size: 500 }),
- ).toEqual({ bytes: 0, quantity: 0 });
+ ).toEqual({ [UsageUnit.BYTE]: 0, [UsageUnit.FILE]: 0 });
});
it('charges a growing replacement only for what it adds', () => {
expect(buildStockDelta({ existingFile: existingFile(1), size: 2 })).toEqual(
- { bytes: 1, quantity: 0 },
+ { [UsageUnit.BYTE]: 1, [UsageUnit.FILE]: 0 },
);
});
it('gives back what a shrinking replacement frees', () => {
expect(
buildStockDelta({ existingFile: existingFile(500), size: 2 }),
- ).toEqual({ bytes: -498, quantity: 0 });
+ ).toEqual({ [UsageUnit.BYTE]: -498, [UsageUnit.FILE]: 0 });
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-released-stock-by-application.util.ts b/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-released-stock-by-application.util.ts
index f39982cd0d3..fc1dc20622e 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-released-stock-by-application.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-released-stock-by-application.util.ts
@@ -1,9 +1,13 @@
import { type FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
-import { type StockCost } from 'src/engine/core-modules/usage-limit/types/stock-cost.type';
+
+type ReleasedStorageStock = {
+ bytes: number;
+ quantity: number;
+};
export const buildReleasedStockByApplication = (
deletedRows: Pick<FileEntity, 'applicationId' | 'size'>[],
-): Map<string, Required<Pick<StockCost, 'bytes' | 'quantity'>>> =>
+): Map<string, ReleasedStorageStock> =>
deletedRows.reduce((byApplication, row) => {
const released = byApplication.get(row.applicationId) ?? {
bytes: 0,
@@ -16,4 +20,4 @@ export const buildReleasedStockByApplication = (
});
return byApplication;
- }, new Map<string, Required<Pick<StockCost, 'bytes' | 'quantity'>>>());
+ }, new Map<string, ReleasedStorageStock>());
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-stock-delta.util.ts b/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-stock-delta.util.ts
index e68caa31d90..d8c82e0d9ad 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-stock-delta.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/utils/build-stock-delta.util.ts
@@ -2,6 +2,7 @@ import { isDefined } from 'twenty-shared/utils';
import { type FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import { type StockCost } from 'src/engine/core-modules/usage-limit/types/stock-cost.type';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export const buildStockDelta = ({
existingFile,
@@ -10,6 +11,6 @@ export const buildStockDelta = ({
existingFile: Pick<FileEntity, 'size'> | null;
size: number;
}): StockCost => ({
- bytes: size - (existingFile?.size ?? 0),
- quantity: isDefined(existingFile) ? 0 : 1,
+ [UsageUnit.BYTE]: size - (existingFile?.size ?? 0),
+ [UsageUnit.FILE]: isDefined(existingFile) ? 0 : 1,
});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
index 23be2e295ec..faf84f80506 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
@@ -42,7 +42,7 @@ import { buildApplicationLogEnvelopes } from 'src/engine/core-modules/event-logs
import { parseApplicationLogLines } from 'src/engine/core-modules/event-logs/producers/application-log/parse-application-log-lines';
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { LogicFunctionDriverFactory } from 'src/engine/core-modules/logic-function/logic-function-drivers/logic-function-driver.factory';
-import { computeLogicFunctionExecutionCreditsMicro } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/compute-logic-function-execution-credits-micro.util';
+import { buildLogicFunctionExecutionUsage } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util';
import { resolveWorkspaceMemberIdForUser } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/resolve-workspace-member-id-for-user.util';
import { LogicFunctionPrebuiltWarmUpService } from 'src/engine/core-modules/logic-function/logic-function-prebuilt-warm-up/logic-function-prebuilt-warm-up.service';
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
@@ -55,7 +55,6 @@ import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twent
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
@@ -648,51 +647,29 @@ export class LogicFunctionExecutorService {
functionName: flatLogicFunction.name,
});
- // Billing-exempt apps skip the invocation charge; their explicit chargeCredits and AI usage are still billed.
- const { invocationCreditsMicro, durationCreditsMicro, billedDurationMs } =
- computeLogicFunctionExecutionCreditsMicro({
- durationMs: result.billedDurationMs,
- isBillingExempt: isBillingExemptApplication(
- flatApplication.universalIdentifier,
- ),
- });
-
- const totalCreditsMicro = invocationCreditsMicro + durationCreditsMicro;
-
const spenders = {
logicFunctionId: flatLogicFunction.id,
applicationId: flatApplication.id,
};
- if (totalCreditsMicro > 0) {
- await this.usageLimitQuotaService.consumeQuota({
- workspaceId,
- resourceType: UsageResourceType.LOGIC_FUNCTION,
- operationType: UsageOperationType.CODE_EXECUTION,
- spenders,
- cost: { creditsUsedMicro: totalCreditsMicro, quantity: 1 },
- });
- }
+ // Billing-exempt apps skip the invocation charge; their explicit chargeCredits and AI usage are still billed.
+ const { usageEvents, cost } = buildLogicFunctionExecutionUsage({
+ durationMs: result.billedDurationMs,
+ isBillingExempt: isBillingExemptApplication(
+ flatApplication.universalIdentifier,
+ ),
+ resourceId: flatLogicFunction.id,
+ spenders,
+ });
- await this.usageRecorderService.record(workspaceId, [
- {
- resourceType: UsageResourceType.LOGIC_FUNCTION,
- operationType: UsageOperationType.CODE_EXECUTION,
- creditsUsedMicro: invocationCreditsMicro,
- quantity: 1,
- unit: UsageUnit.INVOCATION,
- resourceId: flatLogicFunction.id,
- spenders,
- },
- {
- resourceType: UsageResourceType.LOGIC_FUNCTION,
- operationType: UsageOperationType.CODE_EXECUTION,
- creditsUsedMicro: durationCreditsMicro,
- quantity: billedDurationMs,
- unit: UsageUnit.MILLISECOND,
- resourceId: flatLogicFunction.id,
- spenders,
- },
- ]);
+ await this.usageLimitQuotaService.consumeQuota({
+ workspaceId,
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ spenders,
+ cost,
+ });
+
+ await this.usageRecorderService.record(workspaceId, usageEvents);
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/build-logic-function-execution-usage.util.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/build-logic-function-execution-usage.util.spec.ts
new file mode 100644
index 00000000000..42a57d326f2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/build-logic-function-execution-usage.util.spec.ts
@@ -0,0 +1,64 @@
+import { MARKETPLACE_BILLING_EXEMPT_UNIVERSAL_IDENTIFIERS } from 'src/engine/core-modules/application/application-marketplace/constants/marketplace-billing-exempt-applications.constant';
+import { isBillingExemptApplication } from 'src/engine/core-modules/application/application-marketplace/utils/is-billing-exempt-application.util';
+import { buildLogicFunctionExecutionUsage } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+
+const LOGIC_FUNCTION_ID = '9f1c2b3a-4d5e-4f60-8a71-b2c3d4e5f607';
+const APPLICATION_ID = '1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d';
+
+const SPENDERS = {
+ logicFunctionId: LOGIC_FUNCTION_ID,
+ applicationId: APPLICATION_ID,
+};
+
+const buildExpectedUsageEvent = ({
+ creditsUsedMicro,
+ quantity,
+ unit,
+}: {
+ creditsUsedMicro: number;
+ quantity: number;
+ unit: UsageUnit;
+}) => ({
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ creditsUsedMicro,
+ quantity,
+ unit,
+ resourceId: LOGIC_FUNCTION_ID,
+ spenders: SPENDERS,
+});
+
+describe('buildLogicFunctionExecutionUsage', () => {
+ it('counts the run of a billing-exempt app at no credits and no runtime', () => {
+ expect(
+ buildLogicFunctionExecutionUsage({
+ durationMs: 5_000,
+ isBillingExempt: isBillingExemptApplication(
+ MARKETPLACE_BILLING_EXEMPT_UNIVERSAL_IDENTIFIERS[0],
+ ),
+ resourceId: LOGIC_FUNCTION_ID,
+ spenders: SPENDERS,
+ }),
+ ).toEqual({
+ usageEvents: [
+ buildExpectedUsageEvent({
+ creditsUsedMicro: 0,
+ quantity: 1,
+ unit: UsageUnit.INVOCATION,
+ }),
+ buildExpectedUsageEvent({
+ creditsUsedMicro: 0,
+ quantity: 0,
+ unit: UsageUnit.MILLISECOND,
+ }),
+ ],
+ cost: {
+ [UsageUnit.CREDIT]: 0,
+ [UsageUnit.INVOCATION]: 1,
+ },
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util.ts
new file mode 100644
index 00000000000..09771e68760
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/build-logic-function-execution-usage.util.ts
@@ -0,0 +1,51 @@
+import { computeLogicFunctionExecutionCreditsMicro } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/compute-logic-function-execution-credits-micro.util';
+import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { type RecordUsageInput } from 'src/engine/core-modules/usage/types/record-usage-input.type';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
+
+export const buildLogicFunctionExecutionUsage = ({
+ durationMs,
+ isBillingExempt,
+ resourceId,
+ spenders,
+}: {
+ durationMs: number;
+ isBillingExempt: boolean;
+ resourceId: string;
+ spenders: UsageSpenders;
+}): { usageEvents: RecordUsageInput[]; cost: QuotaCost } => {
+ const { invocationCreditsMicro, durationCreditsMicro, billedDurationMs } =
+ computeLogicFunctionExecutionCreditsMicro({ durationMs, isBillingExempt });
+
+ const usageEvents: RecordUsageInput[] = [
+ {
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ creditsUsedMicro: invocationCreditsMicro,
+ quantity: 1,
+ unit: UsageUnit.INVOCATION,
+ resourceId,
+ spenders,
+ },
+ {
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ creditsUsedMicro: durationCreditsMicro,
+ quantity: billedDurationMs,
+ unit: UsageUnit.MILLISECOND,
+ resourceId,
+ spenders,
+ },
+ ];
+
+ return {
+ usageEvents,
+ cost: {
+ [UsageUnit.CREDIT]: invocationCreditsMicro + durationCreditsMicro,
+ [UsageUnit.INVOCATION]: 1,
+ },
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kind-rules.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kind-rules.constant.ts
index c143e4c7034..58db161c5b8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kind-rules.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/limit-kind-rules.constant.ts
@@ -1,9 +1,4 @@
import { ANCHORED_PERIOD_UNITS } from 'src/engine/core-modules/usage-limit/constants/period-units.constant';
-import {
- QUOTA_METERS,
- SPEED_METERS,
- STOCK_METERS,
-} from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
import { type LimitKindRule } from 'src/engine/core-modules/usage-limit/types/limit-kind-rule.type';
@@ -12,21 +7,18 @@ export const LIMIT_KIND_RULES: Record<LimitKind, LimitKindRule> = {
isAllOperationTypeAllowed: false,
allowedPeriodUnits: ['second'],
requiredPeriodCount: null,
- allowedMeters: SPEED_METERS,
isBurstValueAllowed: true,
},
quota: {
isAllOperationTypeAllowed: true,
allowedPeriodUnits: ANCHORED_PERIOD_UNITS,
requiredPeriodCount: 1,
- allowedMeters: QUOTA_METERS,
isBurstValueAllowed: false,
},
stock: {
isAllOperationTypeAllowed: false,
allowedPeriodUnits: ['lifetime'],
requiredPeriodCount: 1,
- allowedMeters: STOCK_METERS,
isBurstValueAllowed: false,
},
};
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 b094f923b2d..db935ba02f9 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
@@ -1,11 +1,17 @@
import { type UsageLimitDefinitionsByResourceType } from 'src/engine/core-modules/usage-limit/types/usage-limit-definition.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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export const USAGE_LIMIT_DEFINITIONS = {
[UsageResourceType.API]: {
speed: {
- allowedOperationTypes: [UsageOperationType.API_REQUEST],
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.API_REQUEST,
+ allowedUnits: [UsageUnit.REQUEST],
+ },
+ ],
allowedSpenderTypes: ['apiKey', 'application'],
defaults: [
{
@@ -14,7 +20,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'speed',
spenderType: 'apiKey',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
periodUnit: 'second',
windowMsConfigVariable: 'API_RATE_LIMITING_SHORT_TTL_IN_MS',
limitValueConfigVariable: 'API_RATE_LIMITING_SHORT_LIMIT',
@@ -27,7 +33,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'speed',
spenderType: 'apiKey',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
periodUnit: 'second',
windowMsConfigVariable: 'API_RATE_LIMITING_LONG_TTL_IN_MS',
limitValueConfigVariable: 'API_RATE_LIMITING_LONG_LIMIT',
@@ -40,7 +46,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'speed',
spenderType: 'application',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
periodUnit: 'second',
windowMsConfigVariable: 'APPLICATION_API_RATE_LIMITING_TTL_IN_MS',
limitValueConfigVariable: 'APPLICATION_API_RATE_LIMITING_LIMIT',
@@ -52,10 +58,19 @@ export const USAGE_LIMIT_DEFINITIONS = {
},
[UsageResourceType.AI]: {
quota: {
- allowedOperationTypes: [
- UsageOperationType.AI_CHAT_TOKEN,
- UsageOperationType.AI_WORKFLOW_TOKEN,
- UsageOperationType.WEB_SEARCH,
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.TOKEN],
+ },
+ {
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.TOKEN],
+ },
+ {
+ operationType: UsageOperationType.WEB_SEARCH,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
],
allowedSpenderTypes: [
'workspace',
@@ -63,24 +78,31 @@ export const USAGE_LIMIT_DEFINITIONS = {
'apiKey',
'application',
],
- allowedMeters: ['creditsUsedMicro', 'quantity'],
defaults: [],
},
},
[UsageResourceType.WORKFLOW]: {
quota: {
- allowedOperationTypes: [UsageOperationType.WORKFLOW_EXECUTION],
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.WORKFLOW_EXECUTION,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
+ ],
allowedSpenderTypes: ['workspace', 'application'],
- allowedMeters: ['creditsUsedMicro', 'quantity'],
defaults: [],
},
},
[UsageResourceType.APP]: {},
[UsageResourceType.STORAGE]: {
stock: {
- allowedOperationTypes: [UsageOperationType.STORAGE_FILE],
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.STORAGE_FILE,
+ allowedUnits: [UsageUnit.BYTE, UsageUnit.FILE],
+ },
+ ],
allowedSpenderTypes: ['workspace', 'application'],
- allowedMeters: ['bytes', 'quantity'],
defaults: [
{
resourceType: UsageResourceType.STORAGE,
@@ -88,7 +110,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'stock',
spenderType: 'workspace',
spenderId: '',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
periodUnit: 'lifetime',
periodCount: 1,
limitValueConfigVariable: 'WORKSPACE_STORAGE_LIMIT_BYTES',
@@ -99,17 +121,27 @@ export const USAGE_LIMIT_DEFINITIONS = {
},
[UsageResourceType.LOGIC_FUNCTION]: {
quota: {
- allowedOperationTypes: [UsageOperationType.CODE_EXECUTION],
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.CODE_EXECUTION,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
+ ],
allowedSpenderTypes: ['workspace', 'application', 'logicFunction'],
- allowedMeters: ['creditsUsedMicro', 'quantity'],
defaults: [],
},
},
[UsageResourceType.EMAIL]: {
speed: {
- allowedOperationTypes: [
- UsageOperationType.EMAIL_SEND,
- UsageOperationType.MESSAGE_CAMPAIGN_SEND,
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.EMAIL_SEND,
+ allowedUnits: [UsageUnit.INVOCATION],
+ },
+ {
+ operationType: UsageOperationType.MESSAGE_CAMPAIGN_SEND,
+ allowedUnits: [UsageUnit.INVOCATION],
+ },
],
allowedSpenderTypes: ['workspace'],
// Two buckets, and a send has to fit both. The workspace one keeps a
@@ -124,7 +156,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'speed',
spenderType: 'workspace',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
periodUnit: 'second',
windowMsConfigVariable:
'EMAIL_SEND_WORKSPACE_RATE_LIMITING_TTL_IN_MS',
@@ -138,7 +170,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'speed',
spenderType: 'workspace',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
periodUnit: 'second',
windowMsConfigVariable: 'EMAIL_SEND_RATE_LIMITING_TTL_IN_MS',
limitValueConfigVariable: 'EMAIL_SEND_RATE_LIMITING_LIMIT',
@@ -151,7 +183,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'speed',
spenderType: 'workspace',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
periodUnit: 'second',
windowMsConfigVariable:
'EMAIL_SEND_WORKSPACE_RATE_LIMITING_TTL_IN_MS',
@@ -165,7 +197,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'speed',
spenderType: 'workspace',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
periodUnit: 'second',
windowMsConfigVariable: 'EMAIL_SEND_RATE_LIMITING_TTL_IN_MS',
limitValueConfigVariable: 'EMAIL_SEND_RATE_LIMITING_LIMIT',
@@ -175,9 +207,13 @@ export const USAGE_LIMIT_DEFINITIONS = {
],
},
quota: {
- allowedOperationTypes: [UsageOperationType.EMAIL_SEND],
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.EMAIL_SEND,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
+ ],
allowedSpenderTypes: ['workspace', 'userWorkspace'],
- allowedMeters: ['creditsUsedMicro', 'quantity'],
defaults: [
{
resourceType: UsageResourceType.EMAIL,
@@ -185,7 +221,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'quota',
spenderType: 'workspace',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
periodUnit: 'day',
periodCount: 1,
limitValueConfigVariable: 'EMAIL_SEND_WORKSPACE_DAILY_LIMIT',
@@ -196,7 +232,12 @@ export const USAGE_LIMIT_DEFINITIONS = {
},
[UsageResourceType.WEBHOOK]: {
speed: {
- allowedOperationTypes: [UsageOperationType.WEBHOOK_CALL],
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.WEBHOOK_CALL,
+ allowedUnits: [UsageUnit.REQUEST],
+ },
+ ],
allowedSpenderTypes: ['workspace'],
defaults: [
{
@@ -205,7 +246,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'speed',
spenderType: 'workspace',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
periodUnit: 'second',
windowMsConfigVariable: 'WEBHOOK_CALL_RATE_LIMITING_TTL_IN_MS',
limitValueConfigVariable: 'WEBHOOK_CALL_RATE_LIMITING_LIMIT',
@@ -217,9 +258,13 @@ export const USAGE_LIMIT_DEFINITIONS = {
},
[UsageResourceType.RECORD]: {
stock: {
- allowedOperationTypes: [UsageOperationType.RECORD_WRITE],
+ allowedOperations: [
+ {
+ operationType: UsageOperationType.RECORD_WRITE,
+ allowedUnits: [UsageUnit.RECORD],
+ },
+ ],
allowedSpenderTypes: ['workspace'],
- allowedMeters: ['quantity'],
defaults: [
{
resourceType: UsageResourceType.RECORD,
@@ -227,7 +272,7 @@ export const USAGE_LIMIT_DEFINITIONS = {
limitKind: 'stock',
spenderType: 'workspace',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.RECORD,
periodUnit: 'lifetime',
periodCount: 1,
limitValueConfigVariable: 'WORKSPACE_RECORD_LIMIT',
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-meters.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-meters.constant.ts
deleted file mode 100644
index 9d77ff8f374..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/usage-meters.constant.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export const SPEED_METERS = ['quantity'] as const;
-
-export const QUOTA_METERS = ['creditsUsedMicro', 'quantity'] as const;
-
-export const STOCK_METERS = ['quantity', 'bytes'] as const;
-
-export const USAGE_METERS = ['creditsUsedMicro', 'quantity', 'bytes'] as const;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/create-usage-limit.input.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/create-usage-limit.input.ts
index f0e4530fbcb..43f8a74097d 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/create-usage-limit.input.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/create-usage-limit.input.ts
@@ -13,14 +13,13 @@ import {
import { LIMIT_KINDS } from 'src/engine/core-modules/usage-limit/constants/limit-kinds.constant';
import { PERIOD_UNITS } from 'src/engine/core-modules/usage-limit/constants/period-units.constant';
-import { USAGE_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
import { SPENDER_TYPES } from 'src/engine/core-modules/usage-limit/constants/spender-types.constant';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
-import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
@InputType()
export class CreateUsageLimitInput {
@@ -54,9 +53,9 @@ export class CreateUsageLimitInput {
@IsIn(PERIOD_UNITS)
periodUnit: PeriodUnit;
- @Field(() => String)
- @IsIn(USAGE_METERS)
- meter: UsageMeter;
+ @Field(() => UsageUnit)
+ @IsEnum(UsageUnit)
+ unit: UsageUnit;
@Field(() => GraphQLBigInt)
@IsInt()
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-limit-operation-definition.dto.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-limit-operation-definition.dto.ts
new file mode 100644
index 00000000000..77b43310954
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-limit-operation-definition.dto.ts
@@ -0,0 +1,13 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+
+@ObjectType('UsageLimitOperationDefinition')
+export class UsageLimitOperationDefinitionDTO {
+ @Field(() => UsageOperationType)
+ operationType: UsageOperationType;
+
+ @Field(() => [UsageUnit])
+ allowedUnits: UsageUnit[];
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-limit.dto.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-limit.dto.ts
index 287763d7dde..358e38c0aa7 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-limit.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/dtos/usage-limit.dto.ts
@@ -5,10 +5,10 @@ import { GraphQLBigInt } from 'graphql-scalars';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
-import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
@ObjectType('UsageLimit')
export class UsageLimitDTO {
@@ -36,8 +36,8 @@ export class UsageLimitDTO {
@Field(() => String)
periodUnit: PeriodUnit;
- @Field(() => String)
- meter: UsageMeter;
+ @Field(() => UsageUnit)
+ unit: UsageUnit;
@Field(() => GraphQLBigInt)
limitValue: number;
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
index 3362c697679..8fbbac4e9ae 100644
--- 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
@@ -1,9 +1,8 @@
import { Field, ObjectType } from '@nestjs/graphql';
+import { UsageLimitOperationDefinitionDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-limit-operation-definition.dto';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.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('UsageQuotaDefinition')
@@ -14,12 +13,9 @@ export class UsageQuotaDefinitionDTO {
@Field(() => String)
limitKind: LimitKind;
- @Field(() => [UsageOperationType])
- allowedOperationTypes: UsageOperationType[];
+ @Field(() => [UsageLimitOperationDefinitionDTO])
+ allowedOperations: UsageLimitOperationDefinitionDTO[];
@Field(() => [String])
allowedSpenderTypes: SpenderType[];
-
- @Field(() => [String])
- allowedMeters: UsageMeter[];
}
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
index a71baec3e8b..ae306a8fb53 100644
--- 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
@@ -5,9 +5,9 @@ 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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
@ObjectType('UsageQuotaWithConsumption')
export class UsageQuotaWithConsumptionDTO {
@@ -32,8 +32,8 @@ export class UsageQuotaWithConsumptionDTO {
@Field(() => String)
periodUnit: PeriodUnit;
- @Field(() => String)
- meter: UsageMeter;
+ @Field(() => UsageUnit)
+ unit: UsageUnit;
@Field(() => GraphQLBigInt)
limitValue: number;
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 b4a26295992..2024b481146 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
@@ -37,6 +37,7 @@ import { buildOverriddenQuotaDefaultCounterKeys } from 'src/engine/core-modules/
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';
import { buildQuotaCounters } from 'src/engine/core-modules/usage-limit/utils/build-quota-counters.util';
+import { buildQuotaDebits } from 'src/engine/core-modules/usage-limit/utils/build-quota-debits.util';
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';
@@ -50,6 +51,7 @@ import { fromConsumeResultsToRemainings } from 'src/engine/core-modules/usage-li
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
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';
@@ -118,8 +120,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
const clampedCost = clampQuotaCost(cost);
if (
- clampedCost.creditsUsedMicro !== cost.creditsUsedMicro ||
- clampedCost.quantity !== cost.quantity
+ Object.values(UsageUnit).some((unit) => clampedCost[unit] !== cost[unit])
) {
this.logger.error(
`Refusing to consume invalid quota cost ${JSON.stringify(cost)} for workspace ${args.workspaceId}; treating it as 0`,
@@ -209,7 +210,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
operationType: usageLimit.operationType,
spenderType: usageLimit.spenderType,
spenderId: usageLimit.spenderId,
- meter: usageLimit.meter,
+ unit: usageLimit.unit,
periodUnit: usageLimit.periodUnit,
periodStart: period.periodStart,
limitValue: usageLimit.limitValue,
@@ -435,12 +436,17 @@ export class UsageLimitQuotaService implements OnModuleInit {
...args
}: QuotaConsumeArgs & { cost: QuotaCost }): Promise<ExhaustedScope[]> {
try {
- const counters = await this.buildCounters(args);
+ const debits = buildQuotaDebits({
+ counters: await this.buildCounters(args),
+ cost,
+ });
- if (counters.length === 0) {
+ if (debits.length === 0) {
return [];
}
+ const counters = debits.map((debit) => debit.counter);
+
// The consume script only debits keys that exist: warm cold counters
// first so a consume-only caller (workflow, logic function) is metered
// from its first call instead of waiting for an assert to warm the key.
@@ -449,7 +455,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
const consumeResults = await this.cacheStorage.runScript<number[]>({
script: CONSUME_QUOTA_COUNTERS_SCRIPT,
keys: counters.map((counter) => counter.key),
- args: [JSON.stringify(counters.map((counter) => cost[counter.meter]))],
+ args: [JSON.stringify(debits.map((debit) => debit.amount))],
});
const remainings = fromConsumeResultsToRemainings(consumeResults);
@@ -551,10 +557,10 @@ export class UsageLimitQuotaService implements OnModuleInit {
attributes,
});
- if (isDefined(cost) && cost.creditsUsedMicro > 0) {
+ if (isDefined(cost) && cost[UsageUnit.CREDIT] > 0) {
this.metricsService.incrementCounterBy({
key: MetricsKeys.UsageLimitQuotaAdmittedOnFailureCreditsMicro,
- amount: cost.creditsUsedMicro,
+ amount: cost[UsageUnit.CREDIT],
attributes,
});
}
@@ -657,7 +663,7 @@ export class UsageLimitQuotaService implements OnModuleInit {
workspaceId,
periodStart: period.periodStart,
}),
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
periodStart: period.periodStart,
periodEnd: period.periodEnd,
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
index ae9c1f65d41..0800f18fa34 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-stock.service.ts
@@ -26,7 +26,6 @@ import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spen
import { type StockCost } from 'src/engine/core-modules/usage-limit/types/stock-cost.type';
import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
import { type StockLimitDefault } from 'src/engine/core-modules/usage-limit/types/stock-limit-default.type';
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
import { type StockResourceType } from 'src/engine/core-modules/usage-limit/types/stock-resource-type.type';
import { buildStockCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util';
import { buildStockCounters } from 'src/engine/core-modules/usage-limit/utils/build-stock-counters.util';
@@ -42,6 +41,7 @@ import { isStockLimit } from 'src/engine/core-modules/usage-limit/utils/is-stock
import { isStockResourceType } from 'src/engine/core-modules/usage-limit/utils/is-stock-resource-type.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 { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@@ -122,7 +122,7 @@ export class UsageLimitStockService {
cost,
script: CONSUME_QUOTA_COUNTERS_SCRIPT,
buildArgs: (counters) => [
- JSON.stringify(counters.map((counter) => cost[counter.meter] ?? 0)),
+ JSON.stringify(counters.map((counter) => cost[counter.unit] ?? 0)),
],
});
}
@@ -136,7 +136,7 @@ export class UsageLimitStockService {
cost,
script: RELEASE_STOCK_COUNTERS_SCRIPT,
buildArgs: (counters) => [
- JSON.stringify(counters.map((counter) => cost[counter.meter] ?? 0)),
+ JSON.stringify(counters.map((counter) => cost[counter.unit] ?? 0)),
JSON.stringify(counters.map((counter) => counter.limitValue)),
],
});
@@ -148,7 +148,7 @@ export class UsageLimitStockService {
operationType,
spenderType,
spenderId,
- meter,
+ unit,
limitValue,
}: {
workspaceId: string;
@@ -156,7 +156,7 @@ export class UsageLimitStockService {
operationType: UsageOperationType;
spenderType: SpenderType;
spenderId: string | null;
- meter: StockMeter;
+ unit: UsageUnit;
limitValue: number;
}) {
const keys = [
@@ -166,7 +166,7 @@ export class UsageLimitStockService {
operationType,
spenderType,
spenderId,
- meter,
+ unit,
limitValue,
}),
];
@@ -184,7 +184,7 @@ export class UsageLimitStockService {
resourceType,
operationType,
spenderType,
- meter: stockLimitDefault.meter,
+ unit: stockLimitDefault.unit,
limitValue: stockLimitDefault.limitValue,
}),
),
@@ -252,7 +252,7 @@ export class UsageLimitStockService {
}): Promise<void> {
try {
const counters = (await this.buildCounters(args)).filter(
- (counter) => (cost[counter.meter] ?? 0) > 0,
+ (counter) => (cost[counter.unit] ?? 0) > 0,
);
if (counters.length === 0) {
@@ -324,7 +324,7 @@ export class UsageLimitStockService {
)
.map((stockLimitDefaultDefinition) => ({
spenderType: stockLimitDefaultDefinition.spenderType,
- meter: stockLimitDefaultDefinition.meter,
+ unit: stockLimitDefaultDefinition.unit,
isOverridable: stockLimitDefaultDefinition.isOverridable,
limitValue: this.twentyConfigService.get(
stockLimitDefaultDefinition.limitValueConfigVariable,
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 3efeb7c998f..34ff87812a3 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
@@ -301,7 +301,7 @@ export class UsageLimitService {
operationType: usageLimit.operationType,
spenderType: usageLimit.spenderType,
spenderId: usageLimit.spenderId,
- meter: usageLimit.meter,
+ unit: usageLimit.unit,
limitValue: usageLimit.limitValue,
});
}
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
index 16a7951ea37..d7e91ec8e07 100644
--- 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
@@ -17,9 +17,9 @@ import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage
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 { isAnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/utils/is-anchored-period-unit.util';
-import { isQuotaMeter } from 'src/engine/core-modules/usage-limit/utils/is-quota-meter.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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
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';
@@ -64,12 +64,10 @@ export class UsageQuotaConsumptionService {
}): Promise<UsageQuotaScopeConsumption | null> {
const periodUnit = scope.periodUnit;
- if (!isAnchoredPeriodUnit(periodUnit) || !isQuotaMeter(scope.meter)) {
+ if (!isAnchoredPeriodUnit(periodUnit)) {
return null;
}
- const meter = scope.meter;
-
const period = await this.usagePeriodService.findCurrentPeriod({
workspaceId,
periodUnit,
@@ -79,13 +77,15 @@ export class UsageQuotaConsumptionService {
return null;
}
+ const isCreditLimit = scope.unit === UsageUnit.CREDIT;
+
try {
const totals =
await this.usageAnalyticsService.getConsumptionTotalsForScope({
workspaceId,
resourceType: scope.resourceType,
operationType: scope.operationType,
- unit: null,
+ unit: isCreditLimit ? null : scope.unit,
spenderType: scope.spenderType,
spenderId: normalizeSpenderId(scope.spenderId ?? ''),
periodStart: period.periodStart,
@@ -94,7 +94,9 @@ export class UsageQuotaConsumptionService {
});
return {
- consumedValue: Number(totals[meter]),
+ consumedValue: Number(
+ isCreditLimit ? totals.creditsUsedMicro : totals.quantity,
+ ),
periodStart: period.periodStart,
periodEnd: period.periodEnd,
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/workspace-record-stock.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/workspace-record-stock.service.ts
index ffb07c2e335..da0e62f42b8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/workspace-record-stock.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/workspace-record-stock.service.ts
@@ -5,9 +5,11 @@ import { DataSource } from 'typeorm';
import { COUNT_LIVE_RECORDS_QUERY } from 'src/engine/core-modules/usage-limit/constants/count-live-records-query.constant';
import { UsageLimitStockService } from 'src/engine/core-modules/usage-limit/services/usage-limit-stock.service';
+import { type StockCost } from 'src/engine/core-modules/usage-limit/types/stock-cost.type';
import { buildRecordStockTableNames } from 'src/engine/core-modules/usage-limit/utils/build-record-stock-table-names.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
@@ -42,7 +44,7 @@ export class WorkspaceRecordStockService {
await this.usageLimitStockService.assertStockAvailable({
...RECORD_STOCK_SCOPE,
workspaceId,
- cost: { quantity },
+ cost: { [UsageUnit.RECORD]: quantity },
computeUsedStock: () =>
this.computeRecordUsedStock({ workspaceId, flatObjectMetadataMaps }),
});
@@ -62,7 +64,7 @@ export class WorkspaceRecordStockService {
await this.usageLimitStockService.acquireStock({
...RECORD_STOCK_SCOPE,
workspaceId,
- cost: { quantity },
+ cost: { [UsageUnit.RECORD]: quantity },
});
}
@@ -80,7 +82,7 @@ export class WorkspaceRecordStockService {
await this.usageLimitStockService.releaseStock({
...RECORD_STOCK_SCOPE,
workspaceId,
- cost: { quantity },
+ cost: { [UsageUnit.RECORD]: quantity },
});
}
@@ -90,7 +92,7 @@ export class WorkspaceRecordStockService {
}: {
workspaceId: string;
flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
- }): Promise<{ quantity: number; bytes: number }> {
+ }): Promise<StockCost> {
const [used] = await this.coreDataSource.query<{ quantity: string }[]>(
COUNT_LIVE_RECORDS_QUERY,
[
@@ -99,6 +101,6 @@ export class WorkspaceRecordStockService {
],
);
- return { quantity: Number(used?.quantity ?? 0), bytes: 0 };
+ return { [UsageUnit.RECORD]: Number(used?.quantity ?? 0) };
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/allowance-quota-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/allowance-quota-counter.type.ts
index 07ef21e8636..e742a68364a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/allowance-quota-counter.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/allowance-quota-counter.type.ts
@@ -1,7 +1,9 @@
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+
export type AllowanceQuotaCounter = {
kind: 'allowance';
key: string;
- meter: 'creditsUsedMicro';
+ unit: UsageUnit.CREDIT;
periodStart: Date;
periodEnd: Date;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/compute-used-stock.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/compute-used-stock.type.ts
index 1f9549448d2..40439f93077 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/compute-used-stock.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/compute-used-stock.type.ts
@@ -1,6 +1,6 @@
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
import { type StockScope } from 'src/engine/core-modules/usage-limit/types/stock-scope.type';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export type ComputeUsedStock = (
scope: StockScope,
-) => Promise<Record<StockMeter, number>>;
+) => Promise<Partial<Record<UsageUnit, number>>>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-scope.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-scope.type.ts
index 7d235530a51..1fc403f429f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-scope.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/exhausted-scope.type.ts
@@ -1,5 +1,6 @@
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 { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type ExhaustedKind } from 'src/engine/core-modules/usage-limit/types/exhausted-kind.type';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
@@ -12,6 +13,7 @@ export type ExhaustedScope = {
spenderType: SpenderType;
spenderId: string | null;
operationType: UsageOperationType;
+ unit?: UsageUnit;
limitValue: number;
// Speed limits only. What admission is actually tested against: a bucket
// never holds more than its burst, so a cost above it can never be admitted
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-quota-limit.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-quota-limit.type.ts
index 11025ef727c..7ae486b472a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-quota-limit.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-quota-limit.type.ts
@@ -1,6 +1,5 @@
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
-import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.type';
-export type FlatQuotaLimit = Omit<FlatUsageLimit, 'meter'> & {
- meter: QuotaMeter;
+export type FlatQuotaLimit = FlatUsageLimit & {
+ limitKind: 'quota';
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-stock-limit.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-stock-limit.type.ts
index 0cbfa8431e6..975f9ed69e3 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-stock-limit.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-stock-limit.type.ts
@@ -1,8 +1,6 @@
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
import { type StockResourceType } from 'src/engine/core-modules/usage-limit/types/stock-resource-type.type';
-export type FlatStockLimit = Omit<FlatUsageLimit, 'meter' | 'resourceType'> & {
- meter: StockMeter;
+export type FlatStockLimit = Omit<FlatUsageLimit, 'resourceType'> & {
resourceType: StockResourceType;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-usage-limit.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-usage-limit.type.ts
index 25879472dab..fa9eb43e771 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-usage-limit.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/flat-usage-limit.type.ts
@@ -1,9 +1,9 @@
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 { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
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';
export type FlatUsageLimit = {
id: string;
@@ -14,7 +14,7 @@ export type FlatUsageLimit = {
limitKind: LimitKind;
periodCount: number;
periodUnit: PeriodUnit;
- meter: UsageMeter;
+ unit: UsageUnit;
limitValue: number;
burstValue: number | null;
isInstanceOverride: boolean;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-kind-rule.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-kind-rule.type.ts
index 2e3d76756d3..6e0157909eb 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-kind-rule.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-kind-rule.type.ts
@@ -1,10 +1,8 @@
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
-import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
export type LimitKindRule = {
isAllOperationTypeAllowed: boolean;
allowedPeriodUnits: readonly PeriodUnit[];
requiredPeriodCount: number | null;
- allowedMeters: readonly UsageMeter[];
isBurstValueAllowed: boolean;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
index 6da7fa42efa..5970b5180df 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
@@ -1,15 +1,15 @@
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 QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-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';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export type LimitQuotaCounter = {
kind: 'limit';
isDefault: boolean;
key: string;
limitValue: number;
- meter: QuotaMeter;
+ unit: UsageUnit;
resourceType: UsageResourceType;
periodUnit: PeriodUnit;
periodStart: Date;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts
index 31e83b0b76a..887610cdc1a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts
@@ -1,3 +1,4 @@
-import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.type';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
-export type QuotaCost = Record<QuotaMeter, number>;
+export type QuotaCost = Record<UsageUnit.CREDIT, number> &
+ Partial<Record<UsageUnit, number>>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-debit.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-debit.type.ts
new file mode 100644
index 00000000000..98850bd5550
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-debit.type.ts
@@ -0,0 +1,6 @@
+import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';
+
+export type QuotaDebit = {
+ counter: QuotaCounter;
+ amount: number;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-default-key-scope.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-default-key-scope.type.ts
index 63f4358a2e4..38ecbbac438 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-default-key-scope.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-default-key-scope.type.ts
@@ -1,8 +1,8 @@
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
-import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.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';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export type QuotaDefaultKeyScope = {
workspaceId: string;
@@ -10,7 +10,7 @@ export type QuotaDefaultKeyScope = {
operationType: UsageOperationType;
spenderType: SpenderType;
spenderId?: string | null;
- meter: QuotaMeter;
+ unit: UsageUnit;
periodUnit: PeriodUnit;
periodStart: Date;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-limit-default-definition.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-limit-default-definition.type.ts
index 27eeaeb6675..a856515d529 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-limit-default-definition.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-limit-default-definition.type.ts
@@ -1,9 +1,9 @@
import { type NumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/numeric-config-variable-key.type';
import { type AnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/types/anchored-period-unit.type';
-import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.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';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export type QuotaLimitDefaultDefinition<
TResourceType extends UsageResourceType = UsageResourceType,
@@ -13,7 +13,7 @@ export type QuotaLimitDefaultDefinition<
limitKind: 'quota';
spenderType: SpenderType;
spenderId: '';
- meter: QuotaMeter;
+ unit: UsageUnit;
periodUnit: AnchoredPeriodUnit;
periodCount: 1;
limitValueConfigVariable: NumericConfigVariableKey;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-meter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-meter.type.ts
deleted file mode 100644
index bdc9461d27b..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-meter.type.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { type QUOTA_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
-
-export type QuotaMeter = (typeof QUOTA_METERS)[number];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-limit-default-definition.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-limit-default-definition.type.ts
index 72837855e2a..2550c73891e 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-limit-default-definition.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-limit-default-definition.type.ts
@@ -1,9 +1,9 @@
import { type NumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/numeric-config-variable-key.type';
import { type CounterScope } from 'src/engine/core-modules/usage-limit/types/counter-scope.type';
-import { type SpeedMeter } from 'src/engine/core-modules/usage-limit/types/speed-meter.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.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';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export type SpeedLimitDefaultDefinition<
TResourceType extends UsageResourceType = UsageResourceType,
@@ -13,7 +13,7 @@ export type SpeedLimitDefaultDefinition<
limitKind: 'speed';
spenderType: SpenderType;
spenderId: '';
- meter: SpeedMeter;
+ unit: UsageUnit;
periodUnit: 'second';
windowMsConfigVariable: NumericConfigVariableKey;
limitValueConfigVariable: NumericConfigVariableKey;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-meter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-meter.type.ts
deleted file mode 100644
index 89a9b3b5e2e..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/speed-meter.type.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { type SPEED_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
-
-export type SpeedMeter = (typeof SPEED_METERS)[number];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-cost.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-cost.type.ts
index 94085ba28a5..9474f1f1b37 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-cost.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-cost.type.ts
@@ -1,3 +1,3 @@
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
-export type StockCost = Partial<Record<StockMeter, number>>;
+export type StockCost = Partial<Record<UsageUnit, number>>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-counter.type.ts
index eb30fd0d750..54f27ae1c69 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-counter.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-counter.type.ts
@@ -1,13 +1,13 @@
import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
import { type StockResourceType } from 'src/engine/core-modules/usage-limit/types/stock-resource-type.type';
export type StockCounter = {
key: string;
isDefault: boolean;
limitValue: number;
- meter: StockMeter;
+ unit: UsageUnit;
resourceType: StockResourceType;
operationType: UsageOperationType;
spenderType: SpenderType;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type.ts
index 415e7d60ceb..ac1db7e1fb0 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type.ts
@@ -1,8 +1,8 @@
import { type NumericConfigVariableKey } from 'src/engine/core-modules/twenty-config/types/numeric-config-variable-key.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-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';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export type StockLimitDefaultDefinition<
TResourceType extends UsageResourceType = UsageResourceType,
@@ -12,7 +12,7 @@ export type StockLimitDefaultDefinition<
limitKind: 'stock';
spenderType: SpenderType;
spenderId: '';
- meter: StockMeter;
+ unit: UsageUnit;
periodUnit: 'lifetime';
periodCount: 1;
limitValueConfigVariable: NumericConfigVariableKey;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default.type.ts
index 7a6dad2cfc1..24daf14ba75 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-limit-default.type.ts
@@ -2,7 +2,7 @@ import { type StockLimitDefaultDefinition } from 'src/engine/core-modules/usage-
export type StockLimitDefault = Pick<
StockLimitDefaultDefinition,
- 'spenderType' | 'meter' | 'isOverridable'
+ 'spenderType' | 'unit' | 'isOverridable'
> & {
limitValue: number;
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-meter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-meter.type.ts
deleted file mode 100644
index 1458f66bcdd..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/stock-meter.type.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { type STOCK_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
-
-export type StockMeter = (typeof STOCK_METERS)[number];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type.ts
index 8193316edd5..d4398ddfce1 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type.ts
@@ -9,6 +9,6 @@ export type UsageLimitCounterScope = Pick<
| 'spenderId'
| 'limitKind'
| 'periodUnit'
- | 'meter'
+ | 'unit'
| 'limitValue'
>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-definition.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-definition.type.ts
index 397a703bf81..3f69497a150 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-definition.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-definition.type.ts
@@ -1,29 +1,25 @@
import { type QuotaLimitDefaultDefinition } from 'src/engine/core-modules/usage-limit/types/quota-limit-default-definition.type';
-import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.type';
import { type SpeedLimitDefaultDefinition } from 'src/engine/core-modules/usage-limit/types/speed-limit-default-definition.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
import { type StockLimitDefaultDefinition } from 'src/engine/core-modules/usage-limit/types/stock-limit-default-definition.type';
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
-import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageLimitOperationDefinition } from 'src/engine/core-modules/usage-limit/types/usage-limit-operation-definition.type';
import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
type SpeedLimitDefinition<TResourceType extends UsageResourceType> = {
- allowedOperationTypes: UsageOperationType[];
+ allowedOperations: UsageLimitOperationDefinition[];
allowedSpenderTypes: SpenderType[];
defaults: SpeedLimitDefaultDefinition<TResourceType>[];
};
type QuotaLimitDefinition<TResourceType extends UsageResourceType> = {
- allowedOperationTypes: UsageOperationType[];
+ allowedOperations: UsageLimitOperationDefinition[];
allowedSpenderTypes: SpenderType[];
- allowedMeters: QuotaMeter[];
defaults: QuotaLimitDefaultDefinition<TResourceType>[];
};
type StockLimitDefinition<TResourceType extends UsageResourceType> = {
- allowedOperationTypes: UsageOperationType[];
+ allowedOperations: UsageLimitOperationDefinition[];
allowedSpenderTypes: SpenderType[];
- allowedMeters: StockMeter[];
defaults: StockLimitDefaultDefinition<TResourceType>[];
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-operation-definition.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-operation-definition.type.ts
new file mode 100644
index 00000000000..4f64a779c89
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-operation-definition.type.ts
@@ -0,0 +1,7 @@
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+
+export type UsageLimitOperationDefinition = {
+ operationType: UsageOperationType;
+ allowedUnits: UsageUnit[];
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-rest-response-body.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-rest-response-body.type.ts
index e2b4f0aaf22..5189a9964a4 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-rest-response-body.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-rest-response-body.type.ts
@@ -3,6 +3,7 @@ import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-
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 UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export type UsageLimitRestResponseBody = {
statusCode: number;
@@ -16,6 +17,7 @@ export type UsageLimitRestResponseBody = {
operationType: UsageOperationType;
};
limit: number;
+ unit?: UsageUnit;
remaining: number;
periodCount: number | null;
periodUnit: PeriodUnit | null;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-meter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-meter.type.ts
deleted file mode 100644
index 9f15e9cbc67..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-meter.type.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import { type USAGE_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
-
-export type UsageMeter = (typeof USAGE_METERS)[number];
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
index 3cc8fda7012..233611ac183 100644
--- 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
@@ -1,8 +1,8 @@
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';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export type UsageQuotaWithConsumption = {
id: string;
@@ -12,7 +12,7 @@ export type UsageQuotaWithConsumption = {
spenderId: string | null;
spenderLabel: string | null;
periodUnit: PeriodUnit;
- meter: UsageMeter;
+ unit: UsageUnit;
limitValue: number;
isEnforced: boolean;
consumedValue: number | null;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.entity.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.entity.ts
index 7c55cb8f0ae..aefb53d5d51 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.entity.ts
@@ -10,10 +10,10 @@ import {
import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
-import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
import { nullableBigintColumnTransformer } from 'src/engine/twenty-orm/utils/nullable-bigint-column-transformer.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 { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity.type';
@Unique('UQ_USAGE_LIMIT_SCOPE', [
@@ -25,7 +25,7 @@ import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/works
'limitKind',
'periodCount',
'periodUnit',
- 'meter',
+ 'unit',
])
@Entity({ name: 'usageLimit', schema: 'core' })
export class UsageLimitEntity extends WorkspaceRelatedEntity {
@@ -54,7 +54,7 @@ export class UsageLimitEntity extends WorkspaceRelatedEntity {
periodUnit: PeriodUnit;
@Column({ type: 'varchar' })
- meter: UsageMeter;
+ unit: UsageUnit;
@Column({ type: 'bigint', transformer: nullableBigintColumnTransformer })
limitValue: number;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/assert-usage-limit-default-override-is-allowed.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/assert-usage-limit-default-override-is-allowed.util.spec.ts
index 605931ed7b9..5b36802d6e5 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/assert-usage-limit-default-override-is-allowed.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/assert-usage-limit-default-override-is-allowed.util.spec.ts
@@ -6,6 +6,7 @@ import {
} 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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const buildScope = (
overrides: Partial<UsageLimitScope> = {},
@@ -18,7 +19,7 @@ const buildScope = (
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
...overrides,
});
@@ -54,7 +55,7 @@ describe('assertUsageLimitDefaultOverrideIsAllowed', () => {
spenderType: 'application',
limitKind: 'speed',
periodUnit: 'second',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
}),
isOperator: false,
}),
@@ -75,7 +76,7 @@ describe('assertUsageLimitDefaultOverrideIsAllowed', () => {
it('lets a workspace write on a scope no default covers', () => {
expect(() =>
assertUsageLimitDefaultOverrideIsAllowed({
- scope: buildScope({ meter: 'quantity' }),
+ scope: buildScope({ unit: UsageUnit.FILE }),
isOperator: false,
}),
).not.toThrow();
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
index f0fa043846d..b45528f318a 100644
--- 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
@@ -2,6 +2,7 @@ import { buildCustomQuota } from 'src/engine/core-modules/usage-limit/utils/buil
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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const MONTH_PERIOD = {
periodStart: new Date('2026-09-01T00:00:00.000Z'),
@@ -15,7 +16,7 @@ const buildUsageLimit = (overrides: Partial<UsageLimitEntity> = {}) => ({
spenderType: 'workspace' as const,
spenderId: '',
periodUnit: 'month' as const,
- meter: 'creditsUsedMicro' as const,
+ unit: UsageUnit.CREDIT,
limitValue: 1_000_000,
...overrides,
});
@@ -37,6 +38,7 @@ describe('buildCustomQuota', () => {
expect.objectContaining({
id: 'limit-1',
spenderId: null,
+ unit: UsageUnit.CREDIT,
consumedValue: 250_000,
remainingValue: 750_000,
periodEnd: MONTH_PERIOD.periodEnd,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-intra-workspace-limit-counter-keys.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-intra-workspace-limit-counter-keys.util.spec.ts
index f7924cda3e6..a75bede69e8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-intra-workspace-limit-counter-keys.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-intra-workspace-limit-counter-keys.util.spec.ts
@@ -2,6 +2,7 @@ import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/f
import { buildIntraWorkspaceLimitCounterKeys } from 'src/engine/core-modules/usage-limit/utils/build-intra-workspace-limit-counter-keys.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const MONTH_PERIOD = {
periodStart: new Date('2026-08-01T00:00:00.000Z'),
@@ -22,7 +23,7 @@ const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 1_000,
burstValue: null,
isInstanceOverride: false,
@@ -46,8 +47,8 @@ describe('buildIntraWorkspaceLimitCounterKeys', () => {
periodByUnit: { month: MONTH_PERIOD, week: WEEK_PERIOD },
}),
).toEqual([
- `{workspace-1}:quota:AI:ALL:userWorkspace:-:creditsUsedMicro:month:${MONTH_PERIOD.periodStart.getTime()}:1000`,
- `{workspace-1}:quota:AI:ALL:agent:agent-1:creditsUsedMicro:week:${WEEK_PERIOD.periodStart.getTime()}:1000`,
+ `{workspace-1}:quota:AI:ALL:userWorkspace:-:CREDIT:month:${MONTH_PERIOD.periodStart.getTime()}:1000`,
+ `{workspace-1}:quota:AI:ALL:agent:agent-1:CREDIT:week:${WEEK_PERIOD.periodStart.getTime()}:1000`,
]);
});
@@ -60,7 +61,7 @@ describe('buildIntraWorkspaceLimitCounterKeys', () => {
buildLimit({
limitKind: 'speed',
periodUnit: 'second',
- meter: 'quantity',
+ unit: UsageUnit.TOKEN,
}),
],
periodByUnit: { month: MONTH_PERIOD },
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 63c683f0781..c8b44a6b8a9 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
@@ -15,7 +15,7 @@ const buildCounter = (
isDefault: false,
key: 'counter-key',
limitValue: 1_000,
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
resourceType: UsageResourceType.AI,
periodUnit: 'month',
periodStart: new Date('2026-08-01T00:00:00.000Z'),
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-overridden-quota-default-counter-keys.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-overridden-quota-default-counter-keys.util.spec.ts
index 1419bcd72bc..5f321181671 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-overridden-quota-default-counter-keys.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-overridden-quota-default-counter-keys.util.spec.ts
@@ -5,13 +5,14 @@ import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usag
import { buildOverriddenQuotaDefaultCounterKeys } from 'src/engine/core-modules/usage-limit/utils/build-overridden-quota-default-counter-keys.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const DAY_PERIOD = {
periodStart: new Date('2026-08-20T00:00:00.000Z'),
periodEnd: new Date('2026-08-21T00:00:00.000Z'),
};
-const DEFAULT_COUNTER_KEY = `{workspace-1}:quota:EMAIL:EMAIL_SEND:workspace:-:quantity:day:${DAY_PERIOD.periodStart.getTime()}:1000:default`;
+const DEFAULT_COUNTER_KEY = `{workspace-1}:quota:EMAIL:EMAIL_SEND:workspace:-:INVOCATION:day:${DAY_PERIOD.periodStart.getTime()}:1000:default`;
const buildUsageLimit = (
overrides: Partial<UsageLimitCounterScope> = {},
@@ -23,7 +24,7 @@ const buildUsageLimit = (
spenderId: '',
limitKind: 'quota',
periodUnit: 'day',
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
limitValue: 500,
...overrides,
});
@@ -36,7 +37,7 @@ const buildDefault = (
limitKind: 'quota',
spenderType: 'workspace',
spenderId: '',
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
periodUnit: 'day',
periodCount: 1,
isOverridable: true,
@@ -72,7 +73,7 @@ describe('buildOverriddenQuotaDefaultCounterKeys', () => {
it.each([
{ spenderType: 'userWorkspace' as const },
- { meter: 'creditsUsedMicro' as const },
+ { unit: UsageUnit.CREDIT },
{ operationType: UsageOperationType.ALL },
])('leaves a default on another scope alone: %j', (overrides) => {
expect(buildKeys({ usageLimit: buildUsageLimit(overrides) })).toEqual([]);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counter-key.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counter-key.util.spec.ts
index 440cbe36c3f..87423a66999 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counter-key.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counter-key.util.spec.ts
@@ -1,6 +1,7 @@
import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const WORKSPACE_ID = 'workspace-1';
const PERIOD_START = new Date('2026-09-01T00:00:00.000Z');
@@ -14,7 +15,7 @@ const buildKey = (
operationType: UsageOperationType.AI_CHAT_TOKEN,
spenderType: 'workspace',
spenderId: null,
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
periodUnit: 'month',
periodStart: PERIOD_START,
limitValue: 1000,
@@ -24,13 +25,13 @@ const buildKey = (
describe('buildQuotaCounterKey', () => {
it('hashes on the workspace so every counter of a workspace shares a slot', () => {
expect(buildKey()).toBe(
- `{${WORKSPACE_ID}}:quota:AI:AI_CHAT_TOKEN:workspace:-:creditsUsedMicro:month:${PERIOD_START.getTime()}:1000`,
+ `{${WORKSPACE_ID}}:quota:AI:AI_CHAT_TOKEN:workspace:-:CREDIT:month:${PERIOD_START.getTime()}:1000`,
);
});
it.each([
['operationType', { operationType: UsageOperationType.WEB_SEARCH }],
- ['meter', { meter: 'quantity' as const }],
+ ['unit', { unit: UsageUnit.TOKEN }],
['spenderId', { spenderId: 'user-1' }],
['periodUnit', { periodUnit: 'week' as const }],
['periodStart', { periodStart: new Date('2026-10-01T00:00:00.000Z') }],
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 60bc6af98ba..d7309fdeb80 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
@@ -3,6 +3,7 @@ import { type QuotaLimitDefault } from 'src/engine/core-modules/usage-limit/type
import { buildQuotaCounters } from 'src/engine/core-modules/usage-limit/utils/build-quota-counters.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const MONTH_PERIOD = {
periodStart: new Date('2026-08-01T00:00:00.000Z'),
@@ -23,7 +24,7 @@ const buildLimit = (overrides: Partial<FlatQuotaLimit>): FlatQuotaLimit => ({
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 1_000_000,
burstValue: null,
isInstanceOverride: false,
@@ -38,7 +39,7 @@ const buildDefault = (
limitKind: 'quota',
spenderType: 'workspace',
spenderId: '',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
periodUnit: 'month',
periodCount: 1,
isOverridable: true,
@@ -72,9 +73,9 @@ describe('buildQuotaCounters', () => {
{
kind: 'limit',
isDefault: false,
- key: `{workspace-1}:quota:AI:AI_CHAT_TOKEN:workspace:-:creditsUsedMicro:month:${MONTH_PERIOD.periodStart.getTime()}:1000000`,
+ key: `{workspace-1}:quota:AI:AI_CHAT_TOKEN:workspace:-:CREDIT:month:${MONTH_PERIOD.periodStart.getTime()}:1000000`,
limitValue: 1_000_000,
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
resourceType: UsageResourceType.AI,
periodUnit: 'month',
periodStart: MONTH_PERIOD.periodStart,
@@ -167,9 +168,9 @@ describe('buildQuotaCounters', () => {
{
kind: 'limit',
isDefault: true,
- key: `{workspace-1}:quota:AI:AI_CHAT_TOKEN:workspace:-:creditsUsedMicro:month:${MONTH_PERIOD.periodStart.getTime()}:5000:default`,
+ key: `{workspace-1}:quota:AI:AI_CHAT_TOKEN:workspace:-:CREDIT:month:${MONTH_PERIOD.periodStart.getTime()}:5000:default`,
limitValue: 5_000,
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
resourceType: UsageResourceType.AI,
periodUnit: 'month',
periodStart: MONTH_PERIOD.periodStart,
@@ -207,7 +208,7 @@ describe('buildQuotaCounters', () => {
it.each([
{ spenderType: 'userWorkspace' as const, spenderId: 'user-1' },
- { meter: 'quantity' as const },
+ { unit: UsageUnit.TOKEN },
])('preserves the default for a different scope: %j', (overrides) => {
const counters = buildCounters({
limits: [buildLimit(overrides)],
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
new file mode 100644
index 00000000000..6e9357bcf16
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-debits.util.spec.ts
@@ -0,0 +1,87 @@
+import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { buildQuotaDebits } from 'src/engine/core-modules/usage-limit/utils/build-quota-debits.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+
+const PERIOD_START = new Date('2026-08-01T00:00:00.000Z');
+const PERIOD_END = new Date('2026-09-01T00:00:00.000Z');
+
+const allowanceCounter: AllowanceQuotaCounter = {
+ kind: 'allowance',
+ key: 'allowance',
+ unit: UsageUnit.CREDIT,
+ periodStart: PERIOD_START,
+ periodEnd: PERIOD_END,
+};
+
+const buildLimitCounter = (unit: UsageUnit): LimitQuotaCounter => ({
+ kind: 'limit',
+ isDefault: false,
+ key: unit,
+ limitValue: 1_000,
+ unit,
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ periodUnit: 'month',
+ periodStart: PERIOD_START,
+ periodEnd: PERIOD_END,
+ spenderType: 'workspace',
+ spenderId: null,
+});
+
+describe('buildQuotaDebits', () => {
+ it('debits each counter the amount of its own unit', () => {
+ const creditCounter = buildLimitCounter(UsageUnit.CREDIT);
+ const invocationCounter = buildLimitCounter(UsageUnit.INVOCATION);
+
+ expect(
+ buildQuotaDebits({
+ counters: [allowanceCounter, creditCounter, invocationCounter],
+ cost: {
+ [UsageUnit.CREDIT]: 2_500,
+ [UsageUnit.INVOCATION]: 1,
+ [UsageUnit.MILLISECOND]: 15_000,
+ },
+ }),
+ ).toEqual([
+ { counter: allowanceCounter, amount: 2_500 },
+ { counter: creditCounter, amount: 2_500 },
+ { counter: invocationCounter, amount: 1 },
+ ]);
+ });
+
+ it('drops a counter whose unit the cost leaves out', () => {
+ expect(
+ buildQuotaDebits({
+ counters: [buildLimitCounter(UsageUnit.TOKEN)],
+ cost: { [UsageUnit.CREDIT]: 2_500, [UsageUnit.INVOCATION]: 1 },
+ }),
+ ).toEqual([]);
+ });
+
+ it('drops a counter whose unit costs zero', () => {
+ expect(
+ buildQuotaDebits({
+ counters: [buildLimitCounter(UsageUnit.INVOCATION)],
+ cost: { [UsageUnit.CREDIT]: 2_500, [UsageUnit.INVOCATION]: 0 },
+ }),
+ ).toEqual([]);
+ });
+
+ it('debits only the run counter for an exempt run, leaving the allowance alone', () => {
+ const invocationCounter = buildLimitCounter(UsageUnit.INVOCATION);
+
+ expect(
+ buildQuotaDebits({
+ counters: [allowanceCounter, invocationCounter],
+ cost: {
+ [UsageUnit.CREDIT]: 0,
+ [UsageUnit.INVOCATION]: 1,
+ [UsageUnit.MILLISECOND]: 0,
+ },
+ }),
+ ).toEqual([{ counter: invocationCounter, amount: 1 }]);
+ });
+});
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
index b9db3050122..913f214b229 100644
--- 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
@@ -1,5 +1,12 @@
import { buildQuotaDefinitions } from 'src/engine/core-modules/usage-limit/utils/build-quota-definitions.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+
+const findQuotaDefinition = (resourceType: UsageResourceType) =>
+ buildQuotaDefinitions().find(
+ (definition) => definition.resourceType === resourceType,
+ );
describe('buildQuotaDefinitions', () => {
it('exposes only resources with quota definitions', () => {
@@ -21,8 +28,41 @@ describe('buildQuotaDefinitions', () => {
(definition) => definition.limitKind === 'quota',
);
- expect(quota?.allowedOperationTypes.length).toBeGreaterThan(0);
+ expect(quota?.allowedOperations.length).toBeGreaterThan(0);
expect(quota?.allowedSpenderTypes).toContain('workspace');
- expect(quota?.allowedMeters).toContain('creditsUsedMicro');
+ });
+
+ it('lists every operation first, counted in credits only, when a resource has several', () => {
+ expect(
+ findQuotaDefinition(UsageResourceType.AI)?.allowedOperations,
+ ).toEqual([
+ {
+ operationType: UsageOperationType.ALL,
+ allowedUnits: [UsageUnit.CREDIT],
+ },
+ {
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.TOKEN],
+ },
+ {
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.TOKEN],
+ },
+ {
+ operationType: UsageOperationType.WEB_SEARCH,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
+ ]);
+ });
+
+ it('offers credits and runs on code execution, with no every-operation entry', () => {
+ expect(
+ findQuotaDefinition(UsageResourceType.LOGIC_FUNCTION)?.allowedOperations,
+ ).toEqual([
+ {
+ operationType: UsageOperationType.CODE_EXECUTION,
+ allowedUnits: [UsageUnit.CREDIT, UsageUnit.INVOCATION],
+ },
+ ]);
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
index 2b9577c5529..031c50263f5 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
@@ -3,6 +3,7 @@ import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/type
import { buildQuotaExhaustedScope } from 'src/engine/core-modules/usage-limit/utils/build-quota-exhausted-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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const NOW = new Date('2026-08-20T00:00:00.000Z');
const PERIOD_START = new Date('2026-08-01T00:00:00.000Z');
@@ -15,7 +16,7 @@ const buildLimitCounter = (
isDefault: false,
key: 'counter-key',
limitValue: 1_000,
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
resourceType: UsageResourceType.AI,
periodUnit: 'month',
periodStart: PERIOD_START,
@@ -29,7 +30,7 @@ const buildLimitCounter = (
const allowanceCounter: AllowanceQuotaCounter = {
kind: 'allowance',
key: 'allowance-key',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
periodStart: PERIOD_START,
periodEnd: PERIOD_END,
};
@@ -57,6 +58,7 @@ describe('buildQuotaExhaustedScope', () => {
spenderType: 'userWorkspace',
spenderId: 'user-1',
operationType: UsageOperationType.AI_CHAT_TOKEN,
+ unit: UsageUnit.CREDIT,
limitValue: 1_000,
remaining: 0,
periodCount: 1,
@@ -95,6 +97,7 @@ describe('buildQuotaExhaustedScope', () => {
spenderType: 'workspace',
spenderId: null,
operationType: UsageOperationType.ALL,
+ unit: UsageUnit.CREDIT,
limitValue: 2_000_000,
remaining: 0,
periodCount: null,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts
index 1484019260d..e668724099a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-speed-buckets.util.spec.ts
@@ -1,6 +1,7 @@
import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type SpeedLimitDefault } from 'src/engine/core-modules/usage-limit/types/speed-limit-default.type';
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
import { buildSpeedBuckets } from 'src/engine/core-modules/usage-limit/utils/build-speed-buckets.util';
@@ -42,7 +43,7 @@ const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
limitKind: 'speed',
periodCount: 60,
periodUnit: 'second',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
limitValue: 100,
burstValue: null,
isInstanceOverride: false,
@@ -97,7 +98,7 @@ const systemContext = { type: 'system', workspace } as WorkspaceAuthContext;
// workspace-wide counter and applications against a cross-workspace one, and
// left every other caller alone.
describe('buildSpeedBuckets with no limits configured', () => {
- it('meters an api key against one shared counter per window', () => {
+ it('counts an api key against one shared counter per window', () => {
expect(buildBuckets({ authContext: apiKeyContext })).toEqual([
expect.objectContaining({
key: '{workspace-1}:speed:API:API_REQUEST:apiKey:-:1',
@@ -113,7 +114,7 @@ describe('buildSpeedBuckets with no limits configured', () => {
]);
});
- it('meters an application against one counter across every workspace', () => {
+ it('counts an application against one counter across every workspace', () => {
expect(buildBuckets({ authContext: applicationContext })).toEqual([
expect.objectContaining({
key: '{server}:speed:API:API_REQUEST:application:app-uid:60',
@@ -148,7 +149,7 @@ describe('buildSpeedBuckets for a spender no application identifies', () => {
},
];
- it('meters a system sender against one counter across every workspace', () => {
+ it('counts a system sender against one counter across every workspace', () => {
expect(
buildBuckets({
authContext: systemContext,
@@ -164,7 +165,7 @@ describe('buildSpeedBuckets for a spender no application identifies', () => {
]);
});
- it('meters a user request against that same counter', () => {
+ it('counts a user request against that same counter', () => {
const [bucket] = buildBuckets({
authContext: userContext,
speedLimitDefaults: WORKSPACE_DEFAULTS,
@@ -310,7 +311,7 @@ describe('buildSpeedBuckets with limits configured', () => {
spenderId: '',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
}),
],
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counter-key.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counter-key.util.spec.ts
index 57668ddd508..c69b889317e 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counter-key.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counter-key.util.spec.ts
@@ -1,6 +1,7 @@
import { buildStockCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-counter-key.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const WORKSPACE_ID = 'workspace-1';
@@ -13,7 +14,7 @@ const buildKey = (
operationType: UsageOperationType.STORAGE_FILE,
spenderType: 'workspace',
spenderId: null,
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
limitValue: 1000,
...overrides,
});
@@ -21,19 +22,19 @@ const buildKey = (
describe('buildStockCounterKey', () => {
it('hashes on the workspace so every counter of a workspace shares a slot', () => {
expect(buildKey()).toBe(
- `{${WORKSPACE_ID}}:stock:STORAGE:STORAGE_FILE:workspace:-:bytes:1000`,
+ `{${WORKSPACE_ID}}:stock:STORAGE:STORAGE_FILE:workspace:-:BYTE:1000`,
);
});
it('names an absent spender rather than leaving the segment empty', () => {
expect(buildKey({ spenderType: 'application', spenderId: 'app-1' })).toBe(
- `{${WORKSPACE_ID}}:stock:STORAGE:STORAGE_FILE:application:app-1:bytes:1000`,
+ `{${WORKSPACE_ID}}:stock:STORAGE:STORAGE_FILE:application:app-1:BYTE:1000`,
);
});
it.each([
['operationType', { operationType: UsageOperationType.CALL_RECORDING }],
- ['meter', { meter: 'quantity' as const }],
+ ['unit', { unit: UsageUnit.FILE }],
['spenderId', { spenderId: 'app-1' }],
['limitValue', { limitValue: 2000 }],
])(
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counters.util.spec.ts
index b1fe6eba1ae..0e53dca2f57 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counters.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-counters.util.spec.ts
@@ -3,6 +3,7 @@ import { type StockLimitDefault } from 'src/engine/core-modules/usage-limit/type
import { buildStockCounters } from 'src/engine/core-modules/usage-limit/utils/build-stock-counters.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const WORKSPACE_ID = 'workspace-1';
@@ -17,7 +18,7 @@ const buildLimit = (
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
limitValue: 500,
burstValue: null,
isInstanceOverride: false,
@@ -28,7 +29,7 @@ const buildDefault = (
overrides: Partial<StockLimitDefault> = {},
): StockLimitDefault => ({
spenderType: 'workspace',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
limitValue: 1_000,
isOverridable: true,
...overrides,
@@ -58,7 +59,7 @@ describe('buildStockCounters', () => {
expect.objectContaining({
isDefault: true,
limitValue: 1_000,
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
spenderType: 'workspace',
spenderId: null,
}),
@@ -89,7 +90,7 @@ describe('buildStockCounters', () => {
it.each([
{ spenderType: 'application' as const, spenderId: 'application-1' },
- { meter: 'quantity' as const },
+ { unit: UsageUnit.FILE },
])(
'preserves the workspace byte default for a different scope: %j',
(overrides) => {
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-warmed-entries.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-warmed-entries.util.spec.ts
index 178c1c0b249..809b82026a0 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-warmed-entries.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-stock-warmed-entries.util.spec.ts
@@ -3,14 +3,15 @@ import { buildStockScopeKey } from 'src/engine/core-modules/usage-limit/utils/bu
import { buildStockWarmedEntries } from 'src/engine/core-modules/usage-limit/utils/build-stock-warmed-entries.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const TTL = 1_000;
const buildCounter = (overrides: Partial<StockCounter> = {}): StockCounter => ({
- key: 'stock:bytes',
+ key: 'stock:BYTE',
isDefault: false,
limitValue: 1_000,
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
resourceType: UsageResourceType.STORAGE,
operationType: UsageOperationType.STORAGE_FILE,
spenderType: 'workspace',
@@ -26,17 +27,20 @@ describe('buildStockWarmedEntries', () => {
buildStockWarmedEntries({
coldCounters: [counter],
usedByScope: new Map([
- [buildStockScopeKey(counter), { bytes: 400, quantity: 2 }],
+ [
+ buildStockScopeKey(counter),
+ { [UsageUnit.BYTE]: 400, [UsageUnit.FILE]: 2 },
+ ],
]),
ttl: TTL,
}),
- ).toEqual([{ key: 'stock:bytes', value: 600, ttl: TTL }]);
+ ).toEqual([{ key: 'stock:BYTE', value: 600, ttl: TTL }]);
});
- it('reads each counter against its own meter', () => {
+ it('reads each counter against its own unit', () => {
const counter = buildCounter({
- key: 'stock:quantity',
- meter: 'quantity',
+ key: 'stock:FILE',
+ unit: UsageUnit.FILE,
limitValue: 5,
});
@@ -44,11 +48,57 @@ describe('buildStockWarmedEntries', () => {
buildStockWarmedEntries({
coldCounters: [counter],
usedByScope: new Map([
- [buildStockScopeKey(counter), { bytes: 400, quantity: 2 }],
+ [
+ buildStockScopeKey(counter),
+ { [UsageUnit.BYTE]: 400, [UsageUnit.FILE]: 2 },
+ ],
]),
ttl: TTL,
}),
- ).toEqual([{ key: 'stock:quantity', value: 3, ttl: TTL }]);
+ ).toEqual([{ key: 'stock:FILE', value: 3, ttl: TTL }]);
+ });
+
+ it('warms counters of different units on the same scope from one read', () => {
+ const byteCounter = buildCounter();
+ const fileCounter = buildCounter({
+ key: 'stock:FILE',
+ unit: UsageUnit.FILE,
+ limitValue: 5,
+ });
+
+ expect(
+ buildStockWarmedEntries({
+ coldCounters: [byteCounter, fileCounter],
+ usedByScope: new Map([
+ [
+ buildStockScopeKey(byteCounter),
+ { [UsageUnit.BYTE]: 400, [UsageUnit.FILE]: 2 },
+ ],
+ ]),
+ ttl: TTL,
+ }),
+ ).toEqual([
+ { key: 'stock:BYTE', value: 600, ttl: TTL },
+ { key: 'stock:FILE', value: 3, ttl: TTL },
+ ]);
+ });
+
+ it('leaves a counter cold when its unit was not counted', () => {
+ const counter = buildCounter({
+ key: 'stock:FILE',
+ unit: UsageUnit.FILE,
+ limitValue: 5,
+ });
+
+ expect(
+ buildStockWarmedEntries({
+ coldCounters: [counter],
+ usedByScope: new Map([
+ [buildStockScopeKey(counter), { [UsageUnit.BYTE]: 400 }],
+ ]),
+ ttl: TTL,
+ }),
+ ).toEqual([]);
});
it('warms a lowered limit into the red rather than clamping it', () => {
@@ -58,11 +108,14 @@ describe('buildStockWarmedEntries', () => {
buildStockWarmedEntries({
coldCounters: [counter],
usedByScope: new Map([
- [buildStockScopeKey(counter), { bytes: 900, quantity: 4 }],
+ [
+ buildStockScopeKey(counter),
+ { [UsageUnit.BYTE]: 900, [UsageUnit.FILE]: 4 },
+ ],
]),
ttl: TTL,
}),
- ).toEqual([{ key: 'stock:bytes', value: -400, ttl: TTL }]);
+ ).toEqual([{ key: 'stock:BYTE', value: -400, ttl: TTL }]);
});
it('skips a counter whose scope was never counted', () => {
@@ -78,7 +131,7 @@ describe('buildStockWarmedEntries', () => {
it('warms each spender from its own scope', () => {
const workspaceCounter = buildCounter();
const applicationCounter = buildCounter({
- key: 'stock:application:bytes',
+ key: 'stock:application:BYTE',
spenderType: 'application',
spenderId: 'application-1',
limitValue: 800,
@@ -88,14 +141,20 @@ describe('buildStockWarmedEntries', () => {
buildStockWarmedEntries({
coldCounters: [workspaceCounter, applicationCounter],
usedByScope: new Map([
- [buildStockScopeKey(workspaceCounter), { bytes: 400, quantity: 2 }],
- [buildStockScopeKey(applicationCounter), { bytes: 100, quantity: 1 }],
+ [
+ buildStockScopeKey(workspaceCounter),
+ { [UsageUnit.BYTE]: 400, [UsageUnit.FILE]: 2 },
+ ],
+ [
+ buildStockScopeKey(applicationCounter),
+ { [UsageUnit.BYTE]: 100, [UsageUnit.FILE]: 1 },
+ ],
]),
ttl: TTL,
}),
).toEqual([
- { key: 'stock:bytes', value: 600, ttl: TTL },
- { key: 'stock:application:bytes', value: 700, ttl: TTL },
+ { key: 'stock:BYTE', value: 600, ttl: TTL },
+ { key: 'stock:application:BYTE', value: 700, ttl: TTL },
]);
});
});
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
index 49d36289973..d1a08ffd63b 100644
--- 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
@@ -2,6 +2,7 @@ import { type CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/
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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const buildInput = (
overrides: Partial<CreateUsageLimitInput> = {},
@@ -13,7 +14,7 @@ const buildInput = (
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 1_000_000,
burstValue: null,
...overrides,
@@ -29,7 +30,7 @@ describe('buildUsageLimitScope', () => {
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
});
});
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 a10cee8152a..c1cc285d773 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
@@ -28,7 +28,7 @@ const buildCounter = (
isDefault: false,
key: 'counter-key',
limitValue: 1_000,
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
resourceType: UsageResourceType.AI,
periodUnit: 'month',
periodStart: new Date('2026-08-01T00:00:00.000Z'),
@@ -56,7 +56,7 @@ const rows = [
];
describe('computeQuotaConsumed', () => {
- it('sums every row for a workspace scope with no operation', () => {
+ it('sums the credits of every operation for a credit counter on every operation', () => {
expect(computeQuotaConsumed({ rows, scope: buildCounter({}) })).toBe(147);
});
@@ -95,11 +95,27 @@ describe('computeQuotaConsumed', () => {
).toBe(140);
});
- it('sums the quantity column when the counter meters on it', () => {
+ it('sums the token quantity of every operation for a token counter', () => {
expect(
computeQuotaConsumed({
rows,
- scope: buildCounter({ meter: 'quantity' }),
+ scope: buildCounter({ unit: UsageUnit.TOKEN }),
+ }),
+ ).toBe(23);
+ });
+
+ it('leaves rows of another unit out of a token counter', () => {
+ expect(
+ computeQuotaConsumed({
+ rows: [
+ ...rows,
+ buildRow({
+ operationType: UsageOperationType.WEB_SEARCH,
+ unit: UsageUnit.INVOCATION,
+ quantity: '5',
+ }),
+ ],
+ scope: buildCounter({ unit: UsageUnit.TOKEN }),
}),
).toBe(23);
});
@@ -170,13 +186,31 @@ describe('computeQuotaConsumed', () => {
).toBe(3150);
});
- it('sums the quantity of both units', () => {
+ it('counts the run once on an INVOCATION counter', () => {
expect(
computeQuotaConsumed({
rows: logicFunctionRunRows,
- scope: { ...logicFunctionScope, meter: 'quantity' },
+ scope: { ...logicFunctionScope, unit: UsageUnit.INVOCATION },
}),
- ).toBe(1501);
+ ).toBe(1);
});
});
+
+ it('counts the credits of a credit-unit row, never its quantity', () => {
+ expect(
+ computeQuotaConsumed({
+ rows: [
+ buildRow({
+ operationType: UsageOperationType.SUBSCRIPTION,
+ unit: UsageUnit.CREDIT,
+ userWorkspaceId: '',
+ applicationId: 'application-1',
+ quantity: '1',
+ creditsUsedMicro: '20000000',
+ }),
+ ],
+ scope: buildCounter({}),
+ }),
+ ).toBe(20_000_000);
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts
index a345e5e1472..2fb1e3fde83 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/does-usage-limit-row-suppress-default.util.spec.ts
@@ -6,6 +6,7 @@ import {
import { doesUsageLimitRowSuppressDefault } from 'src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const buildDefault = (
overrides: Partial<StockLimitDefaultDefinition> = {},
@@ -15,7 +16,7 @@ const buildDefault = (
limitKind: 'stock',
spenderType: 'workspace',
spenderId: '',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
periodUnit: 'lifetime',
periodCount: 1,
limitValueConfigVariable: 'WORKSPACE_STORAGE_LIMIT_BYTES',
@@ -34,7 +35,7 @@ const buildScope = (
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
...overrides,
});
@@ -69,7 +70,7 @@ describe('doesUsageLimitRowSuppressDefault', () => {
});
it.each([
- ['meter', { meter: 'quantity' } as Partial<UsageLimitScope>],
+ ['unit', { unit: UsageUnit.FILE } as Partial<UsageLimitScope>],
[
'spender type',
{ spenderType: 'application' } as Partial<UsageLimitScope>,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-enforceable-limits.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-enforceable-limits.util.spec.ts
index d49c684d54f..8a58e11995b 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-enforceable-limits.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-enforceable-limits.util.spec.ts
@@ -3,6 +3,7 @@ import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spen
import { findEnforceableLimits } from 'src/engine/core-modules/usage-limit/utils/find-enforceable-limits.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const buildLimit = (
spenderType: SpenderType,
@@ -17,7 +18,7 @@ const buildLimit = (
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
limitValue: 100,
burstValue: null,
isInstanceOverride,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.ts
index 691083c96bb..0529e5a7cd1 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counters.util.spec.ts
@@ -3,6 +3,7 @@ import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/type
import { findExhaustedCounters } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counters.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const PERIOD_START = new Date('2026-08-01T00:00:00.000Z');
const PERIOD_END = new Date('2026-09-01T00:00:00.000Z');
@@ -10,17 +11,20 @@ const PERIOD_END = new Date('2026-09-01T00:00:00.000Z');
const buildAllowanceCounter = (key: string): AllowanceQuotaCounter => ({
kind: 'allowance',
key,
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
periodStart: PERIOD_START,
periodEnd: PERIOD_END,
});
-const buildLimitCounter = (key: string): LimitQuotaCounter => ({
+const buildLimitCounter = (
+ key: string,
+ overrides: Partial<LimitQuotaCounter> = {},
+): LimitQuotaCounter => ({
kind: 'limit',
isDefault: false,
key,
limitValue: 1_000,
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
resourceType: UsageResourceType.AI,
operationType: UsageOperationType.AI_CHAT_TOKEN,
periodUnit: 'month',
@@ -28,6 +32,7 @@ const buildLimitCounter = (key: string): LimitQuotaCounter => ({
periodEnd: PERIOD_END,
spenderType: 'workspace',
spenderId: null,
+ ...overrides,
});
describe('findExhaustedCounters', () => {
@@ -91,7 +96,7 @@ describe('findExhaustedCounters', () => {
findExhaustedCounters({
counters: [buildLimitCounter('first')],
remainings: [100],
- cost: { creditsUsedMicro: 101, quantity: 0 },
+ cost: { [UsageUnit.CREDIT]: 101, [UsageUnit.TOKEN]: 0 },
}),
).toMatchObject([{ key: 'first' }]);
});
@@ -101,17 +106,27 @@ describe('findExhaustedCounters', () => {
findExhaustedCounters({
counters: [buildLimitCounter('first')],
remainings: [100],
- cost: { creditsUsedMicro: 100, quantity: 0 },
+ cost: { [UsageUnit.CREDIT]: 100, [UsageUnit.TOKEN]: 0 },
}),
).toEqual([]);
});
- it('charges a limit only for the meter it counts', () => {
+ it('charges a limit only for the unit it counts', () => {
expect(
findExhaustedCounters({
counters: [buildLimitCounter('first')],
remainings: [10],
- cost: { creditsUsedMicro: 0, quantity: 500 },
+ cost: { [UsageUnit.CREDIT]: 0, [UsageUnit.TOKEN]: 500 },
+ }),
+ ).toEqual([]);
+ });
+
+ it('counts a unit missing from the cost as zero', () => {
+ expect(
+ findExhaustedCounters({
+ counters: [buildLimitCounter('first', { unit: UsageUnit.TOKEN })],
+ remainings: [10],
+ cost: { [UsageUnit.CREDIT]: 5_000 },
}),
).toEqual([]);
});
@@ -121,7 +136,7 @@ describe('findExhaustedCounters', () => {
findExhaustedCounters({
counters: [buildLimitCounter('first')],
remainings: [0],
- cost: { creditsUsedMicro: 0, quantity: 0 },
+ cost: { [UsageUnit.CREDIT]: 0, [UsageUnit.TOKEN]: 0 },
}),
).toMatchObject([{ key: 'first' }]);
});
@@ -131,7 +146,7 @@ describe('findExhaustedCounters', () => {
findExhaustedCounters({
counters: [buildAllowanceCounter('allowance')],
remainings: [10],
- cost: { creditsUsedMicro: 5_000, quantity: 100 },
+ cost: { [UsageUnit.CREDIT]: 5_000, [UsageUnit.TOKEN]: 100 },
}),
).toMatchObject([{ key: 'allowance' }]);
});
@@ -141,7 +156,7 @@ describe('findExhaustedCounters', () => {
findExhaustedCounters({
counters: [buildAllowanceCounter('allowance')],
remainings: [5_000],
- cost: { creditsUsedMicro: 5_000, quantity: 100 },
+ cost: { [UsageUnit.CREDIT]: 5_000, [UsageUnit.TOKEN]: 100 },
}),
).toEqual([]);
});
@@ -151,7 +166,7 @@ describe('findExhaustedCounters', () => {
findExhaustedCounters({
counters: [buildAllowanceCounter('allowance')],
remainings: [0],
- cost: { creditsUsedMicro: 5_000, quantity: 100 },
+ cost: { [UsageUnit.CREDIT]: 5_000, [UsageUnit.TOKEN]: 100 },
}),
).toMatchObject([{ key: 'allowance' }]);
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-stock-counter.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-stock-counter.util.spec.ts
index e527a380b14..fa3e565c0ad 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-stock-counter.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-stock-counter.util.spec.ts
@@ -2,12 +2,13 @@ import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/sto
import { findExhaustedStockCounter } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const buildCounter = (overrides: Partial<StockCounter> = {}): StockCounter => ({
- key: 'stock:bytes',
+ key: 'stock:BYTE',
isDefault: false,
limitValue: 1_000,
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
resourceType: UsageResourceType.STORAGE,
operationType: UsageOperationType.STORAGE_FILE,
spenderType: 'workspace',
@@ -21,7 +22,7 @@ describe('findExhaustedStockCounter', () => {
findExhaustedStockCounter({
counters: [buildCounter()],
remainings: [250],
- cost: { bytes: 250 },
+ cost: { [UsageUnit.BYTE]: 250 },
}),
).toBeNull();
});
@@ -33,7 +34,7 @@ describe('findExhaustedStockCounter', () => {
findExhaustedStockCounter({
counters: [counter],
remainings: [250],
- cost: { bytes: 251 },
+ cost: { [UsageUnit.BYTE]: 251 },
}),
).toEqual({ counter, remaining: 250 });
});
@@ -41,9 +42,9 @@ describe('findExhaustedStockCounter', () => {
it('admits a counter the cost does not touch', () => {
expect(
findExhaustedStockCounter({
- counters: [buildCounter({ meter: 'quantity' })],
+ counters: [buildCounter({ unit: UsageUnit.FILE })],
remainings: [0],
- cost: { bytes: 400 },
+ cost: { [UsageUnit.BYTE]: 400 },
}),
).toBeNull();
});
@@ -53,7 +54,7 @@ describe('findExhaustedStockCounter', () => {
findExhaustedStockCounter({
counters: [buildCounter()],
remainings: [null],
- cost: { bytes: 400 },
+ cost: { [UsageUnit.BYTE]: 400 },
}),
).toBeNull();
});
@@ -63,24 +64,24 @@ describe('findExhaustedStockCounter', () => {
findExhaustedStockCounter({
counters: [buildCounter()],
remainings: [-10],
- cost: { bytes: 1 },
+ cost: { [UsageUnit.BYTE]: 1 },
}),
).toMatchObject({ remaining: -10 });
});
it('keeps looking past a counter the cost fits in', () => {
- const quantityCounter = buildCounter({
- key: 'stock:quantity',
- meter: 'quantity',
+ const fileCounter = buildCounter({
+ key: 'stock:FILE',
+ unit: UsageUnit.FILE,
limitValue: 5,
});
expect(
findExhaustedStockCounter({
- counters: [buildCounter(), quantityCounter],
+ counters: [buildCounter(), fileCounter],
remainings: [500, 0],
- cost: { bytes: 400, quantity: 1 },
+ cost: { [UsageUnit.BYTE]: 400, [UsageUnit.FILE]: 1 },
}),
- ).toEqual({ counter: quantityCounter, remaining: 0 });
+ ).toEqual({ counter: fileCounter, remaining: 0 });
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-limits-for-spender.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-limits-for-spender.util.spec.ts
index ecb2f720cbd..47706e1d596 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-limits-for-spender.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-limits-for-spender.util.spec.ts
@@ -1,5 +1,6 @@
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
import { findLimitsForSpender } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util';
@@ -12,7 +13,7 @@ const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
limitKind: 'speed',
periodCount: 60,
periodUnit: 'second',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.REQUEST,
limitValue: 100,
burstValue: null,
isInstanceOverride: false,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts
index e3ca2fd32b6..e7cb95fce16 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-suppressed-usage-limit-defaults.util.spec.ts
@@ -6,6 +6,7 @@ import {
import { findSuppressedUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/utils/find-suppressed-usage-limit-defaults.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const buildSpeedScope = (
overrides: Partial<UsageLimitScope> = {},
@@ -18,7 +19,7 @@ const buildSpeedScope = (
limitKind: 'speed',
periodCount: 10,
periodUnit: 'second',
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
...overrides,
});
@@ -33,7 +34,7 @@ const buildStockScope = (
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
...overrides,
});
@@ -48,7 +49,7 @@ const buildQuotaScope = (
limitKind: 'quota',
periodCount: 1,
periodUnit: 'day',
- meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
...overrides,
});
@@ -84,6 +85,7 @@ describe('findSuppressedUsageLimitDefaults', () => {
operationType: UsageOperationType.API_REQUEST,
spenderType: 'apiKey',
periodCount: 1,
+ unit: UsageUnit.REQUEST,
}),
);
@@ -99,14 +101,17 @@ describe('findSuppressedUsageLimitDefaults', () => {
resourceType: UsageResourceType.API,
operationType: UsageOperationType.API_REQUEST,
spenderType: 'application',
+ unit: UsageUnit.REQUEST,
}),
),
).toEqual([]);
});
- it('returns nothing for a meter no default is declared on', () => {
+ it('returns nothing for a unit no default is declared on', () => {
expect(
- findSuppressedUsageLimitDefaults(buildStockScope({ meter: 'quantity' })),
+ findSuppressedUsageLimitDefaults(
+ buildStockScope({ unit: UsageUnit.FILE }),
+ ),
).toEqual([]);
});
@@ -124,7 +129,7 @@ describe('findSuppressedUsageLimitDefaults', () => {
.filter((usageLimitDefault) => usageLimitDefault.isOverridable)
.map(
(usageLimitDefault) =>
- `${usageLimitDefault.resourceType}:${usageLimitDefault.operationType}:${usageLimitDefault.spenderType}:${usageLimitDefault.limitKind}:${usageLimitDefault.meter}`,
+ `${usageLimitDefault.resourceType}:${usageLimitDefault.operationType}:${usageLimitDefault.spenderType}:${usageLimitDefault.limitKind}:${usageLimitDefault.unit}`,
)
.filter(
(suppressionKey, _index, suppressionKeys) =>
@@ -168,7 +173,7 @@ describe('findSuppressedUsageLimitDefaults', () => {
operationType: UsageOperationType.AI_CHAT_TOKEN,
limitKind: 'quota',
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
}),
),
).toEqual([]);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/from-usage-limit-entity-to-dto.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/from-usage-limit-entity-to-dto.util.spec.ts
index 1e02ba16b81..dfb51b07251 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/from-usage-limit-entity-to-dto.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/from-usage-limit-entity-to-dto.util.spec.ts
@@ -1,5 +1,6 @@
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
import { fromUsageLimitEntityToDto } from 'src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util';
@@ -14,7 +15,7 @@ const buildEntity = (overrides: Partial<UsageLimitEntity>): UsageLimitEntity =>
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 3000,
burstValue: null,
createdAt: new Date('2026-01-01'),
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 50af0361c3c..21793e0bf4e 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,8 +1,11 @@
+import { isDefined } from 'twenty-shared/utils';
+
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';
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const validSpeedLimit: CreateUsageLimitInput = {
resourceType: UsageResourceType.API,
@@ -12,7 +15,7 @@ const validSpeedLimit: CreateUsageLimitInput = {
limitKind: 'speed',
periodCount: 60,
periodUnit: 'second',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
limitValue: 100,
};
@@ -24,7 +27,7 @@ const validQuotaLimit: CreateUsageLimitInput = {
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 1_000_000,
};
@@ -36,57 +39,64 @@ const validStockLimit: CreateUsageLimitInput = {
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
limitValue: 10_737_418_240,
};
-const rejects = (input: CreateUsageLimitInput) =>
+const validCodeExecutionQuotaLimit: CreateUsageLimitInput = {
+ ...validQuotaLimit,
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+};
+
+const rejects = (input: CreateUsageLimitInput, message?: string) =>
expect(() => validateUsageLimitAgainstDefinition(input)).toThrow(
expect.objectContaining({
code: UsageLimitExceptionCode.LIMIT_INVALID,
+ ...(isDefined(message) ? { message } : {}),
}),
);
+const accepts = (input: CreateUsageLimitInput) =>
+ expect(() => validateUsageLimitAgainstDefinition(input)).not.toThrow();
+
describe('validateUsageLimitAgainstDefinition', () => {
it('accepts a limit the definition allows', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition(validSpeedLimit),
- ).not.toThrow();
+ accepts(validSpeedLimit);
});
it('accepts a limit targeting every spender of a type', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validSpeedLimit,
- spenderId: null,
- }),
- ).not.toThrow();
+ accepts({ ...validSpeedLimit, spenderId: null });
});
- it('accepts a quota covering every operation of the resource', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validQuotaLimit,
- operationType: UsageOperationType.ALL,
- }),
- ).not.toThrow();
+ it('accepts a credit quota covering every operation of the resource', () => {
+ accepts({ ...validQuotaLimit, operationType: UsageOperationType.ALL });
});
it('accepts a quota scoped to one application', () => {
- expect(() =>
- validateUsageLimitAgainstDefinition({
- ...validQuotaLimit,
- spenderType: 'application',
- spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
- }),
- ).not.toThrow();
+ accepts({
+ ...validQuotaLimit,
+ spenderType: 'application',
+ spenderId: '20202020-1c25-4d02-bf25-6aeccf7ea419',
+ });
+ });
+
+ it.each([UsageUnit.CREDIT, UsageUnit.INVOCATION])(
+ 'accepts a code execution quota counted in %s',
+ (unit) => {
+ accepts({ ...validCodeExecutionQuotaLimit, unit });
+ },
+ );
+
+ it('leaves a speed limit on every operation to the kind rule', () => {
+ accepts({ ...validSpeedLimit, operationType: UsageOperationType.ALL });
});
it('rejects a resource that has no definition', () => {
rejects({ ...validSpeedLimit, resourceType: UsageResourceType.WORKFLOW });
});
- it('rejects an operation the resource does not meter', () => {
+ it('rejects an operation the resource does not limit', () => {
rejects({
...validSpeedLimit,
operationType: UsageOperationType.EMAIL_SEND,
@@ -117,8 +127,31 @@ describe('validateUsageLimitAgainstDefinition', () => {
rejects({ ...validQuotaLimit, spenderType: 'workflow' });
});
- it('rejects a quota metered on bytes, which the resource does not track', () => {
- rejects({ ...validQuotaLimit, meter: 'bytes' });
+ it('rejects a runtime quota on email sends, naming the units it allows', () => {
+ rejects(
+ {
+ ...validQuotaLimit,
+ resourceType: UsageResourceType.EMAIL,
+ operationType: UsageOperationType.EMAIL_SEND,
+ unit: UsageUnit.MILLISECOND,
+ },
+ 'EMAIL EMAIL_SEND quota limits cannot count MILLISECOND, only CREDIT, INVOCATION',
+ );
+ });
+
+ it('rejects a quota counted in bytes, which the resource does not track', () => {
+ rejects({ ...validQuotaLimit, unit: UsageUnit.BYTE });
+ });
+
+ it('rejects a quota on every operation counted in anything but credits', () => {
+ rejects(
+ {
+ ...validQuotaLimit,
+ operationType: UsageOperationType.ALL,
+ unit: UsageUnit.INVOCATION,
+ },
+ 'A INVOCATION quota needs an operation: only credits aggregate across operations',
+ );
});
it('rejects a stock scoped below the workspace', () => {
@@ -129,7 +162,7 @@ describe('validateUsageLimitAgainstDefinition', () => {
});
});
- it('rejects a stock metered on credits, which the resource does not track', () => {
- rejects({ ...validStockLimit, meter: 'creditsUsedMicro' });
+ it('rejects a storage stock counted in credits', () => {
+ rejects({ ...validStockLimit, unit: UsageUnit.CREDIT });
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-kind-rule.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-kind-rule.util.spec.ts
index 2b4609fda61..2c338533840 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-kind-rule.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/validate-usage-limit-against-kind-rule.util.spec.ts
@@ -3,6 +3,7 @@ import { UsageLimitExceptionCode } from 'src/engine/core-modules/usage-limit/exc
import { validateUsageLimitAgainstKindRule } from 'src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-kind-rule.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';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const validSpeedLimit: CreateUsageLimitInput = {
resourceType: UsageResourceType.API,
@@ -12,7 +13,7 @@ const validSpeedLimit: CreateUsageLimitInput = {
limitKind: 'speed',
periodCount: 60,
periodUnit: 'second',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
limitValue: 100,
};
@@ -24,7 +25,7 @@ const validQuotaLimit: CreateUsageLimitInput = {
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 1_000_000,
};
@@ -36,7 +37,7 @@ const validStockLimit: CreateUsageLimitInput = {
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
limitValue: 10_737_418_240,
};
@@ -68,8 +69,18 @@ describe('validateUsageLimitAgainstKindRule', () => {
rejects({ ...validSpeedLimit, periodUnit: 'month' });
});
- it('rejects a speed limit metered on credits', () => {
- rejects({ ...validSpeedLimit, meter: 'creditsUsedMicro' });
+ it('rejects a speed limit on every operation', () => {
+ expect(() =>
+ validateUsageLimitAgainstKindRule({
+ ...validSpeedLimit,
+ operationType: UsageOperationType.ALL,
+ }),
+ ).toThrow(
+ expect.objectContaining({
+ code: UsageLimitExceptionCode.LIMIT_INVALID,
+ message: 'A speed limit targets a single operation, not ALL',
+ }),
+ );
});
});
@@ -98,15 +109,6 @@ describe('validateUsageLimitAgainstKindRule', () => {
).not.toThrow();
});
- it('accepts a quantity quota on one operation', () => {
- expect(() =>
- validateUsageLimitAgainstKindRule({
- ...validQuotaLimit,
- meter: 'quantity',
- }),
- ).not.toThrow();
- });
-
it('rejects a quota on a rolling window', () => {
rejects({ ...validQuotaLimit, periodUnit: 'second' });
});
@@ -122,18 +124,6 @@ describe('validateUsageLimitAgainstKindRule', () => {
it('rejects a quota with a burst value', () => {
rejects({ ...validQuotaLimit, burstValue: 200 });
});
-
- it('rejects a quota metered on bytes', () => {
- rejects({ ...validQuotaLimit, meter: 'bytes' });
- });
-
- it('rejects a quantity quota covering every operation', () => {
- rejects({
- ...validQuotaLimit,
- operationType: UsageOperationType.ALL,
- meter: 'quantity',
- });
- });
});
describe('stock', () => {
@@ -143,15 +133,6 @@ describe('validateUsageLimitAgainstKindRule', () => {
).not.toThrow();
});
- it('accepts a stock metered on a file count', () => {
- expect(() =>
- validateUsageLimitAgainstKindRule({
- ...validStockLimit,
- meter: 'quantity',
- }),
- ).not.toThrow();
- });
-
it('accepts a stock capping one application', () => {
expect(() =>
validateUsageLimitAgainstKindRule({
@@ -178,10 +159,6 @@ describe('validateUsageLimitAgainstKindRule', () => {
rejects({ ...validStockLimit, burstValue: 10 });
});
- it('rejects a stock metered on credits', () => {
- rejects({ ...validStockLimit, meter: 'creditsUsedMicro' });
- });
-
it('rejects an application stock that names no application', () => {
rejects({
...validStockLimit,
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
index 0e70d2c30ea..731686e947d 100644
--- 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
@@ -13,7 +13,7 @@ type CustomQuotaScope = Pick<
| 'spenderType'
| 'spenderId'
| 'periodUnit'
- | 'meter'
+ | 'unit'
| 'limitValue'
>;
@@ -35,7 +35,7 @@ export const buildCustomQuota = ({
spenderId: normalizeSpenderId(usageLimit.spenderId),
spenderLabel,
periodUnit: usageLimit.periodUnit,
- meter: usageLimit.meter,
+ unit: usageLimit.unit,
limitValue: usageLimit.limitValue,
isEnforced,
consumedValue: consumption?.consumedValue ?? null,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-intra-workspace-limit-counter-keys.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-intra-workspace-limit-counter-keys.util.ts
index 2c7d9ea78ed..6d37f7729f7 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-intra-workspace-limit-counter-keys.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-intra-workspace-limit-counter-keys.util.ts
@@ -35,7 +35,7 @@ export const buildIntraWorkspaceLimitCounterKeys = ({
operationType: limit.operationType,
spenderType: limit.spenderType,
spenderId: limit.spenderId,
- meter: limit.meter,
+ unit: limit.unit,
periodUnit: limit.periodUnit,
periodStart: period.periodStart,
limitValue: limit.limitValue,
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
index f7be928f6a5..288c84d6c4c 100644
--- 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
@@ -24,13 +24,13 @@ export const buildLimitQuotaCounter = ({
operationType: limit.operationType,
spenderType: limit.spenderType,
spenderId: limit.spenderId,
- meter: limit.meter,
+ unit: limit.unit,
periodUnit: limit.periodUnit,
periodStart: period.periodStart,
limitValue: limit.limitValue,
}),
limitValue: limit.limitValue,
- meter: limit.meter,
+ unit: limit.unit,
resourceType: limit.resourceType,
periodUnit: limit.periodUnit,
periodStart: period.periodStart,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-overridden-quota-default-counter-keys.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-overridden-quota-default-counter-keys.util.ts
index bf8c9b365b6..3da622d6d41 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-overridden-quota-default-counter-keys.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-overridden-quota-default-counter-keys.util.ts
@@ -37,7 +37,7 @@ export const buildOverriddenQuotaDefaultCounterKeys = ({
operationType: quotaLimitDefault.operationType,
spenderType: quotaLimitDefault.spenderType,
spenderId: quotaLimitDefault.spenderId,
- meter: quotaLimitDefault.meter,
+ unit: quotaLimitDefault.unit,
periodUnit: quotaLimitDefault.periodUnit,
periodStart: period.periodStart,
limitValue: quotaLimitDefault.limitValue,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts
index bc1dda7abd7..f1ffc408845 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts
@@ -2,9 +2,9 @@ import { isNonEmptyString } from '@sniptt/guards';
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';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const ABSENT = '-';
@@ -14,7 +14,7 @@ export const buildQuotaCounterKey = ({
operationType,
spenderType,
spenderId,
- meter,
+ unit,
periodUnit,
periodStart,
limitValue,
@@ -24,9 +24,9 @@ export const buildQuotaCounterKey = ({
operationType: UsageOperationType;
spenderType: SpenderType;
spenderId?: string | null;
- meter: UsageMeter;
+ unit: UsageUnit;
periodUnit: PeriodUnit;
periodStart: Date;
limitValue: number;
}): string =>
- `{${workspaceId}}:quota:${resourceType}:${operationType}:${spenderType}:${isNonEmptyString(spenderId) ? spenderId : ABSENT}:${meter}:${periodUnit}:${periodStart.getTime()}:${limitValue}`;
+ `{${workspaceId}}:quota:${resourceType}:${operationType}:${spenderType}:${isNonEmptyString(spenderId) ? spenderId : ABSENT}:${unit}:${periodUnit}:${periodStart.getTime()}:${limitValue}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
new file mode 100644
index 00000000000..e4fd1b82484
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-debits.util.ts
@@ -0,0 +1,16 @@
+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 QuotaDebit } from 'src/engine/core-modules/usage-limit/types/quota-debit.type';
+
+export const buildQuotaDebits = ({
+ counters,
+ cost,
+}: {
+ counters: QuotaCounter[];
+ cost: QuotaCost;
+}): QuotaDebit[] =>
+ counters.flatMap((counter) => {
+ const amount = cost[counter.unit] ?? 0;
+
+ return amount > 0 ? [{ counter, amount }] : [];
+ });
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-default-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-default-counter.util.ts
index ee79cbdc872..2ac730948b0 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-default-counter.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-default-counter.util.ts
@@ -20,13 +20,13 @@ export const buildQuotaDefaultCounter = ({
operationType: quotaLimitDefault.operationType,
spenderType: quotaLimitDefault.spenderType,
spenderId: quotaLimitDefault.spenderId,
- meter: quotaLimitDefault.meter,
+ unit: quotaLimitDefault.unit,
periodUnit: quotaLimitDefault.periodUnit,
periodStart: period.periodStart,
limitValue: quotaLimitDefault.limitValue,
}),
limitValue: quotaLimitDefault.limitValue,
- meter: quotaLimitDefault.meter,
+ unit: quotaLimitDefault.unit,
resourceType: quotaLimitDefault.resourceType,
periodUnit: quotaLimitDefault.periodUnit,
periodStart: period.periodStart,
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
index 4566e9eafe0..9b133f30f09 100644
--- 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
@@ -1,9 +1,34 @@
import { isDefined } from 'twenty-shared/utils';
import { type UsageQuotaDefinitionDTO } from 'src/engine/core-modules/usage-limit/dtos/usage-quota-definition.dto';
+import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
+import { type UsageLimitOperationDefinition } from 'src/engine/core-modules/usage-limit/types/usage-limit-operation-definition.type';
+import { findAllowedUsageLimitUnits } from 'src/engine/core-modules/usage-limit/utils/find-allowed-usage-limit-units.util';
import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.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 buildAllowedOperations = ({
+ limitKind,
+ definition,
+}: {
+ limitKind: LimitKind;
+ definition: { allowedOperations: UsageLimitOperationDefinition[] };
+}): UsageLimitOperationDefinition[] =>
+ definition.allowedOperations.length >= 2
+ ? [
+ {
+ operationType: UsageOperationType.ALL,
+ allowedUnits: findAllowedUsageLimitUnits({
+ limitKind,
+ definition,
+ operationType: UsageOperationType.ALL,
+ }),
+ },
+ ...definition.allowedOperations,
+ ]
+ : definition.allowedOperations;
+
export const buildQuotaDefinitions = (): UsageQuotaDefinitionDTO[] =>
Object.values(UsageResourceType).flatMap((resourceType) => {
const limitKind = 'quota';
@@ -14,9 +39,11 @@ export const buildQuotaDefinitions = (): UsageQuotaDefinitionDTO[] =>
{
resourceType,
limitKind,
- allowedOperationTypes: definition.allowedOperationTypes,
+ allowedOperations: buildAllowedOperations({
+ limitKind,
+ definition,
+ }),
allowedSpenderTypes: definition.allowedSpenderTypes,
- allowedMeters: definition.allowedMeters,
},
]
: [];
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
index 10bcf5c847c..2b37977b0c8 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
@@ -23,6 +23,7 @@ export const buildQuotaExhaustedScope = ({
spenderType: counter.spenderType,
spenderId: counter.spenderId,
operationType: counter.operationType,
+ unit: counter.unit,
limitValue: counter.limitValue,
remaining: 0,
periodCount: 1,
@@ -39,6 +40,7 @@ export const buildQuotaExhaustedScope = ({
spenderType: 'workspace',
spenderId: null,
operationType: UsageOperationType.ALL,
+ unit: counter.unit,
limitValue: allowance?.allowanceMicro ?? 0,
remaining: 0,
periodCount: null,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util.ts
index 8ce7e1726ca..be16cbc1748 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter-key.util.ts
@@ -1,9 +1,9 @@
import { isNonEmptyString } from '@sniptt/guards';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-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';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
const ABSENT = '-';
@@ -16,7 +16,7 @@ export const buildStockCounterKey = ({
operationType,
spenderType,
spenderId,
- meter,
+ unit,
limitValue,
}: {
workspaceId: string;
@@ -24,7 +24,7 @@ export const buildStockCounterKey = ({
operationType: UsageOperationType;
spenderType: SpenderType;
spenderId?: string | null;
- meter: StockMeter;
+ unit: UsageUnit;
limitValue: number;
}): string =>
- `{${workspaceId}}:stock:${resourceType}:${operationType}:${spenderType}:${isNonEmptyString(spenderId) ? spenderId : ABSENT}:${meter}:${limitValue}`;
+ `{${workspaceId}}:stock:${resourceType}:${operationType}:${spenderType}:${isNonEmptyString(spenderId) ? spenderId : ABSENT}:${unit}:${limitValue}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter.util.ts
index daabe358d1a..2cf98b57af3 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counter.util.ts
@@ -16,12 +16,12 @@ export const buildStockCounter = ({
operationType: limit.operationType,
spenderType: limit.spenderType,
spenderId: limit.spenderId,
- meter: limit.meter,
+ unit: limit.unit,
limitValue: limit.limitValue,
}),
isDefault: false,
limitValue: limit.limitValue,
- meter: limit.meter,
+ unit: limit.unit,
resourceType: limit.resourceType,
operationType: limit.operationType,
spenderType: limit.spenderType,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counters.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counters.util.ts
index 834f7c83436..848aaf77b4b 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counters.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-counters.util.ts
@@ -47,7 +47,7 @@ export const buildStockCounters = ({
counter.resourceType === resourceType &&
counter.spenderType === stockLimitDefault.spenderType &&
counter.spenderId === null &&
- counter.meter === stockLimitDefault.meter,
+ counter.unit === stockLimitDefault.unit,
)
),
)
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter-key.util.ts
index c27ff6da002..8a0ffef0ecb 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter-key.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter-key.util.ts
@@ -1,22 +1,22 @@
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
import { buildStockCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-counter-key.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 { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export const buildStockDefaultCounterKey = ({
workspaceId,
resourceType,
operationType,
spenderType,
- meter,
+ unit,
limitValue,
}: {
workspaceId: string;
resourceType: UsageResourceType;
operationType: UsageOperationType;
spenderType: SpenderType;
- meter: StockMeter;
+ unit: UsageUnit;
limitValue: number;
}): string =>
- `${buildStockCounterKey({ workspaceId, resourceType, operationType, spenderType, meter, limitValue })}:default`;
+ `${buildStockCounterKey({ workspaceId, resourceType, operationType, spenderType, unit, limitValue })}:default`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter.util.ts
index c263e7464e0..de0727cd342 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-default-counter.util.ts
@@ -20,12 +20,12 @@ export const buildStockDefaultCounter = ({
resourceType,
operationType,
spenderType: stockLimitDefault.spenderType,
- meter: stockLimitDefault.meter,
+ unit: stockLimitDefault.unit,
limitValue: stockLimitDefault.limitValue,
}),
isDefault: true,
limitValue: stockLimitDefault.limitValue,
- meter: stockLimitDefault.meter,
+ unit: stockLimitDefault.unit,
resourceType,
operationType,
spenderType: stockLimitDefault.spenderType,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-exhausted-scope.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-exhausted-scope.util.ts
index c35649870ff..a01dfa045ba 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-exhausted-scope.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-exhausted-scope.util.ts
@@ -14,6 +14,7 @@ export const buildStockExhaustedScope = ({
spenderType: counter.spenderType,
spenderId: counter.spenderId,
operationType: counter.operationType,
+ unit: counter.unit,
limitValue: counter.limitValue,
remaining,
periodCount: null,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-warmed-entries.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-warmed-entries.util.ts
index 052b1e306b2..aea88f02044 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-warmed-entries.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-stock-warmed-entries.util.ts
@@ -1,8 +1,8 @@
import { isDefined } from 'twenty-shared/utils';
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
import { type StockCounter } from 'src/engine/core-modules/usage-limit/types/stock-counter.type';
import { buildStockScopeKey } from 'src/engine/core-modules/usage-limit/utils/build-stock-scope-key.util';
+import { type UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export const buildStockWarmedEntries = ({
coldCounters,
@@ -10,11 +10,11 @@ export const buildStockWarmedEntries = ({
ttl,
}: {
coldCounters: StockCounter[];
- usedByScope: Map<string, Record<StockMeter, number>>;
+ usedByScope: Map<string, Partial<Record<UsageUnit, number>>>;
ttl: number;
}): { key: string; value: number; ttl: number }[] =>
coldCounters.flatMap((counter) => {
- const used = usedByScope.get(buildStockScopeKey(counter))?.[counter.meter];
+ const used = usedByScope.get(buildStockScopeKey(counter))?.[counter.unit];
return isDefined(used)
? [{ key: counter.key, value: counter.limitValue - used, ttl }]
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-default-scopes.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-default-scopes.util.ts
index 3e5e38890ae..d5348b12190 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-default-scopes.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-usage-limit-default-scopes.util.ts
@@ -32,7 +32,7 @@ export const buildUsageLimitDefaultScopes = ({
spenderType: usageLimitDefault.spenderType,
spenderId: usageLimitDefault.spenderId,
limitKind: usageLimitDefault.limitKind,
- meter: usageLimitDefault.meter,
+ unit: usageLimitDefault.unit,
periodUnit: usageLimitDefault.periodUnit,
periodCount: buildPeriodCount({ usageLimitDefault, getConfigValue }),
limitValue: getConfigValue(usageLimitDefault.limitValueConfigVariable),
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
index cc9a279af3e..e63bf8d3c7c 100644
--- 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
@@ -9,7 +9,7 @@ export type UsageLimitScope = Pick<
| 'limitKind'
| 'periodCount'
| 'periodUnit'
- | 'meter'
+ | 'unit'
>;
type UsageLimitScopeSource = Omit<UsageLimitScope, 'spenderId'> & {
@@ -26,5 +26,5 @@ export const buildUsageLimitScope = (
limitKind: source.limitKind,
periodCount: source.periodCount,
periodUnit: source.periodUnit,
- meter: source.meter,
+ unit: source.unit,
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util.ts
index 42ab1c42046..ca49dcdbe70 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/clamp-quota-cost.util.ts
@@ -1,9 +1,20 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { isValidCreditAmountMicro } from 'src/engine/core-modules/usage/utils/is-valid-credit-amount-micro.util';
import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';
-export const clampQuotaCost = (cost: QuotaCost): QuotaCost => ({
- creditsUsedMicro: isValidCreditAmountMicro(cost.creditsUsedMicro)
- ? cost.creditsUsedMicro
- : 0,
- quantity: isValidCreditAmountMicro(cost.quantity) ? cost.quantity : 0,
-});
+const clampAmount = (amount: number): number =>
+ isValidCreditAmountMicro(amount) ? amount : 0;
+
+export const clampQuotaCost = (cost: QuotaCost): QuotaCost =>
+ Object.values(UsageUnit).reduce<QuotaCost>(
+ (clampedCost, unit) => {
+ const amount = cost[unit];
+
+ return isDefined(amount)
+ ? { ...clampedCost, [unit]: clampAmount(amount) }
+ : clampedCost;
+ },
+ { [UsageUnit.CREDIT]: clampAmount(cost[UsageUnit.CREDIT]) },
+ );
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 5b86f8d39eb..4150e4fca71 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,6 +2,7 @@ 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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.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';
@@ -15,7 +16,7 @@ const spenderColumnMatches = (
export type QuotaConsumptionScope = Pick<
LimitQuotaCounter,
- 'operationType' | 'spenderType' | 'spenderId' | 'meter'
+ 'operationType' | 'spenderType' | 'spenderId' | 'unit'
>;
const rowMatchesScope = (
@@ -39,6 +40,17 @@ const rowMatchesScope = (
);
};
+const computeRowConsumed = (
+ row: UsageConsumptionRow,
+ unit: UsageUnit,
+): number => {
+ if (unit === UsageUnit.CREDIT) {
+ return Number(row.creditsUsedMicro);
+ }
+
+ return row.unit === unit ? Number(row.quantity) : 0;
+};
+
export const computeQuotaConsumed = ({
rows,
scope,
@@ -48,4 +60,4 @@ export const computeQuotaConsumed = ({
}): number =>
rows
.filter((row) => rowMatchesScope(row, scope))
- .reduce((total, row) => total + Number(row[scope.meter]), 0);
+ .reduce((total, row) => total + computeRowConsumed(row, scope.unit), 0);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts
index 1ba70447742..1dce1fc2f43 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/does-usage-limit-row-suppress-default.util.ts
@@ -15,4 +15,4 @@ export const doesUsageLimitRowSuppressDefault = ({
scope.spenderType === usageLimitDefault.spenderType &&
scope.spenderId === usageLimitDefault.spenderId &&
scope.limitKind === usageLimitDefault.limitKind &&
- scope.meter === usageLimitDefault.meter;
+ scope.unit === usageLimitDefault.unit;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-allowed-usage-limit-units.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-allowed-usage-limit-units.util.ts
new file mode 100644
index 00000000000..bb69a2ed1c9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-allowed-usage-limit-units.util.ts
@@ -0,0 +1,28 @@
+import { LIMIT_KIND_RULES } from 'src/engine/core-modules/usage-limit/constants/limit-kind-rules.constant';
+import { type LimitKind } from 'src/engine/core-modules/usage-limit/types/limit-kind.type';
+import { type UsageLimitOperationDefinition } from 'src/engine/core-modules/usage-limit/types/usage-limit-operation-definition.type';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+
+export const findAllowedUsageLimitUnits = ({
+ limitKind,
+ definition,
+ operationType,
+}: {
+ limitKind: LimitKind;
+ definition: { allowedOperations: UsageLimitOperationDefinition[] };
+ operationType: UsageOperationType;
+}): UsageUnit[] => {
+ if (
+ operationType === UsageOperationType.ALL &&
+ LIMIT_KIND_RULES[limitKind].isAllOperationTypeAllowed
+ ) {
+ return [UsageUnit.CREDIT];
+ }
+
+ return (
+ definition.allowedOperations.find(
+ (allowedOperation) => allowedOperation.operationType === operationType,
+ )?.allowedUnits ?? []
+ );
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util.ts
index 35178578eae..0c566e01d4a 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counters.util.ts
@@ -23,5 +23,5 @@ export const findExhaustedCounters = ({
return true;
}
- return remaining < (cost?.[counter.meter] ?? 0);
+ return remaining < (cost?.[counter.unit] ?? 0);
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.util.ts
index 05ba9fe745d..4ffecabf595 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-stock-counter.util.ts
@@ -15,7 +15,7 @@ export const findExhaustedStockCounter = ({
for (const [index, counter] of counters.entries()) {
const remaining = remainings[index];
- if (isDefined(remaining) && remaining < (cost[counter.meter] ?? 0)) {
+ if (isDefined(remaining) && remaining < (cost[counter.unit] ?? 0)) {
return { counter, remaining };
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util.ts
index 6ed4cd6405f..8096cb2be3b 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-dto.util.ts
@@ -13,7 +13,7 @@ export const fromUsageLimitEntityToDto = (
limitKind: usageLimit.limitKind,
periodCount: usageLimit.periodCount,
periodUnit: usageLimit.periodUnit,
- meter: usageLimit.meter,
+ unit: usageLimit.unit,
limitValue: usageLimit.limitValue,
burstValue: usageLimit.burstValue,
createdAt: usageLimit.createdAt,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-flat.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-flat.util.ts
index e7b78b813c1..db31832ac42 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-flat.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-usage-limit-entity-to-flat.util.ts
@@ -12,7 +12,7 @@ export const fromUsageLimitEntityToFlat = (
limitKind: usageLimit.limitKind,
periodCount: usageLimit.periodCount,
periodUnit: usageLimit.periodUnit,
- meter: usageLimit.meter,
+ unit: usageLimit.unit,
limitValue: usageLimit.limitValue,
burstValue: usageLimit.burstValue,
isInstanceOverride: usageLimit.isInstanceOverride,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-limit.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-limit.util.ts
index f036cb98527..fe57dab84ec 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-limit.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-limit.util.ts
@@ -1,6 +1,5 @@
import { type FlatQuotaLimit } from 'src/engine/core-modules/usage-limit/types/flat-quota-limit.type';
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
-import { isQuotaMeter } from 'src/engine/core-modules/usage-limit/utils/is-quota-meter.util';
export const isQuotaLimit = (limit: FlatUsageLimit): limit is FlatQuotaLimit =>
- limit.limitKind === 'quota' && isQuotaMeter(limit.meter);
+ limit.limitKind === 'quota';
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-meter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-meter.util.ts
deleted file mode 100644
index 38347f3208c..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-quota-meter.util.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { QUOTA_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
-import { type QuotaMeter } from 'src/engine/core-modules/usage-limit/types/quota-meter.type';
-import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
-
-export const isQuotaMeter = (meter: UsageMeter): meter is QuotaMeter =>
- QUOTA_METERS.includes(meter as QuotaMeter);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-limit.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-limit.util.ts
index ed59eb8158f..cbe648a9b15 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-limit.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-limit.util.ts
@@ -1,9 +1,6 @@
import { type FlatStockLimit } from 'src/engine/core-modules/usage-limit/types/flat-stock-limit.type';
import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
-import { isStockMeter } from 'src/engine/core-modules/usage-limit/utils/is-stock-meter.util';
import { isStockResourceType } from 'src/engine/core-modules/usage-limit/utils/is-stock-resource-type.util';
export const isStockLimit = (limit: FlatUsageLimit): limit is FlatStockLimit =>
- limit.limitKind === 'stock' &&
- isStockMeter(limit.meter) &&
- isStockResourceType(limit.resourceType);
+ limit.limitKind === 'stock' && isStockResourceType(limit.resourceType);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-meter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-meter.util.ts
deleted file mode 100644
index 7dddd856f68..00000000000
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/is-stock-meter.util.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { STOCK_METERS } from 'src/engine/core-modules/usage-limit/constants/usage-meters.constant';
-import { type StockMeter } from 'src/engine/core-modules/usage-limit/types/stock-meter.type';
-import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
-
-export const isStockMeter = (meter: UsageMeter): meter is StockMeter =>
- STOCK_METERS.includes(meter as StockMeter);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util.ts
index 0db3b284f04..f8d0b614d61 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-graphql-api-exception-handler.util.ts
@@ -30,6 +30,7 @@ export const usageLimitToGraphqlApiExceptionHandler = (
limitKind: exhaustedScope.limitKind,
exhaustedKind: exhaustedScope.exhaustedKind,
limit: exhaustedScope.limitValue,
+ unit: exhaustedScope.unit,
remaining: exhaustedScope.remaining,
periodCount: exhaustedScope.periodCount,
periodUnit: exhaustedScope.periodUnit,
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts
index 79571a43dee..e2b9c726ead 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/usage-limit-to-rest-api-exception-handler.util.ts
@@ -48,6 +48,7 @@ export const buildUsageLimitHttpException = (
operationType: exhaustedScope.operationType,
},
limit: exhaustedScope.limitValue,
+ unit: exhaustedScope.unit,
remaining: exhaustedScope.remaining,
periodCount: exhaustedScope.periodCount,
periodUnit: exhaustedScope.periodUnit,
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 cfcef70d85b..f332a859aa3 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,12 +1,13 @@
import { isNonEmptyString } from '@sniptt/guards';
import { isDefined, isValidUuid } from 'twenty-shared/utils';
+import { LIMIT_KIND_RULES } from 'src/engine/core-modules/usage-limit/constants/limit-kind-rules.constant';
import { type CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/dtos/create-usage-limit.input';
import {
UsageLimitException,
UsageLimitExceptionCode,
} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
-import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+import { findAllowedUsageLimitUnits } from 'src/engine/core-modules/usage-limit/utils/find-allowed-usage-limit-units.util';
import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
@@ -25,9 +26,14 @@ export const validateUsageLimitAgainstDefinition = (
);
}
+ const spansEveryOperation = input.operationType === UsageOperationType.ALL;
+
if (
- input.operationType !== UsageOperationType.ALL &&
- !definition.allowedOperationTypes.includes(input.operationType)
+ !spansEveryOperation &&
+ !definition.allowedOperations.some(
+ (allowedOperation) =>
+ allowedOperation.operationType === input.operationType,
+ )
) {
throw new UsageLimitException(
`${input.resourceType} ${input.limitKind} limits cannot target the ${input.operationType} operation`,
@@ -49,14 +55,25 @@ export const validateUsageLimitAgainstDefinition = (
);
}
- if ('allowedMeters' in definition) {
- const allowedMeters: readonly UsageMeter[] = definition.allowedMeters;
+ if (
+ spansEveryOperation &&
+ !LIMIT_KIND_RULES[input.limitKind].isAllOperationTypeAllowed
+ ) {
+ return;
+ }
+
+ const allowedUnits = findAllowedUsageLimitUnits({
+ limitKind: input.limitKind,
+ definition,
+ operationType: input.operationType,
+ });
- if (!allowedMeters.includes(input.meter)) {
- throw new UsageLimitException(
- `${input.resourceType} ${input.limitKind} limits cannot be metered on ${input.meter}`,
- UsageLimitExceptionCode.LIMIT_INVALID,
- );
- }
+ if (!allowedUnits.includes(input.unit)) {
+ throw new UsageLimitException(
+ spansEveryOperation
+ ? `A ${input.unit} quota needs an operation: only credits aggregate across operations`
+ : `${input.resourceType} ${input.operationType} ${input.limitKind} limits cannot count ${input.unit}, only ${allowedUnits.join(', ')}`,
+ UsageLimitExceptionCode.LIMIT_INVALID,
+ );
}
};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-kind-rule.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-kind-rule.util.ts
index 5a985a85c61..7838cd01a56 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-kind-rule.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-kind-rule.util.ts
@@ -47,13 +47,6 @@ export const validateUsageLimitAgainstKindRule = (
);
}
- if (!rule.allowedMeters.includes(input.meter)) {
- throw new UsageLimitException(
- `A ${input.limitKind} limit cannot be metered on ${input.meter}, only on ${rule.allowedMeters.join(', ')}`,
- UsageLimitExceptionCode.LIMIT_INVALID,
- );
- }
-
if (!rule.isBurstValueAllowed && isDefined(input.burstValue)) {
throw new UsageLimitException(
`A ${input.limitKind} limit cannot hold a burst value`,
@@ -61,17 +54,6 @@ export const validateUsageLimitAgainstKindRule = (
);
}
- if (
- input.limitKind === 'quota' &&
- input.meter === 'quantity' &&
- spansEveryOperation
- ) {
- throw new UsageLimitException(
- 'A quantity quota needs an operation: only credits aggregate across operations',
- UsageLimitExceptionCode.LIMIT_INVALID,
- );
- }
-
if (
input.limitKind === 'stock' &&
input.spenderType !== 'workspace' &&
diff --git a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
index b11fa095e58..3da4f96ab49 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
@@ -1,5 +1,7 @@
/* @license Enterprise */
+import { registerEnumType } from '@nestjs/graphql';
+
export enum UsageUnit {
CREDIT = 'CREDIT',
TOKEN = 'TOKEN',
@@ -7,8 +9,13 @@ export enum UsageUnit {
MINUTE = 'MINUTE',
MILLISECOND = 'MILLISECOND',
BYTE = 'BYTE',
+ FILE = 'FILE',
REQUEST = 'REQUEST',
SEAT = 'SEAT',
RECORD = 'RECORD',
COMPLEXITY = 'COMPLEXITY',
}
+
+registerEnumType(UsageUnit, {
+ name: 'UsageUnit',
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
index 0e66f290f7b..184b6c27277 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service.ts
@@ -141,7 +141,10 @@ export class AiBillingService {
workspaceId,
operationType,
spenders: { userWorkspaceId, agentId },
- cost: { creditsUsedMicro, quantity: totalTokens },
+ cost: {
+ [UsageUnit.CREDIT]: creditsUsedMicro,
+ [UsageUnit.TOKEN]: totalTokens,
+ },
});
await this.emitAiTokenUsageEvent(
@@ -179,7 +182,10 @@ export class AiBillingService {
workspaceId,
operationType,
spenders,
- cost: { creditsUsedMicro, quantity: totalTokens },
+ cost: {
+ [UsageUnit.CREDIT]: creditsUsedMicro,
+ [UsageUnit.TOKEN]: totalTokens,
+ },
});
}
@@ -204,7 +210,10 @@ export class AiBillingService {
workspaceId,
operationType: UsageOperationType.WEB_SEARCH,
spenders: { userWorkspaceId },
- cost: { creditsUsedMicro, quantity: nativeWebSearchCallCount },
+ cost: {
+ [UsageUnit.CREDIT]: creditsUsedMicro,
+ [UsageUnit.INVOCATION]: nativeWebSearchCallCount,
+ },
});
await this.usageRecorderService.record(workspaceId, [
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-ai-chat-credit-limits.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-ai-chat-credit-limits.util.spec.ts
index 081ed2c1525..82e0897a878 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-ai-chat-credit-limits.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-ai-chat-credit-limits.util.spec.ts
@@ -2,6 +2,7 @@ import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/f
import { type UsageLimits } from 'src/engine/core-modules/usage-limit/types/usage-limits.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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { findAiChatCreditLimits } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-ai-chat-credit-limits.util';
const buildLimit = (
@@ -15,7 +16,7 @@ const buildLimit = (
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 1000,
burstValue: null,
isInstanceOverride: false,
@@ -86,7 +87,7 @@ describe('findAiChatCreditLimits', () => {
'another operation',
{ operationType: UsageOperationType.AI_WORKFLOW_TOKEN },
],
- ['another meter', { meter: 'quantity' }],
+ ['another unit', { unit: UsageUnit.TOKEN }],
['a speed limit', { limitKind: 'speed' }],
])('ignores %s', (_, overrides) => {
expect(findLimits([buildLimit(overrides)])).toEqual([]);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/select-ai-chat-usage.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/select-ai-chat-usage.util.spec.ts
index 5f5926e2b66..d786d7978a2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/select-ai-chat-usage.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/select-ai-chat-usage.util.spec.ts
@@ -2,6 +2,7 @@ import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/f
import { type LimitConsumption } from 'src/engine/core-modules/usage-limit/types/limit-consumption.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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { selectAiChatUsage } from 'src/engine/metadata-modules/ai/ai-chat/utils/select-ai-chat-usage.util';
const periodStart = new Date('2026-09-01T00:00:00Z');
@@ -18,7 +19,7 @@ const buildLimit = (
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 1000,
burstValue: null,
isInstanceOverride: false,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-ai-chat-credit-limits.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-ai-chat-credit-limits.util.ts
index 3e440908a17..3916b6d56af 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-ai-chat-credit-limits.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-ai-chat-credit-limits.util.ts
@@ -4,6 +4,7 @@ import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/f
import { type UsageLimits } from 'src/engine/core-modules/usage-limit/types/usage-limits.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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
export const findAiChatCreditLimits = ({
usageLimits,
@@ -15,8 +16,7 @@ export const findAiChatCreditLimits = ({
const creditQuotas = (
usageLimits.byResourceType[UsageResourceType.AI] ?? []
).filter(
- (limit) =>
- limit.limitKind === 'quota' && limit.meter === 'creditsUsedMicro',
+ (limit) => limit.limitKind === 'quota' && limit.unit === UsageUnit.CREDIT,
);
return buildSpendersFromUsageSpenders({ userWorkspaceId }).flatMap(
diff --git a/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts b/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts
index b1f22fa1038..1a6e1652f5c 100644
--- a/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts
+++ b/packages/twenty-server/src/modules/emailing/services/email-billing.service.ts
@@ -70,7 +70,10 @@ export class EmailBillingService {
resourceType: UsageResourceType.EMAIL,
operationType: UsageOperationType.EMAIL_SEND,
spenders,
- cost: { creditsUsedMicro, quantity: sentEmailCount },
+ cost: {
+ [UsageUnit.CREDIT]: creditsUsedMicro,
+ [UsageUnit.INVOCATION]: sentEmailCount,
+ },
});
await this.usageRecorderService.record(workspaceId, [
diff --git a/packages/twenty-server/src/modules/emailing/utils/__tests__/build-email-quota-cost.util.spec.ts b/packages/twenty-server/src/modules/emailing/utils/__tests__/build-email-quota-cost.util.spec.ts
index be9ce82ebcd..ca5b29a9152 100644
--- a/packages/twenty-server/src/modules/emailing/utils/__tests__/build-email-quota-cost.util.spec.ts
+++ b/packages/twenty-server/src/modules/emailing/utils/__tests__/build-email-quota-cost.util.spec.ts
@@ -1,11 +1,12 @@
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { buildEmailQuotaCost } from 'src/modules/emailing/utils/build-email-quota-cost.util';
import { computeEmailCreditsUsedMicro } from 'src/modules/emailing/utils/compute-email-credits-used-micro.util';
describe('buildEmailQuotaCost', () => {
- it('names both meters a send will spend', () => {
+ it('names both units a send will spend', () => {
expect(buildEmailQuotaCost(30)).toEqual({
- quantity: 30,
- creditsUsedMicro: computeEmailCreditsUsedMicro(30),
+ [UsageUnit.CREDIT]: computeEmailCreditsUsedMicro(30),
+ [UsageUnit.INVOCATION]: 30,
});
});
@@ -15,8 +16,8 @@ describe('buildEmailQuotaCost', () => {
it('names a zero cost rather than none for an empty send', () => {
expect(buildEmailQuotaCost(0)).toEqual({
- quantity: 0,
- creditsUsedMicro: 0,
+ [UsageUnit.CREDIT]: 0,
+ [UsageUnit.INVOCATION]: 0,
});
});
});
diff --git a/packages/twenty-server/src/modules/emailing/utils/build-email-quota-cost.util.ts b/packages/twenty-server/src/modules/emailing/utils/build-email-quota-cost.util.ts
index b0e23c2c18b..b37c9b2dc3e 100644
--- a/packages/twenty-server/src/modules/emailing/utils/build-email-quota-cost.util.ts
+++ b/packages/twenty-server/src/modules/emailing/utils/build-email-quota-cost.util.ts
@@ -1,6 +1,7 @@
import { isDefined } from 'twenty-shared/utils';
import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';
+import { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { computeEmailCreditsUsedMicro } from 'src/modules/emailing/utils/compute-email-credits-used-micro.util';
export const buildEmailQuotaCost = (
@@ -8,7 +9,7 @@ export const buildEmailQuotaCost = (
): QuotaCost | undefined =>
isDefined(emailCount)
? {
- quantity: emailCount,
- creditsUsedMicro: computeEmailCreditsUsedMicro(emailCount),
+ [UsageUnit.CREDIT]: computeEmailCreditsUsedMicro(emailCount),
+ [UsageUnit.INVOCATION]: emailCount,
}
: undefined;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
index a642e8c647f..8be52118deb 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
@@ -461,7 +461,7 @@ export class WorkflowExecutorWorkspaceService {
resourceType: UsageResourceType.WORKFLOW,
operationType: UsageOperationType.WORKFLOW_EXECUTION,
spenders: billingSpenders,
- cost: { creditsUsedMicro: 100, quantity: 1 },
+ cost: { [UsageUnit.CREDIT]: 100, [UsageUnit.INVOCATION]: 1 },
});
await this.usageRecorderService.record(workspaceId, [
diff --git a/packages/twenty-server/test/integration/graphql/suites/admin-panel/workspace-usage-limits.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/admin-panel/workspace-usage-limits.integration-spec.ts
index b2b0660739d..6e98b93e26c 100644
--- a/packages/twenty-server/test/integration/graphql/suites/admin-panel/workspace-usage-limits.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/admin-panel/workspace-usage-limits.integration-spec.ts
@@ -12,6 +12,7 @@ import { UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limi
import { UserEntity } from 'src/engine/core-modules/user/user.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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
@@ -23,7 +24,7 @@ const WORKSPACE_USAGE_LIMITS = gql`
operationType
spenderType
limitKind
- meter
+ unit
limitValue
isOverridable
overriddenByUsageLimitId
@@ -79,7 +80,7 @@ const STORAGE_STOCK_PAYLOAD = {
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
limitValue: 5_000_000,
burstValue: null,
};
@@ -114,7 +115,7 @@ describe('Workspace usage limits from the admin panel', () => {
expect.objectContaining({
resourceType: UsageResourceType.STORAGE,
limitKind: 'stock',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
isOverridable: true,
overriddenByUsageLimitId: null,
}),
@@ -149,12 +150,12 @@ describe('Workspace usage limits from the admin panel', () => {
resourceType: UsageResourceType;
operationType: UsageOperationType;
spenderType: string;
- meter: string;
+ unit: UsageUnit;
}) =>
usageLimitDefault.resourceType === UsageResourceType.STORAGE &&
usageLimitDefault.operationType === UsageOperationType.STORAGE_FILE &&
usageLimitDefault.spenderType === 'workspace' &&
- usageLimitDefault.meter === 'bytes',
+ usageLimitDefault.unit === UsageUnit.BYTE,
),
).toEqual(
expect.objectContaining({ overriddenByUsageLimitId: usageLimitId }),
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-46-instance-command-fast-1791186790123-rename-usage-limit-meter-to-unit.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-46-instance-command-fast-1791186790123-rename-usage-limit-meter-to-unit.integration-spec.ts
new file mode 100644
index 00000000000..6a2ad5cad47
--- /dev/null
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-46-instance-command-fast-1791186790123-rename-usage-limit-meter-to-unit.integration-spec.ts
@@ -0,0 +1,317 @@
+import { type QueryRunner } from 'typeorm';
+import { v4 } from 'uuid';
+
+import { RenameUsageLimitMeterToUnitFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791186790123-rename-usage-limit-meter-to-unit';
+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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+jest.useRealTimers();
+
+type UsageLimitFixture = {
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ limitKind: 'speed' | 'quota' | 'stock';
+ meter: string;
+ unit: UsageUnit;
+};
+
+const PERIOD_BY_LIMIT_KIND = {
+ speed: { periodCount: 1, periodUnit: 'second' },
+ quota: { periodCount: 1, periodUnit: 'month' },
+ stock: { periodCount: 1, periodUnit: 'lifetime' },
+} as const;
+
+const METER_FIXTURES: UsageLimitFixture[] = [
+ {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.ALL,
+ limitKind: 'quota',
+ meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
+ },
+ {
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ limitKind: 'stock',
+ meter: 'bytes',
+ unit: UsageUnit.BYTE,
+ },
+ {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ limitKind: 'quota',
+ meter: 'quantity',
+ unit: UsageUnit.TOKEN,
+ },
+ {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ limitKind: 'quota',
+ meter: 'quantity',
+ unit: UsageUnit.TOKEN,
+ },
+ {
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.WEB_SEARCH,
+ limitKind: 'quota',
+ meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
+ },
+ {
+ resourceType: UsageResourceType.WORKFLOW,
+ operationType: UsageOperationType.WORKFLOW_EXECUTION,
+ limitKind: 'quota',
+ meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
+ },
+ {
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ limitKind: 'quota',
+ meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
+ },
+ {
+ resourceType: UsageResourceType.EMAIL,
+ operationType: UsageOperationType.EMAIL_SEND,
+ limitKind: 'quota',
+ meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
+ },
+ {
+ resourceType: UsageResourceType.EMAIL,
+ operationType: UsageOperationType.MESSAGE_CAMPAIGN_SEND,
+ limitKind: 'speed',
+ meter: 'quantity',
+ unit: UsageUnit.INVOCATION,
+ },
+ {
+ resourceType: UsageResourceType.API,
+ operationType: UsageOperationType.API_REQUEST,
+ limitKind: 'speed',
+ meter: 'quantity',
+ unit: UsageUnit.REQUEST,
+ },
+ {
+ resourceType: UsageResourceType.WEBHOOK,
+ operationType: UsageOperationType.WEBHOOK_CALL,
+ limitKind: 'speed',
+ meter: 'quantity',
+ unit: UsageUnit.REQUEST,
+ },
+ {
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ limitKind: 'stock',
+ meter: 'quantity',
+ unit: UsageUnit.FILE,
+ },
+ {
+ resourceType: UsageResourceType.RECORD,
+ operationType: UsageOperationType.RECORD_WRITE,
+ limitKind: 'stock',
+ meter: 'quantity',
+ unit: UsageUnit.RECORD,
+ },
+];
+
+describe('2-46 fast instance command 1791186790123 - RenameUsageLimitMeterToUnitFastInstanceCommand (integration)', () => {
+ const command = new RenameUsageLimitMeterToUnitFastInstanceCommand();
+ let queryRunner: QueryRunner;
+ let spenderId: string;
+
+ const insertUsageLimit = async ({
+ resourceType,
+ operationType,
+ limitKind,
+ column,
+ value,
+ }: {
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ limitKind: UsageLimitFixture['limitKind'];
+ column: 'meter' | 'unit';
+ value: string;
+ }): Promise<string> => {
+ const id = v4();
+ const { periodCount, periodUnit } = PERIOD_BY_LIMIT_KIND[limitKind];
+
+ await queryRunner.query(
+ `INSERT INTO "core"."usageLimit" (
+ "id",
+ "workspaceId",
+ "resourceType",
+ "operationType",
+ "spenderType",
+ "spenderId",
+ "limitKind",
+ "periodCount",
+ "periodUnit",
+ "${column}",
+ "limitValue"
+ ) VALUES ($1, $2, $3, $4, 'application', $5, $6, $7, $8, $9, 1000)`,
+ [
+ id,
+ SEED_APPLE_WORKSPACE_ID,
+ resourceType,
+ operationType,
+ spenderId,
+ limitKind,
+ periodCount,
+ periodUnit,
+ value,
+ ],
+ );
+
+ return id;
+ };
+
+ const findColumnValues = async (
+ column: 'meter' | 'unit',
+ ): Promise<Record<string, string>> => {
+ const rows: { id: string; value: string }[] = await queryRunner.query(
+ `SELECT "id", "${column}" AS "value"
+ FROM "core"."usageLimit"
+ WHERE "spenderId" = $1`,
+ [spenderId],
+ );
+
+ return Object.fromEntries(rows.map(({ id, value }) => [id, value]));
+ };
+
+ const findUsageLimitColumns = async (): Promise<
+ {
+ columnName: string;
+ dataType: string;
+ isNullable: string;
+ columnDefault: string | null;
+ }[]
+ > =>
+ queryRunner.query(
+ `SELECT column_name AS "columnName", data_type AS "dataType",
+ is_nullable AS "isNullable", column_default AS "columnDefault"
+ FROM information_schema.columns
+ WHERE table_schema = 'core'
+ AND table_name = 'usageLimit'
+ AND column_name IN ('meter', 'unit')`,
+ );
+
+ const findScopeConstraintDefinition = async (): Promise<string> => {
+ const [row]: { definition: string }[] = await queryRunner.query(
+ `SELECT pg_get_constraintdef(oid) AS "definition"
+ FROM pg_constraint
+ WHERE conname = 'UQ_USAGE_LIMIT_SCOPE'
+ AND conrelid = '"core"."usageLimit"'::regclass`,
+ );
+
+ return row.definition;
+ };
+
+ beforeEach(async () => {
+ spenderId = v4();
+ queryRunner = global.testDataSource.createQueryRunner();
+ await queryRunner.connect();
+ await queryRunner.startTransaction();
+ });
+
+ afterEach(async () => {
+ await queryRunner.rollbackTransaction();
+ await queryRunner.release();
+ });
+
+ it('maps every meter to the unit it counts', async () => {
+ await command.down(queryRunner);
+
+ const expectedUnitById: Record<string, UsageUnit> = {};
+
+ for (const {
+ resourceType,
+ operationType,
+ limitKind,
+ meter,
+ unit,
+ } of METER_FIXTURES) {
+ const usageLimitId = await insertUsageLimit({
+ resourceType,
+ operationType,
+ limitKind,
+ column: 'meter',
+ value: meter,
+ });
+
+ expectedUnitById[usageLimitId] = unit;
+ }
+
+ await command.up(queryRunner);
+
+ expect(await findColumnValues('unit')).toEqual(expectedUnitById);
+ expect(await findUsageLimitColumns()).toEqual([
+ {
+ columnName: 'unit',
+ dataType: 'character varying',
+ isNullable: 'NO',
+ columnDefault: null,
+ },
+ ]);
+ expect(await findScopeConstraintDefinition()).toMatch(
+ /^UNIQUE \("workspaceId", "resourceType", "operationType", "spenderType", "spenderId", "limitKind", "periodCount", "periodUnit", "?unit"?\)$/,
+ );
+ });
+
+ it('drops the limits no meter can hold and maps the rest back on down', async () => {
+ const insertCodeExecutionUsageLimit = (unit: UsageUnit) =>
+ insertUsageLimit({
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ limitKind: 'quota',
+ column: 'unit',
+ value: unit,
+ });
+
+ const creditUsageLimitId = await insertCodeExecutionUsageLimit(
+ UsageUnit.CREDIT,
+ );
+ const invocationUsageLimitId = await insertCodeExecutionUsageLimit(
+ UsageUnit.INVOCATION,
+ );
+
+ await insertCodeExecutionUsageLimit(UsageUnit.MILLISECOND);
+
+ const byteUsageLimitId = await insertUsageLimit({
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ limitKind: 'stock',
+ column: 'unit',
+ value: UsageUnit.BYTE,
+ });
+ const fileUsageLimitId = await insertUsageLimit({
+ resourceType: UsageResourceType.STORAGE,
+ operationType: UsageOperationType.STORAGE_FILE,
+ limitKind: 'stock',
+ column: 'unit',
+ value: UsageUnit.FILE,
+ });
+ const tokenUsageLimitId = await insertUsageLimit({
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ limitKind: 'quota',
+ column: 'unit',
+ value: UsageUnit.TOKEN,
+ });
+
+ await command.down(queryRunner);
+
+ expect(await findColumnValues('meter')).toEqual({
+ [creditUsageLimitId]: 'creditsUsedMicro',
+ [invocationUsageLimitId]: 'quantity',
+ [byteUsageLimitId]: 'bytes',
+ [fileUsageLimitId]: 'quantity',
+ [tokenUsageLimitId]: 'quantity',
+ });
+ expect(await findScopeConstraintDefinition()).toMatch(
+ /"periodUnit", "?meter"?\)$/,
+ );
+ });
+});
diff --git a/packages/twenty-server/test/integration/usage-limit/api-rate-limit.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/api-rate-limit.integration-spec.ts
index b1d75a3dc91..273c143a915 100644
--- a/packages/twenty-server/test/integration/usage-limit/api-rate-limit.integration-spec.ts
+++ b/packages/twenty-server/test/integration/usage-limit/api-rate-limit.integration-spec.ts
@@ -14,6 +14,7 @@ import { ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
const WINDOW_SECONDS = 1;
@@ -131,7 +132,7 @@ describe('API rate limiting', () => {
limitKind: 'speed',
periodCount: WINDOW_SECONDS,
periodUnit: 'second',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
limitValue: LIMIT_VALUE,
burstValue: LIMIT_VALUE,
},
diff --git a/packages/twenty-server/test/integration/usage-limit/quota-consumption.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/quota-consumption.integration-spec.ts
new file mode 100644
index 00000000000..e86bd1c01b8
--- /dev/null
+++ b/packages/twenty-server/test/integration/usage-limit/quota-consumption.integration-spec.ts
@@ -0,0 +1,375 @@
+import { createOneLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/create-logic-function.util';
+import { deleteLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/delete-logic-function.util';
+import { executeLogicFunction } from 'test/integration/metadata/suites/logic-function/utils/execute-logic-function.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { expectEventually } from 'test/integration/utils/expect-eventually.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
+
+import {
+ type ClickHouseClient,
+ ClickHouseLogLevel,
+ createClient as createClickHouseClient,
+} from '@clickhouse/client';
+import { gql } from 'graphql-tag';
+import { createClient as createRedisClient } from 'redis';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { type Repository } from 'typeorm';
+
+import { formatDateTimeForClickHouse } from 'src/database/clickhouse/utils/format-date-time-for-clickhouse.util';
+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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
+import { LogicFunctionExecutionStatus } from 'src/engine/metadata-modules/logic-function/dtos/logic-function-execution-result.dto';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const LOGIC_FUNCTION_CODE = `export const main = async (): Promise<object> => {
+ return { isDone: true };
+};`;
+
+const SEEDED_RUNS = [
+ {
+ invocationCreditsMicro: 1_000,
+ durationMs: 1_500,
+ durationCreditsMicro: 150,
+ },
+ {
+ invocationCreditsMicro: 1_000,
+ durationMs: 3_000,
+ durationCreditsMicro: 300,
+ },
+ {
+ invocationCreditsMicro: 1_000,
+ durationMs: 4_500,
+ durationCreditsMicro: 450,
+ },
+];
+
+const SEEDED_CONSUMPTION_BY_UNIT = {
+ [UsageUnit.INVOCATION]: SEEDED_RUNS.length,
+ [UsageUnit.CREDIT]: 3_900,
+};
+
+const QUOTA_UNITS = [UsageUnit.INVOCATION, UsageUnit.CREDIT] as const;
+
+const EXECUTED_RUN_COUNT = 2;
+const UNREACHABLE_LIMIT_VALUE = 1_000_000_000_000;
+const CLICKHOUSE_FLUSH_TIMEOUT_MS = 30_000;
+const EXECUTION_TIMEOUT_MS = 120_000;
+
+const USAGE_QUOTAS_WITH_CONSUMPTION = gql`
+ query UsageQuotasWithConsumption {
+ usageQuotasWithConsumption {
+ id
+ unit
+ isEnforced
+ consumedValue
+ }
+ }
+`;
+
+const USAGE_QUOTA_SCOPE_CONSUMPTION = gql`
+ query UsageQuotaScopeConsumption($input: UsageQuotaScopeInput!) {
+ usageQuotaScopeConsumption(input: $input) {
+ consumedValue
+ }
+ }
+`;
+
+type QuotaUnit = (typeof QUOTA_UNITS)[number];
+
+describe('Usage quota consumption', () => {
+ let clickHouseClient: ClickHouseClient;
+ let redis: Awaited<ReturnType<typeof createRedisClient>>;
+ let usageLimitRepository: Repository<UsageLimitEntity>;
+ let logicFunctionId: string;
+ let usageLimitIdByUnit: Record<QuotaUnit, string>;
+ const savedUsageLimitIds: string[] = [];
+
+ const refreshUsageLimitsCache = () =>
+ getAppProviderByClassName<WorkspaceCacheService>(
+ 'WorkspaceCacheService',
+ ).invalidateAndRecompute(SEED_APPLE_WORKSPACE_ID, ['usageLimits']);
+
+ const findQuotaCounterKeys = () =>
+ redis.keys(
+ `*{${SEED_APPLE_WORKSPACE_ID}}:quota:${UsageResourceType.LOGIC_FUNCTION}:${UsageOperationType.CODE_EXECUTION}:logicFunction:${logicFunctionId}:*`,
+ );
+
+ const countUsageEventRows = async (): Promise<number> => {
+ const result = await clickHouseClient.query({
+ query: `SELECT count() AS rowCount
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND logicFunctionId = {logicFunctionId:String}`,
+ query_params: { workspaceId: SEED_APPLE_WORKSPACE_ID, logicFunctionId },
+ format: 'JSONEachRow',
+ });
+
+ const [row] = await result.json<{ rowCount: string }>();
+
+ return Number(row?.rowCount ?? 0);
+ };
+
+ const waitForUsageEventRows = (expectedRowCount: number) =>
+ expectEventually(
+ async () => {
+ expect(await countUsageEventRows()).toBe(expectedRowCount);
+ },
+ { timeoutMs: CLICKHOUSE_FLUSH_TIMEOUT_MS, intervalMs: 250 },
+ );
+
+ const insertSeededRuns = async () => {
+ const timestamp = formatDateTimeForClickHouse(new Date());
+ const baseRow = {
+ timestamp,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ resourceId: logicFunctionId,
+ logicFunctionId,
+ metadata: {},
+ };
+
+ await clickHouseClient.insert({
+ table: 'usageEvent',
+ values: SEEDED_RUNS.flatMap(
+ ({ invocationCreditsMicro, durationMs, durationCreditsMicro }) => [
+ {
+ ...baseRow,
+ unit: UsageUnit.INVOCATION,
+ quantity: 1,
+ creditsUsedMicro: invocationCreditsMicro,
+ },
+ {
+ ...baseRow,
+ unit: UsageUnit.MILLISECOND,
+ quantity: durationMs,
+ creditsUsedMicro: durationCreditsMicro,
+ },
+ ],
+ ),
+ format: 'JSONEachRow',
+ });
+ };
+
+ const saveCodeExecutionQuota = async (unit: QuotaUnit): Promise<string> => {
+ const usageLimit = await usageLimitRepository.save({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ spenderType: 'logicFunction',
+ spenderId: logicFunctionId,
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ unit,
+ limitValue: UNREACHABLE_LIMIT_VALUE,
+ burstValue: null,
+ isInstanceOverride: true,
+ });
+
+ savedUsageLimitIds.push(usageLimit.id);
+
+ return usageLimit.id;
+ };
+
+ const findQuotaConsumedValue = async (unit: QuotaUnit) => {
+ const response = await makeMetadataApiRequest({
+ query: USAGE_QUOTAS_WITH_CONSUMPTION,
+ });
+
+ expect(response.body.errors).toBeUndefined();
+
+ const usageQuota = response.body.data.usageQuotasWithConsumption.find(
+ (quota: { id: string }) => quota.id === usageLimitIdByUnit[unit],
+ );
+
+ jestExpectToBeDefined(usageQuota);
+ expect(usageQuota).toMatchObject({ unit, isEnforced: true });
+
+ return usageQuota.consumedValue;
+ };
+
+ const findScopeConsumedValue = async (unit: QuotaUnit) => {
+ const response = await makeMetadataApiRequest({
+ query: USAGE_QUOTA_SCOPE_CONSUMPTION,
+ variables: {
+ input: {
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ spenderType: 'logicFunction',
+ spenderId: logicFunctionId,
+ periodUnit: 'month',
+ unit,
+ },
+ },
+ });
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.usageQuotaScopeConsumption.consumedValue;
+ };
+
+ const executeRun = () =>
+ executeLogicFunction({
+ input: { id: logicFunctionId, payload: {} },
+ expectToFail: false,
+ });
+
+ beforeAll(async () => {
+ clickHouseClient = createClickHouseClient({
+ url: process.env.CLICKHOUSE_URL,
+ clickhouse_settings: {
+ allow_experimental_json_type: 1,
+ },
+ log: { level: ClickHouseLogLevel.OFF },
+ });
+ redis = await createRedisClient({ url: process.env.REDIS_URL }).connect();
+ usageLimitRepository =
+ getCoreRepository<UsageLimitEntity>(UsageLimitEntity);
+
+ const { data } = await createOneLogicFunction({
+ input: {
+ name: 'Usage quota consumption',
+ source: {
+ sourceHandlerCode: LOGIC_FUNCTION_CODE,
+ handlerName: 'main',
+ },
+ },
+ expectToFail: false,
+ });
+
+ logicFunctionId = data?.createOneLogicFunction?.id;
+ jestExpectToBeDefined(logicFunctionId);
+
+ await insertSeededRuns();
+ await waitForUsageEventRows(SEEDED_RUNS.length * 2);
+
+ usageLimitIdByUnit = {
+ [UsageUnit.INVOCATION]: await saveCodeExecutionQuota(
+ UsageUnit.INVOCATION,
+ ),
+ [UsageUnit.CREDIT]: await saveCodeExecutionQuota(UsageUnit.CREDIT),
+ };
+
+ await refreshUsageLimitsCache();
+ }, EXECUTION_TIMEOUT_MS);
+
+ afterAll(async () => {
+ if (isNonEmptyArray(savedUsageLimitIds)) {
+ await usageLimitRepository.delete(savedUsageLimitIds);
+ }
+
+ await refreshUsageLimitsCache();
+
+ const quotaCounterKeys = await findQuotaCounterKeys();
+
+ if (quotaCounterKeys.length > 0) {
+ await redis.del(quotaCounterKeys);
+ }
+
+ await clickHouseClient.command({
+ query: `ALTER TABLE usageEvent DELETE WHERE workspaceId = '${SEED_APPLE_WORKSPACE_ID}' AND logicFunctionId = '${logicFunctionId}'`,
+ clickhouse_settings: { mutations_sync: '2' },
+ });
+
+ await deleteLogicFunction({
+ input: { id: logicFunctionId },
+ expectToFail: false,
+ });
+
+ await redis.quit();
+ await clickHouseClient.close();
+ }, EXECUTION_TIMEOUT_MS);
+
+ it.each(QUOTA_UNITS)(
+ 'previews the same cold %s consumption as the quota list',
+ async (unit) => {
+ expect(await findQuotaCounterKeys()).toEqual([]);
+
+ const quotaConsumedValue = await findQuotaConsumedValue(unit);
+ const scopeConsumedValue = await findScopeConsumedValue(unit);
+
+ expect(quotaConsumedValue).toBe(SEEDED_CONSUMPTION_BY_UNIT[unit]);
+ expect(scopeConsumedValue).toBe(SEEDED_CONSUMPTION_BY_UNIT[unit]);
+ },
+ EXECUTION_TIMEOUT_MS,
+ );
+
+ it(
+ 'keeps the warm counters equal to the recorded rows',
+ async () => {
+ for (let runIndex = 0; runIndex < EXECUTED_RUN_COUNT; runIndex++) {
+ const { data, errors } = await executeRun();
+
+ expect(errors).toBeUndefined();
+ expect(data?.executeOneLogicFunction?.status).toBe(
+ LogicFunctionExecutionStatus.SUCCESS,
+ );
+ }
+
+ expect(await findQuotaCounterKeys()).toHaveLength(QUOTA_UNITS.length);
+
+ await waitForUsageEventRows(
+ (SEEDED_RUNS.length + EXECUTED_RUN_COUNT) * 2,
+ );
+
+ for (const unit of QUOTA_UNITS) {
+ const quotaConsumedValue = await findQuotaConsumedValue(unit);
+ const scopeConsumedValue = await findScopeConsumedValue(unit);
+
+ expect(quotaConsumedValue).toBe(scopeConsumedValue);
+ expect(quotaConsumedValue).toBeGreaterThanOrEqual(
+ SEEDED_CONSUMPTION_BY_UNIT[unit],
+ );
+ }
+
+ expect(await findQuotaConsumedValue(UsageUnit.INVOCATION)).toBe(
+ SEEDED_RUNS.length + EXECUTED_RUN_COUNT,
+ );
+ },
+ EXECUTION_TIMEOUT_MS,
+ );
+
+ it(
+ 'admits the last run under the invocation quota and refuses the next one',
+ async () => {
+ const invocationLimit =
+ Number(await findQuotaConsumedValue(UsageUnit.INVOCATION)) + 1;
+ const usageEventRowCount = await countUsageEventRows();
+
+ await usageLimitRepository.update(
+ { id: usageLimitIdByUnit[UsageUnit.INVOCATION] },
+ { limitValue: invocationLimit },
+ );
+ await refreshUsageLimitsCache();
+
+ const admitted = await executeRun();
+
+ expect(admitted.errors).toBeUndefined();
+ expect(admitted.data?.executeOneLogicFunction?.status).toBe(
+ LogicFunctionExecutionStatus.SUCCESS,
+ );
+
+ const refused = await executeLogicFunction({
+ input: { id: logicFunctionId, payload: {} },
+ expectToFail: true,
+ });
+
+ expect(refused.errors?.[0]?.extensions).toMatchObject({
+ subCode: 'QUOTA_EXHAUSTED',
+ exhaustedKind: 'limit',
+ unit: UsageUnit.INVOCATION,
+ limit: invocationLimit,
+ scope: { spenderType: 'logicFunction', spenderId: logicFunctionId },
+ });
+
+ await waitForUsageEventRows(usageEventRowCount + 2);
+ },
+ EXECUTION_TIMEOUT_MS,
+ );
+});
diff --git a/packages/twenty-server/test/integration/usage-limit/record-stock-limit.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/record-stock-limit.integration-spec.ts
index 0e850f48961..b659e6e5c9e 100644
--- a/packages/twenty-server/test/integration/usage-limit/record-stock-limit.integration-spec.ts
+++ b/packages/twenty-server/test/integration/usage-limit/record-stock-limit.integration-spec.ts
@@ -14,6 +14,7 @@ import { RECORD_STOCK_TRACKED_SYSTEM_OBJECT_UNIVERSAL_IDENTIFIERS } from 'src/en
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
@@ -168,7 +169,7 @@ describe('Record stock limit', () => {
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'quantity',
+ unit: UsageUnit.RECORD,
limitValue: baselineRecordCount + HEADROOM,
burstValue: null,
},
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
index 5a18d0df660..9d88d272070 100644
--- 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
@@ -10,6 +10,7 @@ import { type CreateUsageLimitInput } from 'src/engine/core-modules/usage-limit/
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
const CREATE_USAGE_LIMIT = gql`
@@ -59,7 +60,7 @@ const buildPayload = (
limitKind: 'quota',
periodCount: 1,
periodUnit: 'month',
- meter: 'creditsUsedMicro',
+ unit: UsageUnit.CREDIT,
limitValue: 1_000_000,
burstValue: null,
...overrides,
@@ -163,6 +164,18 @@ describe('Usage limit mutations', () => {
'A quota limit cannot hold a burst value',
);
});
+
+ it('refuses a unit the operation does not record', async () => {
+ const response = await createUsageLimitRequest({
+ resourceType: UsageResourceType.EMAIL,
+ operationType: UsageOperationType.EMAIL_SEND,
+ unit: UsageUnit.MILLISECOND,
+ });
+
+ expect(response.body.errors?.[0]?.message).toBe(
+ 'EMAIL EMAIL_SEND quota limits cannot count MILLISECOND, only CREDIT, INVOCATION',
+ );
+ });
});
describe('updateUsageLimit', () => {
@@ -261,7 +274,7 @@ describe('Usage limit mutations', () => {
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'quantity',
+ unit: UsageUnit.FILE,
limitValue: 5_000,
}),
spenderId: '',
@@ -271,7 +284,7 @@ describe('Usage limit mutations', () => {
const usageLimit = await usageLimitRepository.findOneByOrFail({
workspaceId: SEED_APPLE_WORKSPACE_ID,
- meter: 'quantity',
+ unit: UsageUnit.FILE,
});
return usageLimit;
@@ -287,7 +300,7 @@ describe('Usage limit mutations', () => {
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'quantity',
+ unit: UsageUnit.FILE,
limitValue: 9_000_000,
});
@@ -329,7 +342,7 @@ describe('Usage limit mutations', () => {
limitKind: 'stock',
periodCount: 1,
periodUnit: 'lifetime',
- meter: 'bytes',
+ unit: UsageUnit.BYTE,
limitValue: 1_000_000,
...overrides,
});
@@ -368,10 +381,10 @@ describe('Usage limit mutations', () => {
).toBe(0);
});
- it('allows a workspace write on a meter no default covers', async () => {
+ it('allows a workspace write on a unit no default covers', async () => {
const response = await makeMetadataApiRequest({
query: CREATE_USAGE_LIMIT,
- variables: { input: storageStockPayload({ meter: 'quantity' }) },
+ variables: { input: storageStockPayload({ unit: UsageUnit.FILE }) },
});
expect(response.body.errors).toBeUndefined();
@@ -385,7 +398,7 @@ describe('Usage limit mutations', () => {
variables: {
input: {
id: usageLimit.id,
- payload: storageStockPayload({ meter: 'quantity' }),
+ payload: storageStockPayload({ unit: UsageUnit.FILE }),
},
},
});
@@ -395,8 +408,8 @@ describe('Usage limit mutations', () => {
);
expect(
(await usageLimitRepository.findOneByOrFail({ id: usageLimit.id }))
- .meter,
- ).toBe('bytes');
+ .unit,
+ ).toBe(UsageUnit.BYTE);
});
it('refuses deleting an operator override', async () => {
diff --git a/packages/twenty-server/test/integration/usage-limit/webhook-rate-limit.integration-spec.ts b/packages/twenty-server/test/integration/usage-limit/webhook-rate-limit.integration-spec.ts
index a0c26cc1db8..c28fb555840 100644
--- a/packages/twenty-server/test/integration/usage-limit/webhook-rate-limit.integration-spec.ts
+++ b/packages/twenty-server/test/integration/usage-limit/webhook-rate-limit.integration-spec.ts
@@ -18,6 +18,7 @@ import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-
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 { UsageUnit } from 'src/engine/core-modules/usage/enums/usage-unit.enum';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
const WEBHOOK_RECEIVER_PORT = 4318;
@@ -120,7 +121,7 @@ describe('Webhook rate limiting', () => {
limitKind: 'speed',
periodCount: WINDOW_SECONDS,
periodUnit: 'second',
- meter: 'quantity',
+ unit: UsageUnit.REQUEST,
limitValue: LIMIT_VALUE,
burstValue: LIMIT_VALUE,
},