The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(billing): add workspace credits per seat (#28207)
Etienne7e09b9a6b963
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex f9f9353a026..2d4a20ea855 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -885,6 +885,8 @@ type BillingResourceCreditUsage {userCreditsUsed: Float!workspaceCreditsExtraGranted: Float!workspaceCreditsGranted: Float!+ workspaceCreditsGrantedForSeats: Float!+ workspaceCreditsSeats: Int!workspaceCreditsTotalGranted: Float!workspaceCreditsUsed: Float!}diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 6d67f869be9..6d1b473d269 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -789,6 +789,8 @@ export interface BillingResourceCreditUsage {userCreditsUsed: Scalars['Float']workspaceCreditsExtraGranted: Scalars['Float']workspaceCreditsGranted: Scalars['Float']+ workspaceCreditsGrantedForSeats: Scalars['Float']+ workspaceCreditsSeats: Scalars['Int']workspaceCreditsTotalGranted: Scalars['Float']workspaceCreditsUsed: Scalars['Float']__typename: 'BillingResourceCreditUsage'@@ -4821,6 +4823,8 @@ export interface BillingResourceCreditUsageGenqlSelection{userCreditsUsed?: boolean | numberworkspaceCreditsExtraGranted?: boolean | numberworkspaceCreditsGranted?: boolean | number+ workspaceCreditsGrantedForSeats?: boolean | number+ workspaceCreditsSeats?: boolean | numberworkspaceCreditsTotalGranted?: boolean | numberworkspaceCreditsUsed?: boolean | number__typename?: boolean | numberdiff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex 8ea89d2d820..3776d36de45 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -1942,6 +1942,12 @@ export default {"workspaceCreditsGranted": [11],+ "workspaceCreditsGrantedForSeats": [+ 11+ ],+ "workspaceCreditsSeats": [+ 8+ ],"workspaceCreditsTotalGranted": [11],diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 9799c2e9a66..e6222bb9dad 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -966,6 +966,8 @@ export type BillingResourceCreditUsage = {userCreditsUsed: Scalars['Float']['output'];workspaceCreditsExtraGranted: Scalars['Float']['output'];workspaceCreditsGranted: Scalars['Float']['output'];+ workspaceCreditsGrantedForSeats: Scalars['Float']['output'];+ workspaceCreditsSeats: Scalars['Int']['output'];workspaceCreditsTotalGranted: Scalars['Float']['output'];workspaceCreditsUsed: Scalars['Float']['output'];};@@ -10155,7 +10157,7 @@ export type BillingPortalSessionQuery = { __typename?: 'Query', billingPortalSesexport type GetResourceCreditUsageQueryVariables = Exact<{ [key: string]: never; }>;-export type GetResourceCreditUsageQuery = { __typename?: 'Query', getResourceCreditUsage: Array<{ __typename?: 'BillingResourceCreditUsage', productKey: BillingProductKey, workspaceCreditsUsed: number, workspaceCreditsGranted: number, workspaceCreditsExtraGranted: number, workspaceCreditsTotalGranted: number, unitPriceCents: number }> };+export type GetResourceCreditUsageQuery = { __typename?: 'Query', getResourceCreditUsage: Array<{ __typename?: 'BillingResourceCreditUsage', productKey: BillingProductKey, workspaceCreditsUsed: number, workspaceCreditsGranted: number, workspaceCreditsGrantedForSeats: number, workspaceCreditsSeats: number, workspaceCreditsExtraGranted: number, workspaceCreditsTotalGranted: number, unitPriceCents: number }> };export type ListPlansQueryVariables = Exact<{ [key: string]: never; }>;@@ -11224,7 +11226,7 @@ export const SwitchBillingPlanDocument = {"kind":"Document","definitions":[{"kinexport const SwitchSubscriptionIntervalDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SwitchSubscriptionInterval"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"switchSubscriptionInterval"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"currentBillingSubscription"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"price"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhase"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"start_date"}},{"kind":"Field","name":{"kind":"Name","value":"end_date"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseItemFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"CurrentBillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"interval"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"currentPeriodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"collectionMethod"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"billingSubscriptionItems"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hasReachedCurrentPeriodCap"}},{"kind":"Field","name":{"kind":"Name","value":"quantity"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"creditAmount"}},{"kind":"Field","name":{"kind":"Name","value":"billingProduct"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingSubscriptionFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingSubscription"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"cancelAt"}},{"kind":"Field","name":{"kind":"Name","value":"phases"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingSubscriptionSchedulePhaseFragment"}}]}}]}}]} as unknown as DocumentNode<SwitchSubscriptionIntervalMutation, SwitchSubscriptionIntervalMutationVariables>;export const UpdateUsageLimitDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateUsageLimit"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateUsageLimitInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateUsageLimit"},"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"}}]}}]}}]} as unknown as DocumentNode<UpdateUsageLimitMutation, UpdateUsageLimitMutationVariables>;export const BillingPortalSessionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"BillingPortalSession"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"returnUrlPath"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"forPaymentMethodUpdate"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"billingPortalSession"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"returnUrlPath"},"value":{"kind":"Variable","name":{"kind":"Name","value":"returnUrlPath"}}},{"kind":"Argument","name":{"kind":"Name","value":"forPaymentMethodUpdate"},"value":{"kind":"Variable","name":{"kind":"Name","value":"forPaymentMethodUpdate"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"url"}}]}}]}}]} as unknown as DocumentNode<BillingPortalSessionQuery, BillingPortalSessionQueryVariables>;-export const GetResourceCreditUsageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetResourceCreditUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getResourceCreditUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsUsed"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsGranted"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsExtraGranted"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsTotalGranted"}},{"kind":"Field","name":{"kind":"Name","value":"unitPriceCents"}}]}}]}}]} as unknown as DocumentNode<GetResourceCreditUsageQuery, GetResourceCreditUsageQueryVariables>;+export const GetResourceCreditUsageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetResourceCreditUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getResourceCreditUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsUsed"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsGranted"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsGrantedForSeats"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsSeats"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsExtraGranted"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceCreditsTotalGranted"}},{"kind":"Field","name":{"kind":"Name","value":"unitPriceCents"}}]}}]}}]} as unknown as DocumentNode<GetResourceCreditUsageQuery, GetResourceCreditUsageQueryVariables>;export const ListPlansDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"listPlans"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"listPlans"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"isSellable"}},{"kind":"Field","name":{"kind":"Name","value":"upgradePlanKeys"}},{"kind":"Field","name":{"kind":"Name","value":"downgradePlanKeys"}},{"kind":"Field","name":{"kind":"Name","value":"baseProducts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingLicensedProduct"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"prices"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingPriceLicensedFragment"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"resourceCreditProducts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingLicensedProduct"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"prices"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingPriceLicensedFragment"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"meteredProducts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"images"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"productKey"}},{"kind":"Field","name":{"kind":"Name","value":"planKey"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageBased"}},{"kind":"Field","name":{"kind":"Name","value":"isLegacy"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingMeteredProduct"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"prices"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"BillingPriceMeteredFragment"}}]}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingPriceLicensedFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingPriceLicensed"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"recurringInterval"}},{"kind":"Field","name":{"kind":"Name","value":"priceUsageType"}},{"kind":"Field","name":{"kind":"Name","value":"creditAmount"}},{"kind":"Field","name":{"kind":"Name","value":"isSellable"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"BillingPriceMeteredFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BillingPriceMetered"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"priceUsageType"}},{"kind":"Field","name":{"kind":"Name","value":"recurringInterval"}},{"kind":"Field","name":{"kind":"Name","value":"stripePriceId"}},{"kind":"Field","name":{"kind":"Name","value":"tiers"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"flatAmount"}},{"kind":"Field","name":{"kind":"Name","value":"unitAmount"}},{"kind":"Field","name":{"kind":"Name","value":"upTo"}}]}}]}}]} as unknown as DocumentNode<ListPlansQuery, ListPlansQueryVariables>;export const UsageQuotaDefinitionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UsageQuotaDefinitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageQuotaDefinitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"definitions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"resourceType"}},{"kind":"Field","name":{"kind":"Name","value":"allowedOperations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"operationType"}},{"kind":"Field","name":{"kind":"Name","value":"allowedUnits"}}]}},{"kind":"Field","name":{"kind":"Name","value":"allowedSpenderTypes"}},{"kind":"Field","name":{"kind":"Name","value":"operatorOnlyScopes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"operationType"}},{"kind":"Field","name":{"kind":"Name","value":"spenderType"}},{"kind":"Field","name":{"kind":"Name","value":"unit"}},{"kind":"Field","name":{"kind":"Name","value":"periodUnit"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"isIntraWorkspaceLimitEntitled"}},{"kind":"Field","name":{"kind":"Name","value":"hasAllowancePeriod"}}]}}]}}]} as unknown as DocumentNode<UsageQuotaDefinitionsQuery, UsageQuotaDefinitionsQueryVariables>;export const UsageQuotaScopeConsumptionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"UsageQuotaScopeConsumption"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UsageQuotaScopeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"usageQuotaScopeConsumption"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"consumedValue"}},{"kind":"Field","name":{"kind":"Name","value":"periodStart"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}}]}}]}}]} as unknown as DocumentNode<UsageQuotaScopeConsumptionQuery, UsageQuotaScopeConsumptionQueryVariables>;diff --git a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsxindex bf79535aa98..3eef08a2ffc 100644--- a/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx+++ b/packages/twenty-front/src/modules/settings/billing/components/SettingsBillingCreditsSection.tsx@@ -19,7 +19,7 @@ import { useDialog } from '@/ui/layout/dialog/hooks/useDialog';import { isSubscriptionPaymentOverdue } from '@/settings/billing/utils/isSubscriptionPaymentOverdue';import { useSubscriptionStatus } from '@/workspace/hooks/useSubscriptionStatus';import { styled } from '@linaria/react';-import { t } from '@lingui/core/macro';+import { plural, t } from '@lingui/core/macro';import { DOCUMENTATION_PATHS } from 'twenty-shared/constants';import { SettingsPath } from 'twenty-shared/types';import { getSettingsPath, isDefined } from 'twenty-shared/utils';@@ -96,6 +96,11 @@ const StyledRolloverText = styled.div`min-width: 0;`;+const StyledSeatCreditsText = styled.div`+ color: ${themeCssVariables.font.color.tertiary};+ font-size: ${themeCssVariables.font.size.sm};+`;+const StyledUsageMetrics = styled.div`align-items: center;display: flex;@@ -165,12 +170,18 @@ export const SettingsBillingCreditsSection = ({workspaceCreditsGranted,workspaceCreditsTotalGranted,workspaceCreditsExtraGranted,+ workspaceCreditsGrantedForSeats,+ workspaceCreditsSeats,} = getResourceCreditUsage();const intervalLabel = getIntervalLabel(isMonthlyPlan);const packageCredits = currentResourceCreditBillingPrice?.creditAmount;const nextCreditsByPeriod = nextResourceCreditPrice?.creditAmount;- const displayedGrantedCredits = packageCredits ?? workspaceCreditsGranted;+ const hasSeatCredits = workspaceCreditsGrantedForSeats > 0;+ const displayedPackageCredits =+ packageCredits ?? workspaceCreditsGranted - workspaceCreditsGrantedForSeats;+ const displayedGrantedCredits =+ displayedPackageCredits + workspaceCreditsGrantedForSeats;const canCancelCreditPackSwitch =!isCancellationScheduled &&!shouldUpdatePayment &&@@ -205,9 +216,16 @@ export const SettingsBillingCreditsSection = ({const extraCreditsDisplay = formatNumber(workspaceCreditsExtraGranted, {decimals: 2,});- const rolloverCapDisplay = formatNumber(displayedGrantedCredits * 2, {+ const rolloverCapDisplay = formatNumber(displayedPackageCredits * 2, {decimals: 2,});+ const seatCreditsDisplay = formatNumber(workspaceCreditsGrantedForSeats, {+ decimals: 2,+ });+ const seatCreditsLabel = plural(workspaceCreditsSeats, {+ one: `Includes ${seatCreditsDisplay} credits for # seat, reset each period`,+ other: `Includes ${seatCreditsDisplay} credits for # seats, reset each period`,+ });const remainingCreditsPercentageDisplay = formatNumber(clampedRemainingCreditsPercentage,{ decimals: 0 },@@ -261,6 +279,9 @@ export const SettingsBillingCreditsSection = ({/></StyledSettingsBillingCardHeader><StyledCreditsCardBody>+ {hasSeatCredits && (+ <StyledSeatCreditsText>{seatCreditsLabel}</StyledSeatCreditsText>+ )}<ProgressBarvalue={clampedRemainingCreditsPercentage}aria-label={t`Remaining credits`}@@ -286,7 +307,9 @@ export const SettingsBillingCreditsSection = ({) : (<StyledRolloverText><IconInfoCircle size={theme.icon.size.sm} />- {t`Unused credits roll over, up to 2× your plan's credits (max ${rolloverCapDisplay}).`}+ {hasSeatCredits+ ? t`Unused credits from your credit pack roll over, up to 2× the pack (max ${rolloverCapDisplay}).`+ : t`Unused credits roll over, up to 2× your plan's credits (max ${rolloverCapDisplay}).`}</StyledRolloverText>)}<StyledUsageMetrics>diff --git a/packages/twenty-front/src/modules/settings/billing/graphql/queries/getResourceCreditUsage.ts b/packages/twenty-front/src/modules/settings/billing/graphql/queries/getResourceCreditUsage.tsindex dcc3959e462..708c07761dd 100644--- a/packages/twenty-front/src/modules/settings/billing/graphql/queries/getResourceCreditUsage.ts+++ b/packages/twenty-front/src/modules/settings/billing/graphql/queries/getResourceCreditUsage.ts@@ -6,6 +6,8 @@ export const GET_RESOURCE_CREDIT_USAGE = gql`productKeyworkspaceCreditsUsedworkspaceCreditsGranted+ workspaceCreditsGrantedForSeats+ workspaceCreditsSeatsworkspaceCreditsExtraGrantedworkspaceCreditsTotalGrantedunitPriceCentsdiff --git a/packages/twenty-front/src/testing/graphqlMocks.ts b/packages/twenty-front/src/testing/graphqlMocks.tsindex 13f91660606..ec43dda4be8 100644--- a/packages/twenty-front/src/testing/graphqlMocks.ts+++ b/packages/twenty-front/src/testing/graphqlMocks.ts@@ -554,6 +554,8 @@ export const graphqlMocks = {productKey: 'RESOURCE_CREDIT',workspaceCreditsUsed: 1000,workspaceCreditsGranted: 500000,+ workspaceCreditsGrantedForSeats: 0,+ workspaceCreditsSeats: 0,workspaceCreditsExtraGranted: 0,workspaceCreditsTotalGranted: 500000,unitPriceCents: 1,diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-50/2-50-instance-command-fast-1792410699010-add-period-max-seats-to-billing-subscription.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-50/2-50-instance-command-fast-1792410699010-add-period-max-seats-to-billing-subscription.tsnew file mode 100644index 00000000000..56cb1b72f43--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-50/2-50-instance-command-fast-1792410699010-add-period-max-seats-to-billing-subscription.ts@@ -0,0 +1,43 @@+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.50.0', 1792410699010)+export class AddPeriodMaxSeatsToBillingSubscriptionFastInstanceCommand+ implements FastInstanceCommand+{+ public async up(queryRunner: QueryRunner): Promise<void> {+ const billingSubscriptionTables = await queryRunner.query(+ `SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = 'billingSubscription'`,+ );++ if (billingSubscriptionTables.length === 0) {+ return;+ }++ await queryRunner.query(+ `ALTER TABLE "core"."billingSubscription" ADD COLUMN IF NOT EXISTS "currentPeriodMaxSeats" integer`,+ );+ await queryRunner.query(+ `ALTER TABLE "core"."billingSubscription" ADD COLUMN IF NOT EXISTS "previousPeriodMaxSeats" integer`,+ );+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ const billingSubscriptionTables = await queryRunner.query(+ `SELECT 1 FROM pg_tables WHERE schemaname = 'core' AND tablename = 'billingSubscription'`,+ );++ if (billingSubscriptionTables.length === 0) {+ return;+ }++ await queryRunner.query(+ `ALTER TABLE "core"."billingSubscription" DROP COLUMN IF EXISTS "previousPeriodMaxSeats"`,+ );+ await queryRunner.query(+ `ALTER TABLE "core"."billingSubscription" DROP COLUMN IF EXISTS "currentPeriodMaxSeats"`,+ );+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.tsindex 1ddff90d26f..72eeed1f72b 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@@ -248,6 +248,7 @@ import { AddUserCreditsFallbackToBillingCustomerFastInstanceCommand } from 'src/import { AddConnectionProviderScopeFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-49/2-49-instance-command-fast-1792162723868-add-connection-provider-scope';import { AddConnectedAccountScopeFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-49/2-49-instance-command-fast-1792170228100-add-connected-account-scope';import { AddExcludePrivateEventsToCalendarChannelFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-49/2-49-instance-command-fast-1792319637000-add-exclude-private-events-to-calendar-channel';+import { AddPeriodMaxSeatsToBillingSubscriptionFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-50/2-50-instance-command-fast-1792410699010-add-period-max-seats-to-billing-subscription';export const INSTANCE_COMMANDS = [AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,@@ -498,4 +499,5 @@ export const INSTANCE_COMMANDS = [AddConnectionProviderScopeFastInstanceCommand,AddConnectedAccountScopeFastInstanceCommand,AddExcludePrivateEventsToCalendarChannelFastInstanceCommand,+ AddPeriodMaxSeatsToBillingSubscriptionFastInstanceCommand,];diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.tsindex bf0623f7218..586b09584e5 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-invoice.service.ts@@ -123,27 +123,28 @@ export class BillingWebhookInvoiceService {return;}+ const boundary = resolveBillingTransitionBoundary({+ invoiceCreatedAt,+ subscriptionCurrentPeriodStart: subscription.currentPeriodStart,+ subscriptionCurrentPeriodEnd: subscription.currentPeriodEnd,+ });+const params =- await this.resourceCreditService.getResourceCreditRolloverParameters(- subscription.workspaceId,- subscription.id,- );+ await this.resourceCreditService.getResourceCreditRolloverParameters({+ workspaceId: subscription.workspaceId,+ subscriptionId: subscription.id,+ boundary,+ });// Skipping the transition forfeits the unspent part of every grant of this workspaceif (!isDefined(params)) {this.logger.error(- `Skipping credit rollover for workspace ${subscription.workspaceId}: subscription ${subscription.id} carries no priced resource credit item`,+ `Skipping credit rollover for workspace ${subscription.workspaceId}: subscription ${subscription.id} gives no workspace credits from a credit pack or seats`,);return;}- const boundary = resolveBillingTransitionBoundary({- invoiceCreatedAt,- subscriptionCurrentPeriodStart: subscription.currentPeriodStart,- subscriptionCurrentPeriodEnd: subscription.currentPeriodEnd,- });-// Only needed while subscriptions predating previousPeriodStart transition for the first timeconst ledgerPeriodStart =await this.billingCreditGrantService.findPeriodStartBefore({@@ -169,15 +170,18 @@ export class BillingWebhookInvoiceService {// Trial credits carry into the first paid period; the trial allowance comes from config, not the priceconst closingAllowanceMicro = isFirstPeriodAfterTrial? this.billingUsageService.getTrialResourceUsageCap(subscription)- : params.tierQuantity;+ : params.workspaceCreditsForPackMicro;await this.billingCreditRolloverService.processRolloverOnPeriodTransition({workspaceId: subscription.workspaceId,closingPeriodStart,closingPeriodEnd,closingAllowanceMicro,+ closingSeatAllowanceMicro: isFirstPeriodAfterTrial+ ? 0+ : params.workspaceCreditsForSeatsMicro,nextPeriodStart,- nextAllowanceMicro: params.tierQuantity,+ nextAllowanceMicro: params.workspaceCreditsForPackMicro,});}diff --git a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.tsindex 0df578e0195..f8ba1d0abd5 100644--- a/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing-webhook/services/billing-webhook-subscription.service.ts@@ -167,7 +167,12 @@ export class BillingWebhookSubscriptionService {id: true,currentPeriodStart: true,currentPeriodEnd: true,+ currentPeriodMaxSeats: true,},+ relations: [+ 'billingSubscriptionItems',+ 'billingSubscriptionItems.billingProduct',+ ],},);@@ -200,6 +205,7 @@ export class BillingWebhookSubscriptionService {await this.updateBillingSubscriptionItems(updatedBillingSubscription.id,event,+ subscriptionWithSchedule,workspaceId,);@@ -319,6 +325,7 @@ export class BillingWebhookSubscriptionService {| Stripe.CustomerSubscriptionUpdatedEvent| Stripe.CustomerSubscriptionCreatedEvent| Stripe.CustomerSubscriptionDeletedEvent,+ liveSubscription: SubscriptionWithSchedule,workspaceId: string,) {const deletedSubscriptionItemIds =@@ -334,7 +341,7 @@ export class BillingWebhookSubscriptionService {await this.billingSubscriptionItemRepository.upsert(transformStripeSubscriptionEventToDatabaseSubscriptionItem(subscriptionId,- event.data,+ { object: liveSubscription },workspaceId,),{diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.tsindex ad08c118551..8473b49151e 100644--- a/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.resolver.ts@@ -532,6 +532,9 @@ export class BillingResolver {workspaceCreditsUsed: toDisplayCredits(item.workspaceCreditsUsed),userCreditsUsed: toDisplayCredits(item.userCreditsUsed),workspaceCreditsGranted: toDisplayCredits(item.workspaceCreditsGranted),+ workspaceCreditsGrantedForSeats: toDisplayCredits(+ item.workspaceCreditsGrantedForSeats,+ ),workspaceCreditsExtraGranted: toDisplayCredits(item.workspaceCreditsExtraGranted,),diff --git a/packages/twenty-server/src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto.ts b/packages/twenty-server/src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto.tsindex e1ffbf67ef8..60fe00796ce 100644--- a/packages/twenty-server/src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto.ts@@ -1,4 +1,4 @@-import { Field, Float, ObjectType } from '@nestjs/graphql';+import { Field, Float, Int, ObjectType } from '@nestjs/graphql';import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';@@ -22,6 +22,12 @@ export class BillingResourceCreditUsageDTO {@Field(() => Float)workspaceCreditsGranted: number;+ @Field(() => Float)+ workspaceCreditsGrantedForSeats: number;++ @Field(() => Int)+ workspaceCreditsSeats: number;+@Field(() => Float)workspaceCreditsExtraGranted: number;diff --git a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.tsindex a302caf70a0..e494d11bc3d 100644--- a/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/entities/billing-subscription.entity.ts@@ -139,6 +139,12 @@ export class BillingSubscriptionEntity extends WorkspaceRelatedEntity {@Column({ nullable: true, type: 'timestamptz' })previousPeriodStart: Date | null;+ @Column({ nullable: true, type: 'integer' })+ currentPeriodMaxSeats: number | null;++ @Column({ nullable: true, type: 'integer' })+ previousPeriodMaxSeats: number | null;+@Field(() => graphqlTypeJson)@Column({ nullable: false, type: 'jsonb', default: {} })metadata: Stripe.Metadata;diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.tsindex e331c799c49..02bf902ac4f 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-credit-rollover.service.ts@@ -25,6 +25,7 @@ type ProcessRolloverParams = {closingPeriodStart: Date;closingPeriodEnd: Date;closingAllowanceMicro: number;+ closingSeatAllowanceMicro: number;nextPeriodStart: Date;nextAllowanceMicro: number;};@@ -100,6 +101,7 @@ export class BillingCreditRolloverService {closingPeriodStart,closingPeriodEnd,closingAllowanceMicro,+ closingSeatAllowanceMicro,nextPeriodStart,usageMicro,rolloverCapMicro,@@ -120,6 +122,7 @@ export class BillingCreditRolloverService {const carryForwardGrants = computeCarryForwardGrants({allowanceMicro: closingAllowanceMicro,+ seatAllowanceMicro: closingSeatAllowanceMicro,liveGrants: closingGrants.map((grant) => ({grantId: grant.id,type: grant.type,diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.tsindex a342eae31b0..2d1beca99f8 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts@@ -363,7 +363,12 @@ export class BillingSubscriptionService {id: true,currentPeriodStart: true,currentPeriodEnd: true,+ currentPeriodMaxSeats: true,},+ relations: [+ 'billingSubscriptionItems',+ 'billingSubscriptionItems.billingProduct',+ ],},);diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-usage.service.tsindex ea38206e493..c5af7005ea3 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@@ -15,14 +15,15 @@ import {import { NO_BILLING_SUBSCRIPTION } from 'src/engine/core-modules/billing/constants/no-billing-subscription.constant';import { type BillingResourceCreditUsageDTO } from 'src/engine/core-modules/billing/dtos/billing-resource-credit-usage.dto';import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';-import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';import { SubscriptionStatus } from 'src/engine/core-modules/billing/enums/billing-subscription-status.enum';import { BillingCreditGrantService } from 'src/engine/core-modules/billing/services/billing-credit-grant.service';import { BillingSubscriptionItemService } from 'src/engine/core-modules/billing/services/billing-subscription-item.service';import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';import { type CurrentBillingSubscription } from 'src/engine/core-modules/billing/types/flat-billing-subscription.type';import { type SubscriptionInactiveReason } from 'src/engine/core-modules/billing/types/subscription-inactive-reason.type';+import { computePlanWorkspaceCreditsMicro } from 'src/engine/core-modules/billing/utils/compute-plan-workspace-credits-micro.util';import { getBillingSubscriptionPeriod } from 'src/engine/core-modules/billing/utils/get-billing-subscription-period.util';+import { getCurrentPeriodMaxSeats } from 'src/engine/core-modules/billing/utils/get-current-period-max-seats.util';import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';@@ -137,10 +138,19 @@ export class BillingUsageService {this.billingCreditGrantService.getActiveCreditsMicro(workspaceId),]);+ const workspaceCreditsSeats = getCurrentPeriodMaxSeats(subscription);++ const workspaceCreditsGrantedForSeats =+ computePlanWorkspaceCreditsMicro({+ billingSubscriptionItems: subscription.billingSubscriptionItems,+ interval: subscription.interval,+ seats: workspaceCreditsSeats,+ })?.workspaceCreditsForSeatsMicro ?? 0;+const workspaceCreditsGranted =subscription.status === SubscriptionStatus.Trialing? item.freeTrialQuantity- : item.creditAmount;+ : item.creditAmount + workspaceCreditsGrantedForSeats;return {productKey: item.productKey,@@ -149,6 +159,8 @@ export class BillingUsageService {workspaceCreditsUsed: creditsUsed.workspaceCreditsUsedMicro,userCreditsUsed: creditsUsed.userCreditsUsedMicro,workspaceCreditsGranted,+ workspaceCreditsGrantedForSeats,+ workspaceCreditsSeats,workspaceCreditsExtraGranted,workspaceCreditsTotalGranted:workspaceCreditsGranted + workspaceCreditsExtraGranted,@@ -169,22 +181,20 @@ export class BillingUsageService {return this.getTrialResourceUsageCap(subscription);}- const resourceCreditItem = subscription.billingSubscriptionItems.find(- (item) =>- item.billingProduct.metadata?.productKey ===- BillingProductKey.RESOURCE_CREDIT,- );-- const resourceCreditPrice =- resourceCreditItem?.billingProduct.billingPrices.find(- (price) => price.stripePriceId === resourceCreditItem.stripePriceId,- );+ const planWorkspaceCredits = computePlanWorkspaceCreditsMicro({+ billingSubscriptionItems: subscription.billingSubscriptionItems,+ interval: subscription.interval,+ seats: getCurrentPeriodMaxSeats(subscription),+ });- if (!isDefined(resourceCreditPrice)) {+ if (!isDefined(planWorkspaceCredits)) {return null;}- return Number(resourceCreditPrice.metadata?.credit_amount ?? 0);+ return (+ planWorkspaceCredits.workspaceCreditsForPackMicro ++ planWorkspaceCredits.workspaceCreditsForSeatsMicro+ );}// By event timestamp: at a transition currentPeriodStart has moved on, so periodStart would read the new perioddiff --git a/packages/twenty-server/src/engine/core-modules/billing/services/resource-credit.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/resource-credit.service.tsindex cbb674113cc..d6a182609ee 100644--- a/packages/twenty-server/src/engine/core-modules/billing/services/resource-credit.service.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/services/resource-credit.service.ts@@ -5,13 +5,13 @@ import { Injectable, Logger } from '@nestjs/common';import { isDefined } from 'twenty-shared/utils';import { BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';-import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import {+ computePlanWorkspaceCreditsMicro,+ type PlanWorkspaceCreditsMicro,+} from 'src/engine/core-modules/billing/utils/compute-plan-workspace-credits-micro.util';+import { getCurrentPeriodMaxSeats } from 'src/engine/core-modules/billing/utils/get-current-period-max-seats.util';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';-export type ResourceCreditPricingInfo = {- tierCap: number;- unitPriceCents: number;-};@Injectable()export class ResourceCreditService {@@ -22,44 +22,15 @@ export class ResourceCreditService {private readonly billingSubscriptionRepository: WorkspaceScopedRepository<BillingSubscriptionEntity>,) {}- extractResourceCreditPricingInfo(- subscription: BillingSubscriptionEntity,- ): ResourceCreditPricingInfo | null {- const resourceCreditItem = subscription.billingSubscriptionItems?.find(- (item) =>- item.billingProduct?.metadata?.productKey ===- BillingProductKey.RESOURCE_CREDIT,- );-- if (!isDefined(resourceCreditItem)) {- return null;- }-- const matchingPrice =- resourceCreditItem.billingProduct?.billingPrices?.find(- (price) => price.stripePriceId === resourceCreditItem.stripePriceId,- );-- if (!isDefined(matchingPrice)) {- return null;- }-- const tierCap = Number(matchingPrice.metadata?.credit_amount ?? 0);-- if (!Number.isFinite(tierCap) || tierCap <= 0) {- return null;- }-- return {- tierCap,- unitPriceCents: matchingPrice.unitAmount ?? 0,- };- }-- async getResourceCreditRolloverParameters(- workspaceId: string,- subscriptionId: string,- ): Promise<{ tierQuantity: number } | null> {+ async getResourceCreditRolloverParameters({+ workspaceId,+ subscriptionId,+ boundary,+ }: {+ workspaceId: string;+ subscriptionId: string;+ boundary: Date;+ }): Promise<PlanWorkspaceCreditsMicro | null> {const subscription = await this.billingSubscriptionRepository.findOne(workspaceId,{@@ -76,12 +47,26 @@ export class ResourceCreditService {return null;}- const pricingInfo = this.extractResourceCreditPricingInfo(subscription);-- if (!isDefined(pricingInfo)) {+ const closingPeriodMaxSeats =+ subscription.currentPeriodStart.getTime() === boundary.getTime()+ ? (subscription.previousPeriodMaxSeats ?? 0)+ : getCurrentPeriodMaxSeats(subscription);++ const planWorkspaceCredits = computePlanWorkspaceCreditsMicro({+ billingSubscriptionItems: subscription.billingSubscriptionItems,+ interval: subscription.interval,+ seats: closingPeriodMaxSeats,+ });++ if (+ !isDefined(planWorkspaceCredits) ||+ planWorkspaceCredits.workspaceCreditsForPackMicro ++ planWorkspaceCredits.workspaceCreditsForSeatsMicro <=+ 0+ ) {return null;}- return { tierQuantity: pricingInfo.tierCap };+ return planWorkspaceCredits;}}diff --git a/packages/twenty-server/src/engine/core-modules/billing/types/billing-product-metadata.type.ts b/packages/twenty-server/src/engine/core-modules/billing/types/billing-product-metadata.type.tsindex 1fa60dedf5d..72de78c9815 100644--- a/packages/twenty-server/src/engine/core-modules/billing/types/billing-product-metadata.type.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/types/billing-product-metadata.type.ts@@ -21,5 +21,7 @@ export class BillingProductMetadata {@Field(() => String, { nullable: true })isLegacy?: string;+ workspaceCreditsPerSeat?: string;+[key: string]: string | undefined;}diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.tsindex db92469989d..f24fbd21062 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-carry-forward-grants.util.spec.ts@@ -69,6 +69,89 @@ describe('computeCarryForwardGrants', () => {});});+ describe('seat allowance', () => {+ const SEAT_ALLOWANCE = 400_000;++ it('spends seat credits first and rolls the whole pack over', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: ALLOWANCE,+ seatAllowanceMicro: SEAT_ALLOWANCE,+ liveGrants: [],+ usageMicro: 300_000,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.ROLLOVER,+ amountMicro: ALLOWANCE,+ sourceGrantId: null,+ expiresAt: null,+ },+ ]);+ });++ it('takes usage beyond the seat credits from the pack', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: ALLOWANCE,+ seatAllowanceMicro: SEAT_ALLOWANCE,+ liveGrants: [],+ usageMicro: 700_000,+ rolloverCapMicro: ROLLOVER_CAP,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.ROLLOVER,+ amountMicro: 700_000,+ sourceGrantId: null,+ expiresAt: null,+ },+ ]);+ });++ it('never carries unspent seat credits over', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ seatAllowanceMicro: SEAT_ALLOWANCE,+ liveGrants: [],+ usageMicro: 0,+ rolloverCapMicro: 0,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([]);+ });++ it('keeps a purchase next to a free pack', () => {+ const result = computeCarryForwardGrants({+ allowanceMicro: 0,+ seatAllowanceMicro: SEAT_ALLOWANCE,+ liveGrants: [+ grant({+ grantId: 'purchase_1',+ type: BillingCreditGrantType.PURCHASE,+ amountMicro: 200_000,+ }),+ ],+ usageMicro: 500_000,+ rolloverCapMicro: 0,+ boundary: BOUNDARY,+ });++ expect(result).toEqual([+ {+ type: BillingCreditGrantType.PURCHASE,+ amountMicro: 100_000,+ sourceGrantId: 'purchase_1',+ expiresAt: null,+ },+ ]);+ });+ });+describe('rollover cap', () => {it('clamps the rolled-over amount to the cap', () => {const result = computeCarryForwardGrants({diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-plan-workspace-credits-micro.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-plan-workspace-credits-micro.util.spec.tsnew file mode 100644index 00000000000..36d7631e3f9--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/compute-plan-workspace-credits-micro.util.spec.ts@@ -0,0 +1,119 @@+/* @license Enterprise */++import { type BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';+import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';+import { computePlanWorkspaceCreditsMicro } from 'src/engine/core-modules/billing/utils/compute-plan-workspace-credits-micro.util';++const buildBaseItem = (workspaceCreditsPerSeat?: string) =>+ ({+ stripePriceId: 'price_base',+ billingProduct: {+ metadata: {+ productKey: BillingProductKey.BASE_PRODUCT,+ workspaceCreditsPerSeat,+ },+ },+ }) as BillingSubscriptionItemEntity;++const buildPackItem = (creditAmount: string) =>+ ({+ stripePriceId: 'price_pack',+ billingProduct: {+ metadata: { productKey: BillingProductKey.RESOURCE_CREDIT },+ billingPrices: [+ { stripePriceId: 'price_other_pack', metadata: { credit_amount: '1' } },+ {+ stripePriceId: 'price_pack',+ metadata: { credit_amount: creditAmount },+ },+ ],+ },+ }) as BillingSubscriptionItemEntity;++describe('computePlanWorkspaceCreditsMicro', () => {+ it('only counts the pack when the plan gives no credits per seat', () => {+ expect(+ computePlanWorkspaceCreditsMicro({+ billingSubscriptionItems: [buildBaseItem(), buildPackItem('50')],+ interval: SubscriptionInterval.Month,+ seats: 5,+ }),+ ).toEqual({+ workspaceCreditsForSeatsMicro: 0,+ workspaceCreditsForPackMicro: 50,+ });+ });++ it('adds the credits of every seat to the pack', () => {+ expect(+ computePlanWorkspaceCreditsMicro({+ billingSubscriptionItems: [buildBaseItem('4'), buildPackItem('50')],+ interval: SubscriptionInterval.Month,+ seats: 5,+ }),+ ).toEqual({+ workspaceCreditsForSeatsMicro: 20,+ workspaceCreditsForPackMicro: 50,+ });+ });++ it('gives twelve months of seat credits on a yearly plan', () => {+ expect(+ computePlanWorkspaceCreditsMicro({+ billingSubscriptionItems: [buildBaseItem('4'), buildPackItem('600')],+ interval: SubscriptionInterval.Year,+ seats: 5,+ }),+ ).toEqual({+ workspaceCreditsForSeatsMicro: 240,+ workspaceCreditsForPackMicro: 600,+ });+ });++ it('gives seat credits next to a free pack', () => {+ expect(+ computePlanWorkspaceCreditsMicro({+ billingSubscriptionItems: [buildBaseItem('4'), buildPackItem('0')],+ interval: SubscriptionInterval.Month,+ seats: 5,+ }),+ ).toEqual({+ workspaceCreditsForSeatsMicro: 20,+ workspaceCreditsForPackMicro: 0,+ });+ });++ it('gives seat credits without any pack', () => {+ expect(+ computePlanWorkspaceCreditsMicro({+ billingSubscriptionItems: [buildBaseItem('4')],+ interval: SubscriptionInterval.Month,+ seats: 5,+ }),+ ).toEqual({+ workspaceCreditsForSeatsMicro: 20,+ workspaceCreditsForPackMicro: 0,+ });+ });++ it('returns null when neither the pack nor the seats give credits', () => {+ expect(+ computePlanWorkspaceCreditsMicro({+ billingSubscriptionItems: [buildBaseItem()],+ interval: SubscriptionInterval.Month,+ seats: 5,+ }),+ ).toBeNull();+ });++ it('ignores a per-seat amount that is not a positive number', () => {+ expect(+ computePlanWorkspaceCreditsMicro({+ billingSubscriptionItems: [buildBaseItem('lots'), buildPackItem('50')],+ interval: SubscriptionInterval.Month,+ seats: 5,+ }),+ ).toMatchObject({ workspaceCreditsForSeatsMicro: 0 });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.tsindex 98432cb9ddf..53103437e8d 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/__tests__/resolve-billing-period-boundary-update.util.spec.ts@@ -1,34 +1,86 @@/* @license Enterprise */+import { type BillingSubscriptionItemEntity } from 'src/engine/core-modules/billing/entities/billing-subscription-item.entity';+import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';import { resolveBillingPeriodBoundaryUpdate } from 'src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util';const JANUARY = new Date('2026-01-01T00:00:00.000Z');const FEBRUARY = new Date('2026-02-01T00:00:00.000Z');const MARCH = new Date('2026-03-01T00:00:00.000Z');+const buildStoredSubscription = ({+ currentPeriodStart,+ currentPeriodEnd,+ currentPeriodMaxSeats,+ seats,+}: {+ currentPeriodStart: Date;+ currentPeriodEnd: Date;+ currentPeriodMaxSeats: number | null;+ seats: number;+}) => ({+ currentPeriodStart,+ currentPeriodEnd,+ currentPeriodMaxSeats,+ billingSubscriptionItems: [+ {+ quantity: seats,+ billingProduct: {+ metadata: { productKey: BillingProductKey.BASE_PRODUCT },+ },+ } as BillingSubscriptionItemEntity,+ ],+});+describe('resolveBillingPeriodBoundaryUpdate', () => {- it('records the period the subscription just moved off', () => {+ it('records the period the subscription just moved off with its max seats', () => {expect(resolveBillingPeriodBoundaryUpdate({incomingPeriodStart: FEBRUARY,- storedSubscription: {+ storedSubscription: buildStoredSubscription({currentPeriodStart: JANUARY,currentPeriodEnd: FEBRUARY,- },+ currentPeriodMaxSeats: 8,+ seats: 6,+ }),}),- ).toEqual({ previousPeriodStart: JANUARY });+ ).toEqual({+ previousPeriodStart: JANUARY,+ previousPeriodMaxSeats: 8,+ currentPeriodMaxSeats: null,+ });});- it('leaves the boundary alone when the period has not moved', () => {+ it('keeps the seats held at the end of the period when no max seats were recorded', () => {expect(resolveBillingPeriodBoundaryUpdate({incomingPeriodStart: FEBRUARY,- storedSubscription: {+ storedSubscription: buildStoredSubscription({+ currentPeriodStart: JANUARY,+ currentPeriodEnd: FEBRUARY,+ currentPeriodMaxSeats: null,+ seats: 6,+ }),+ }),+ ).toEqual({+ previousPeriodStart: JANUARY,+ previousPeriodMaxSeats: 6,+ currentPeriodMaxSeats: null,+ });+ });++ it('raises the max seats to the seats about to be replaced when the period has not moved', () => {+ expect(+ resolveBillingPeriodBoundaryUpdate({+ incomingPeriodStart: FEBRUARY,+ storedSubscription: buildStoredSubscription({currentPeriodStart: FEBRUARY,currentPeriodEnd: MARCH,- },+ currentPeriodMaxSeats: 5,+ seats: 8,+ }),}),- ).toEqual({});+ ).toEqual({ currentPeriodMaxSeats: 8 });});// Out-of-order events must not rewind the window the rollover settles against@@ -36,12 +88,18 @@ describe('resolveBillingPeriodBoundaryUpdate', () => {expect(resolveBillingPeriodBoundaryUpdate({incomingPeriodStart: JANUARY,- storedSubscription: {+ storedSubscription: buildStoredSubscription({currentPeriodStart: FEBRUARY,currentPeriodEnd: MARCH,- },+ currentPeriodMaxSeats: 8,+ seats: 6,+ }),}),- ).toEqual({ currentPeriodStart: FEBRUARY, currentPeriodEnd: MARCH });+ ).toEqual({+ currentPeriodStart: FEBRUARY,+ currentPeriodEnd: MARCH,+ currentPeriodMaxSeats: 8,+ });});it('has nothing to record for a subscription seen for the first time', () => {@@ -57,10 +115,12 @@ describe('resolveBillingPeriodBoundaryUpdate', () => {expect(resolveBillingPeriodBoundaryUpdate({incomingPeriodStart: undefined,- storedSubscription: {+ storedSubscription: buildStoredSubscription({currentPeriodStart: JANUARY,currentPeriodEnd: FEBRUARY,- },+ currentPeriodMaxSeats: 8,+ seats: 6,+ }),}),).toEqual({});});diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.tsindex bd5ac8cdd72..497e4385641 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-carry-forward-grants.util.ts@@ -84,12 +84,14 @@ const compareSpendingOrder = (a: CreditBucket, b: CreditBucket): number => {export const computeCarryForwardGrants = ({allowanceMicro,+ seatAllowanceMicro = 0,liveGrants,usageMicro,rolloverCapMicro,boundary,}: {allowanceMicro: number;+ seatAllowanceMicro?: number;liveGrants: CarryForwardGrantInput[];usageMicro: number;rolloverCapMicro: number;@@ -108,7 +110,7 @@ export const computeCarryForwardGrants = ({...liveGrants.filter((grant) => grant.amountMicro > 0),].sort(compareSpendingOrder);- let remainingUsageMicro = Math.max(0, usageMicro);+ let remainingUsageMicro = Math.max(0, usageMicro - seatAllowanceMicro);const unspentBuckets = buckets.map((bucket) => {const consumedMicro = Math.min(bucket.amountMicro, remainingUsageMicro);diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/compute-plan-workspace-credits-micro.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-plan-workspace-credits-micro.util.tsnew file mode 100644index 00000000000..e49a0001668--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/compute-plan-workspace-credits-micro.util.ts@@ -0,0 +1,58 @@+/* @license Enterprise */++import { isDefined } from 'twenty-shared/utils';++import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';+import { BillingProductKey } from 'src/engine/core-modules/billing/enums/billing-product-key.enum';+import { SubscriptionInterval } from 'src/engine/core-modules/billing/enums/billing-subscription-interval.enum';+import { isBaseProductSubscriptionItem } from 'src/engine/core-modules/billing/utils/is-base-product-subscription-item.util';++export type PlanWorkspaceCreditsMicro = {+ workspaceCreditsForSeatsMicro: number;+ workspaceCreditsForPackMicro: number;+};++const toPositiveAmount = (value: string | undefined): number => {+ const amount = Number(value ?? 0);++ return Number.isFinite(amount) && amount > 0 ? amount : 0;+};++export const computePlanWorkspaceCreditsMicro = ({+ billingSubscriptionItems,+ interval,+ seats,+}: Pick<BillingSubscriptionEntity, 'billingSubscriptionItems' | 'interval'> & {+ seats: number;+}): PlanWorkspaceCreditsMicro | null => {+ const baseProductItem = billingSubscriptionItems.find(+ isBaseProductSubscriptionItem,+ );+ const resourceCreditItem = billingSubscriptionItems.find(+ ({ billingProduct }) =>+ billingProduct?.metadata?.productKey ===+ BillingProductKey.RESOURCE_CREDIT,+ );+ const resourceCreditPrice =+ resourceCreditItem?.billingProduct?.billingPrices?.find(+ ({ stripePriceId }) => stripePriceId === resourceCreditItem.stripePriceId,+ );++ const workspaceCreditsForSeatsMicro =+ toPositiveAmount(+ baseProductItem?.billingProduct?.metadata?.workspaceCreditsPerSeat,+ ) *+ seats *+ (interval === SubscriptionInterval.Year ? 12 : 1);++ if (!isDefined(resourceCreditPrice) && workspaceCreditsForSeatsMicro === 0) {+ return null;+ }++ return {+ workspaceCreditsForSeatsMicro,+ workspaceCreditsForPackMicro: toPositiveAmount(+ resourceCreditPrice?.metadata?.credit_amount,+ ),+ };+};diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/get-current-period-max-seats.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/get-current-period-max-seats.util.tsnew file mode 100644index 00000000000..c5db926bf4e--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/get-current-period-max-seats.util.ts@@ -0,0 +1,16 @@+/* @license Enterprise */++import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';+import { isBaseProductSubscriptionItem } from 'src/engine/core-modules/billing/utils/is-base-product-subscription-item.util';++export const getCurrentPeriodMaxSeats = ({+ currentPeriodMaxSeats,+ billingSubscriptionItems,+}: Pick<+ BillingSubscriptionEntity,+ 'currentPeriodMaxSeats' | 'billingSubscriptionItems'+>): number =>+ Math.max(+ currentPeriodMaxSeats ?? 0,+ billingSubscriptionItems.find(isBaseProductSubscriptionItem)?.quantity ?? 0,+ );diff --git a/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.ts b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.tsindex bfbf89991b3..6742c731f28 100644--- a/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.ts+++ b/packages/twenty-server/src/engine/core-modules/billing/utils/resolve-billing-period-boundary-update.util.ts@@ -2,15 +2,23 @@import { isDefined } from 'twenty-shared/utils';-type StoredBillingPeriod = {- currentPeriodStart: Date;- currentPeriodEnd: Date;-};+import { type BillingSubscriptionEntity } from 'src/engine/core-modules/billing/entities/billing-subscription.entity';+import { getCurrentPeriodMaxSeats } from 'src/engine/core-modules/billing/utils/get-current-period-max-seats.util';++type StoredBillingPeriod = Pick<+ BillingSubscriptionEntity,+ | 'currentPeriodStart'+ | 'currentPeriodEnd'+ | 'currentPeriodMaxSeats'+ | 'billingSubscriptionItems'+>;type BillingPeriodBoundaryUpdate = {previousPeriodStart?: Date;currentPeriodStart?: Date;currentPeriodEnd?: Date;+ previousPeriodMaxSeats?: number;+ currentPeriodMaxSeats?: number | null;};// Stripe only reports the current window, so the boundary a period moves off must be captured here or is lost;@@ -27,15 +35,20 @@ export const resolveBillingPeriodBoundaryUpdate = ({}const { currentPeriodStart, currentPeriodEnd } = storedSubscription;+ const currentPeriodMaxSeats = getCurrentPeriodMaxSeats(storedSubscription);if (incomingPeriodStart.getTime() > currentPeriodStart.getTime()) {- return { previousPeriodStart: currentPeriodStart };+ return {+ previousPeriodStart: currentPeriodStart,+ previousPeriodMaxSeats: currentPeriodMaxSeats,+ currentPeriodMaxSeats: null,+ };}// Stripe never moves a period backwards, so an older window is a late event and must not rewind the boundary.if (incomingPeriodStart.getTime() < currentPeriodStart.getTime()) {- return { currentPeriodStart, currentPeriodEnd };+ return { currentPeriodStart, currentPeriodEnd, currentPeriodMaxSeats };}- return {};+ return { currentPeriodMaxSeats };};