Skip to content

The open alternative to Salesforce, designed for AI.

Split usage by application and give apps a billing block: usage, recurring fees, and pricing (#24541)

Félix Malfait33f2bc470898
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 25ab105688b..9fbd6ec07d1 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -968,6 +968,7 @@ enum UsageOperationType {
CALL_RECORDING
EMAIL_SEND
API_REQUEST
+ SUBSCRIPTION
}
"""
@@ -1774,6 +1775,7 @@ type UsageUserDaily {
type UsageAnalytics {
usageByUser: [UsageBreakdownItem!]!
usageByOperationType: [UsageBreakdownItem!]!
+ usageByApplication: [UsageBreakdownItem!]!
usageByModel: [UsageBreakdownItem!]!
timeSeries: [UsageTimeSeries!]!
periodStart: DateTime!
@@ -2260,6 +2262,7 @@ type MarketplaceAppDetail {
logoUrl: String
websiteUrl: String
aboutDescription: String
+ pricingDescription: String
termsUrl: String
emailSupport: String
issueReportUrl: String
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 23f9e879342..64c271df351 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -682,7 +682,7 @@ export interface UsageLimit {
export type UsageResourceType = 'AI' | 'WORKFLOW' | 'APP' | 'STORAGE' | 'API' | 'LOGIC_FUNCTION' | 'EMAIL'
-export type UsageOperationType = 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST'
+export type UsageOperationType = 'AI_CHAT_TOKEN' | 'AI_WORKFLOW_TOKEN' | 'WORKFLOW_EXECUTION' | 'CODE_EXECUTION' | 'WEB_SEARCH' | 'CALL_RECORDING' | 'EMAIL_SEND' | 'API_REQUEST' | 'SUBSCRIPTION'
export interface SdkClientChecksums {
core?: Scalars['String']
@@ -1414,6 +1414,7 @@ export interface UsageUserDaily {
export interface UsageAnalytics {
usageByUser: UsageBreakdownItem[]
usageByOperationType: UsageBreakdownItem[]
+ usageByApplication: UsageBreakdownItem[]
usageByModel: UsageBreakdownItem[]
timeSeries: UsageTimeSeries[]
periodStart: Scalars['DateTime']
@@ -1914,6 +1915,7 @@ export interface MarketplaceAppDetail {
logoUrl?: Scalars['String']
websiteUrl?: Scalars['String']
aboutDescription?: Scalars['String']
+ pricingDescription?: Scalars['String']
termsUrl?: Scalars['String']
emailSupport?: Scalars['String']
issueReportUrl?: Scalars['String']
@@ -4860,6 +4862,7 @@ export interface UsageUserDailyGenqlSelection{
export interface UsageAnalyticsGenqlSelection{
usageByUser?: UsageBreakdownItemGenqlSelection
usageByOperationType?: UsageBreakdownItemGenqlSelection
+ usageByApplication?: UsageBreakdownItemGenqlSelection
usageByModel?: UsageBreakdownItemGenqlSelection
timeSeries?: UsageTimeSeriesGenqlSelection
periodStart?: boolean | number
@@ -5397,6 +5400,7 @@ export interface MarketplaceAppDetailGenqlSelection{
logoUrl?: boolean | number
websiteUrl?: boolean | number
aboutDescription?: boolean | number
+ pricingDescription?: boolean | number
termsUrl?: boolean | number
emailSupport?: boolean | number
issueReportUrl?: boolean | number
@@ -9973,7 +9977,8 @@ export const enumUsageOperationType = {
WEB_SEARCH: 'WEB_SEARCH' as const,
CALL_RECORDING: 'CALL_RECORDING' as const,
EMAIL_SEND: 'EMAIL_SEND' as const,
- API_REQUEST: 'API_REQUEST' as const
+ API_REQUEST: 'API_REQUEST' as const,
+ SUBSCRIPTION: 'SUBSCRIPTION' as const
}
export const enumWidgetType = {
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 3096945fc2e..b1441c9676b 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -3410,6 +3410,9 @@ export default {
"usageByOperationType": [
171
],
+ "usageByApplication": [
+ 171
+ ],
"usageByModel": [
171
],
@@ -4507,6 +4510,9 @@ export default {
"aboutDescription": [
1
],
+ "pricingDescription": [
+ 1
+ ],
"termsUrl": [
1
],
diff --git a/packages/twenty-docs/developers/extend/apps/config/application.mdx b/packages/twenty-docs/developers/extend/apps/config/application.mdx
index 0204c68ec83..e767be1a9ee 100644
--- a/packages/twenty-docs/developers/extend/apps/config/application.mdx
+++ b/packages/twenty-docs/developers/extend/apps/config/application.mdx
@@ -10,6 +10,7 @@ Every app must have exactly one `defineApplication` call. It declares:
- **Permissions** — which role its logic functions and front components run under.
- **Variables** *(optional)* — key–value pairs exposed to your code as environment variables.
- **Pre-install / post-install / uninstall hooks** *(optional)* — see [Logic Functions](/developers/extend/apps/logic/logic-functions).
+- **Billing** *(optional)* — `billing.recurring` for subscription fees the platform raises automatically, `billing.operations` for what your app charges credits for, and `billing.description` for the marketplace; see [Charging Credits](/developers/extend/apps/logic/credits).
```ts src/application-config.ts
import { defineApplication } from 'twenty-sdk/define';
@@ -115,6 +116,7 @@ If you plan to [publish your app](/developers/extend/apps/operations/publishing)
| `logo` | Path to your app logo bundled in `public/` (e.g., `public/logo.png`) |
| `galleryImages` | Array of gallery image paths bundled in `public/` (e.g., `public/screenshot-1.png`) |
| `aboutDescription` | Longer markdown description for the "About" tab. If omitted, the marketplace uses the package's `README.md` from npm |
+| `billing.description` | What the app costs, in one short friendly line shown next to the install button (e.g. `$0.02 per minute recorded`). Set it if your app [charges credits](/developers/extend/apps/logic/credits) |
| `websiteUrl` | Link to your website |
| `termsUrl` | Link to terms of service |
| `emailSupport` | Support email address |
diff --git a/packages/twenty-docs/developers/extend/apps/logic/credits.mdx b/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
new file mode 100644
index 00000000000..51daa89fc1a
--- /dev/null
+++ b/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
@@ -0,0 +1,179 @@
+---
+title: Charging Credits
+description: Declare what your app bills for and charge workspace credits from a logic function.
+icon: "coins"
+---
+
+<Warning>
+ Not live yet. Credit charging for apps launches officially in October. This page is published early for partners who want to experiment with it.
+</Warning>
+
+Apps that cost money to run — a call recorder paying a transcription provider, an enrichment app paying per match — charge the workspace in **credits**. Everything an app bills for is declared in one `billing` block on your application config:
+
+```ts src/application-config.ts
+import { defineApplication } from 'twenty-sdk/define';
+
+export default defineApplication({
+ // ...identity, variables...
+ billing: {
+ description: '$20/month + $0.02 per minute recorded',
+ recurring: {
+ platformFee: {
+ period: 'MONTH',
+ amountMicroCredits: 20_000_000,
+ label: 'Platform fee',
+ },
+ },
+ operations: {
+ recordMeeting: {
+ operationType: 'CALL_RECORDING',
+ label: 'Meeting recording',
+ },
+ },
+ },
+});
+```
+
+- `recurring` — flat and per-member fees the **platform** raises for you, once per billing period.
+- `operations` — what you charge for as you use it, from a logic function.
+- `description` — one friendly line shown to buyers on your marketplace listing.
+
+All three land on the same credit meter and the same **Settings > Usage** breakdown, so a workspace sees one bill.
+
+## Recurring charges
+
+A recurring charge is a subscription fee: a flat monthly amount, an amount per workspace member, or both. You declare the amount and the platform charges it. Your app never calls `chargeCredits` for these.
+
+```ts src/application-config.ts
+billing: {
+ recurring: {
+ platformFee: {
+ period: 'MONTH',
+ amountMicroCredits: 20_000_000,
+ label: 'Platform fee',
+ },
+ seat: {
+ period: 'MONTH',
+ amountMicroCredits: 5_000_000,
+ per: 'WORKSPACE_MEMBER',
+ label: 'Per member',
+ },
+ },
+},
+```
+
+| Field | Description |
+|-------|-------------|
+| `period` | `MONTH` — the only period today |
+| `amountMicroCredits` | Amount in micro-credits (1 USD = 1,000,000), a positive integer up to 100,000,000 ($100). For a `WORKSPACE_MEMBER` charge this is the rate **per member**, not the total |
+| `per` | Omit for a flat fee. `WORKSPACE_MEMBER` multiplies the amount by the number of members in the workspace when the period is charged |
+| `label` | What admins read for that line in Usage |
+
+How they are raised:
+
+- Once per workspace billing period, on the workspace's own period boundary, not on the first of the month.
+- Not prorated. An app installed mid-period is charged the full amount for that period; uninstalling stops the next period, it does not refund the current one.
+- Per-member charges count all workspace members at the moment the charge is raised, so a workspace that grows mid-period pays the higher count from the next period.
+- Only on monthly subscriptions. A workspace on a yearly plan is not charged a `MONTH` fee, rather than being charged once for the whole year.
+- Bounded. A declared rate above $100, or a per-member charge whose rate multiplied by the member count would exceed $1,000 for the period, is refused and not raised. The platform raises these itself, so it will not write a debit it cannot justify.
+
+## Billable operations
+
+An operation is what your app charges for as it works. Each entry maps an operation name you choose onto the billing category the platform meters, plus the label shown to workspace admins in **Settings > Usage**.
+
+```ts src/application-config.ts
+billing: {
+ operations: {
+ recordMeeting: {
+ operationType: 'CALL_RECORDING',
+ label: 'Meeting recording',
+ },
+ summarizeMeeting: {
+ operationType: 'AI_CHAT_TOKEN',
+ label: 'Meeting summary',
+ },
+ },
+},
+```
+
+`operationType` must be one of the platform's billing categories: `AI_CHAT_TOKEN`, `AI_WORKFLOW_TOKEN`, `WORKFLOW_EXECUTION`, `CODE_EXECUTION`, `WEB_SEARCH`, `CALL_RECORDING`, `EMAIL_SEND`. It decides how the spend is metered and which counting unit applies (tokens, invocations, minutes) — it is not what admins read. The `label` is.
+
+The build rejects an unknown `operationType`, an empty `label`, and a name used by both a recurring charge and an operation.
+
+## Charging
+
+Charge against a declared operation by name:
+
+```ts
+import { chargeCredits } from 'twenty-sdk/billing';
+
+await chargeCredits({
+ operation: 'recordMeeting',
+ creditsUsedMicro: 250_000,
+ quantity: 12,
+});
+```
+
+`creditsUsedMicro` is the amount in micro-credits (1 USD = 1,000,000). `quantity` is how many units the charge covers, in the unit implied by the operation's category — minutes for `CALL_RECORDING`, invocations for `CODE_EXECUTION`, and so on.
+
+Notes:
+
+- Declaring operations is what lets Usage split your app's spend by what it charged for. An app that declares nothing is still reported, as a single slice under its display name.
+- Charging an operation your manifest does not declare is rejected. Add it to `billing.operations` and sync.
+- Several operations may share one `operationType`. Two enrichment operations both metered as `CODE_EXECUTION` still show as two labelled slices.
+- Without `operation`, name the billing category directly with `operationType`, optionally with a free-form `resourceContext`. The two forms are mutually exclusive: `operation` carries the label, `operationType` does not.
+- Charging never fails your function. A billing error is logged and swallowed, and the call no-ops outside the logic function runtime so local runs and tests do not crash.
+
+## Checking before you spend
+
+A workspace can run out of credits. Your app is not stopped when that happens, but some of the platform's own work is. `runAgent` returns an error instead of running, and the other AI entry points refuse outright. So an app that does its expensive work first and calls the platform at the end can fail late, on a call it did not write.
+
+Ask first:
+
+```ts
+import { getCreditAvailability } from 'twenty-sdk/billing';
+
+const { hasAvailableCredits } = await getCreditAvailability();
+
+if (!hasAvailableCredits) {
+ return;
+}
+```
+
+When credits are unavailable a `reason` comes with it: `no-credits`, `no-subscription`, or `workspace-suspended`.
+
+Notes:
+
+- It answers whether the workspace may spend, not how much it has left. Your app does not see the balance or the plan.
+- It fails open. If the check times out or the server is unreachable it reports credits available, so an infrastructure hiccup does not stop your app. Treat it as a hint worth honouring, not as an authorization decision.
+- It is a snapshot. Credits can run out between the check and the work.
+- The gate is not applied uniformly. Workflow runs are not credit-gated, and neither is every outbound email path, so a `false` here tells you the workspace is out of credits rather than predicting exactly which calls will fail.
+
+## Telling people what it costs
+
+Declaring charges tells the platform how to *meter* your app; it does not tell a buyer what they will pay. Set `billing.description` for that — one short, friendly line rendered next to the install button on your marketplace listing, before anyone installs.
+
+```ts src/application-config.ts
+billing: {
+ description: '$0.02 per minute recorded, billed to your Twenty credits',
+},
+```
+
+It is free text on purpose: real pricing has tiers, minimums and per-unit rates that a single number cannot express. Keep it to a line — it renders in a narrow column.
+
+## Attribution
+
+Spend is attributed to whoever triggered the run, so it shows up in **Usage by User**. Runs with nobody behind them (a webhook, a cron) have no triggering person — pass `userWorkspaceId` if your app knows who the spend belongs to. It must belong to the workspace the app is installed in, and it is ignored when the run does have a triggering user.
+
+```ts
+await chargeCredits({
+ operation: 'recordMeeting',
+ creditsUsedMicro: 250_000,
+ quantity: 12,
+ userWorkspaceId: ownerUserWorkspaceId,
+});
+```
+
+Where to get one: `context.userWorkspaceId` on a triggered run, or [`listConnections()`](/developers/extend/apps/logic/connections), which returns the `userWorkspaceId` of each connection's owner.
+
+Recurring charges have no triggering person, so they are reported against the app only, never against a member.
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index c8e7cd56387..8e87e5a492a 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -521,7 +521,7 @@ const asApplication = new RestApiClient({ runAs: 'application' });
Check `context.workspaceMemberId` when a function behaves differently depending on whether someone is behind it, for instance to attribute a record.
</Note>
-The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), `runAgent`, `getPublicAssetUrl` and credit charging.
+The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), `runAgent`, `getPublicAssetUrl` and [credit charging](/developers/extend/apps/logic/credits).
#### Exposing a function as an AI tool or workflow action
diff --git a/packages/twenty-docs/developers/extend/apps/logic/overview.mdx b/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
index 2f7d841a648..428f1ff5b84 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
@@ -40,6 +40,9 @@ A Twenty app's **logic layer** is the code that *runs* — server-side TypeScrip
<Card title="Background Jobs" icon="layer-group" href="/developers/extend/apps/logic/background-jobs">
Enqueue a logic function run on the workers to get past the per-run timeout.
</Card>
+ <Card title="Charging Credits" icon="coins" href="/developers/extend/apps/logic/credits">
+ Declare what your app bills for and charge workspace credits for it.
+ </Card>
</CardGroup>
## Trigger types at a glance
diff --git a/packages/twenty-docs/docs.json b/packages/twenty-docs/docs.json
index 976e7f7f122..1b95dc35f56 100644
--- a/packages/twenty-docs/docs.json
+++ b/packages/twenty-docs/docs.json
@@ -439,7 +439,8 @@
"developers/extend/apps/logic/key-value-store",
"developers/extend/apps/logic/background-jobs",
"developers/extend/apps/logic/skills-and-agents",
- "developers/extend/apps/logic/connections"
+ "developers/extend/apps/logic/connections",
+ "developers/extend/apps/logic/credits"
]
},
{
diff --git a/packages/twenty-docs/navigation/base-structure.json b/packages/twenty-docs/navigation/base-structure.json
index bff899d3e51..6db4f47b838 100644
--- a/packages/twenty-docs/navigation/base-structure.json
+++ b/packages/twenty-docs/navigation/base-structure.json
@@ -440,7 +440,8 @@
"developers/extend/apps/logic/key-value-store",
"developers/extend/apps/logic/background-jobs",
"developers/extend/apps/logic/skills-and-agents",
- "developers/extend/apps/logic/connections"
+ "developers/extend/apps/logic/connections",
+ "developers/extend/apps/logic/credits"
]
},
{
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 58168f6bd23..a1ee4fba57e 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -2484,6 +2484,7 @@ export type MarketplaceAppDetail = {
/** @deprecated Use the explicit MarketplaceAppDetail fields (description, author, roles, ...) instead */
manifest?: Maybe<Scalars['JSON']['output']>;
name: Scalars['String']['output'];
+ pricingDescription?: Maybe<Scalars['String']['output']>;
roles?: Maybe<Array<MarketplaceAppRole>>;
/** @deprecated Use galleryImages instead */
screenshots: Array<Scalars['String']['output']>;
@@ -6481,6 +6482,7 @@ export type UsageAnalytics = {
periodEnd: Scalars['DateTime']['output'];
periodStart: Scalars['DateTime']['output'];
timeSeries: Array<UsageTimeSeries>;
+ usageByApplication: Array<UsageBreakdownItem>;
usageByModel: Array<UsageBreakdownItem>;
usageByOperationType: Array<UsageBreakdownItem>;
usageByUser: Array<UsageBreakdownItem>;
@@ -6524,6 +6526,7 @@ export enum UsageOperationType {
CALL_RECORDING = 'CALL_RECORDING',
CODE_EXECUTION = 'CODE_EXECUTION',
EMAIL_SEND = 'EMAIL_SEND',
+ SUBSCRIPTION = 'SUBSCRIPTION',
WEB_SEARCH = 'WEB_SEARCH',
WORKFLOW_EXECUTION = 'WORKFLOW_EXECUTION'
}
@@ -8039,7 +8042,7 @@ export type GetLogicFunctionSourceCodeQueryVariables = Exact<{
export type GetLogicFunctionSourceCodeQuery = { __typename?: 'Query', getLogicFunctionSourceCode?: string | null };
-export type MarketplaceAppDetailFieldsFragment = { __typename?: 'MarketplaceAppDetail', id: string, universalIdentifier: string, name: string, sourceType: ApplicationRegistrationSourceType, sourcePackage?: string | null, latestAvailableVersion?: string | null, isListed: boolean, isVetted: boolean, description?: string | null, author?: string | null, category?: string | null, logoUrl?: string | null, websiteUrl?: string | null, aboutDescription?: string | null, termsUrl?: string | null, emailSupport?: string | null, issueReportUrl?: string | null, galleryImages: Array<string>, defaultRoleUniversalIdentifier?: string | null, roles?: Array<{ __typename?: 'MarketplaceAppRole', universalIdentifier: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings?: boolean | null, canAccessAllTools?: boolean | null, canReadAllObjectRecords?: boolean | null, canUpdateAllObjectRecords?: boolean | null, canSoftDeleteAllObjectRecords?: boolean | null, canDestroyAllObjectRecords?: boolean | null, permissionFlagUniversalIdentifiers?: Array<string> | null, objectPermissions?: Array<{ __typename?: 'MarketplaceAppRoleObjectPermission', universalIdentifier: string, objectUniversalIdentifier: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null }> | null, fieldPermissions?: Array<{ __typename?: 'MarketplaceAppRoleFieldPermission', universalIdentifier: string, objectUniversalIdentifier: string, fieldUniversalIdentifier: string, canReadFieldValue?: boolean | null, canUpdateFieldValue?: boolean | null }> | null }> | null };
+export type MarketplaceAppDetailFieldsFragment = { __typename?: 'MarketplaceAppDetail', id: string, universalIdentifier: string, name: string, sourceType: ApplicationRegistrationSourceType, sourcePackage?: string | null, latestAvailableVersion?: string | null, isListed: boolean, isVetted: boolean, description?: string | null, author?: string | null, category?: string | null, logoUrl?: string | null, websiteUrl?: string | null, aboutDescription?: string | null, pricingDescription?: string | null, termsUrl?: string | null, emailSupport?: string | null, issueReportUrl?: string | null, galleryImages: Array<string>, defaultRoleUniversalIdentifier?: string | null, roles?: Array<{ __typename?: 'MarketplaceAppRole', universalIdentifier: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings?: boolean | null, canAccessAllTools?: boolean | null, canReadAllObjectRecords?: boolean | null, canUpdateAllObjectRecords?: boolean | null, canSoftDeleteAllObjectRecords?: boolean | null, canDestroyAllObjectRecords?: boolean | null, permissionFlagUniversalIdentifiers?: Array<string> | null, objectPermissions?: Array<{ __typename?: 'MarketplaceAppRoleObjectPermission', universalIdentifier: string, objectUniversalIdentifier: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null }> | null, fieldPermissions?: Array<{ __typename?: 'MarketplaceAppRoleFieldPermission', universalIdentifier: string, objectUniversalIdentifier: string, fieldUniversalIdentifier: string, canReadFieldValue?: boolean | null, canUpdateFieldValue?: boolean | null }> | null }> | null };
export type MarketplaceAppFieldsFragment = { __typename?: 'MarketplaceApp', id: string, name: string, description: string, author: string, category: string, logoUrl?: string | null, sourcePackage?: string | null, isVetted: boolean };
@@ -8075,7 +8078,7 @@ export type FindMarketplaceAppDetailQueryVariables = Exact<{
}>;
-export type FindMarketplaceAppDetailQuery = { __typename?: 'Query', findMarketplaceAppDetail: { __typename?: 'MarketplaceAppDetail', id: string, universalIdentifier: string, name: string, sourceType: ApplicationRegistrationSourceType, sourcePackage?: string | null, latestAvailableVersion?: string | null, isListed: boolean, isVetted: boolean, description?: string | null, author?: string | null, category?: string | null, logoUrl?: string | null, websiteUrl?: string | null, aboutDescription?: string | null, termsUrl?: string | null, emailSupport?: string | null, issueReportUrl?: string | null, galleryImages: Array<string>, defaultRoleUniversalIdentifier?: string | null, roles?: Array<{ __typename?: 'MarketplaceAppRole', universalIdentifier: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings?: boolean | null, canAccessAllTools?: boolean | null, canReadAllObjectRecords?: boolean | null, canUpdateAllObjectRecords?: boolean | null, canSoftDeleteAllObjectRecords?: boolean | null, canDestroyAllObjectRecords?: boolean | null, permissionFlagUniversalIdentifiers?: Array<string> | null, objectPermissions?: Array<{ __typename?: 'MarketplaceAppRoleObjectPermission', universalIdentifier: string, objectUniversalIdentifier: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null }> | null, fieldPermissions?: Array<{ __typename?: 'MarketplaceAppRoleFieldPermission', universalIdentifier: string, objectUniversalIdentifier: string, fieldUniversalIdentifier: string, canReadFieldValue?: boolean | null, canUpdateFieldValue?: boolean | null }> | null }> | null } };
+export type FindMarketplaceAppDetailQuery = { __typename?: 'Query', findMarketplaceAppDetail: { __typename?: 'MarketplaceAppDetail', id: string, universalIdentifier: string, name: string, sourceType: ApplicationRegistrationSourceType, sourcePackage?: string | null, latestAvailableVersion?: string | null, isListed: boolean, isVetted: boolean, description?: string | null, author?: string | null, category?: string | null, logoUrl?: string | null, websiteUrl?: string | null, aboutDescription?: string | null, pricingDescription?: string | null, termsUrl?: string | null, emailSupport?: string | null, issueReportUrl?: string | null, galleryImages: Array<string>, defaultRoleUniversalIdentifier?: string | null, roles?: Array<{ __typename?: 'MarketplaceAppRole', universalIdentifier: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings?: boolean | null, canAccessAllTools?: boolean | null, canReadAllObjectRecords?: boolean | null, canUpdateAllObjectRecords?: boolean | null, canSoftDeleteAllObjectRecords?: boolean | null, canDestroyAllObjectRecords?: boolean | null, permissionFlagUniversalIdentifiers?: Array<string> | null, objectPermissions?: Array<{ __typename?: 'MarketplaceAppRoleObjectPermission', universalIdentifier: string, objectUniversalIdentifier: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null }> | null, fieldPermissions?: Array<{ __typename?: 'MarketplaceAppRoleFieldPermission', universalIdentifier: string, objectUniversalIdentifier: string, fieldUniversalIdentifier: string, canReadFieldValue?: boolean | null, canUpdateFieldValue?: boolean | null }> | null }> | null } };
export type FindMarketplaceAppManifestQueryVariables = Exact<{
universalIdentifier: Scalars['String']['input'];
@@ -9302,7 +9305,7 @@ export type GetUsageAnalyticsQueryVariables = Exact<{
}>;
-export type GetUsageAnalyticsQuery = { __typename?: 'Query', getUsageAnalytics: { __typename?: 'UsageAnalytics', periodStart: string, periodEnd: string, usageByUser: Array<{ __typename?: 'UsageBreakdownItem', key: string, label?: string | null, creditsUsed: number }>, usageByOperationType: Array<{ __typename?: 'UsageBreakdownItem', key: string, creditsUsed: number }>, usageByModel: Array<{ __typename?: 'UsageBreakdownItem', key: string, creditsUsed: number }>, timeSeries: Array<{ __typename?: 'UsageTimeSeries', date: string, creditsUsed: number }>, userDailyUsage?: { __typename?: 'UsageUserDaily', userWorkspaceId: string, dailyUsage: Array<{ __typename?: 'UsageTimeSeries', date: string, creditsUsed: number }> } | null } };
+export type GetUsageAnalyticsQuery = { __typename?: 'Query', getUsageAnalytics: { __typename?: 'UsageAnalytics', periodStart: string, periodEnd: string, usageByUser: Array<{ __typename?: 'UsageBreakdownItem', key: string, label?: string | null, creditsUsed: number }>, usageByOperationType: Array<{ __typename?: 'UsageBreakdownItem', key: string, creditsUsed: number }>, usageByApplication: Array<{ __typename?: 'UsageBreakdownItem', key: string, label?: string | null, creditsUsed: number }>, usageByModel: Array<{ __typename?: 'UsageBreakdownItem', key: string, creditsUsed: number }>, timeSeries: Array<{ __typename?: 'UsageTimeSeries', date: string, creditsUsed: number }>, userDailyUsage?: { __typename?: 'UsageUserDaily', userWorkspaceId: string, dailyUsage: Array<{ __typename?: 'UsageTimeSeries', date: string, creditsUsed: number }> } | null } };
export type AddQueryToEventStreamMutationVariables = Exact<{
input: AddQuerySubscriptionInput;
@@ -9782,7 +9785,7 @@ export const CommandMenuItemFieldsFragmentDoc = {"kind":"Document","definitions"
export const PageLayoutWidgetFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PageLayoutWidgetFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidget"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isSystemSideEffect"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalAvailabilityExpression"}},{"kind":"Field","name":{"kind":"Name","value":"gridPosition"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"column"}},{"kind":"Field","name":{"kind":"Name","value":"columnSpan"}},{"kind":"Field","name":{"kind":"Name","value":"row"}},{"kind":"Field","name":{"kind":"Name","value":"rowSpan"}}]}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetGridPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"row"}},{"kind":"Field","name":{"kind":"Name","value":"column"}},{"kind":"Field","name":{"kind":"Name","value":"rowSpan"}},{"kind":"Field","name":{"kind":"Name","value":"columnSpan"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetVerticalListPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"index"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetCanvasPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"configuration"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BarChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"omitNullValues"}},{"kind":"Field","name":{"kind":"Name","value":"axisNameDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMin"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMax"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"groupMode"}},{"kind":"Field","name":{"kind":"Name","value":"layout"}},{"kind":"Field","name":{"kind":"Name","value":"isCumulative"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"LineChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"omitNullValues"}},{"kind":"Field","name":{"kind":"Name","value":"axisNameDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMin"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMax"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"isStacked"}},{"kind":"Field","name":{"kind":"Name","value":"isCumulative"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PieChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"groupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"groupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"dateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"orderBy"}},{"kind":"Field","name":{"kind":"Name","value":"manualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"showCenterMetric"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"hideEmptyCategory"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AggregateChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"prefix"}},{"kind":"Field","name":{"kind":"Name","value":"suffix"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}},{"kind":"Field","name":{"kind":"Name","value":"ratioAggregateConfig"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"optionValue"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"IframeConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"url"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"StandaloneRichTextConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"body"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"blocknote"}},{"kind":"Field","name":{"kind":"Name","value":"markdown"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CalendarConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"EmailsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"EmailThreadConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CallRecordingSummaryConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CallRecordingTranscriptConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MessageCampaignBodyConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MessageCampaignDetailsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"fieldDisplayMode"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"nestedRelationFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldRichTextConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"newFieldDefaultVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"shouldAllowUserToSeeHiddenFields"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FormFieldConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FilesConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"NotesConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TasksConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ViewConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RecordTableConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"recordLimit"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowRunConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowVersionConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FrontComponentConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentId"}},{"kind":"Field","name":{"kind":"Name","value":"headerCommandMenuItemUniversalIdentifiers"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutTabId"}}]}}]} as unknown as DocumentNode<PageLayoutWidgetFragmentFragment, unknown>;
export const PageLayoutTabFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PageLayoutTabFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutTab"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isSystemSideEffect"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"widgets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"PageLayoutWidgetFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutId"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PageLayoutWidgetFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidget"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isSystemSideEffect"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalAvailabilityExpression"}},{"kind":"Field","name":{"kind":"Name","value":"gridPosition"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"column"}},{"kind":"Field","name":{"kind":"Name","value":"columnSpan"}},{"kind":"Field","name":{"kind":"Name","value":"row"}},{"kind":"Field","name":{"kind":"Name","value":"rowSpan"}}]}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetGridPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"row"}},{"kind":"Field","name":{"kind":"Name","value":"column"}},{"kind":"Field","name":{"kind":"Name","value":"rowSpan"}},{"kind":"Field","name":{"kind":"Name","value":"columnSpan"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetVerticalListPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"index"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetCanvasPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"configuration"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BarChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"omitNullValues"}},{"kind":"Field","name":{"kind":"Name","value":"axisNameDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMin"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMax"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"groupMode"}},{"kind":"Field","name":{"kind":"Name","value":"layout"}},{"kind":"Field","name":{"kind":"Name","value":"isCumulative"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"LineChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"omitNullValues"}},{"kind":"Field","name":{"kind":"Name","value":"axisNameDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMin"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMax"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"isStacked"}},{"kind":"Field","name":{"kind":"Name","value":"isCumulative"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PieChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"groupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"groupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"dateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"orderBy"}},{"kind":"Field","name":{"kind":"Name","value":"manualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"showCenterMetric"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"hideEmptyCategory"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AggregateChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"prefix"}},{"kind":"Field","name":{"kind":"Name","value":"suffix"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}},{"kind":"Field","name":{"kind":"Name","value":"ratioAggregateConfig"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"optionValue"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"IframeConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"url"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"StandaloneRichTextConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"body"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"blocknote"}},{"kind":"Field","name":{"kind":"Name","value":"markdown"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CalendarConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"EmailsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"EmailThreadConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CallRecordingSummaryConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CallRecordingTranscriptConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MessageCampaignBodyConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MessageCampaignDetailsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"fieldDisplayMode"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"nestedRelationFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldRichTextConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"newFieldDefaultVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"shouldAllowUserToSeeHiddenFields"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FormFieldConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FilesConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"NotesConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TasksConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ViewConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RecordTableConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"recordLimit"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowRunConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowVersionConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FrontComponentConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentId"}},{"kind":"Field","name":{"kind":"Name","value":"headerCommandMenuItemUniversalIdentifiers"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutTabId"}}]}}]} as unknown as DocumentNode<PageLayoutTabFragmentFragment, unknown>;
export const PageLayoutFragmentFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PageLayoutFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayout"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isSystemSideEffect"}},{"kind":"Field","name":{"kind":"Name","value":"isFirstTabPinned"}},{"kind":"Field","name":{"kind":"Name","value":"defaultTabToFocusOnMobileAndSidePanelId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"tabs"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"PageLayoutTabFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PageLayoutWidgetFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidget"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isSystemSideEffect"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalAvailabilityExpression"}},{"kind":"Field","name":{"kind":"Name","value":"gridPosition"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"column"}},{"kind":"Field","name":{"kind":"Name","value":"columnSpan"}},{"kind":"Field","name":{"kind":"Name","value":"row"}},{"kind":"Field","name":{"kind":"Name","value":"rowSpan"}}]}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetGridPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"row"}},{"kind":"Field","name":{"kind":"Name","value":"column"}},{"kind":"Field","name":{"kind":"Name","value":"rowSpan"}},{"kind":"Field","name":{"kind":"Name","value":"columnSpan"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetVerticalListPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"index"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetCanvasPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"configuration"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BarChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"omitNullValues"}},{"kind":"Field","name":{"kind":"Name","value":"axisNameDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMin"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMax"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"groupMode"}},{"kind":"Field","name":{"kind":"Name","value":"layout"}},{"kind":"Field","name":{"kind":"Name","value":"isCumulative"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"LineChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"omitNullValues"}},{"kind":"Field","name":{"kind":"Name","value":"axisNameDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMin"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMax"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"isStacked"}},{"kind":"Field","name":{"kind":"Name","value":"isCumulative"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PieChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"groupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"groupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"dateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"orderBy"}},{"kind":"Field","name":{"kind":"Name","value":"manualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"showCenterMetric"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"hideEmptyCategory"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AggregateChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"prefix"}},{"kind":"Field","name":{"kind":"Name","value":"suffix"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}},{"kind":"Field","name":{"kind":"Name","value":"ratioAggregateConfig"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"optionValue"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"IframeConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"url"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"StandaloneRichTextConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"body"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"blocknote"}},{"kind":"Field","name":{"kind":"Name","value":"markdown"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CalendarConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"EmailsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"EmailThreadConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CallRecordingSummaryConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CallRecordingTranscriptConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MessageCampaignBodyConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MessageCampaignDetailsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"fieldDisplayMode"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"nestedRelationFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldRichTextConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"newFieldDefaultVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"shouldAllowUserToSeeHiddenFields"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FormFieldConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FilesConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"NotesConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TasksConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ViewConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RecordTableConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"recordLimit"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowRunConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowVersionConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FrontComponentConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentId"}},{"kind":"Field","name":{"kind":"Name","value":"headerCommandMenuItemUniversalIdentifiers"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutTabId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PageLayoutTabFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutTab"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isSystemSideEffect"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"widgets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"PageLayoutWidgetFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutId"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<PageLayoutFragmentFragment, unknown>;
-export const MarketplaceAppDetailFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"MarketplaceAppDetailFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MarketplaceAppDetail"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}},{"kind":"Field","name":{"kind":"Name","value":"sourcePackage"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"isListed"}},{"kind":"Field","name":{"kind":"Name","value":"isVetted"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"author"}},{"kind":"Field","name":{"kind":"Name","value":"category"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"websiteUrl"}},{"kind":"Field","name":{"kind":"Name","value":"aboutDescription"}},{"kind":"Field","name":{"kind":"Name","value":"termsUrl"}},{"kind":"Field","name":{"kind":"Name","value":"emailSupport"}},{"kind":"Field","name":{"kind":"Name","value":"issueReportUrl"}},{"kind":"Field","name":{"kind":"Name","value":"galleryImages"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRoleUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"roles"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllSettings"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllTools"}},{"kind":"Field","name":{"kind":"Name","value":"canReadAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"permissionFlagUniversalIdentifiers"}},{"kind":"Field","name":{"kind":"Name","value":"objectPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"canReadObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyObjectRecords"}}]}},{"kind":"Field","name":{"kind":"Name","value":"fieldPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"fieldUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"canReadFieldValue"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateFieldValue"}}]}}]}}]}}]} as unknown as DocumentNode<MarketplaceAppDetailFieldsFragment, unknown>;
+export const MarketplaceAppDetailFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"MarketplaceAppDetailFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MarketplaceAppDetail"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}},{"kind":"Field","name":{"kind":"Name","value":"sourcePackage"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"isListed"}},{"kind":"Field","name":{"kind":"Name","value":"isVetted"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"author"}},{"kind":"Field","name":{"kind":"Name","value":"category"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"websiteUrl"}},{"kind":"Field","name":{"kind":"Name","value":"aboutDescription"}},{"kind":"Field","name":{"kind":"Name","value":"pricingDescription"}},{"kind":"Field","name":{"kind":"Name","value":"termsUrl"}},{"kind":"Field","name":{"kind":"Name","value":"emailSupport"}},{"kind":"Field","name":{"kind":"Name","value":"issueReportUrl"}},{"kind":"Field","name":{"kind":"Name","value":"galleryImages"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRoleUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"roles"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllSettings"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllTools"}},{"kind":"Field","name":{"kind":"Name","value":"canReadAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"permissionFlagUniversalIdentifiers"}},{"kind":"Field","name":{"kind":"Name","value":"objectPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"canReadObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyObjectRecords"}}]}},{"kind":"Field","name":{"kind":"Name","value":"fieldPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"fieldUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"canReadFieldValue"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateFieldValue"}}]}}]}}]}}]} as unknown as DocumentNode<MarketplaceAppDetailFieldsFragment, unknown>;
export const MarketplaceAppFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"MarketplaceAppFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MarketplaceApp"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"author"}},{"kind":"Field","name":{"kind":"Name","value":"category"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"sourcePackage"}},{"kind":"Field","name":{"kind":"Name","value":"isVetted"}}]}}]} as unknown as DocumentNode<MarketplaceAppFieldsFragment, unknown>;
export const NavigationMenuItemFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"NavigationMenuItemFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"NavigationMenuItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"targetRecordId"}},{"kind":"Field","name":{"kind":"Name","value":"targetObjectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"folderId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"link"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutId"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<NavigationMenuItemFieldsFragment, unknown>;
export const NavigationMenuItemQueryFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"NavigationMenuItemQueryFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"NavigationMenuItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"NavigationMenuItemFields"}},{"kind":"Field","name":{"kind":"Name","value":"targetRecordIdentifier"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"labelIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"imageIdentifier"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"NavigationMenuItemFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"NavigationMenuItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"targetRecordId"}},{"kind":"Field","name":{"kind":"Name","value":"targetObjectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"folderId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"link"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutId"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<NavigationMenuItemQueryFieldsFragment, unknown>;
@@ -9928,7 +9931,7 @@ export const InstallApplicationDocument = {"kind":"Document","definitions":[{"ki
export const SyncMarketplaceCatalogDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SyncMarketplaceCatalog"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"syncMarketplaceCatalog"}}]}}]} as unknown as DocumentNode<SyncMarketplaceCatalogMutation, SyncMarketplaceCatalogMutationVariables>;
export const UpgradeApplicationDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpgradeApplication"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"appRegistrationId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"targetVersion"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"upgradeApplication"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"appRegistrationId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"appRegistrationId"}}},{"kind":"Argument","name":{"kind":"Name","value":"targetVersion"},"value":{"kind":"Variable","name":{"kind":"Name","value":"targetVersion"}}}]}]}}]} as unknown as DocumentNode<UpgradeApplicationMutation, UpgradeApplicationMutationVariables>;
export const FindManyMarketplaceAppsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyMarketplaceApps"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifiers"}},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findManyMarketplaceApps"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"universalIdentifiers"},"value":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifiers"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"MarketplaceAppFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"MarketplaceAppFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MarketplaceApp"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"author"}},{"kind":"Field","name":{"kind":"Name","value":"category"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"sourcePackage"}},{"kind":"Field","name":{"kind":"Name","value":"isVetted"}}]}}]} as unknown as DocumentNode<FindManyMarketplaceAppsQuery, FindManyMarketplaceAppsQueryVariables>;
-export const FindMarketplaceAppDetailDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindMarketplaceAppDetail"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findMarketplaceAppDetail"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"universalIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"MarketplaceAppDetailFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"MarketplaceAppDetailFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MarketplaceAppDetail"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}},{"kind":"Field","name":{"kind":"Name","value":"sourcePackage"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"isListed"}},{"kind":"Field","name":{"kind":"Name","value":"isVetted"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"author"}},{"kind":"Field","name":{"kind":"Name","value":"category"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"websiteUrl"}},{"kind":"Field","name":{"kind":"Name","value":"aboutDescription"}},{"kind":"Field","name":{"kind":"Name","value":"termsUrl"}},{"kind":"Field","name":{"kind":"Name","value":"emailSupport"}},{"kind":"Field","name":{"kind":"Name","value":"issueReportUrl"}},{"kind":"Field","name":{"kind":"Name","value":"galleryImages"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRoleUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"roles"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllSettings"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllTools"}},{"kind":"Field","name":{"kind":"Name","value":"canReadAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"permissionFlagUniversalIdentifiers"}},{"kind":"Field","name":{"kind":"Name","value":"objectPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"canReadObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyObjectRecords"}}]}},{"kind":"Field","name":{"kind":"Name","value":"fieldPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"fieldUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"canReadFieldValue"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateFieldValue"}}]}}]}}]}}]} as unknown as DocumentNode<FindMarketplaceAppDetailQuery, FindMarketplaceAppDetailQueryVariables>;
+export const FindMarketplaceAppDetailDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindMarketplaceAppDetail"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findMarketplaceAppDetail"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"universalIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"MarketplaceAppDetailFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"MarketplaceAppDetailFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MarketplaceAppDetail"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"sourceType"}},{"kind":"Field","name":{"kind":"Name","value":"sourcePackage"}},{"kind":"Field","name":{"kind":"Name","value":"latestAvailableVersion"}},{"kind":"Field","name":{"kind":"Name","value":"isListed"}},{"kind":"Field","name":{"kind":"Name","value":"isVetted"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"author"}},{"kind":"Field","name":{"kind":"Name","value":"category"}},{"kind":"Field","name":{"kind":"Name","value":"logoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"websiteUrl"}},{"kind":"Field","name":{"kind":"Name","value":"aboutDescription"}},{"kind":"Field","name":{"kind":"Name","value":"pricingDescription"}},{"kind":"Field","name":{"kind":"Name","value":"termsUrl"}},{"kind":"Field","name":{"kind":"Name","value":"emailSupport"}},{"kind":"Field","name":{"kind":"Name","value":"issueReportUrl"}},{"kind":"Field","name":{"kind":"Name","value":"galleryImages"}},{"kind":"Field","name":{"kind":"Name","value":"defaultRoleUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"roles"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllSettings"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessAllTools"}},{"kind":"Field","name":{"kind":"Name","value":"canReadAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyAllObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"permissionFlagUniversalIdentifiers"}},{"kind":"Field","name":{"kind":"Name","value":"objectPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"canReadObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canSoftDeleteObjectRecords"}},{"kind":"Field","name":{"kind":"Name","value":"canDestroyObjectRecords"}}]}},{"kind":"Field","name":{"kind":"Name","value":"fieldPermissions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"fieldUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"canReadFieldValue"}},{"kind":"Field","name":{"kind":"Name","value":"canUpdateFieldValue"}}]}}]}}]}}]} as unknown as DocumentNode<FindMarketplaceAppDetailQuery, FindMarketplaceAppDetailQueryVariables>;
export const FindMarketplaceAppManifestDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindMarketplaceAppManifest"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"findMarketplaceAppDetail"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"universalIdentifier"},"value":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifier"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"manifest"}}]}}]}}]} as unknown as DocumentNode<FindMarketplaceAppManifestQuery, FindMarketplaceAppManifestQueryVariables>;
export const FindMinimalMetadataDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindMinimalMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"minimalMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"objectMetadataItems"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}},{"kind":"Field","name":{"kind":"Name","value":"labelSingular"}},{"kind":"Field","name":{"kind":"Name","value":"labelPlural"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isRemote"}}]}},{"kind":"Field","name":{"kind":"Name","value":"views"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"collectionHashes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"collectionName"}},{"kind":"Field","name":{"kind":"Name","value":"hash"}}]}}]}}]}}]} as unknown as DocumentNode<FindMinimalMetadataQuery, FindMinimalMetadataQueryVariables>;
export const CreateManyNavigationMenuItemsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateManyNavigationMenuItems"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"inputs"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateNavigationMenuItemInput"}}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createManyNavigationMenuItems"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"inputs"},"value":{"kind":"Variable","name":{"kind":"Name","value":"inputs"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"NavigationMenuItemQueryFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"NavigationMenuItemFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"NavigationMenuItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"targetRecordId"}},{"kind":"Field","name":{"kind":"Name","value":"targetObjectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"folderId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"link"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutId"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"NavigationMenuItemQueryFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"NavigationMenuItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"NavigationMenuItemFields"}},{"kind":"Field","name":{"kind":"Name","value":"targetRecordIdentifier"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"labelIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"imageIdentifier"}}]}}]}}]} as unknown as DocumentNode<CreateManyNavigationMenuItemsMutation, CreateManyNavigationMenuItemsMutationVariables>;
@@ -10069,7 +10072,7 @@ export const CreateUnsubscribeTopicDocument = {"kind":"Document","definitions":[
export const DeleteUnsubscribeTopicDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteUnsubscribeTopic"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteUnsubscribeTopic"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}]}]}}]} as unknown as DocumentNode<DeleteUnsubscribeTopicMutation, DeleteUnsubscribeTopicMutationVariables>;
export const UpdateUnsubscribeTopicDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateUnsubscribeTopic"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateUnsubscribeTopicInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateUnsubscribeTopic"},"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":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}}]}}]}}]} as unknown as DocumentNode<UpdateUnsubscribeTopicMutation, UpdateUnsubscribeTopicMutationVariables>;
export const MessageSuppressionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MessageSuppressions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"FindMessageSuppressionsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"messageSuppressions"},"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":"records"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"emailAddress"}},{"kind":"Field","name":{"kind":"Name","value":"reason"}},{"kind":"Field","name":{"kind":"Name","value":"unsubscribeTopicId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}}]}}]}}]} as unknown as DocumentNode<MessageSuppressionsQuery, MessageSuppressionsQueryVariables>;
-export const GetUsageAnalyticsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetUsageAnalytics"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UsageAnalyticsInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getUsageAnalytics"},"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":"usageByUser"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByOperationType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByModel"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"timeSeries"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"date"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"userDailyUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"dailyUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"date"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GetUsageAnalyticsQuery, GetUsageAnalyticsQueryVariables>;
+export const GetUsageAnalyticsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetUsageAnalytics"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UsageAnalyticsInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getUsageAnalytics"},"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":"usageByUser"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByOperationType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByApplication"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"usageByModel"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"timeSeries"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"date"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}},{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"userDailyUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"dailyUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"date"}},{"kind":"Field","name":{"kind":"Name","value":"creditsUsed"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GetUsageAnalyticsQuery, GetUsageAnalyticsQueryVariables>;
export const AddQueryToEventStreamDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AddQueryToEventStream"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AddQuerySubscriptionInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"addQueryToEventStream"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<AddQueryToEventStreamMutation, AddQueryToEventStreamMutationVariables>;
export const RemoveQueryFromEventStreamDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RemoveQueryFromEventStream"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"RemoveQueryFromEventStreamInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"removeQueryFromEventStream"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<RemoveQueryFromEventStreamMutation, RemoveQueryFromEventStreamMutationVariables>;
export const OnEventSubscriptionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"OnEventSubscription"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"eventStreamId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"onEventSubscription"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"eventStreamId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"eventStreamId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"eventStreamId"}},{"kind":"Field","name":{"kind":"Name","value":"objectRecordEventsWithQueryIds"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"objectRecordEvent"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"action"}},{"kind":"Field","name":{"kind":"Name","value":"objectNameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"recordId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberId"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updatedFields"}},{"kind":"Field","name":{"kind":"Name","value":"before"}},{"kind":"Field","name":{"kind":"Name","value":"after"}},{"kind":"Field","name":{"kind":"Name","value":"diff"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"queryIds"}}]}},{"kind":"Field","name":{"kind":"Name","value":"metadataEvents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"metadataName"}},{"kind":"Field","name":{"kind":"Name","value":"recordId"}},{"kind":"Field","name":{"kind":"Name","value":"updatedCollectionHash"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updatedFields"}},{"kind":"Field","name":{"kind":"Name","value":"before"}},{"kind":"Field","name":{"kind":"Name","value":"after"}},{"kind":"Field","name":{"kind":"Name","value":"diff"}}]}}]}}]}}]}}]} as unknown as DocumentNode<OnEventSubscriptionSubscription, OnEventSubscriptionSubscriptionVariables>;
diff --git a/packages/twenty-front/src/modules/marketplace/graphql/fragments/marketplaceAppDetailFragment.ts b/packages/twenty-front/src/modules/marketplace/graphql/fragments/marketplaceAppDetailFragment.ts
index 79a53c86253..78c7b2bfad8 100644
--- a/packages/twenty-front/src/modules/marketplace/graphql/fragments/marketplaceAppDetailFragment.ts
+++ b/packages/twenty-front/src/modules/marketplace/graphql/fragments/marketplaceAppDetailFragment.ts
@@ -16,6 +16,7 @@ export const MARKETPLACE_APP_DETAIL_FRAGMENT = gql`
logoUrl
websiteUrl
aboutDescription
+ pricingDescription
termsUrl
emailSupport
issueReportUrl
diff --git a/packages/twenty-front/src/modules/settings/applications/components/SettingsApplicationAboutSidebar.tsx b/packages/twenty-front/src/modules/settings/applications/components/SettingsApplicationAboutSidebar.tsx
index 4e54998ea09..5801381f8e3 100644
--- a/packages/twenty-front/src/modules/settings/applications/components/SettingsApplicationAboutSidebar.tsx
+++ b/packages/twenty-front/src/modules/settings/applications/components/SettingsApplicationAboutSidebar.tsx
@@ -31,6 +31,7 @@ export type DeveloperLinks = {
type SettingsApplicationAboutSidebarProps = {
actionButton?: ReactNode;
+ pricingDescription?: string;
author?: string;
category?: string;
contentEntries?: ContentEntry[];
@@ -64,6 +65,14 @@ const StyledSidebarValue = styled.div`
font-weight: ${themeCssVariables.font.weight.medium};
`;
+// Prose rather than a datum: it wraps, and stays regular weight so a sentence
+// does not shout next to the short sidebar values.
+const StyledPricingValue = styled.div`
+ color: ${themeCssVariables.font.color.primary};
+ font-size: ${themeCssVariables.font.size.md};
+ overflow-wrap: anywhere;
+`;
+
const StyledContentList = styled.div`
align-items: flex-start;
display: flex;
@@ -91,6 +100,7 @@ const StyledLink = styled.a`
export const SettingsApplicationAboutSidebar = ({
actionButton,
+ pricingDescription,
author,
category,
contentEntries,
@@ -128,6 +138,13 @@ export const SettingsApplicationAboutSidebar = ({
<StyledSidebarSection>{actionButton}</StyledSidebarSection>
)}
+ {isNonEmptyString(pricingDescription) && (
+ <StyledSidebarSection>
+ <StyledSidebarLabel>{t`Pricing`}</StyledSidebarLabel>
+ <StyledPricingValue>{pricingDescription}</StyledPricingValue>
+ </StyledSidebarSection>
+ )}
+
{isDefined(author) && (
<StyledSidebarSection>
<StyledSidebarLabel>{t`Created by`}</StyledSidebarLabel>
diff --git a/packages/twenty-front/src/modules/settings/usage/components/SettingsUsageAnalyticsSection.tsx b/packages/twenty-front/src/modules/settings/usage/components/SettingsUsageAnalyticsSection.tsx
index a16ed6816ee..34f9e41f997 100644
--- a/packages/twenty-front/src/modules/settings/usage/components/SettingsUsageAnalyticsSection.tsx
+++ b/packages/twenty-front/src/modules/settings/usage/components/SettingsUsageAnalyticsSection.tsx
@@ -75,6 +75,11 @@ export const SettingsUsageAnalyticsSection = () => {
breakdownField="operationType"
sectionId="usage-type"
/>
+ <UsageBreakdownPieSection
+ title={t`Usage by App`}
+ breakdownField="application"
+ sectionId="usage-app"
+ />
<UsageDailyChartSection
title={t`Daily Usage`}
description={t`Credit consumption over time.`}
diff --git a/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx b/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx
index 4385afe3ec2..5742372b319 100644
--- a/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx
+++ b/packages/twenty-front/src/modules/settings/usage/components/UsageBreakdownPieSection.tsx
@@ -5,15 +5,17 @@ import { UsagePieChart } from '@/settings/usage/components/UsagePieChart';
import { UsageSectionSkeleton } from '@/settings/usage/components/UsageSectionSkeleton';
import { useUsageAnalyticsData } from '@/settings/usage/hooks/useUsageAnalyticsData';
import { useUsageValueFormatter } from '@/settings/usage/hooks/useUsageValueFormatter';
-import { getOperationTypeLabel } from '@/settings/usage/utils/getOperationTypeLabel';
+import { getUsageOperationTypeLabel } from '@/settings/usage/utils/getUsageOperationTypeLabel';
import { Select } from '@/ui/input/components/Select';
+import { useLingui } from '@lingui/react/macro';
import { useContext } from 'react';
+import { isDefined } from 'twenty-shared/utils';
import { H2Title } from 'twenty-ui/typography';
import { Section } from 'twenty-ui/layout';
import { ThemeContext } from 'twenty-ui/theme-constants';
import { type UsageOperationType } from '~/generated-metadata/graphql';
-type UsageBreakdownField = 'operationType' | 'model';
+type UsageBreakdownField = 'operationType' | 'application' | 'model';
type UsageBreakdownPieSectionProps = {
title: string;
@@ -35,6 +37,7 @@ export const UsageBreakdownPieSection = ({
sectionId,
}: UsageBreakdownPieSectionProps) => {
const { theme } = useContext(ThemeContext);
+ const { t } = useLingui();
const { formatUsageValue } = useUsageValueFormatter();
const colorRegistry = createGraphColorRegistry(theme.color);
@@ -53,10 +56,12 @@ export const UsageBreakdownPieSection = ({
return null;
}
- const breakdownData =
- breakdownField === 'operationType'
- ? analytics.usageByOperationType
- : analytics.usageByModel;
+ const breakdownDataByField = {
+ operationType: analytics.usageByOperationType,
+ application: analytics.usageByApplication,
+ model: analytics.usageByModel,
+ };
+ const breakdownData = breakdownDataByField[breakdownField];
if (breakdownData.length === 0) {
return null;
@@ -64,13 +69,26 @@ export const UsageBreakdownPieSection = ({
const total = breakdownData.reduce((sum, item) => sum + item.creditsUsed, 0);
- const formatLabel =
- breakdownField === 'operationType'
- ? getOperationTypeLabel
- : (key: string) => key;
+ // Operation types are a fixed platform vocabulary translated here; the other
+ // breakdowns name workspace data, which only the server can resolve.
+ const formatLabel = ({
+ key,
+ label,
+ }: {
+ key: string;
+ label?: string | null;
+ }) => {
+ if (breakdownField !== 'operationType') {
+ return label ?? key;
+ }
+
+ const operationTypeLabel = getUsageOperationTypeLabel(key);
+
+ return isDefined(operationTypeLabel) ? t(operationTypeLabel) : key;
+ };
const pieData = breakdownData.map((item, index) => ({
- id: formatLabel(item.key),
+ id: formatLabel(item),
value: item.creditsUsed,
color: getColorSchemeByIndex(colorRegistry, index).solid,
}));
diff --git a/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts b/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
new file mode 100644
index 00000000000..7a880cdb092
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/usage/constants/UsageOperationTypeLabels.ts
@@ -0,0 +1,21 @@
+import { type MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+
+import { UsageOperationType } from '~/generated-metadata/graphql';
+
+// Exhaustive over the enum, so a new operation type is a compile error here
+// rather than a raw key on screen.
+export const USAGE_OPERATION_TYPE_LABELS: Record<
+ UsageOperationType,
+ MessageDescriptor
+> = {
+ [UsageOperationType.AI_CHAT_TOKEN]: msg`AI Chat`,
+ [UsageOperationType.AI_WORKFLOW_TOKEN]: msg`AI Workflow`,
+ [UsageOperationType.WORKFLOW_EXECUTION]: msg`Workflow Execution`,
+ [UsageOperationType.CODE_EXECUTION]: msg`Code Execution`,
+ [UsageOperationType.WEB_SEARCH]: msg`Web Search`,
+ [UsageOperationType.CALL_RECORDING]: msg`Call Recording`,
+ [UsageOperationType.EMAIL_SEND]: msg`Email Send`,
+ [UsageOperationType.API_REQUEST]: msg`API Request`,
+ [UsageOperationType.SUBSCRIPTION]: msg`Subscription`,
+};
diff --git a/packages/twenty-front/src/modules/settings/usage/graphql/queries/getUsageAnalytics.ts b/packages/twenty-front/src/modules/settings/usage/graphql/queries/getUsageAnalytics.ts
index c53f64ccc63..060a043a340 100644
--- a/packages/twenty-front/src/modules/settings/usage/graphql/queries/getUsageAnalytics.ts
+++ b/packages/twenty-front/src/modules/settings/usage/graphql/queries/getUsageAnalytics.ts
@@ -12,6 +12,11 @@ export const GET_USAGE_ANALYTICS = gql`
key
creditsUsed
}
+ usageByApplication {
+ key
+ label
+ creditsUsed
+ }
usageByModel {
key
creditsUsed
diff --git a/packages/twenty-front/src/modules/settings/usage/utils/getOperationTypeLabel.ts b/packages/twenty-front/src/modules/settings/usage/utils/getOperationTypeLabel.ts
deleted file mode 100644
index 46c27adde5d..00000000000
--- a/packages/twenty-front/src/modules/settings/usage/utils/getOperationTypeLabel.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { t } from '@lingui/core/macro';
-
-export const getOperationTypeLabel = (key: string): string => {
- switch (key) {
- case 'AI_CHAT_TOKEN':
- return t`AI Chat`;
- case 'AI_WORKFLOW_TOKEN':
- return t`AI Workflow`;
- case 'WORKFLOW_EXECUTION':
- return t`Workflow Execution`;
- case 'CODE_EXECUTION':
- return t`Code Execution`;
- default:
- return key;
- }
-};
diff --git a/packages/twenty-front/src/modules/settings/usage/utils/getUsageOperationTypeLabel.ts b/packages/twenty-front/src/modules/settings/usage/utils/getUsageOperationTypeLabel.ts
new file mode 100644
index 00000000000..cfe7a2cf1fb
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/usage/utils/getUsageOperationTypeLabel.ts
@@ -0,0 +1,14 @@
+import { type MessageDescriptor } from '@lingui/core';
+
+import { USAGE_OPERATION_TYPE_LABELS } from '@/settings/usage/constants/UsageOperationTypeLabels';
+
+// A Map rather than a direct record index: a source key can name an
+// application, and without `noUncheckedIndexedAccess` indexing the record
+// would type that miss as a MessageDescriptor instead of undefined.
+const LABEL_BY_OPERATION_TYPE: ReadonlyMap<string, MessageDescriptor> = new Map(
+ Object.entries(USAGE_OPERATION_TYPE_LABELS),
+);
+
+export const getUsageOperationTypeLabel = (
+ key: string,
+): MessageDescriptor | undefined => LABEL_BY_OPERATION_TYPE.get(key);
diff --git a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx
index d6c1c07def5..57d55990543 100644
--- a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationDetails.tsx
@@ -293,6 +293,7 @@ export const SettingsApplicationDetails = () => {
displayName={displayName}
description={description}
aboutDescription={detail?.aboutDescription ?? undefined}
+ pricingDescription={detail?.pricingDescription ?? undefined}
screenshots={screenshots}
author={detail?.author ?? undefined}
category={detail?.category ?? undefined}
diff --git a/packages/twenty-front/src/pages/settings/applications/SettingsAvailableApplicationDetails.tsx b/packages/twenty-front/src/pages/settings/applications/SettingsAvailableApplicationDetails.tsx
index f86d6d8fb1d..c7cc0837fd4 100644
--- a/packages/twenty-front/src/pages/settings/applications/SettingsAvailableApplicationDetails.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/SettingsAvailableApplicationDetails.tsx
@@ -222,6 +222,7 @@ export const SettingsAvailableApplicationDetails = () => {
displayName={displayName}
description={description}
aboutDescription={detail.aboutDescription ?? undefined}
+ pricingDescription={detail.pricingDescription ?? undefined}
screenshots={detail.galleryImages}
author={detail.author ?? 'Unknown'}
category={detail.category ?? undefined}
diff --git a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailAboutTab.tsx b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailAboutTab.tsx
index 101331c2c37..755cafc9868 100644
--- a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailAboutTab.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationDetailAboutTab.tsx
@@ -23,6 +23,7 @@ type SettingsApplicationDetailAboutTabProps = {
displayName: string;
description?: string;
aboutDescription?: string;
+ pricingDescription?: string;
screenshots?: string[];
author?: string;
category?: string;
@@ -100,6 +101,7 @@ export const SettingsApplicationDetailAboutTab = ({
displayName,
description,
aboutDescription,
+ pricingDescription,
screenshots,
author,
category,
@@ -236,6 +238,7 @@ export const SettingsApplicationDetailAboutTab = ({
<SettingsApplicationAboutSidebar
actionButton={getActionButton()}
+ pricingDescription={pricingDescription}
author={author}
category={category}
contentEntries={contentEntries}
diff --git a/packages/twenty-sdk/src/sdk/billing/charge-credits.ts b/packages/twenty-sdk/src/sdk/billing/charge-credits.ts
index 8706cd41127..ec4e81822c3 100644
--- a/packages/twenty-sdk/src/sdk/billing/charge-credits.ts
+++ b/packages/twenty-sdk/src/sdk/billing/charge-credits.ts
@@ -1,4 +1,7 @@
-import { DEFAULT_API_URL_NAME } from 'twenty-shared/application';
+import {
+ DEFAULT_API_URL_NAME,
+ type UsageOperationTypeValue,
+} from 'twenty-shared/application';
import { getApplicationAccessToken } from '@/sdk/utils/get-application-access-token';
@@ -6,10 +9,26 @@ const BILLING_CHARGE_TIMEOUT_MS = 5_000;
export type ChargeCreditsParams = {
creditsUsedMicro: number;
- operationType: string;
quantity?: number;
- resourceContext?: string;
-};
+ // Who the spend belongs to, for runs with no triggering user (a webhook, a
+ // cron). Ignored otherwise: the token already names them.
+ userWorkspaceId?: string;
+} & (
+ | {
+ // An operation name declared in `billing.operations` on the application
+ // manifest. The platform resolves its billing category and its label.
+ operation: string;
+ operationType?: never;
+ resourceContext?: never;
+ }
+ | {
+ // For applications that declare no billable operations: name the
+ // platform billing category directly, unlabelled.
+ operationType: UsageOperationTypeValue;
+ operation?: never;
+ resourceContext?: string;
+ }
+);
// Records credit usage against the running application via the Twenty
// server's `/app/billing/charge` endpoint. Reads `TWENTY_API_URL` and the
@@ -19,9 +38,11 @@ export type ChargeCreditsParams = {
// never surfaces as a tool failure.
export const chargeCredits = async ({
creditsUsedMicro,
- operationType,
quantity = 1,
+ operation,
+ operationType,
resourceContext,
+ userWorkspaceId,
}: ChargeCreditsParams): Promise<void> => {
const apiUrl = process.env[DEFAULT_API_URL_NAME];
const token = getApplicationAccessToken();
@@ -42,8 +63,10 @@ export const chargeCredits = async ({
body: JSON.stringify({
creditsUsedMicro,
quantity,
+ operation,
operationType,
resourceContext,
+ userWorkspaceId,
}),
signal: AbortSignal.timeout(BILLING_CHARGE_TIMEOUT_MS),
},
diff --git a/packages/twenty-sdk/src/sdk/billing/get-credit-availability.ts b/packages/twenty-sdk/src/sdk/billing/get-credit-availability.ts
new file mode 100644
index 00000000000..3d812c6da37
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/billing/get-credit-availability.ts
@@ -0,0 +1,97 @@
+import {
+ CREDIT_UNAVAILABLE_REASONS,
+ type CreditAvailability,
+ type CreditUnavailableReason,
+ DEFAULT_API_URL_NAME,
+} from 'twenty-shared/application';
+
+import { getApplicationAccessToken } from '@/sdk/utils/get-application-access-token';
+
+const CREDIT_AVAILABILITY_TIMEOUT_MS = 5_000;
+
+// A fresh object per call: the returned value is handed to app code, and a
+// shared constant could be mutated by one caller and observed by the next.
+const available = (): CreditAvailability => ({ hasAvailableCredits: true });
+
+const parseCreditAvailability = (body: unknown): CreditAvailability | null => {
+ if (typeof body !== 'object' || body === null) {
+ return null;
+ }
+
+ const { hasAvailableCredits, reason } = body as {
+ hasAvailableCredits?: unknown;
+ reason?: unknown;
+ };
+
+ if (hasAvailableCredits === true) {
+ return { hasAvailableCredits: true };
+ }
+
+ if (
+ hasAvailableCredits === false &&
+ CREDIT_UNAVAILABLE_REASONS.includes(reason as CreditUnavailableReason)
+ ) {
+ return {
+ hasAvailableCredits: false,
+ reason: reason as CreditUnavailableReason,
+ };
+ }
+
+ return null;
+};
+
+// Asks whether the workspace can still spend, so an app can stop before doing
+// expensive work rather than finding out when a downstream call it did not
+// write throws. Mirrors the gate the platform applies to AI work and outbound
+// email.
+//
+// Fails open, like the platform's own usage read: a timeout, an unreachable
+// server or an unparseable body reports credits available rather than stopping
+// an app over an infrastructure hiccup. An app must not treat this as an
+// authorization decision, only as a hint worth honouring.
+export const getCreditAvailability = async (): Promise<CreditAvailability> => {
+ const apiUrl = process.env[DEFAULT_API_URL_NAME];
+ const token = getApplicationAccessToken();
+
+ if (!apiUrl || !token) {
+ return available();
+ }
+
+ try {
+ const response = await fetch(
+ `${apiUrl.replace(/\/$/, '')}/app/billing/credits`,
+ {
+ method: 'GET',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/json',
+ },
+ signal: AbortSignal.timeout(CREDIT_AVAILABILITY_TIMEOUT_MS),
+ },
+ );
+
+ if (!response.ok) {
+ console.error(
+ `getCreditAvailability: ${response.status} ${response.statusText}`,
+ );
+
+ return available();
+ }
+
+ const creditAvailability = parseCreditAvailability(await response.json());
+
+ if (creditAvailability === null) {
+ console.error('getCreditAvailability: unexpected response shape');
+
+ return available();
+ }
+
+ return creditAvailability;
+ } catch (error) {
+ console.error(
+ `getCreditAvailability: ${error instanceof Error ? error.message : String(error)}`,
+ );
+
+ return available();
+ }
+};
diff --git a/packages/twenty-sdk/src/sdk/billing/index.ts b/packages/twenty-sdk/src/sdk/billing/index.ts
index 5cd10192a44..4ff71edf7e0 100644
--- a/packages/twenty-sdk/src/sdk/billing/index.ts
+++ b/packages/twenty-sdk/src/sdk/billing/index.ts
@@ -1 +1,2 @@
export { chargeCredits, type ChargeCreditsParams } from './charge-credits';
+export { getCreditAvailability } from './get-credit-availability';
diff --git a/packages/twenty-sdk/src/sdk/define/application/__tests__/define-app.spec.ts b/packages/twenty-sdk/src/sdk/define/application/__tests__/define-app.spec.ts
index d43082f4159..1d650f7523a 100644
--- a/packages/twenty-sdk/src/sdk/define/application/__tests__/define-app.spec.ts
+++ b/packages/twenty-sdk/src/sdk/define/application/__tests__/define-app.spec.ts
@@ -1,3 +1,5 @@
+import { MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT } from 'twenty-shared/application';
+
import { defineApplication } from '@/sdk/define';
describe('defineApplication', () => {
@@ -124,6 +126,203 @@ describe('defineApplication', () => {
expect(warnings.some((warning) => warning.includes('API_KEY'))).toBe(true);
});
+ it('should accept a billable operation mapped to a known operationType', () => {
+ const result = defineApplication({
+ universalIdentifier: 'a9faf5f8-cf7e-4f24-9d37-fd523c30febe',
+ displayName: 'My App',
+ description: 'My app description',
+ billing: {
+ operations: {
+ recordMeeting: {
+ operationType: 'CALL_RECORDING',
+ label: 'Meeting recording',
+ },
+ },
+ },
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.errors).toEqual([]);
+ });
+
+ it('should return error when a billable operation maps to an unknown operationType', () => {
+ const result = defineApplication({
+ universalIdentifier: 'a9faf5f8-cf7e-4f24-9d37-fd523c30febe',
+ displayName: 'My App',
+ description: 'My app description',
+ billing: {
+ operations: {
+ recordMeeting: {
+ operationType: 'MEETING_RECORDING' as never,
+ label: 'Meeting recording',
+ },
+ },
+ },
+ });
+
+ expect(result.success).toBe(false);
+ expect(
+ (result.errors ?? []).some((error) => error.includes('recordMeeting')),
+ ).toBe(true);
+ });
+
+ it('should return error when a billable operation has an empty label', () => {
+ const result = defineApplication({
+ universalIdentifier: 'a9faf5f8-cf7e-4f24-9d37-fd523c30febe',
+ displayName: 'My App',
+ description: 'My app description',
+ billing: {
+ operations: {
+ recordMeeting: { operationType: 'CALL_RECORDING', label: '' },
+ },
+ },
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.errors).toContain(
+ 'Billable operation "recordMeeting" must have a non empty label',
+ );
+ });
+
+ it('should accept a flat and a per member recurring charge', () => {
+ const result = defineApplication({
+ universalIdentifier: 'a9faf5f8-cf7e-4f24-9d37-fd523c30febe',
+ displayName: 'My App',
+ description: 'My app description',
+ billing: {
+ recurring: {
+ platformFee: {
+ period: 'MONTH',
+ amountMicroCredits: 20_000_000,
+ label: 'Platform fee',
+ },
+ seat: {
+ period: 'MONTH',
+ amountMicroCredits: 5_000_000,
+ per: 'WORKSPACE_MEMBER',
+ label: 'Per member',
+ },
+ },
+ },
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.errors).toEqual([]);
+ });
+
+ it('should return error when a recurring charge has an unknown period', () => {
+ const result = defineApplication({
+ universalIdentifier: 'a9faf5f8-cf7e-4f24-9d37-fd523c30febe',
+ displayName: 'My App',
+ description: 'My app description',
+ billing: {
+ recurring: {
+ platformFee: {
+ period: 'WEEK' as never,
+ amountMicroCredits: 20_000_000,
+ label: 'Platform fee',
+ },
+ },
+ },
+ });
+
+ expect(result.success).toBe(false);
+ expect(
+ (result.errors ?? []).some((error) => error.includes('platformFee')),
+ ).toBe(true);
+ });
+
+ it('should return error when a recurring charge amount is not a positive integer', () => {
+ const result = defineApplication({
+ universalIdentifier: 'a9faf5f8-cf7e-4f24-9d37-fd523c30febe',
+ displayName: 'My App',
+ description: 'My app description',
+ billing: {
+ recurring: {
+ platformFee: {
+ period: 'MONTH',
+ amountMicroCredits: 0,
+ label: 'Platform fee',
+ },
+ },
+ },
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.errors).toContain(
+ 'Recurring charge "platformFee" must have a positive integer amountMicroCredits',
+ );
+ });
+
+ it('should return error when a recurring charge amount exceeds the per unit maximum', () => {
+ const result = defineApplication({
+ universalIdentifier: 'a9faf5f8-cf7e-4f24-9d37-fd523c30febe',
+ displayName: 'My App',
+ description: 'My app description',
+ billing: {
+ recurring: {
+ platformFee: {
+ period: 'MONTH',
+ amountMicroCredits: MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT + 1,
+ label: 'Platform fee',
+ },
+ },
+ },
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.errors?.[0]).toContain(
+ 'exceeds the maximum amountMicroCredits',
+ );
+ });
+
+ it('should accept a recurring charge amount exactly at the per unit maximum', () => {
+ const result = defineApplication({
+ universalIdentifier: 'a9faf5f8-cf7e-4f24-9d37-fd523c30febe',
+ displayName: 'My App',
+ description: 'My app description',
+ billing: {
+ recurring: {
+ platformFee: {
+ period: 'MONTH',
+ amountMicroCredits: MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT,
+ label: 'Platform fee',
+ },
+ },
+ },
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it('should return error when a name is both a recurring charge and a billable operation', () => {
+ const result = defineApplication({
+ universalIdentifier: 'a9faf5f8-cf7e-4f24-9d37-fd523c30febe',
+ displayName: 'My App',
+ description: 'My app description',
+ billing: {
+ recurring: {
+ recordMeeting: {
+ period: 'MONTH',
+ amountMicroCredits: 20_000_000,
+ label: 'Platform fee',
+ },
+ },
+ operations: {
+ recordMeeting: {
+ operationType: 'CALL_RECORDING',
+ label: 'Meeting recording',
+ },
+ },
+ },
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.errors).toContain(
+ '"recordMeeting" is declared both as a recurring charge and as a billable operation. Give them distinct names.',
+ );
+ });
+
it('should return error when universalIdentifier is missing', () => {
const config = {
displayName: 'My App',
diff --git a/packages/twenty-sdk/src/sdk/define/application/define-application.ts b/packages/twenty-sdk/src/sdk/define/application/define-application.ts
index 684d5d5f95d..2595e9f9119 100644
--- a/packages/twenty-sdk/src/sdk/define/application/define-application.ts
+++ b/packages/twenty-sdk/src/sdk/define/application/define-application.ts
@@ -2,9 +2,16 @@ import { isNonEmptyString } from '@sniptt/guards';
import {
APPLICATION_CATEGORIES,
isKnownApplicationCategory,
+ isRecurringChargePeriod,
+ isRecurringChargeUnit,
+ isUsageOperationTypeValue,
+ MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT,
+ RECURRING_CHARGE_PERIODS,
+ RECURRING_CHARGE_UNITS,
+ USAGE_OPERATION_TYPES,
} from 'twenty-shared/application';
import { FieldMetadataType } from 'twenty-shared/types';
-import { isNonEmptyArray } from 'twenty-shared/utils';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
import { type ApplicationConfig } from '@/sdk/define/application/application-config';
import { normalizeApplicationAssets } from '@/sdk/define/application/utils/normalize-application-assets';
@@ -37,6 +44,87 @@ export const defineApplication: DefineEntity<ApplicationConfig> = (config) => {
}
}
+ const billableOperations = config.billing?.operations ?? {};
+ const recurringCharges = config.billing?.recurring ?? {};
+
+ for (const [operationName, billableOperation] of Object.entries(
+ billableOperations,
+ )) {
+ if (!isDefined(billableOperation)) {
+ continue;
+ }
+
+ if (!isUsageOperationTypeValue(billableOperation.operationType)) {
+ errors.push(
+ `Billable operation "${operationName}" must map to a known operationType (${USAGE_OPERATION_TYPES.join(
+ ', ',
+ )})`,
+ );
+ }
+
+ if (!isNonEmptyString(billableOperation.label)) {
+ errors.push(
+ `Billable operation "${operationName}" must have a non empty label`,
+ );
+ }
+ }
+
+ for (const [chargeName, recurringCharge] of Object.entries(
+ recurringCharges,
+ )) {
+ if (!isDefined(recurringCharge)) {
+ continue;
+ }
+
+ if (!isRecurringChargePeriod(recurringCharge.period)) {
+ errors.push(
+ `Recurring charge "${chargeName}" must have a known period (${RECURRING_CHARGE_PERIODS.join(
+ ', ',
+ )})`,
+ );
+ }
+
+ if (
+ isDefined(recurringCharge.per) &&
+ !isRecurringChargeUnit(recurringCharge.per)
+ ) {
+ errors.push(
+ `Recurring charge "${chargeName}" must be charged per a known unit (${RECURRING_CHARGE_UNITS.join(
+ ', ',
+ )}) or omit \`per\` for a flat fee`,
+ );
+ }
+
+ if (
+ !Number.isSafeInteger(recurringCharge.amountMicroCredits) ||
+ recurringCharge.amountMicroCredits <= 0
+ ) {
+ errors.push(
+ `Recurring charge "${chargeName}" must have a positive integer amountMicroCredits`,
+ );
+ } else if (
+ recurringCharge.amountMicroCredits >
+ MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT
+ ) {
+ errors.push(
+ `Recurring charge "${chargeName}" exceeds the maximum amountMicroCredits of ${MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT}. A per-member charge declares the rate per member, not the total.`,
+ );
+ }
+
+ if (!isNonEmptyString(recurringCharge.label)) {
+ errors.push(
+ `Recurring charge "${chargeName}" must have a non empty label`,
+ );
+ }
+
+ // Both land in the same per-application usage breakdown, keyed by name.
+ if (Object.prototype.hasOwnProperty.call(billableOperations, chargeName)) {
+ errors.push(
+ `"${chargeName}" is declared both as a recurring charge and as a billable operation. Give them distinct names.`,
+ );
+ }
+ }
+
for (const [variableName, variable] of Object.entries(
config.serverVariables ?? {},
)) {
diff --git a/packages/twenty-server/src/database/commands/cron-register-all.command.ts b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
index 20b313062e7..36f7bf02439 100644
--- a/packages/twenty-server/src/database/commands/cron-register-all.command.ts
+++ b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
@@ -6,6 +6,7 @@ import { isDefined } from 'twenty-shared/utils';
import { MarketplaceCatalogSyncCronCommand } from 'src/engine/core-modules/application/application-marketplace/crons/commands/marketplace-catalog-sync.cron.command';
import { StaleRegistrationCleanupCronCommand } from 'src/engine/core-modules/application/application-oauth/stale-registration-cleanup/commands/stale-registration-cleanup.cron.command';
import { ApplicationVersionCheckCronCommand } from 'src/engine/core-modules/application/application-upgrade/crons/commands/application-version-check.cron.command';
+import { ApplicationRecurringChargeCronCommand } from 'src/engine/core-modules/billing/app-billing/crons/commands/application-recurring-charge.cron.command';
import { BillingReminderCronCommand } from 'src/engine/core-modules/billing/reminders/crons/commands/billing-reminder.cron.command';
import { CheckEmailingDomainVerificationCronCommand } from 'src/engine/core-modules/emailing-domain/crons/commands/check-emailing-domain-verification.cron.command';
import { EnterpriseKeyValidationCronCommand } from 'src/engine/core-modules/enterprise/cron/command/enterprise-key-validation.cron.command';
@@ -81,6 +82,7 @@ export class CronRegisterAllCommand extends CommandRunner {
private readonly staleRegistrationCleanupCronCommand: StaleRegistrationCleanupCronCommand,
private readonly pendingFileCleanupCronCommand: PendingFileCleanupCronCommand,
private readonly billingReminderCronCommand: BillingReminderCronCommand,
+ private readonly applicationRecurringChargeCronCommand: ApplicationRecurringChargeCronCommand,
private readonly userSessionCleanupCronCommand: UserSessionCleanupCronCommand,
private readonly twentyConfigService: TwentyConfigService,
) {
@@ -228,6 +230,11 @@ export class CronRegisterAllCommand extends CommandRunner {
command: this.billingReminderCronCommand,
isEnabled: isBillingEnabled,
},
+ {
+ name: 'ApplicationRecurringCharge',
+ command: this.applicationRecurringChargeCronCommand,
+ isEnabled: isBillingEnabled,
+ },
{
name: 'UserSessionCleanup',
command: this.userSessionCleanupCronCommand,
diff --git a/packages/twenty-server/src/database/commands/database-command.module.ts b/packages/twenty-server/src/database/commands/database-command.module.ts
index 9e91815d71b..fd0b3a9f872 100644
--- a/packages/twenty-server/src/database/commands/database-command.module.ts
+++ b/packages/twenty-server/src/database/commands/database-command.module.ts
@@ -23,6 +23,7 @@ import { StaleRegistrationCleanupModule } from 'src/engine/core-modules/applicat
import { ApplicationUpgradeModule } from 'src/engine/core-modules/application/application-upgrade/application-upgrade.module';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { PreInstalledAppsModule } from 'src/engine/core-modules/application/pre-installed-apps/pre-installed-apps.module';
+import { ApplicationRecurringChargeModule } from 'src/engine/core-modules/billing/app-billing/application-recurring-charge.module';
import { BillingReminderModule } from 'src/engine/core-modules/billing/reminders/billing-reminder.module';
import { EnterpriseKeyValidationCronCommand } from 'src/engine/core-modules/enterprise/cron/command/enterprise-key-validation.cron.command';
import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
@@ -85,6 +86,7 @@ import { WorkflowCoreConsistencyModule } from 'src/modules/workflow/workflow-cor
WorkspaceMigrationModule,
TrashCleanupModule,
BillingReminderModule,
+ ApplicationRecurringChargeModule,
CodeInterpreterSessionCleanupModule,
PublicDomainModule,
EventLogCleanupModule,
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788340843000-add-billing-to-application.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788340843000-add-billing-to-application.ts
new file mode 100644
index 00000000000..177898de087
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788340843000-add-billing-to-application.ts
@@ -0,0 +1,21 @@
+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';
+
+@RegisteredInstanceCommand('2.38.0', 1788340843000)
+export class AddBillingToApplicationFastInstanceCommand
+ implements FastInstanceCommand
+{
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."application" ADD COLUMN IF NOT EXISTS "billing" jsonb NOT NULL DEFAULT \'{}\'',
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."application" DROP COLUMN IF EXISTS "billing"',
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788340844000-add-pricing-description-to-application-registration.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788340844000-add-pricing-description-to-application-registration.ts
new file mode 100644
index 00000000000..4db9a0e214c
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788340844000-add-pricing-description-to-application-registration.ts
@@ -0,0 +1,21 @@
+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';
+
+@RegisteredInstanceCommand('2.38.0', 1788340844000)
+export class AddPricingDescriptionToApplicationRegistrationFastInstanceCommand
+ implements FastInstanceCommand
+{
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."applicationRegistration" ADD COLUMN IF NOT EXISTS "pricingDescription" text',
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."applicationRegistration" DROP COLUMN IF EXISTS "pricingDescription"',
+ );
+ }
+}
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 bb9bb2fb38f..9113b2a2679 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
@@ -161,6 +161,8 @@ import { AddLabelToApplicationVariableFastInstanceCommand } from 'src/database/c
import { AddUsageLimitFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-36/2-36-instance-command-fast-1787821567133-add-usage-limit';
import { MakeUserEmailCaseInsensitiveFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-37/2-37-instance-command-fast-1787836741000-make-user-email-case-insensitive';
import { BackfillMissingPageLayoutWidgetPositionsSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-37/2-37-instance-command-slow-1787838153752-backfill-missing-page-layout-widget-positions';
+import { AddBillingToApplicationFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788340843000-add-billing-to-application';
+import { AddPricingDescriptionToApplicationRegistrationFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788340844000-add-pricing-description-to-application-registration';
import { AddRecordFormPageLayoutAndFormFieldWidgetFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787920209300-add-record-form-page-layout-and-form-field-widget';
import { DropBillingCustomerCreditBalanceMicroFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787906740818-drop-billing-customer-credit-balance-micro';
import { DropHasReachedCurrentPeriodCapFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1787906740819-drop-has-reached-current-period-cap';
@@ -334,6 +336,8 @@ export const INSTANCE_COMMANDS = [
AddUsageLimitFastInstanceCommand,
MakeUserEmailCaseInsensitiveFastInstanceCommand,
BackfillMissingPageLayoutWidgetPositionsSlowInstanceCommand,
+ AddBillingToApplicationFastInstanceCommand,
+ AddPricingDescriptionToApplicationRegistrationFastInstanceCommand,
AddRecordFormPageLayoutAndFormFieldWidgetFastInstanceCommand,
DropBillingCustomerCreditBalanceMicroFastInstanceCommand,
DropHasReachedCurrentPeriodCapFastInstanceCommand,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
index 708269f3fd5..ed17087fbe0 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-sync.service.ts
@@ -167,6 +167,7 @@ export class ApplicationSyncService {
yarnLockChecksum: null,
yarnLockFileId: null,
availablePackages: {},
+ billing: manifest.application.billing ?? {},
logicFunctionLayerId: null,
defaultRoleId: null,
defaultRole: null,
@@ -272,6 +273,7 @@ export class ApplicationSyncService {
version: packageJson.version,
packageJsonChecksum: manifest.application.packageJsonChecksum,
yarnLockChecksum: manifest.application.yarnLockChecksum,
+ billing: manifest.application.billing ?? {},
frontComponentSharedDependenciesChecksum,
frontComponentSharedDependenciesBuiltPath,
applicationRegistrationId: resolvedRegistrationId,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/dtos/marketplace-app-detail.dto.ts b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/dtos/marketplace-app-detail.dto.ts
index 798990bf4e2..e7aef34267e 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/dtos/marketplace-app-detail.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/dtos/marketplace-app-detail.dto.ts
@@ -75,6 +75,11 @@ export class MarketplaceAppDetailDTO {
@Field({ nullable: true })
aboutDescription?: string;
+ @IsOptional()
+ @IsString()
+ @Field({ nullable: true })
+ pricingDescription?: string;
+
@IsOptional()
@IsString()
@Field({ nullable: true })
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-query.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-query.service.ts
index e4c39d46f9f..6e270846e29 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-query.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/marketplace-query.service.ts
@@ -121,6 +121,10 @@ export class MarketplaceQueryService {
registration.aboutDescription ??
registration.manifest?.application?.aboutDescription ??
undefined,
+ pricingDescription:
+ registration.pricingDescription ??
+ registration.manifest?.application?.billing?.description ??
+ undefined,
termsUrl:
registration.termsUrl ??
registration.manifest?.application?.termsUrl ??
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.entity.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.entity.ts
index 4c671d04560..4287e1513c9 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.entity.ts
@@ -194,6 +194,15 @@ export class ApplicationRegistrationEntity {
})
aboutDescription: string | null;
+ // Free text: app pricing is tiered, per-minute, per-match with minimums, so
+ // a single rate cannot express it. Shown on the marketplace listing.
+ @Column({ nullable: true, type: 'text' })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ '2.38.0_AddPricingDescriptionToApplicationRegistrationFastInstanceCommand_1788340844000',
+ })
+ pricingDescription: string | null;
+
@Column({ nullable: true, type: 'text' })
@WasIntroducedInUpgrade({
upgradeCommandName:
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
index c933730fb80..c15129f7f41 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/application-registration.service.ts
@@ -90,6 +90,7 @@ const APPLICATION_REGISTRATION_WITHOUT_MANIFEST_SELECT: (keyof ApplicationRegist
'category',
'websiteUrl',
'aboutDescription',
+ 'pricingDescription',
'termsUrl',
'emailSupport',
'issueReportUrl',
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-registration/utils/from-manifest-application-to-display-fields.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-registration/utils/from-manifest-application-to-display-fields.util.ts
index 5702660f9a2..c34e55eda2f 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-registration/utils/from-manifest-application-to-display-fields.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-registration/utils/from-manifest-application-to-display-fields.util.ts
@@ -12,6 +12,7 @@ export const fromManifestApplicationToDisplayFields = (
category: application?.category ?? null,
websiteUrl: application?.websiteUrl ?? null,
aboutDescription: application?.aboutDescription ?? null,
+ pricingDescription: application?.billing?.description ?? null,
termsUrl: application?.termsUrl ?? null,
emailSupport: application?.emailSupport ?? null,
issueReportUrl: application?.issueReportUrl ?? null,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.entity.ts b/packages/twenty-server/src/engine/core-modules/application/application.entity.ts
index 6eb2662be85..6927b75ea0d 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application.entity.ts
@@ -1,5 +1,6 @@
import { Field, ObjectType } from '@nestjs/graphql';
+import { type ApplicationBilling } from 'twenty-shared/application';
import {
Column,
CreateDateColumn,
@@ -116,6 +117,16 @@ export class ApplicationEntity extends WorkspaceRelatedEntity {
@Column({ type: 'jsonb', nullable: false, default: {} })
availablePackages: Record<string, string>;
+ // What the app declares it bills for: recurring charges the platform raises
+ // each period, and the operations it charges against, each with the billing
+ // category metered and the app-authored label shown for that spend.
+ @Column({ type: 'jsonb', nullable: false, default: {} })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ '2.38.0_AddBillingToApplicationFastInstanceCommand_1788340843000',
+ })
+ billing: ApplicationBilling;
+
@Column({ nullable: true, type: 'uuid' })
logicFunctionLayerId: string | null;
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts
index 19ef1e6e020..db315e7f6c4 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.controller.ts
@@ -4,6 +4,7 @@ import {
Body,
Controller,
ForbiddenException,
+ Get,
HttpCode,
HttpStatus,
NotFoundException,
@@ -15,11 +16,13 @@ import {
} from '@nestjs/common';
import { Request } from 'express';
+import { type CreditAvailability } from 'twenty-shared/application';
import { ApiPath } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { AppBillingService } from 'src/engine/core-modules/billing/app-billing/app-billing.service';
import { ChargeDto } from 'src/engine/core-modules/billing/app-billing/dtos/charge.dto';
+import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
@@ -36,10 +39,35 @@ const APP_BILLING_CHARGE_THROTTLE_TTL_MS = 60_000;
export class AppBillingController {
constructor(
private readonly appBillingService: AppBillingService,
+ private readonly billingUsageService: BillingUsageService,
private readonly throttlerService: ThrottlerService,
private readonly twentyConfigService: TwentyConfigService,
) {}
+ // Lets an app ask the question the platform already asks before AI, workflow
+ // and email work, so it can stop up front instead of failing partway through
+ // on a downstream call it did not write. Returns the verdict and a reason,
+ // never a balance: an app has no business reading what the workspace pays.
+ @Get('credits')
+ async credits(@Req() request: Request): Promise<CreditAvailability> {
+ if (!isDefined(request.application) || !isDefined(request.workspace)) {
+ throw new ForbiddenException(
+ 'App billing endpoint requires an APPLICATION_ACCESS token.',
+ );
+ }
+
+ await this.throttlerService.tokenBucketThrottleOrThrow(
+ `${request.workspace.id}-${request.application.id}-app-billing-credits`,
+ 1,
+ APP_BILLING_CHARGE_THROTTLE_LIMIT,
+ APP_BILLING_CHARGE_THROTTLE_TTL_MS,
+ );
+
+ return this.billingUsageService.getCreditAvailability({
+ workspaceId: request.workspace.id,
+ });
+ }
+
@Post('charge')
@HttpCode(HttpStatus.NO_CONTENT)
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.module.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.module.ts
index f549c8b2902..abe74a3590f 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/app-billing.module.ts
@@ -1,6 +1,7 @@
/* @license Enterprise */
import { Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
import { AppBillingController } from 'src/engine/core-modules/billing/app-billing/app-billing.controller';
import { AppBillingService } from 'src/engine/core-modules/billing/app-billing/app-billing.service';
@@ -8,6 +9,7 @@ import { AuthModule } from 'src/engine/core-modules/auth/auth.module';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';
import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
import { WorkspaceCacheStorageModule } from 'src/engine/workspace-cache-storage/workspace-cache-storage.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@@ -19,6 +21,7 @@ import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/
BillingModule,
ThrottlerModule,
TwentyConfigModule,
+ TypeOrmModule.forFeature([UserWorkspaceEntity]),
UsageModule,
WorkspaceCacheModule,
WorkspaceCacheStorageModule,
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 e54d9b2f9db..8a509f78f30 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
@@ -1,12 +1,20 @@
/* @license Enterprise */
-import { Injectable, Logger } from '@nestjs/common';
+import { BadRequestException, Injectable, Logger } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+import { isUsageOperationTypeValue } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+import { type Repository } from 'typeorm';
+
+import { findActiveFlatApplicationById } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-id.util';
import { type ChargeDto } from 'src/engine/core-modules/billing/app-billing/dtos/charge.dto';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.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 { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
// Each operation type has one canonical counting unit — matches how
// `ai-billing.service.ts` emits native usage events.
@@ -19,6 +27,8 @@ const USAGE_UNIT_BY_OPERATION_TYPE: Record<UsageOperationType, UsageUnit> = {
[UsageOperationType.CALL_RECORDING]: UsageUnit.MINUTE,
[UsageOperationType.EMAIL_SEND]: UsageUnit.INVOCATION,
[UsageOperationType.API_REQUEST]: UsageUnit.REQUEST,
+ // Platform-raised only; ApplicationRecurringChargeService sets its own unit.
+ [UsageOperationType.SUBSCRIPTION]: UsageUnit.CREDIT,
};
// `workspaceId` + `applicationId` come from the application-access token,
@@ -28,7 +38,12 @@ const USAGE_UNIT_BY_OPERATION_TYPE: Record<UsageOperationType, UsageUnit> = {
export class AppBillingService {
private readonly logger = new Logger(AppBillingService.name);
- constructor(private readonly usageRecorderService: UsageRecorderService) {}
+ constructor(
+ private readonly usageRecorderService: UsageRecorderService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ @InjectRepository(UserWorkspaceEntity)
+ private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
+ ) {}
async emitChargeEvent(params: {
workspaceId: string;
@@ -37,24 +52,117 @@ export class AppBillingService {
charge: ChargeDto;
}): Promise<void> {
const { workspaceId, applicationId, userWorkspaceId, charge } = params;
- const unit = USAGE_UNIT_BY_OPERATION_TYPE[charge.operationType];
+
+ const [operationType, attributedUserWorkspaceId] = await Promise.all([
+ this.resolveOperationType({ workspaceId, applicationId, charge }),
+ userWorkspaceId ??
+ this.findWorkspaceScopedUserWorkspaceId({
+ workspaceId,
+ userWorkspaceId: charge.userWorkspaceId,
+ }),
+ ]);
+
+ const unit = USAGE_UNIT_BY_OPERATION_TYPE[operationType];
this.logger.log(
`App charge from applicationId=${applicationId} workspaceId=${workspaceId}: ` +
- `${charge.creditsUsedMicro} micro-credits (${charge.quantity} ${unit}, ${charge.operationType})`,
+ `${charge.creditsUsedMicro} micro-credits (${charge.quantity} ${unit}, ${operationType})`,
);
await this.usageRecorderService.record(workspaceId, [
{
resourceType: UsageResourceType.APP,
- operationType: charge.operationType,
+ operationType,
creditsUsedMicro: charge.creditsUsedMicro,
quantity: charge.quantity,
unit,
resourceId: applicationId,
- resourceContext: charge.resourceContext ?? null,
- spenders: { userWorkspaceId, applicationId },
+ resourceContext: charge.operation ?? charge.resourceContext ?? null,
+ spenders: { userWorkspaceId: attributedUserWorkspaceId, applicationId },
},
]);
}
+
+ private async resolveOperationType({
+ workspaceId,
+ applicationId,
+ charge,
+ }: {
+ workspaceId: string;
+ applicationId: string;
+ charge: ChargeDto;
+ }): Promise<UsageOperationType> {
+ if (!isDefined(charge.operation)) {
+ if (!isDefined(charge.operationType)) {
+ throw new BadRequestException(
+ 'A charge must name either an operation or an operationType.',
+ );
+ }
+
+ return UsageOperationType[charge.operationType];
+ }
+
+ const { flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatApplicationMaps',
+ ]);
+
+ const application = findActiveFlatApplicationById(
+ flatApplicationMaps,
+ applicationId,
+ );
+ // Undefined until the upgrade that adds the column has run.
+ const billableOperations = application?.billing?.operations ?? {};
+ // Own-property only: an operation named `constructor` or `__proto__` would
+ // otherwise resolve to an inherited value and charge under no category.
+ const billableOperation = Object.prototype.hasOwnProperty.call(
+ billableOperations,
+ charge.operation,
+ )
+ ? billableOperations[charge.operation]
+ : undefined;
+
+ if (!isDefined(billableOperation)) {
+ throw new BadRequestException(
+ `Application declares no billable operation named "${charge.operation}".`,
+ );
+ }
+
+ // `operations` is jsonb, so the declaration is untrusted at the point it is
+ // used however the manifest typed it. An unknown value indexes the enum to
+ // undefined and records a row with no category and no unit, and a
+ // platform-only value like SUBSCRIPTION would let the declared-operation
+ // path raise what ChargeDto's @IsIn stops an app raising directly.
+ if (!isUsageOperationTypeValue(billableOperation.operationType)) {
+ throw new BadRequestException(
+ `Billable operation "${charge.operation}" declares an unknown operationType.`,
+ );
+ }
+
+ // Indexing the enum by the manifest literal is also what stops
+ // twenty-shared's USAGE_OPERATION_TYPES from promising apps a category the
+ // platform does not meter: a drifted value fails to compile here.
+ return UsageOperationType[billableOperation.operationType];
+ }
+
+ // Scoped to the token's workspace, so an app cannot attribute its spend to
+ // someone outside the workspace its token was issued for.
+ private async findWorkspaceScopedUserWorkspaceId({
+ workspaceId,
+ userWorkspaceId,
+ }: {
+ workspaceId: string;
+ userWorkspaceId?: string;
+ }): Promise<string | null> {
+ if (!isDefined(userWorkspaceId)) {
+ return null;
+ }
+
+ const userWorkspace = await this.userWorkspaceRepository.findOne({
+ where: { id: userWorkspaceId, workspaceId },
+ select: { id: true },
+ });
+
+ return userWorkspace?.id ?? null;
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.module.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.module.ts
new file mode 100644
index 00000000000..7a8bbf2ec71
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.module.ts
@@ -0,0 +1,31 @@
+/* @license Enterprise */
+
+import { Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
+
+import { ApplicationRecurringChargeService } from 'src/engine/core-modules/billing/app-billing/application-recurring-charge.service';
+import { ApplicationRecurringChargeCronCommand } from 'src/engine/core-modules/billing/app-billing/crons/commands/application-recurring-charge.cron.command';
+import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
+import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/workspace-event-emitter.module';
+
+@Module({
+ imports: [
+ BillingModule,
+ TypeOrmModule.forFeature([WorkspaceEntity]),
+ UsageModule,
+ WorkspaceCacheModule,
+ WorkspaceEventEmitterModule,
+ ],
+ providers: [
+ ApplicationRecurringChargeService,
+ ApplicationRecurringChargeCronCommand,
+ ],
+ exports: [
+ ApplicationRecurringChargeService,
+ ApplicationRecurringChargeCronCommand,
+ ],
+})
+export class ApplicationRecurringChargeModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts
new file mode 100644
index 00000000000..09731e4f1cc
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/application-recurring-charge.service.ts
@@ -0,0 +1,153 @@
+/* @license Enterprise */
+
+import { Injectable, Logger } from '@nestjs/common';
+
+import { buildRecurringChargeUsageEvents } from 'src/engine/core-modules/billing/app-billing/utils/build-recurring-charge-usage-events.util';
+import {
+ collectDeclaredRecurringCharges,
+ type RejectedRecurringCharge,
+} from 'src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util';
+import { collectDueRecurringCharges } from 'src/engine/core-modules/billing/app-billing/utils/collect-due-recurring-charges.util';
+import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
+import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';
+import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
+import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
+import { UsageRecorderService } from 'src/engine/core-modules/usage/services/usage-recorder.service';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
+
+// Flat fees and per-seat fees an app declares in its manifest, raised by the
+// platform once per billing period as ordinary credit usage. Recording through
+// the same usage path as app-initiated charges is what makes them show up in
+// Usage by App and on the credit meter without any separate plumbing.
+@Injectable()
+export class ApplicationRecurringChargeService {
+ private readonly logger = new Logger(ApplicationRecurringChargeService.name);
+
+ constructor(
+ private readonly billingService: BillingService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly usageAnalyticsService: UsageAnalyticsService,
+ private readonly usageRecorderService: UsageRecorderService,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ ) {}
+
+ async chargeDueRecurringCharges(workspaceId: string): Promise<number> {
+ if (!this.billingService.isBillingEnabled()) {
+ return 0;
+ }
+
+ const { currentBillingSubscription, flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'currentBillingSubscription',
+ 'flatApplicationMaps',
+ ]);
+
+ if (currentBillingSubscription === NO_BILLING_SUBSCRIPTION) {
+ return 0;
+ }
+
+ const periodStart = currentBillingSubscription.currentPeriodStart;
+
+ const { declaredCharges, rejectedCharges: malformedCharges } =
+ collectDeclaredRecurringCharges({ flatApplicationMaps });
+
+ this.reportRejectedCharges(workspaceId, malformedCharges);
+
+ // Reading what the period already carries costs a ClickHouse query per
+ // workspace per day, so it waits until an app actually declares something.
+ if (declaredCharges.length === 0) {
+ return 0;
+ }
+
+ // A MONTH charge on a yearly subscription would be raised once a year, not
+ // twelve times, so it is skipped rather than silently under-charged. Only
+ // reached once an app actually declares one, so the workspaces this is said
+ // about are the ones running an app that expects to be paid and is not.
+ // Reported at the level and cadence of a successful raise rather than as a
+ // warning: the condition is by design and unchanging, so a daily warning
+ // would only teach people to ignore it.
+ if (currentBillingSubscription.interval !== SubscriptionInterval.Month) {
+ this.logger.log(
+ `Skipped ${declaredCharges.length} recurring app charge(s) for workspace ${workspaceId}: the workspace is on a ${currentBillingSubscription.interval} subscription and only MONTH charges can be raised`,
+ );
+
+ return 0;
+ }
+
+ const alreadyChargedKeys =
+ await this.usageAnalyticsService.getChargedRecurringKeys({
+ workspaceId,
+ periodStart,
+ });
+
+ const dueCharges = collectDueRecurringCharges({
+ declaredCharges,
+ alreadyChargedKeys,
+ });
+
+ if (dueCharges.length === 0) {
+ return 0;
+ }
+
+ const workspaceMemberCount = dueCharges.some(
+ ({ charge }) => charge.per === 'WORKSPACE_MEMBER',
+ )
+ ? await this.countWorkspaceMembers(workspaceId)
+ : 0;
+
+ const { events, rejectedCharges: overCapCharges } =
+ buildRecurringChargeUsageEvents({
+ dueCharges,
+ workspaceMemberCount,
+ periodStart,
+ });
+
+ this.reportRejectedCharges(workspaceId, overCapCharges);
+
+ if (events.length === 0) {
+ return 0;
+ }
+
+ await this.usageRecorderService.record(workspaceId, events);
+
+ this.logger.log(
+ `Raised ${events.length} recurring app charge(s) for workspace ${workspaceId}`,
+ );
+
+ return events.length;
+ }
+
+ // A refused charge means an installed app is not being billed for the period,
+ // which is invisible to everyone unless it is said out loud.
+ private reportRejectedCharges(
+ workspaceId: string,
+ rejectedCharges: RejectedRecurringCharge[],
+ ): void {
+ for (const { applicationId, chargeKey, reason } of rejectedCharges) {
+ this.logger.error(
+ `Refused recurring charge "${chargeKey}" from application ${applicationId} in workspace ${workspaceId}: ${reason}`,
+ );
+ }
+ }
+
+ private async countWorkspaceMembers(workspaceId: string): Promise<number> {
+ const authContext = buildSystemAuthContext(workspaceId);
+
+ return this.workspaceOrmManager.executeInWorkspaceContext(
+ async () => {
+ const workspaceMemberRepository =
+ this.workspaceOrmManager.getRepository<WorkspaceMemberWorkspaceEntity>(
+ 'workspaceMember',
+ { shouldBypassPermissionChecks: true },
+ );
+
+ return workspaceMemberRepository.count();
+ },
+ authContext,
+ { lite: true },
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/crons/commands/application-recurring-charge.cron.command.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/crons/commands/application-recurring-charge.cron.command.ts
new file mode 100644
index 00000000000..c43edb85f7d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/crons/commands/application-recurring-charge.cron.command.ts
@@ -0,0 +1,34 @@
+/* @license Enterprise */
+
+import { Command, CommandRunner } from 'nest-commander';
+
+import {
+ APPLICATION_RECURRING_CHARGE_CRON_PATTERN,
+ ApplicationRecurringChargeCronJob,
+} from 'src/engine/core-modules/billing/app-billing/crons/jobs/application-recurring-charge.cron.job';
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+
+@Command({
+ name: 'cron:billing:application-recurring-charge',
+ description: 'Raise declared recurring application charges for the period',
+})
+export class ApplicationRecurringChargeCronCommand extends CommandRunner {
+ constructor(
+ @InjectMessageQueue(MessageQueue.cronQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {
+ super();
+ }
+
+ async run(): Promise<void> {
+ await this.messageQueueService.addCron({
+ jobName: ApplicationRecurringChargeCronJob.name,
+ data: undefined,
+ options: {
+ repeat: { pattern: APPLICATION_RECURRING_CHARGE_CRON_PATTERN },
+ },
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/crons/jobs/application-recurring-charge.cron.job.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/crons/jobs/application-recurring-charge.cron.job.ts
new file mode 100644
index 00000000000..8d45d6a83f2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/crons/jobs/application-recurring-charge.cron.job.ts
@@ -0,0 +1,84 @@
+/* @license Enterprise */
+
+import { Logger } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
+import { Repository } from 'typeorm';
+
+import { ApplicationRecurringChargeService } from 'src/engine/core-modules/billing/app-billing/application-recurring-charge.service';
+import { SentryCronMonitor } from 'src/engine/core-modules/cron/sentry-cron-monitor.decorator';
+import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+
+// Daily rather than monthly: the charge is keyed to the workspace's own billing
+// period, which starts on a different day for every workspace, and the service
+// skips periods it has already charged.
+export const APPLICATION_RECURRING_CHARGE_CRON_PATTERN = '0 5 * * *';
+
+const WORKSPACE_BATCH_SIZE = 10;
+
+@Processor(MessageQueue.cronQueue)
+export class ApplicationRecurringChargeCronJob {
+ private readonly logger = new Logger(ApplicationRecurringChargeCronJob.name);
+
+ constructor(
+ @InjectRepository(WorkspaceEntity)
+ private readonly workspaceRepository: Repository<WorkspaceEntity>,
+ private readonly applicationRecurringChargeService: ApplicationRecurringChargeService,
+ private readonly exceptionHandlerService: ExceptionHandlerService,
+ ) {}
+
+ @Process(ApplicationRecurringChargeCronJob.name)
+ @SentryCronMonitor(
+ ApplicationRecurringChargeCronJob.name,
+ APPLICATION_RECURRING_CHARGE_CRON_PATTERN,
+ )
+ async handle() {
+ const activeWorkspaces = await this.workspaceRepository.find({
+ where: { activationStatus: WorkspaceActivationStatus.ACTIVE },
+ select: ['id'],
+ order: { id: 'ASC' },
+ });
+
+ let chargedCount = 0;
+
+ for (
+ let workspaceIndex = 0;
+ workspaceIndex < activeWorkspaces.length;
+ workspaceIndex += WORKSPACE_BATCH_SIZE
+ ) {
+ const batch = activeWorkspaces.slice(
+ workspaceIndex,
+ workspaceIndex + WORKSPACE_BATCH_SIZE,
+ );
+
+ const results = await Promise.allSettled(
+ batch.map((workspace) =>
+ this.applicationRecurringChargeService.chargeDueRecurringCharges(
+ workspace.id,
+ ),
+ ),
+ );
+
+ for (const [index, result] of results.entries()) {
+ if (result.status === 'fulfilled') {
+ chargedCount += result.value;
+ }
+
+ if (result.status === 'rejected') {
+ this.exceptionHandlerService.captureExceptions([result.reason], {
+ workspace: { id: batch[index].id },
+ });
+ }
+ }
+ }
+
+ this.logger.log(
+ `Completed ApplicationRecurringChargeCronJob, raised ${chargedCount} charge(s)`,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/dtos/charge.dto.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/dtos/charge.dto.ts
index 66dfceb5ced..b24abb860b7 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/app-billing/dtos/charge.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/dtos/charge.dto.ts
@@ -1,8 +1,21 @@
/* @license Enterprise */
-import { IsEnum, IsInt, IsOptional, IsString, Max, Min } from 'class-validator';
+import {
+ IsIn,
+ IsInt,
+ IsOptional,
+ IsString,
+ IsUUID,
+ Max,
+ Min,
+ ValidateIf,
+} from 'class-validator';
-import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import {
+ USAGE_OPERATION_TYPES,
+ type UsageOperationTypeValue,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
// $1000 in micro-credits (1 USD = 1_000_000 micro-credits). Bounds a single
// charge so a compromised or buggy app can't drain credits in one request.
@@ -20,10 +33,26 @@ export class ChargeDto {
@Max(MAX_QUANTITY_PER_CHARGE)
quantity!: number;
- @IsEnum(UsageOperationType)
- operationType!: UsageOperationType;
+ // An operation name declared in `billing.operations` on the application
+ // manifest; the server resolves its billing category and its label.
+ @IsOptional()
+ @IsString()
+ operation?: string;
+
+ // Applications that declare no billable operations name the platform billing
+ // category directly. Restricted to the app-facing vocabulary in
+ // twenty-shared, so platform-raised categories cannot be charged by an app.
+ @ValidateIf((charge: ChargeDto) => !isDefined(charge.operation))
+ @IsIn(USAGE_OPERATION_TYPES)
+ operationType?: UsageOperationTypeValue;
@IsOptional()
@IsString()
resourceContext?: string;
+
+ // Webhook and cron runs carry no triggering person on the token, so an app
+ // that knows who the spend belongs to names them here instead.
+ @IsOptional()
+ @IsUUID()
+ userWorkspaceId?: string;
}
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/build-recurring-charge-usage-events.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/build-recurring-charge-usage-events.util.spec.ts
new file mode 100644
index 00000000000..48706d82a51
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/build-recurring-charge-usage-events.util.spec.ts
@@ -0,0 +1,181 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { buildRecurringChargeUsageEvents } from 'src/engine/core-modules/billing/app-billing/utils/build-recurring-charge-usage-events.util';
+import { MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD } from 'twenty-shared/application';
+
+import { type DeclaredRecurringCharge } from 'src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.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 APPLICATION_ID = '20202020-1111-0000-0000-000000000001';
+const PERIOD_START = new Date('2026-08-01T00:00:00.000Z');
+
+const FLAT_CHARGE: DeclaredRecurringCharge = {
+ applicationId: APPLICATION_ID,
+ chargeKey: 'platformFee',
+ charge: {
+ period: 'MONTH',
+ amountMicroCredits: 20_000_000,
+ label: 'Platform fee',
+ },
+};
+
+const SEAT_CHARGE: DeclaredRecurringCharge = {
+ applicationId: APPLICATION_ID,
+ chargeKey: 'seat',
+ charge: {
+ period: 'MONTH',
+ amountMicroCredits: 5_000_000,
+ per: 'WORKSPACE_MEMBER',
+ label: 'Per member',
+ },
+};
+
+describe('buildRecurringChargeUsageEvents', () => {
+ it('should raise a flat charge once, in credits', () => {
+ expect(
+ buildRecurringChargeUsageEvents({
+ dueCharges: [FLAT_CHARGE],
+ workspaceMemberCount: 3,
+ periodStart: PERIOD_START,
+ }).events,
+ ).toEqual([
+ {
+ resourceType: UsageResourceType.APP,
+ operationType: UsageOperationType.SUBSCRIPTION,
+ creditsUsedMicro: 20_000_000,
+ quantity: 1,
+ unit: UsageUnit.CREDIT,
+ resourceId: APPLICATION_ID,
+ resourceContext: 'platformFee',
+ spenders: { applicationId: APPLICATION_ID },
+ periodStart: PERIOD_START,
+ },
+ ]);
+ });
+
+ it('should multiply a per member charge by the member count, in seats', () => {
+ expect(
+ buildRecurringChargeUsageEvents({
+ dueCharges: [SEAT_CHARGE],
+ workspaceMemberCount: 3,
+ periodStart: PERIOD_START,
+ }).events,
+ ).toEqual([
+ {
+ resourceType: UsageResourceType.APP,
+ operationType: UsageOperationType.SUBSCRIPTION,
+ creditsUsedMicro: 15_000_000,
+ quantity: 3,
+ unit: UsageUnit.SEAT,
+ resourceId: APPLICATION_ID,
+ resourceContext: 'seat',
+ spenders: { applicationId: APPLICATION_ID },
+ periodStart: PERIOD_START,
+ },
+ ]);
+ });
+
+ it('should raise nothing for a per member charge when the workspace has no members', () => {
+ expect(
+ buildRecurringChargeUsageEvents({
+ dueCharges: [SEAT_CHARGE],
+ workspaceMemberCount: 0,
+ periodStart: PERIOD_START,
+ }).events,
+ ).toEqual([]);
+ });
+
+ it('should still raise the flat charge when a per member charge is dropped', () => {
+ const { events: result } = buildRecurringChargeUsageEvents({
+ dueCharges: [FLAT_CHARGE, SEAT_CHARGE],
+ workspaceMemberCount: 0,
+ periodStart: PERIOD_START,
+ });
+
+ expect(result).toEqual([
+ expect.objectContaining({ resourceContext: 'platformFee', quantity: 1 }),
+ ]);
+ });
+
+ it('should attribute to the application only, never to a member', () => {
+ const { events: result } = buildRecurringChargeUsageEvents({
+ dueCharges: [FLAT_CHARGE, SEAT_CHARGE],
+ workspaceMemberCount: 2,
+ periodStart: PERIOD_START,
+ });
+
+ expect(
+ result.every((event) => !isDefined(event.spenders?.userWorkspaceId)),
+ ).toBe(true);
+ expect(
+ result.every((event) => event.spenders?.applicationId === APPLICATION_ID),
+ ).toBe(true);
+ expect(result.every((event) => event.resourceId === APPLICATION_ID)).toBe(
+ true,
+ );
+ });
+
+ it('should return no events when nothing is due', () => {
+ expect(
+ buildRecurringChargeUsageEvents({
+ dueCharges: [],
+ workspaceMemberCount: 5,
+ periodStart: PERIOD_START,
+ }).events,
+ ).toEqual([]);
+ });
+
+ // The declared rate is bounded per member, but the member count is not, so a
+ // legitimate rate can still multiply past what the platform will debit.
+ it('should drop a per member charge whose multiplied total exceeds the period maximum', () => {
+ const { events, rejectedCharges } = buildRecurringChargeUsageEvents({
+ dueCharges: [SEAT_CHARGE],
+ workspaceMemberCount:
+ MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD /
+ SEAT_CHARGE.charge.amountMicroCredits +
+ 1,
+ periodStart: PERIOD_START,
+ });
+
+ expect(events).toEqual([]);
+ expect(rejectedCharges).toHaveLength(1);
+ expect(rejectedCharges[0]).toMatchObject({
+ applicationId: APPLICATION_ID,
+ chargeKey: 'seat',
+ });
+ });
+
+ it('should keep a charge whose total lands exactly on the period maximum', () => {
+ const { events, rejectedCharges } = buildRecurringChargeUsageEvents({
+ dueCharges: [SEAT_CHARGE],
+ workspaceMemberCount:
+ MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD /
+ SEAT_CHARGE.charge.amountMicroCredits,
+ periodStart: PERIOD_START,
+ });
+
+ expect(events).toHaveLength(1);
+ expect(events[0].creditsUsedMicro).toBe(
+ MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD,
+ );
+ expect(rejectedCharges).toEqual([]);
+ });
+
+ it('should still raise a charge under the cap when a sibling is dropped over it', () => {
+ const { events, rejectedCharges } = buildRecurringChargeUsageEvents({
+ dueCharges: [FLAT_CHARGE, SEAT_CHARGE],
+ workspaceMemberCount:
+ MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD /
+ SEAT_CHARGE.charge.amountMicroCredits +
+ 1,
+ periodStart: PERIOD_START,
+ });
+
+ expect(events).toEqual([
+ expect.objectContaining({ resourceContext: 'platformFee' }),
+ ]);
+ expect(rejectedCharges).toHaveLength(1);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/collect-declared-recurring-charges.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/collect-declared-recurring-charges.util.spec.ts
new file mode 100644
index 00000000000..333837cdba9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/collect-declared-recurring-charges.util.spec.ts
@@ -0,0 +1,238 @@
+import { MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT } from 'twenty-shared/application';
+
+import { type FlatApplicationCacheMaps } from 'src/engine/core-modules/application/types/flat-application-cache-maps.type';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { collectDeclaredRecurringCharges } from 'src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util';
+
+const APPLICATION_ID = '20202020-1111-0000-0000-000000000001';
+const OTHER_APPLICATION_ID = '20202020-1111-0000-0000-000000000002';
+
+const buildFlatApplicationMaps = (
+ applications: Array<Partial<FlatApplication> & { id: string }>,
+): FlatApplicationCacheMaps => ({
+ byId: Object.fromEntries(
+ applications.map((application) => [
+ application.id,
+ application as FlatApplication,
+ ]),
+ ),
+ idByUniversalIdentifier: {},
+});
+
+const PLATFORM_FEE = {
+ period: 'MONTH',
+ amountMicroCredits: 20_000_000,
+ label: 'Platform fee',
+} as const;
+
+const SEAT_FEE = {
+ period: 'MONTH',
+ amountMicroCredits: 5_000_000,
+ per: 'WORKSPACE_MEMBER',
+ label: 'Per member',
+} as const;
+
+// The column is jsonb, so a declaration reaching the raise path is untrusted
+// whatever the RecurringCharge type claims.
+const collectOne = (charge: unknown) =>
+ collectDeclaredRecurringCharges({
+ flatApplicationMaps: buildFlatApplicationMaps([
+ { id: APPLICATION_ID, billing: { recurring: { fee: charge } } },
+ ] as unknown as Array<Partial<FlatApplication> & { id: string }>),
+ });
+
+describe('collectDeclaredRecurringCharges', () => {
+ it('should collect every recurring charge an installed application declares', () => {
+ const { declaredCharges, rejectedCharges } =
+ collectDeclaredRecurringCharges({
+ flatApplicationMaps: buildFlatApplicationMaps([
+ {
+ id: APPLICATION_ID,
+ billing: {
+ recurring: { platformFee: PLATFORM_FEE, seat: SEAT_FEE },
+ },
+ },
+ ]),
+ });
+
+ expect(declaredCharges).toEqual([
+ {
+ applicationId: APPLICATION_ID,
+ chargeKey: 'platformFee',
+ charge: PLATFORM_FEE,
+ },
+ { applicationId: APPLICATION_ID, chargeKey: 'seat', charge: SEAT_FEE },
+ ]);
+ expect(rejectedCharges).toEqual([]);
+ });
+
+ it('should collect charges from every installed application', () => {
+ const { declaredCharges } = collectDeclaredRecurringCharges({
+ flatApplicationMaps: buildFlatApplicationMaps([
+ { id: APPLICATION_ID, billing: { recurring: { seat: SEAT_FEE } } },
+ {
+ id: OTHER_APPLICATION_ID,
+ billing: { recurring: { seat: SEAT_FEE } },
+ },
+ ]),
+ });
+
+ expect(declaredCharges).toEqual([
+ { applicationId: APPLICATION_ID, chargeKey: 'seat', charge: SEAT_FEE },
+ {
+ applicationId: OTHER_APPLICATION_ID,
+ chargeKey: 'seat',
+ charge: SEAT_FEE,
+ },
+ ]);
+ });
+
+ it('should skip an uninstalled application', () => {
+ const { declaredCharges, rejectedCharges } =
+ collectDeclaredRecurringCharges({
+ flatApplicationMaps: buildFlatApplicationMaps([
+ {
+ id: APPLICATION_ID,
+ deletedAt: new Date('2026-08-01T00:00:00.000Z'),
+ billing: { recurring: { platformFee: PLATFORM_FEE } },
+ },
+ ]),
+ });
+
+ expect(declaredCharges).toEqual([]);
+ expect(rejectedCharges).toEqual([]);
+ });
+
+ it('should skip an application declaring only billable operations', () => {
+ const { declaredCharges } = collectDeclaredRecurringCharges({
+ flatApplicationMaps: buildFlatApplicationMaps([
+ {
+ id: APPLICATION_ID,
+ billing: {
+ operations: {
+ recordMeeting: {
+ operationType: 'CALL_RECORDING',
+ label: 'Meeting recording',
+ },
+ },
+ },
+ },
+ ]),
+ });
+
+ expect(declaredCharges).toEqual([]);
+ });
+
+ // billing is hidden from TypeORM until its upgrade has run.
+ it('should treat a missing billing column as no declarations', () => {
+ const { declaredCharges } = collectDeclaredRecurringCharges({
+ flatApplicationMaps: buildFlatApplicationMaps([{ id: APPLICATION_ID }]),
+ });
+
+ expect(declaredCharges).toEqual([]);
+ });
+
+ it('should return nothing when the workspace has no applications', () => {
+ const { declaredCharges } = collectDeclaredRecurringCharges({
+ flatApplicationMaps: buildFlatApplicationMaps([]),
+ });
+
+ expect(declaredCharges).toEqual([]);
+ });
+
+ // A negative amount would subtract from the period's usage sum, handing the
+ // workspace credits rather than charging it.
+ it('should reject a negative amount rather than crediting the workspace', () => {
+ const { declaredCharges, rejectedCharges } = collectOne({
+ ...PLATFORM_FEE,
+ amountMicroCredits: -1,
+ });
+
+ expect(declaredCharges).toEqual([]);
+ expect(rejectedCharges).toEqual([
+ {
+ applicationId: APPLICATION_ID,
+ chargeKey: 'fee',
+ reason: 'malformed or out-of-bounds recurring charge declaration',
+ },
+ ]);
+ });
+
+ it('should reject a zero amount', () => {
+ const { declaredCharges, rejectedCharges } = collectOne({
+ ...PLATFORM_FEE,
+ amountMicroCredits: 0,
+ });
+
+ expect(declaredCharges).toEqual([]);
+ expect(rejectedCharges).toEqual([
+ {
+ applicationId: APPLICATION_ID,
+ chargeKey: 'fee',
+ reason: 'malformed or out-of-bounds recurring charge declaration',
+ },
+ ]);
+ });
+
+ it('should reject an amount above the per-unit maximum', () => {
+ const { declaredCharges, rejectedCharges } = collectOne({
+ ...PLATFORM_FEE,
+ amountMicroCredits: MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT + 1,
+ });
+
+ expect(declaredCharges).toEqual([]);
+ expect(rejectedCharges).toEqual([
+ {
+ applicationId: APPLICATION_ID,
+ chargeKey: 'fee',
+ reason: 'malformed or out-of-bounds recurring charge declaration',
+ },
+ ]);
+ });
+
+ // An array is typeof 'object', so without an explicit check Object.entries
+ // would bill each element under its numeric index.
+ it('should ignore a recurring block that is an array rather than a map', () => {
+ const { declaredCharges, rejectedCharges } =
+ collectDeclaredRecurringCharges({
+ flatApplicationMaps: buildFlatApplicationMaps([
+ { id: APPLICATION_ID, billing: { recurring: [PLATFORM_FEE] } },
+ ] as unknown as Array<Partial<FlatApplication> & { id: string }>),
+ });
+
+ expect(declaredCharges).toEqual([]);
+ expect(rejectedCharges).toEqual([]);
+ });
+
+ it('should accept an amount exactly at the per-unit maximum', () => {
+ const { declaredCharges } = collectOne({
+ ...PLATFORM_FEE,
+ amountMicroCredits: MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT,
+ });
+
+ expect(declaredCharges).toHaveLength(1);
+ });
+
+ it.each([
+ ['a string amount', { ...PLATFORM_FEE, amountMicroCredits: '20' }],
+ ['a fractional amount', { ...PLATFORM_FEE, amountMicroCredits: 20.5 }],
+ ['a NaN amount', { ...PLATFORM_FEE, amountMicroCredits: Number.NaN }],
+ [
+ 'an infinite amount',
+ { ...PLATFORM_FEE, amountMicroCredits: Number.POSITIVE_INFINITY },
+ ],
+ ['a missing amount', { period: 'MONTH', label: 'Platform fee' }],
+ ['an unknown period', { ...PLATFORM_FEE, period: 'YEAR' }],
+ ['a missing period', { amountMicroCredits: 20_000_000, label: 'Fee' }],
+ ['an unknown per unit', { ...SEAT_FEE, per: 'SEAT' }],
+ ['an empty label', { ...PLATFORM_FEE, label: ' ' }],
+ ['a non-string label', { ...PLATFORM_FEE, label: 42 }],
+ ['a null charge', null],
+ ['a non-object charge', 'platformFee'],
+ ])('should reject %s', (_case, charge) => {
+ const { declaredCharges, rejectedCharges } = collectOne(charge);
+
+ expect(declaredCharges).toEqual([]);
+ expect(rejectedCharges).toHaveLength(1);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/collect-due-recurring-charges.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/collect-due-recurring-charges.util.spec.ts
new file mode 100644
index 00000000000..36635b5b458
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/__tests__/collect-due-recurring-charges.util.spec.ts
@@ -0,0 +1,103 @@
+import { type DeclaredRecurringCharge } from 'src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util';
+import { collectDueRecurringCharges } from 'src/engine/core-modules/billing/app-billing/utils/collect-due-recurring-charges.util';
+import { buildRecurringChargeKey } from 'src/engine/core-modules/usage/utils/build-recurring-charge-key.util';
+
+const APPLICATION_ID = '20202020-1111-0000-0000-000000000001';
+const OTHER_APPLICATION_ID = '20202020-1111-0000-0000-000000000002';
+
+const PLATFORM_FEE = {
+ period: 'MONTH',
+ amountMicroCredits: 20_000_000,
+ label: 'Platform fee',
+} as const;
+
+const SEAT_FEE = {
+ period: 'MONTH',
+ amountMicroCredits: 5_000_000,
+ per: 'WORKSPACE_MEMBER',
+ label: 'Per member',
+} as const;
+
+const PLATFORM_FEE_CHARGE: DeclaredRecurringCharge = {
+ applicationId: APPLICATION_ID,
+ chargeKey: 'platformFee',
+ charge: PLATFORM_FEE,
+};
+
+const SEAT_CHARGE: DeclaredRecurringCharge = {
+ applicationId: APPLICATION_ID,
+ chargeKey: 'seat',
+ charge: SEAT_FEE,
+};
+
+const OTHER_SEAT_CHARGE: DeclaredRecurringCharge = {
+ applicationId: OTHER_APPLICATION_ID,
+ chargeKey: 'seat',
+ charge: SEAT_FEE,
+};
+
+describe('collectDueRecurringCharges', () => {
+ it('should keep every declared charge when none is charged yet', () => {
+ const result = collectDueRecurringCharges({
+ declaredCharges: [PLATFORM_FEE_CHARGE, SEAT_CHARGE],
+ alreadyChargedKeys: new Set(),
+ });
+
+ expect(result).toEqual([PLATFORM_FEE_CHARGE, SEAT_CHARGE]);
+ });
+
+ it('should skip a charge the period already carries', () => {
+ const result = collectDueRecurringCharges({
+ declaredCharges: [PLATFORM_FEE_CHARGE, SEAT_CHARGE],
+ alreadyChargedKeys: new Set([
+ buildRecurringChargeKey({
+ applicationId: APPLICATION_ID,
+ chargeKey: 'platformFee',
+ }),
+ ]),
+ });
+
+ expect(result).toEqual([SEAT_CHARGE]);
+ });
+
+ it('should key already-charged per application, not per charge name alone', () => {
+ const result = collectDueRecurringCharges({
+ declaredCharges: [SEAT_CHARGE, OTHER_SEAT_CHARGE],
+ alreadyChargedKeys: new Set([
+ buildRecurringChargeKey({
+ applicationId: APPLICATION_ID,
+ chargeKey: 'seat',
+ }),
+ ]),
+ });
+
+ expect(result).toEqual([OTHER_SEAT_CHARGE]);
+ });
+
+ it('should return nothing when the period already carries every charge', () => {
+ const result = collectDueRecurringCharges({
+ declaredCharges: [PLATFORM_FEE_CHARGE, SEAT_CHARGE],
+ alreadyChargedKeys: new Set([
+ buildRecurringChargeKey({
+ applicationId: APPLICATION_ID,
+ chargeKey: 'platformFee',
+ }),
+ buildRecurringChargeKey({
+ applicationId: APPLICATION_ID,
+ chargeKey: 'seat',
+ }),
+ ]),
+ });
+
+ expect(result).toEqual([]);
+ });
+
+ it('should return nothing when nothing is declared', () => {
+ const result = collectDueRecurringCharges({
+ declaredCharges: [],
+ alreadyChargedKeys: new Set(),
+ });
+
+ expect(result).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/build-recurring-charge-usage-events.util.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/build-recurring-charge-usage-events.util.ts
new file mode 100644
index 00000000000..1b4168c25de
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/build-recurring-charge-usage-events.util.ts
@@ -0,0 +1,74 @@
+/* @license Enterprise */
+
+import { MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD } from 'twenty-shared/application';
+
+import {
+ type DeclaredRecurringCharge,
+ type RejectedRecurringCharge,
+} from 'src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.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 UsageEvent } from 'src/engine/core-modules/usage/types/usage-event.type';
+
+type BuildRecurringChargeUsageEventsParams = {
+ dueCharges: DeclaredRecurringCharge[];
+ workspaceMemberCount: number;
+ periodStart: Date;
+};
+
+export type BuildRecurringChargeUsageEventsResult = {
+ events: UsageEvent[];
+ rejectedCharges: RejectedRecurringCharge[];
+};
+
+// A per-member charge multiplies by the member count at the moment the period is
+// raised, so a workspace with no members raises nothing rather than a zero-credit
+// row that would still count as charged and suppress the next attempt.
+//
+// The declared rate is already bounded per unit, but the member count is not, so
+// the multiplied total is bounded again here. Over-cap charges are dropped
+// rather than clamped: raising a different amount than the app declared would be
+// a silent mispricing, where dropping leaves the period unraised and reportable.
+export const buildRecurringChargeUsageEvents = ({
+ dueCharges,
+ workspaceMemberCount,
+ periodStart,
+}: BuildRecurringChargeUsageEventsParams): BuildRecurringChargeUsageEventsResult => {
+ const events: UsageEvent[] = [];
+ const rejectedCharges: RejectedRecurringCharge[] = [];
+
+ for (const { applicationId, chargeKey, charge } of dueCharges) {
+ const isPerMember = charge.per === 'WORKSPACE_MEMBER';
+ const quantity = isPerMember ? workspaceMemberCount : 1;
+
+ if (quantity <= 0) {
+ continue;
+ }
+
+ const creditsUsedMicro = charge.amountMicroCredits * quantity;
+
+ if (creditsUsedMicro > MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD) {
+ rejectedCharges.push({
+ applicationId,
+ chargeKey,
+ reason: `charge of ${creditsUsedMicro} micro-credits (${charge.amountMicroCredits} x ${quantity}) exceeds the ${MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD} per-period maximum`,
+ });
+ continue;
+ }
+
+ events.push({
+ resourceType: UsageResourceType.APP,
+ operationType: UsageOperationType.SUBSCRIPTION,
+ creditsUsedMicro,
+ quantity,
+ unit: isPerMember ? UsageUnit.SEAT : UsageUnit.CREDIT,
+ resourceId: applicationId,
+ resourceContext: chargeKey,
+ spenders: { applicationId },
+ periodStart,
+ } satisfies UsageEvent);
+ }
+
+ return { events, rejectedCharges };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util.ts
new file mode 100644
index 00000000000..bc7a78043fd
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util.ts
@@ -0,0 +1,89 @@
+/* @license Enterprise */
+
+import {
+ type ApplicationBilling,
+ isRecurringCharge,
+ type RecurringCharge,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatApplicationCacheMaps } from 'src/engine/core-modules/application/types/flat-application-cache-maps.type';
+
+export type DeclaredRecurringCharge = {
+ applicationId: string;
+ chargeKey: string;
+ charge: RecurringCharge;
+};
+
+export type RejectedRecurringCharge = {
+ applicationId: string;
+ chargeKey: string;
+ reason: string;
+};
+
+export type CollectDeclaredRecurringChargesResult = {
+ declaredCharges: DeclaredRecurringCharge[];
+ rejectedCharges: RejectedRecurringCharge[];
+};
+
+type CollectDeclaredRecurringChargesParams = {
+ flatApplicationMaps: FlatApplicationCacheMaps;
+};
+
+// The recurring charges installed applications declare, read straight from the
+// already-loaded cache. Uninstalled applications are skipped so a removed app
+// stops billing from the next period; the period it was removed in was already
+// raised. Collected before the already-charged lookup so a workspace whose apps
+// declare nothing costs no ClickHouse read.
+//
+// `billing` is jsonb, so a declaration is untrusted input however it got there:
+// the manifest is persisted without a shape check, and nothing stops a row
+// being written by another route. Every declaration is validated here, at the
+// point the platform decides to debit, rather than relying on the SDK having
+// validated it at build time. A rejected declaration is returned rather than
+// dropped silently so the caller can report an app that will not be billed.
+export const collectDeclaredRecurringCharges = ({
+ flatApplicationMaps,
+}: CollectDeclaredRecurringChargesParams): CollectDeclaredRecurringChargesResult => {
+ const declaredCharges: DeclaredRecurringCharge[] = [];
+ const rejectedCharges: RejectedRecurringCharge[] = [];
+
+ for (const application of Object.values(flatApplicationMaps.byId)) {
+ if (!isDefined(application) || isDefined(application.deletedAt)) {
+ continue;
+ }
+
+ // Undefined until the upgrade that adds the column has run.
+ const billing: ApplicationBilling = application.billing ?? {};
+ const recurring = billing.recurring;
+
+ // An array is typeof 'object', and Object.entries would then bill each
+ // element under its numeric index as if it were a charge name.
+ if (
+ !isDefined(recurring) ||
+ typeof recurring !== 'object' ||
+ Array.isArray(recurring)
+ ) {
+ continue;
+ }
+
+ for (const [chargeKey, charge] of Object.entries(recurring)) {
+ if (isRecurringCharge(charge)) {
+ declaredCharges.push({
+ applicationId: application.id,
+ chargeKey,
+ charge,
+ });
+ continue;
+ }
+
+ rejectedCharges.push({
+ applicationId: application.id,
+ chargeKey,
+ reason: 'malformed or out-of-bounds recurring charge declaration',
+ });
+ }
+ }
+
+ return { declaredCharges, rejectedCharges };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-due-recurring-charges.util.ts b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-due-recurring-charges.util.ts
new file mode 100644
index 00000000000..74fad3a10d9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/app-billing/utils/collect-due-recurring-charges.util.ts
@@ -0,0 +1,23 @@
+/* @license Enterprise */
+
+import { type DeclaredRecurringCharge } from 'src/engine/core-modules/billing/app-billing/utils/collect-declared-recurring-charges.util';
+import { buildRecurringChargeKey } from 'src/engine/core-modules/usage/utils/build-recurring-charge-key.util';
+
+type CollectDueRecurringChargesParams = {
+ declaredCharges: DeclaredRecurringCharge[];
+ alreadyChargedKeys: Set<string>;
+};
+
+// The declared charges this period does not already carry. The usage row is its
+// own record of the charge, so keying on application and charge is what keeps
+// the daily job idempotent without separate bookkeeping.
+export const collectDueRecurringCharges = ({
+ declaredCharges,
+ alreadyChargedKeys,
+}: CollectDueRecurringChargesParams): DeclaredRecurringCharge[] =>
+ declaredCharges.filter(
+ ({ applicationId, chargeKey }) =>
+ !alreadyChargedKeys.has(
+ buildRecurringChargeKey({ applicationId, chargeKey }),
+ ),
+ );
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
index e99c356383c..5e85d47db2a 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts
@@ -22,6 +22,7 @@ import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
import { BillingUsageCacheService } from 'src/engine/core-modules/billing/services/billing-usage-cache.service';
import { buildBillingCreditStateLockKey } from 'src/engine/core-modules/billing/utils/build-billing-credit-state-lock-key.util';
+import { isValidCreditAmountMicro } from 'src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util';
import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';
import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';
import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
@@ -250,6 +251,18 @@ export class BillingUsageService {
usedCredits: number;
currentBillingSubscription?: CurrentBillingSubscription;
}): Promise<number> {
+ // Callers derive this from durations and token counts, so clamp at the one
+ // place that writes the counter rather than trusting each of them.
+ const creditsToDecrement = isValidCreditAmountMicro(usedCredits)
+ ? usedCredits
+ : 0;
+
+ if (creditsToDecrement !== usedCredits) {
+ this.logger.error(
+ `Refusing to decrement ${usedCredits} credits for workspace ${workspaceId}; treating as 0`,
+ );
+ }
+
const currentBillingSubscription =
await this.resolveCurrentBillingSubscription({
workspaceId,
@@ -277,9 +290,9 @@ export class BillingUsageService {
? await this.billingUsageCacheService.adjustAvailableCredits(
workspaceId,
currentPeriodStart,
- -usedCredits,
+ -creditsToDecrement,
)
- : availableCredits - usedCredits;
+ : availableCredits - creditsToDecrement;
}
// Warming is a read of the ledger followed by a write of what it implies, so
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-valid-credit-amount-micro.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-valid-credit-amount-micro.util.spec.ts
new file mode 100644
index 00000000000..2f825dbc84b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/is-valid-credit-amount-micro.util.spec.ts
@@ -0,0 +1,22 @@
+import { isValidCreditAmountMicro } from 'src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util';
+
+describe('isValidCreditAmountMicro', () => {
+ it.each([
+ ['a positive integer', 1_000_000],
+ ['zero', 0],
+ ['the largest safe integer', Number.MAX_SAFE_INTEGER],
+ ])('should accept %s', (_case, amountMicro) => {
+ expect(isValidCreditAmountMicro(amountMicro)).toBe(true);
+ });
+
+ it.each([
+ ['a negative amount', -1],
+ ['negative infinity', Number.NEGATIVE_INFINITY],
+ ['positive infinity', Number.POSITIVE_INFINITY],
+ ['NaN', Number.NaN],
+ ['a fractional amount', 1_000.5],
+ ['an amount beyond the safe integer range', Number.MAX_SAFE_INTEGER + 2],
+ ])('should reject %s', (_case, amountMicro) => {
+ expect(isValidCreditAmountMicro(amountMicro)).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util.ts
new file mode 100644
index 00000000000..6ef492787da
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util.ts
@@ -0,0 +1,9 @@
+/* @license Enterprise */
+
+// Credit amounts are summed into a signed Int64 usage column and applied to the
+// cached counter through Redis INCRBY. A negative amount subtracts from the
+// period's usage sum and hands the workspace credits rather than charging it,
+// and a fractional or out-of-safe-range one is not a value either side can
+// hold.
+export const isValidCreditAmountMicro = (amountMicro: number): boolean =>
+ Number.isSafeInteger(amountMicro) && amountMicro >= 0;
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts b/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
index d70edec35b9..425cbc80fca 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
@@ -9,6 +9,8 @@ import { BillingProductEntity } from 'src/engine/core-modules/billing/entities/b
import { BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';
import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';
import { UpdateSubscriptionQuantityJob } from 'src/engine/core-modules/billing/jobs/update-subscription-quantity.job';
+import { ApplicationRecurringChargeModule } from 'src/engine/core-modules/billing/app-billing/application-recurring-charge.module';
+import { ApplicationRecurringChargeCronJob } from 'src/engine/core-modules/billing/app-billing/crons/jobs/application-recurring-charge.cron.job';
import { BillingReminderModule } from 'src/engine/core-modules/billing/reminders/billing-reminder.module';
import { BillingReminderCronJob } from 'src/engine/core-modules/billing/reminders/crons/billing-reminder.cron.job';
import { StripeModule } from 'src/engine/core-modules/billing/stripe/stripe.module';
@@ -105,8 +107,10 @@ import { WorkflowModule } from 'src/modules/workflow/workflow.module';
PreInstalledAppsModule,
OnboardingModule,
BillingReminderModule,
+ ApplicationRecurringChargeModule,
],
providers: [
+ ApplicationRecurringChargeCronJob,
BillingReminderCronJob,
CleanSuspendedWorkspacesJob,
CleanOnboardingWorkspacesJob,
diff --git a/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-analytics.dto.ts b/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-analytics.dto.ts
index d77bfe72753..8b2e5e0595e 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-analytics.dto.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/dtos/usage-analytics.dto.ts
@@ -14,6 +14,9 @@ export class UsageAnalyticsDTO {
@Field(() => [UsageBreakdownItemDTO])
usageByOperationType: UsageBreakdownItemDTO[];
+ @Field(() => [UsageBreakdownItemDTO])
+ usageByApplication: UsageBreakdownItemDTO[];
+
@Field(() => [UsageBreakdownItemDTO])
usageByModel: UsageBreakdownItemDTO[];
diff --git a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
index 7db0b65e06d..651ba4f6135 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-operation-type.enum.ts
@@ -10,7 +10,13 @@ export enum UsageOperationType {
WEB_SEARCH = 'WEB_SEARCH',
CALL_RECORDING = 'CALL_RECORDING',
EMAIL_SEND = 'EMAIL_SEND',
+ // Raised by the query runner and read back by the API rate limit, so it is
+ // out of twenty-shared's USAGE_OPERATION_TYPES: an app billing under it
+ // would spend the workspace's request budget.
API_REQUEST = 'API_REQUEST',
+ // Platform-raised, once per billing period. Also out of
+ // USAGE_OPERATION_TYPES: an app declares the amount, it never charges this.
+ SUBSCRIPTION = 'SUBSCRIPTION',
}
registerEnumType(UsageOperationType, {
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 b5014726067..a363ff86434 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
@@ -8,4 +8,5 @@ export enum UsageUnit {
MILLISECOND = 'MILLISECOND',
BYTE = 'BYTE',
REQUEST = 'REQUEST',
+ SEAT = 'SEAT',
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts
index 9b827d2e209..3b79f5d568f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/__tests__/usage-recorder.service.spec.ts
@@ -95,4 +95,48 @@ describe('UsageRecorderService', () => {
expect.objectContaining({ workspaceId: 'ws-1', quantity: 2 }),
);
});
+
+ // Available credits are a plain sum over a signed Int64, so a negative amount
+ // hands the workspace credits, and a fractional or out-of-range one is not a
+ // value that column can hold.
+ it.each([
+ ['a negative amount', -1_000_000],
+ ['negative infinity', Number.NEGATIVE_INFINITY],
+ ['positive infinity', Number.POSITIVE_INFINITY],
+ ['NaN', Number.NaN],
+ ['a fractional amount', 1_000.5],
+ ['an amount beyond the safe integer range', Number.MAX_SAFE_INTEGER + 2],
+ ])('records zero credits rather than %s', async (_case, creditsUsedMicro) => {
+ recorder.accumulate('ws-1', { ...API_REQUEST, creditsUsedMicro });
+
+ await recorder.onModuleDestroy();
+
+ expect(dispatchedRows()).toEqual([
+ expect.objectContaining({ workspaceId: 'ws-1', creditsUsedMicro: 0 }),
+ ]);
+ });
+
+ it('keeps the event so the activity stays visible when its credits are refused', async () => {
+ recorder.accumulate('ws-1', { ...API_REQUEST, creditsUsedMicro: -5 });
+
+ await recorder.onModuleDestroy();
+
+ expect(dispatchedRows()).toEqual([
+ expect.objectContaining({
+ operationType: UsageOperationType.API_REQUEST,
+ quantity: 1,
+ creditsUsedMicro: 0,
+ }),
+ ]);
+ });
+
+ it('records a positive integer amount unchanged', async () => {
+ recorder.accumulate('ws-1', { ...API_REQUEST, creditsUsedMicro: 1_234 });
+
+ await recorder.onModuleDestroy();
+
+ expect(dispatchedRows()).toEqual([
+ expect.objectContaining({ creditsUsedMicro: 1_234 }),
+ ]);
+ });
});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts b/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
index 1bb689afde6..d1ae1bc9756 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/usage-analytics.service.ts
@@ -1,9 +1,16 @@
/* @license Enterprise */
+import { isNonEmptyString } from '@sniptt/guards';
+
import { Injectable } from '@nestjs/common';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
import { ClickHouseService } from 'src/database/clickhouse/clickhouse.service';
import { formatDateTimeForClickHouse } from 'src/database/clickhouse/utils/format-date-time-for-clickhouse.util';
+import { 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 { buildRecurringChargeKey } from 'src/engine/core-modules/usage/utils/build-recurring-charge-key.util';
import { fillUsageTimeSeriesGaps } from 'src/engine/core-modules/usage/utils/fill-usage-time-series-gaps.util';
import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
import { toDollars } from 'src/engine/core-modules/usage/utils/to-dollars.util';
@@ -14,13 +21,18 @@ export type UsageBreakdownItem = {
creditsUsed: number;
};
+export type UsageApplicationBreakdownItem = {
+ applicationId: string;
+ operation: string;
+ creditsUsed: number;
+};
+
export type UsageTimeSeriesPoint = {
date: string;
creditsUsed: number;
};
-type BreakdownRowMicro = {
- key: string;
+type BreakdownRowMicro<TColumn extends string> = Record<TColumn, string> & {
creditsUsedMicro: number;
};
@@ -48,6 +60,11 @@ type GroupByField = (typeof ALLOWED_GROUP_BY_FIELDS)[number];
const BREAKDOWN_QUERY_LIMIT = 50;
+// Scopes a declared operation name to the application that declared it. Both
+// halves of the comparison are built here so the SQL and the array it is
+// matched against cannot spell the pair differently.
+const DECLARED_OPERATION_KEY_SEPARATOR = ':';
+
@Injectable()
export class UsageAnalyticsService {
constructor(private readonly clickHouseService: ClickHouseService) {}
@@ -74,11 +91,14 @@ export class UsageAnalyticsService {
LIMIT ${BREAKDOWN_QUERY_LIMIT}
`;
- const rows = await this.clickHouseService.select<BreakdownRowMicro>(query, {
- periodStart: formatDateTimeForClickHouse(params.periodStart),
- periodEnd: formatDateTimeForClickHouse(params.periodEnd),
- operationTypes: aiOperationTypes,
- });
+ const rows = await this.clickHouseService.select<BreakdownRowMicro<'key'>>(
+ query,
+ {
+ periodStart: formatDateTimeForClickHouse(params.periodStart),
+ periodEnd: formatDateTimeForClickHouse(params.periodEnd),
+ operationTypes: aiOperationTypes,
+ },
+ );
return rows.map((row) => ({
key: row.key,
@@ -115,6 +135,125 @@ export class UsageAnalyticsService {
});
}
+ // Apps pick their operation type from a closed platform enum, so unrelated
+ // apps merge under whichever one they picked. Grouping on the application
+ // and on the operation it declared answers "what did this app charge me
+ // for" without disturbing the operation-type breakdown, which still
+ // accounts for every credit.
+ //
+ // Contexts the app never declared collapse here rather than in the
+ // resolver, so a row is a displayed slice and the limit truncates the same
+ // way it does for every other breakdown.
+ async getUsageByApplication({
+ workspaceId,
+ periodStart,
+ periodEnd,
+ operationTypes,
+ userWorkspaceId,
+ declaredOperationsByApplicationId,
+ }: PeriodParams & {
+ userWorkspaceId?: string;
+ declaredOperationsByApplicationId: Record<string, string[]>;
+ }): Promise<UsageApplicationBreakdownItem[]> {
+ const hasOperationTypes = isNonEmptyArray(operationTypes);
+ const declaredOperationKeys = Object.entries(
+ declaredOperationsByApplicationId,
+ ).flatMap(([applicationId, operations]) =>
+ operations.map(
+ (operation) =>
+ `${applicationId}${DECLARED_OPERATION_KEY_SEPARATOR}${operation}`,
+ ),
+ );
+
+ const query = `
+ SELECT
+ resourceId,
+ if(
+ has(
+ {declaredOperationKeys:Array(String)},
+ concat(
+ resourceId,
+ {declaredOperationKeySeparator:String},
+ resourceContext
+ )
+ ),
+ resourceContext,
+ ''
+ ) AS operation,
+ sum(creditsUsedMicro) AS creditsUsedMicro
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND timestamp >= {periodStart:String}
+ AND timestamp < {periodEnd:String}
+ AND resourceType = {appResourceType:String}
+ AND resourceId != ''
+ ${hasOperationTypes ? 'AND operationType IN ({operationTypes:Array(String)})' : ''}
+ ${isNonEmptyString(userWorkspaceId) ? 'AND userWorkspaceId = {userWorkspaceId:String}' : ''}
+ GROUP BY resourceId, operation
+ ORDER BY creditsUsedMicro DESC
+ LIMIT ${BREAKDOWN_QUERY_LIMIT}
+ `;
+
+ const rows = await this.clickHouseService.select<
+ BreakdownRowMicro<'resourceId' | 'operation'>
+ >(query, {
+ workspaceId,
+ periodStart: formatDateTimeForClickHouse(periodStart),
+ periodEnd: formatDateTimeForClickHouse(periodEnd),
+ appResourceType: UsageResourceType.APP,
+ declaredOperationKeys,
+ declaredOperationKeySeparator: DECLARED_OPERATION_KEY_SEPARATOR,
+ ...(hasOperationTypes ? { operationTypes } : {}),
+ ...(isNonEmptyString(userWorkspaceId) ? { userWorkspaceId } : {}),
+ });
+
+ return rows.map((row) => ({
+ applicationId: row.resourceId,
+ operation: row.operation,
+ creditsUsed: row.creditsUsedMicro,
+ }));
+ }
+
+ // Which recurring charges an application has already been billed for in a
+ // period. The usage row is itself the record of the charge, so re-running the
+ // cron re-reads it instead of needing separate bookkeeping. Compared with >=
+ // rather than = so a truncated timestamp cannot miss the current period.
+ async getChargedRecurringKeys({
+ workspaceId,
+ periodStart,
+ }: {
+ workspaceId: string;
+ periodStart: Date;
+ }): Promise<Set<string>> {
+ const query = `
+ SELECT resourceId, resourceContext
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND resourceType = {appResourceType:String}
+ AND operationType = {subscriptionOperationType:String}
+ AND periodStart >= {periodStart:String}
+ GROUP BY resourceId, resourceContext
+ `;
+
+ const rows = await this.clickHouseService.select<
+ Record<'resourceId' | 'resourceContext', string>
+ >(query, {
+ workspaceId,
+ appResourceType: UsageResourceType.APP,
+ subscriptionOperationType: UsageOperationType.SUBSCRIPTION,
+ periodStart: formatDateTimeForClickHouse(periodStart),
+ });
+
+ return new Set(
+ rows.map((row) =>
+ buildRecurringChargeKey({
+ applicationId: row.resourceId,
+ chargeKey: row.resourceContext,
+ }),
+ ),
+ );
+ }
+
async getUsageByUserTimeSeries(
params: PeriodParams & { userWorkspaceId: string },
): Promise<UsageTimeSeriesPoint[]> {
@@ -172,15 +311,18 @@ export class UsageAnalyticsService {
LIMIT ${BREAKDOWN_QUERY_LIMIT}
`;
- const rows = await this.clickHouseService.select<BreakdownRowMicro>(query, {
- workspaceId,
- periodStart: formatDateTimeForClickHouse(periodStart),
- periodEnd: formatDateTimeForClickHouse(periodEnd),
- ...(operationTypes && operationTypes.length > 0
- ? { operationTypes }
- : {}),
- ...(extraParams ?? {}),
- });
+ const rows = await this.clickHouseService.select<BreakdownRowMicro<'key'>>(
+ query,
+ {
+ workspaceId,
+ periodStart: formatDateTimeForClickHouse(periodStart),
+ periodEnd: formatDateTimeForClickHouse(periodEnd),
+ ...(operationTypes && operationTypes.length > 0
+ ? { operationTypes }
+ : {}),
+ ...(extraParams ?? {}),
+ },
+ );
return rows.map((row) => ({
key: row.key,
diff --git a/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts b/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
index 73ce779ef75..3f4d15a291f 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/services/usage-recorder.service.ts
@@ -10,6 +10,7 @@ import {
import { isDefined } from 'twenty-shared/utils';
import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';
+import { isValidCreditAmountMicro } from 'src/engine/core-modules/billing/utils/is-valid-credit-amount-micro.util';
import { EventLogEmitterService } from 'src/engine/core-modules/event-logs/emit/event-log-emitter.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { USAGE_RECORDED } from 'src/engine/core-modules/usage/constants/usage-recorded.constant';
@@ -146,8 +147,22 @@ export class UsageRecorderService implements OnModuleInit, OnModuleDestroy {
);
}
+ // Every recorded row funnels through here, so the credit invariant holds for
+ // any caller rather than each one clamping its own arithmetic. The event is
+ // still recorded, at zero credits, so the activity stays visible in the
+ // breakdown.
private withDefaults(input: RecordUsageInput): UsageEvent {
- return { ...input, creditsUsedMicro: input.creditsUsedMicro ?? 0 };
+ const creditsUsedMicro = input.creditsUsedMicro ?? 0;
+
+ if (!isValidCreditAmountMicro(creditsUsedMicro)) {
+ this.logger.error(
+ `Refusing to record ${creditsUsedMicro} creditsUsedMicro on a ${input.operationType} usage event; recording 0 instead`,
+ );
+
+ return { ...input, creditsUsedMicro: 0 };
+ }
+
+ return { ...input, creditsUsedMicro };
}
private async resolvePeriodStart(
diff --git a/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts b/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts
index 4ebc65cc8a6..de57b664a6b 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/usage.resolver.ts
@@ -17,12 +17,14 @@ import {
UsageAnalyticsService,
type UsageBreakdownItem,
} from 'src/engine/core-modules/usage/services/usage-analytics.service';
+import { consolidateUsageByApplication } from 'src/engine/core-modules/usage/utils/consolidate-usage-by-application.util';
import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@MetadataResolver()
@UseFilters(PreventNestToAutoLogGraphqlErrorsFilter)
@@ -32,6 +34,7 @@ export class UsageResolver {
private readonly usageAnalyticsService: UsageAnalyticsService,
@InjectRepository(UserWorkspaceEntity)
private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
+ private readonly workspaceCacheService: WorkspaceCacheService,
) {}
@Query(() => UsageAnalyticsDTO)
@@ -58,22 +61,56 @@ export class UsageResolver {
operationTypes: input?.operationTypes ?? undefined,
};
- const [usageByUser, usageByOperationType, usageByModel, timeSeries] =
- await Promise.all([
- this.usageAnalyticsService.getUsageByUser(periodParams),
- this.usageAnalyticsService.getUsageByOperationType({
- ...periodParams,
- userWorkspaceId: input?.userWorkspaceId ?? undefined,
- }),
- this.usageAnalyticsService.getUsageByModel(periodParams),
- this.usageAnalyticsService.getUsageTimeSeries(periodParams),
+ const { flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspace.id, [
+ 'flatApplicationMaps',
]);
+ // Per application, not workspace-wide: two apps may use the same operation
+ // name, and only the one that declared it should keep it as its own slice.
+ const declaredOperationsByApplicationId = Object.fromEntries(
+ Object.entries(flatApplicationMaps.byId).map(
+ ([applicationId, application]) => [
+ applicationId,
+ [
+ ...Object.keys(application?.billing?.recurring ?? {}),
+ ...Object.keys(application?.billing?.operations ?? {}),
+ ],
+ ],
+ ),
+ );
+
+ const [
+ usageByUser,
+ usageByOperationType,
+ usageByApplication,
+ usageByModel,
+ timeSeries,
+ ] = await Promise.all([
+ this.usageAnalyticsService.getUsageByUser(periodParams),
+ this.usageAnalyticsService.getUsageByOperationType({
+ ...periodParams,
+ userWorkspaceId: input?.userWorkspaceId ?? undefined,
+ }),
+ this.usageAnalyticsService.getUsageByApplication({
+ ...periodParams,
+ userWorkspaceId: input?.userWorkspaceId ?? undefined,
+ declaredOperationsByApplicationId,
+ }),
+ this.usageAnalyticsService.getUsageByModel(periodParams),
+ this.usageAnalyticsService.getUsageTimeSeries(periodParams),
+ ]);
+
const resolvedUsageByUser = await this.resolveBreakdownKeys(
usageByUser,
(ids) => this.resolveUserNames(ids, workspace.id),
);
+ const resolvedUsageByApplication = consolidateUsageByApplication({
+ items: usageByApplication,
+ flatApplicationMaps,
+ });
+
const result: UsageAnalyticsDTO = {
usageByUser: resolvedUsageByUser.map((item) => ({
...item,
@@ -83,6 +120,10 @@ export class UsageResolver {
...item,
creditsUsed: toDisplayCredits(item.creditsUsed),
})),
+ usageByApplication: resolvedUsageByApplication.map((item) => ({
+ ...item,
+ creditsUsed: toDisplayCredits(item.creditsUsed),
+ })),
usageByModel: usageByModel.map((item) => ({
...item,
creditsUsed: toDisplayCredits(item.creditsUsed),
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/consolidate-usage-by-application.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/consolidate-usage-by-application.util.spec.ts
new file mode 100644
index 00000000000..74772f95689
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/__tests__/consolidate-usage-by-application.util.spec.ts
@@ -0,0 +1,219 @@
+import { type FlatApplicationCacheMaps } from 'src/engine/core-modules/application/types/flat-application-cache-maps.type';
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { consolidateUsageByApplication } from 'src/engine/core-modules/usage/utils/consolidate-usage-by-application.util';
+
+const buildFlatApplicationMaps = (
+ applications: Array<Partial<FlatApplication> & { id: string }>,
+): FlatApplicationCacheMaps => ({
+ byId: Object.fromEntries(
+ applications.map((application) => [
+ application.id,
+ application as FlatApplication,
+ ]),
+ ),
+ idByUniversalIdentifier: {},
+});
+
+describe('consolidateUsageByApplication', () => {
+ it('should give each declared operation its own slice under the app name', () => {
+ const result = consolidateUsageByApplication({
+ items: [
+ {
+ applicationId: 'app-1',
+ operation: 'recordMeeting',
+ creditsUsed: 500,
+ },
+ {
+ applicationId: 'app-1',
+ operation: 'summarizeMeeting',
+ creditsUsed: 300,
+ },
+ ],
+ flatApplicationMaps: buildFlatApplicationMaps([
+ {
+ id: 'app-1',
+ name: 'Call Recorder',
+ billing: {
+ operations: {
+ recordMeeting: {
+ operationType: 'CALL_RECORDING',
+ label: 'Meeting recording',
+ },
+ summarizeMeeting: {
+ operationType: 'AI_CHAT_TOKEN',
+ label: 'Meeting summary',
+ },
+ },
+ },
+ },
+ ]),
+ });
+
+ expect(result).toEqual([
+ {
+ key: 'Call Recorder · Meeting recording',
+ label: 'Call Recorder · Meeting recording',
+ creditsUsed: 500,
+ },
+ {
+ key: 'Call Recorder · Meeting summary',
+ label: 'Call Recorder · Meeting summary',
+ creditsUsed: 300,
+ },
+ ]);
+ });
+
+ it('should give each declared recurring charge its own slice', () => {
+ const result = consolidateUsageByApplication({
+ items: [
+ { applicationId: 'app-1', operation: 'seat', creditsUsed: 50 },
+ { applicationId: 'app-1', operation: 'platformFee', creditsUsed: 20 },
+ ],
+ flatApplicationMaps: buildFlatApplicationMaps([
+ {
+ id: 'app-1',
+ name: 'Call Recorder',
+ billing: {
+ recurring: {
+ seat: {
+ period: 'MONTH',
+ amountMicroCredits: 10_000_000,
+ per: 'WORKSPACE_MEMBER',
+ label: 'Per member',
+ },
+ platformFee: {
+ period: 'MONTH',
+ amountMicroCredits: 20_000_000,
+ label: 'Platform fee',
+ },
+ },
+ },
+ },
+ ]),
+ });
+
+ expect(result).toEqual([
+ {
+ key: 'Call Recorder · Per member',
+ label: 'Call Recorder · Per member',
+ creditsUsed: 50,
+ },
+ {
+ key: 'Call Recorder · Platform fee',
+ label: 'Call Recorder · Platform fee',
+ creditsUsed: 20,
+ },
+ ]);
+ });
+
+ it('should fold undeclared operations into a single app-level slice', () => {
+ const result = consolidateUsageByApplication({
+ items: [
+ { applicationId: 'app-1', operation: 'pdl/person', creditsUsed: 100 },
+ { applicationId: 'app-1', operation: 'pdl/company', creditsUsed: 70 },
+ { applicationId: 'app-1', operation: '', creditsUsed: 40 },
+ ],
+ flatApplicationMaps: buildFlatApplicationMaps([
+ { id: 'app-1', name: 'People Data Labs', billing: {} },
+ ]),
+ });
+
+ expect(result).toEqual([
+ {
+ key: 'People Data Labs',
+ label: 'People Data Labs',
+ creditsUsed: 210,
+ },
+ ]);
+ });
+
+ it('should keep an uninstalled application in the breakdown under its name', () => {
+ const result = consolidateUsageByApplication({
+ items: [{ applicationId: 'app-1', operation: '', creditsUsed: 120 }],
+ flatApplicationMaps: buildFlatApplicationMaps([
+ {
+ id: 'app-1',
+ name: 'Retired App',
+ billing: {},
+ deletedAt: new Date('2026-08-01T00:00:00.000Z'),
+ },
+ ]),
+ });
+
+ expect(result).toEqual([
+ { key: 'Retired App', label: 'Retired App', creditsUsed: 120 },
+ ]);
+ });
+
+ it('should fall back to the application id when the application is unknown', () => {
+ const result = consolidateUsageByApplication({
+ items: [{ applicationId: 'app-gone', operation: '', creditsUsed: 90 }],
+ flatApplicationMaps: buildFlatApplicationMaps([]),
+ });
+
+ expect(result).toEqual([
+ { key: 'app-gone', label: 'app-gone', creditsUsed: 90 },
+ ]);
+ });
+
+ it('should merge two applications sharing a display name into one slice', () => {
+ const result = consolidateUsageByApplication({
+ items: [
+ { applicationId: 'app-1', operation: '', creditsUsed: 60 },
+ { applicationId: 'app-2', operation: '', creditsUsed: 25 },
+ ],
+ flatApplicationMaps: buildFlatApplicationMaps([
+ { id: 'app-1', name: 'Enricher', billing: {} },
+ { id: 'app-2', name: 'Enricher', billing: {} },
+ ]),
+ });
+
+ expect(result).toEqual([
+ { key: 'Enricher', label: 'Enricher', creditsUsed: 85 },
+ ]);
+ });
+
+ it('should order slices by credits descending after merging', () => {
+ const result = consolidateUsageByApplication({
+ items: [
+ { applicationId: 'app-1', operation: '', creditsUsed: 10 },
+ { applicationId: 'app-2', operation: '', creditsUsed: 400 },
+ { applicationId: 'app-1', operation: 'undeclared', creditsUsed: 50 },
+ ],
+ flatApplicationMaps: buildFlatApplicationMaps([
+ { id: 'app-1', name: 'Small', billing: {} },
+ { id: 'app-2', name: 'Large', billing: {} },
+ ]),
+ });
+
+ expect(result).toEqual([
+ { key: 'Large', label: 'Large', creditsUsed: 400 },
+ { key: 'Small', label: 'Small', creditsUsed: 60 },
+ ]);
+ });
+
+ // billing is hidden from TypeORM until its upgrade has run.
+ it('should treat a missing billing column as no declarations', () => {
+ const result = consolidateUsageByApplication({
+ items: [
+ { applicationId: 'app-1', operation: 'recordMeeting', creditsUsed: 75 },
+ ],
+ flatApplicationMaps: buildFlatApplicationMaps([
+ { id: 'app-1', name: 'Call Recorder' },
+ ]),
+ });
+
+ expect(result).toEqual([
+ { key: 'Call Recorder', label: 'Call Recorder', creditsUsed: 75 },
+ ]);
+ });
+
+ it('should return an empty breakdown when there is no usage', () => {
+ expect(
+ consolidateUsageByApplication({
+ items: [],
+ flatApplicationMaps: buildFlatApplicationMaps([]),
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/build-recurring-charge-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/build-recurring-charge-key.util.ts
new file mode 100644
index 00000000000..f7fed9564bf
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/build-recurring-charge-key.util.ts
@@ -0,0 +1,12 @@
+// Identifies one recurring charge within a billing period, as the usage row
+// that records it: the application and the charge name it was raised under.
+// Both the ClickHouse read of what a period already carries and the check for
+// what is still due go through this, so the two cannot drift apart and start
+// re-charging every workspace daily.
+export const buildRecurringChargeKey = ({
+ applicationId,
+ chargeKey,
+}: {
+ applicationId: string;
+ chargeKey: string;
+}): string => `${applicationId}:${chargeKey}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts b/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts
new file mode 100644
index 00000000000..4cca1ef8626
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage/utils/consolidate-usage-by-application.util.ts
@@ -0,0 +1,47 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatApplicationCacheMaps } from 'src/engine/core-modules/application/types/flat-application-cache-maps.type';
+import {
+ type UsageApplicationBreakdownItem,
+ type UsageBreakdownItem,
+} from 'src/engine/core-modules/usage/services/usage-analytics.service';
+
+type ConsolidateUsageByApplicationParams = {
+ items: UsageApplicationBreakdownItem[];
+ flatApplicationMaps: FlatApplicationCacheMaps;
+};
+
+// Operations an app declared in its manifest get their own slice under the app
+// name; anything it charged without declaring arrives already folded into a
+// single app-level slice, so undeclared context strings never reach a screen.
+// Uninstalled apps are looked up too, otherwise their spend would drop out of
+// the pie while still counting towards the bill. Keying on the label also
+// merges two apps sharing a display name, which would otherwise collide as one
+// chart id.
+export const consolidateUsageByApplication = ({
+ items,
+ flatApplicationMaps,
+}: ConsolidateUsageByApplicationParams): UsageBreakdownItem[] => {
+ const creditsByKey = new Map<string, number>();
+
+ for (const item of items) {
+ const application = flatApplicationMaps.byId[item.applicationId];
+ // Undefined until the upgrade that adds the column has run.
+ const declaredCharges = {
+ ...(application?.billing?.recurring ?? {}),
+ ...(application?.billing?.operations ?? {}),
+ };
+ const declaredCharge = declaredCharges[item.operation];
+ const applicationName = application?.name ?? item.applicationId;
+
+ const key = isDefined(declaredCharge)
+ ? `${applicationName} · ${declaredCharge.label}`
+ : applicationName;
+
+ creditsByKey.set(key, (creditsByKey.get(key) ?? 0) + item.creditsUsed);
+ }
+
+ return [...creditsByKey.entries()]
+ .map(([key, creditsUsed]) => ({ key, label: key, creditsUsed }))
+ .sort((a, b) => b.creditsUsed - a.creditsUsed);
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/__tests__/morph-relation-from-create-field-input-to-flat-field-metadatas-to-create.spec.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/__tests__/morph-relation-from-create-field-input-to-flat-field-metadatas-to-create.spec.ts
index 436814b00d2..062fe39d266 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/__tests__/morph-relation-from-create-field-input-to-flat-field-metadatas-to-create.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/__tests__/morph-relation-from-create-field-input-to-flat-field-metadatas-to-create.spec.ts
@@ -38,6 +38,7 @@ const MOCK_FLAT_APPLICATION: FlatApplication = {
yarnLockChecksum: null,
yarnLockFileId: null,
availablePackages: {},
+ billing: {},
logicFunctionLayerId: null,
defaultRoleId: null,
defaultRole: null,
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/generate-morph-or-relation-flat-field-metadata-pair.spec.ts b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/generate-morph-or-relation-flat-field-metadata-pair.spec.ts
index 86bc2b1b587..3bfe8b8171c 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/generate-morph-or-relation-flat-field-metadata-pair.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-field-metadata/utils/__tests__/generate-morph-or-relation-flat-field-metadata-pair.spec.ts
@@ -33,6 +33,7 @@ const MOCK_FLAT_APPLICATION: FlatApplication = {
yarnLockChecksum: null,
yarnLockFileId: null,
availablePackages: {},
+ billing: {},
logicFunctionLayerId: null,
defaultRoleId: null,
defaultRole: null,
diff --git a/packages/twenty-shared/src/application/applicationBillingType.ts b/packages/twenty-shared/src/application/applicationBillingType.ts
new file mode 100644
index 00000000000..d42567bd1b8
--- /dev/null
+++ b/packages/twenty-shared/src/application/applicationBillingType.ts
@@ -0,0 +1,73 @@
+import { type BillableOperations } from '@/application/billableOperationsType';
+
+export const RECURRING_CHARGE_PERIODS = ['MONTH'] as const;
+
+export type RecurringChargePeriod = (typeof RECURRING_CHARGE_PERIODS)[number];
+
+export const isRecurringChargePeriod = (
+ value: unknown,
+): value is RecurringChargePeriod =>
+ RECURRING_CHARGE_PERIODS.includes(value as RecurringChargePeriod);
+
+// Omitted for a flat fee. WORKSPACE_MEMBER multiplies the amount by the number
+// of members in the workspace at the moment the period is charged.
+export const RECURRING_CHARGE_UNITS = ['WORKSPACE_MEMBER'] as const;
+
+export type RecurringChargeUnit = (typeof RECURRING_CHARGE_UNITS)[number];
+
+export const isRecurringChargeUnit = (
+ value: unknown,
+): value is RecurringChargeUnit =>
+ RECURRING_CHARGE_UNITS.includes(value as RecurringChargeUnit);
+
+export type RecurringCharge = {
+ period: RecurringChargePeriod;
+ amountMicroCredits: number;
+ per?: RecurringChargeUnit;
+ label: string;
+};
+
+// 1 USD = 1_000_000 micro-credits. Unlike a chargeCredits call, which the app
+// makes and the server validates per request, a recurring charge is raised by
+// the platform from a jsonb column, so these bound what the platform is willing
+// to debit on an app's behalf. PER_UNIT bounds the declared rate, which a
+// WORKSPACE_MEMBER charge multiplies by the member count, and PER_PERIOD bounds
+// the resulting total.
+export const MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT = 100_000_000;
+export const MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD = 1_000_000_000;
+
+export const isRecurringChargeAmount = (value: unknown): value is number =>
+ typeof value === 'number' &&
+ Number.isSafeInteger(value) &&
+ value > 0 &&
+ value <= MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT;
+
+// The declaration reaches the raise path as untrusted jsonb, so its shape is
+// checked at runtime rather than trusted from the RecurringCharge type.
+export const isRecurringCharge = (value: unknown): value is RecurringCharge => {
+ if (typeof value !== 'object' || value === null) {
+ return false;
+ }
+
+ const { period, amountMicroCredits, per, label } =
+ value as Partial<RecurringCharge>;
+
+ return (
+ isRecurringChargePeriod(period) &&
+ isRecurringChargeAmount(amountMicroCredits) &&
+ (per === undefined || isRecurringChargeUnit(per)) &&
+ typeof label === 'string' &&
+ label.trim().length > 0
+ );
+};
+
+// Keyed by a name the application chooses. Unlike operations, the platform
+// raises these itself once per billing period, so the app declares the amount
+// rather than calling chargeCredits.
+export type RecurringCharges = Partial<Record<string, RecurringCharge>>;
+
+export type ApplicationBilling = {
+ description?: string;
+ recurring?: RecurringCharges;
+ operations?: BillableOperations;
+};
diff --git a/packages/twenty-shared/src/application/applicationType.ts b/packages/twenty-shared/src/application/applicationType.ts
index 4200619c9c6..f8976af0b57 100644
--- a/packages/twenty-shared/src/application/applicationType.ts
+++ b/packages/twenty-shared/src/application/applicationType.ts
@@ -3,6 +3,7 @@ import { type PreInstallLogicFunctionApplicationManifest } from '@/application/p
import { type SettingsFrontComponentApplicationManifest } from '@/application/settingsFrontComponentApplicationType';
import { type UninstallLogicFunctionApplicationManifest } from '@/application/uninstallLogicFunctionApplicationType';
import { type FrontComponentSharedDependenciesManifest } from '@/application/frontComponentSharedDependenciesManifestType';
+import { type ApplicationBilling } from './applicationBillingType';
import { type ApplicationCategory } from './applicationCategoryType';
import { type ApplicationVariables } from './applicationVariablesType';
import { type ServerVariables } from './server-variables.type';
@@ -13,6 +14,7 @@ export type ApplicationManifest = SyncableEntityOptions & {
displayName: string;
description: string;
applicationVariables?: ApplicationVariables;
+ billing?: ApplicationBilling;
serverVariables?: ServerVariables;
author?: string;
category?: ApplicationCategory;
diff --git a/packages/twenty-shared/src/application/billableOperationsType.ts b/packages/twenty-shared/src/application/billableOperationsType.ts
new file mode 100644
index 00000000000..ce6672d1f2d
--- /dev/null
+++ b/packages/twenty-shared/src/application/billableOperationsType.ts
@@ -0,0 +1,11 @@
+import { type UsageOperationTypeValue } from '@/application/usageOperationTypesType';
+
+export type BillableOperationManifest = {
+ operationType: UsageOperationTypeValue;
+ label: string;
+};
+
+// Keyed by the operation name the application charges against.
+export type BillableOperations = Partial<
+ Record<string, BillableOperationManifest>
+>;
diff --git a/packages/twenty-shared/src/application/creditAvailabilityType.ts b/packages/twenty-shared/src/application/creditAvailabilityType.ts
new file mode 100644
index 00000000000..3f332f25c64
--- /dev/null
+++ b/packages/twenty-shared/src/application/creditAvailabilityType.ts
@@ -0,0 +1,17 @@
+export const CREDIT_UNAVAILABLE_REASONS = [
+ 'workspace-suspended',
+ 'no-subscription',
+ 'no-credits',
+] as const;
+
+export type CreditUnavailableReason =
+ (typeof CREDIT_UNAVAILABLE_REASONS)[number];
+
+// What an application is told about its workspace's ability to spend. Mirrors
+// the gate the platform already applies to AI, workflows and email, so an app
+// can make the same decision up front instead of discovering the refusal
+// through a downstream call it did not write. Carries no balance: an app learns
+// whether it may spend, not how much the workspace has or what it pays.
+export type CreditAvailability =
+ | { hasAvailableCredits: true }
+ | { hasAvailableCredits: false; reason: CreditUnavailableReason };
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index 873360dd51b..e4a899d2db0 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -11,6 +11,23 @@ export type { AgentManifest } from './agentManifestType';
export type { AppConnection } from './appConnectionType';
export type { AppKeyValueScope } from './appKeyValueScopeType';
export type { AppKeyValue } from './appKeyValueType';
+export type {
+ RecurringChargePeriod,
+ RecurringChargeUnit,
+ RecurringCharge,
+ RecurringCharges,
+ ApplicationBilling,
+} from './applicationBillingType';
+export {
+ RECURRING_CHARGE_PERIODS,
+ isRecurringChargePeriod,
+ RECURRING_CHARGE_UNITS,
+ isRecurringChargeUnit,
+ MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_UNIT,
+ MAX_RECURRING_CHARGE_MICRO_CREDITS_PER_PERIOD,
+ isRecurringChargeAmount,
+ isRecurringCharge,
+} from './applicationBillingType';
export type {
KnownApplicationCategory,
ApplicationCategory,
@@ -29,6 +46,10 @@ export type {
} from './applicationVariablesType';
export { APPLICATION_VARIABLE_FIELD_METADATA_TYPES } from './applicationVariablesType';
export type { AssetManifest } from './assetManifestType';
+export type {
+ BillableOperationManifest,
+ BillableOperations,
+} from './billableOperationsType';
export type { ConnectionProviderManifest } from './connectionProviderManifestType';
export type { ConnectionProviderType } from './connectionProviderType';
export { APPLICATION_FILE_UPLOAD_BATCH_SIZE } from './constants/ApplicationFileUploadBatchSize';
@@ -45,6 +66,11 @@ export { NODE_ESM_CJS_BANNER } from './constants/NodeEsmCjsBanner';
export { OUTPUT_DIR } from './constants/OutputDirectory';
export { TWENTY_STANDARD_APPLICATION_NAME } from './constants/TwentyStandardApplicationName';
export { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from './constants/TwentyStandardApplicationUniversalIdentifier';
+export type {
+ CreditUnavailableReason,
+ CreditAvailability,
+} from './creditAvailabilityType';
+export { CREDIT_UNAVAILABLE_REASONS } from './creditAvailabilityType';
export { computeDeterministicUuid } from './deterministic-identifier/compute-deterministic-uuid.util';
export type { DeterministicEntityNamespace } from './deterministic-identifier/deterministic-entity-namespace.type';
export { getAgentUniversalIdentifier } from './deterministic-identifier/get-agent-universal-identifier.util';
@@ -161,6 +187,11 @@ export type {
} from './timelineActivityTypeManifestType';
export type { ToolTriggerSettings } from './toolTriggerSettingsType';
export type { UninstallLogicFunctionApplicationManifest } from './uninstallLogicFunctionApplicationType';
+export type { UsageOperationTypeValue } from './usageOperationTypesType';
+export {
+ USAGE_OPERATION_TYPES,
+ isUsageOperationTypeValue,
+} from './usageOperationTypesType';
export {
serializeApplicationVariableValue,
deserializeApplicationVariableValue,
diff --git a/packages/twenty-shared/src/application/usageOperationTypesType.ts b/packages/twenty-shared/src/application/usageOperationTypesType.ts
new file mode 100644
index 00000000000..7f585bc1801
--- /dev/null
+++ b/packages/twenty-shared/src/application/usageOperationTypesType.ts
@@ -0,0 +1,20 @@
+// The subset of the server's UsageOperationType an app may bill under, so a
+// manifest can name a category without importing server code. API_REQUEST and
+// SUBSCRIPTION are left out on purpose: the platform raises both itself, and
+// API_REQUEST rows feed the workspace's API rate limit.
+export const USAGE_OPERATION_TYPES = [
+ 'AI_CHAT_TOKEN',
+ 'AI_WORKFLOW_TOKEN',
+ 'WORKFLOW_EXECUTION',
+ 'CODE_EXECUTION',
+ 'WEB_SEARCH',
+ 'CALL_RECORDING',
+ 'EMAIL_SEND',
+] as const;
+
+export type UsageOperationTypeValue = (typeof USAGE_OPERATION_TYPES)[number];
+
+export const isUsageOperationTypeValue = (
+ value: unknown,
+): value is UsageOperationTypeValue =>
+ USAGE_OPERATION_TYPES.includes(value as UsageOperationTypeValue);
diff --git a/packages/twenty-shared/src/constants/DocumentationPaths.ts b/packages/twenty-shared/src/constants/DocumentationPaths.ts
index c8f5d95c353..0b7bb144d97 100644
--- a/packages/twenty-shared/src/constants/DocumentationPaths.ts
+++ b/packages/twenty-shared/src/constants/DocumentationPaths.ts
@@ -63,6 +63,7 @@ export const DOCUMENTATION_PATHS = {
'/developers/extend/apps/logic/background-jobs',
DEVELOPERS_EXTEND_APPS_LOGIC_CONNECTIONS:
'/developers/extend/apps/logic/connections',
+ DEVELOPERS_EXTEND_APPS_LOGIC_CREDITS: '/developers/extend/apps/logic/credits',
DEVELOPERS_EXTEND_APPS_LOGIC_KEY_VALUE_STORE:
'/developers/extend/apps/logic/key-value-store',
DEVELOPERS_EXTEND_APPS_LOGIC_LOGIC_FUNCTIONS: