Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(billing): refresh limit alerts from current billing state (#85993)

Pawel Cebulad4d568563645
diff --git a/frontend/jest.setup.ts b/frontend/jest.setup.ts
index 1e3b26afc57d..67fac599af13 100644
--- a/frontend/jest.setup.ts
+++ b/frontend/jest.setup.ts
@@ -184,7 +184,9 @@ jest.mock('posthog-js', () => {
get_session_id: jest.fn(),
get_session_replay_url: jest.fn(),
get_distinct_id: jest.fn(),
+ get_property: jest.fn(),
register: jest.fn(),
+ unregister: jest.fn(),
reset: jest.fn(),
group: jest.fn(),
updateEarlyAccessFeatureEnrollment: jest.fn(),
diff --git a/frontend/src/layout/navigation/projectNoticeLogic.test.tsx b/frontend/src/layout/navigation/projectNoticeLogic.test.tsx
index e282f01587ef..913c543e3176 100644
--- a/frontend/src/layout/navigation/projectNoticeLogic.test.tsx
+++ b/frontend/src/layout/navigation/projectNoticeLogic.test.tsx
@@ -8,9 +8,12 @@ import { expectLogic } from 'kea-test-utils'
import { reverseProxyCheckerLogic } from 'lib/components/ReverseProxyChecker/reverseProxyCheckerLogic'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { verifyEmailLogic } from 'scenes/authentication/verify-email/verifyEmailLogic'
+import { billingLogic } from 'scenes/billing/billingLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
+import { ProductKey } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { AppContext } from '~/types'
@@ -346,4 +349,35 @@ describe('projectNoticeLogic', () => {
logic.unmount()
})
})
+
+ describe('billing alert CTA navigation', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ it('links single-product billing alerts to that product from the billing root', () => {
+ router.actions.push(urls.organizationBilling())
+ billingLogic.mount()
+ const logic = projectNoticeLogic()
+ logic.mount()
+
+ billingLogic.actions.setBillingAlert({
+ status: 'error',
+ title: 'Usage limit reached',
+ message: 'You have reached the usage limit for Product analytics.',
+ productKey: ProductKey.PRODUCT_ANALYTICS,
+ })
+
+ expect(logic.values.projectNoticeVariant).toBe('billing_alert')
+ expect(logic.values.projectNotice?.action).toEqual(
+ expect.objectContaining({
+ to: urls.organizationBilling([ProductKey.PRODUCT_ANALYTICS]),
+ children: 'Manage billing',
+ })
+ )
+
+ logic.unmount()
+ billingLogic.unmount()
+ })
+ })
})
diff --git a/frontend/src/layout/navigation/projectNoticeLogic.tsx b/frontend/src/layout/navigation/projectNoticeLogic.tsx
index cc31d6e51bab..f78c584e3ab2 100644
--- a/frontend/src/layout/navigation/projectNoticeLogic.tsx
+++ b/frontend/src/layout/navigation/projectNoticeLogic.tsx
@@ -126,29 +126,46 @@ function shouldFetchProxyRecords(user: UserType | null, currentOrganizationId: s
return !!user && !!currentOrganizationId && new Date().getDate() <= 7 && !isNoticeDismissed('missing_reverse_proxy')
}
+function buildBillingAlertAction(
+ billingAlert: BillingAlertConfig,
+ canAccessBilling: boolean
+): LemonBannerProps['action'] | undefined {
+ if (billingAlert.action) {
+ return billingAlert.action
+ }
+
+ if (billingAlert.contactSupport) {
+ return {
+ to: 'mailto:[email protected]',
+ children: billingAlert.buttonCTA || 'Contact support',
+ onClick: () => billingLogic.actions.reportBillingAlertActionClicked(billingAlert),
+ }
+ }
+
+ if (!canAccessBilling) {
+ return undefined
+ }
+
+ return {
+ to: getBillingAlertBillingUrl(billingAlert),
+ children: 'Manage billing',
+ onClick: () => billingLogic.actions.reportBillingAlertActionClicked(billingAlert),
+ }
+}
+
+function getBillingAlertBillingUrl(billingAlert: BillingAlertConfig): string {
+ return urls.organizationBilling(billingAlert.productKey ? [billingAlert.productKey] : undefined)
+}
+
function buildBillingAlertNotice(
billingAlert: BillingAlertConfig,
canAccessBilling: boolean,
- currentPathname: string
+ currentLocation: { pathname: string; search: string }
): ProjectNoticeBlueprint {
+ const currentUrl = `${currentLocation.pathname}${currentLocation.search}`
const showButton =
- billingAlert.action || billingAlert.contactSupport || currentPathname !== urls.organizationBilling()
-
- const action = billingAlert.action
- ? billingAlert.action
- : billingAlert.contactSupport
- ? {
- to: 'mailto:[email protected]',
- children: billingAlert.buttonCTA || 'Contact support',
- onClick: () => billingLogic.actions.reportBillingAlertActionClicked(billingAlert),
- }
- : canAccessBilling
- ? {
- to: urls.organizationBilling(),
- children: 'Manage billing',
- onClick: () => billingLogic.actions.reportBillingAlertActionClicked(billingAlert),
- }
- : undefined
+ billingAlert.action || billingAlert.contactSupport || currentUrl !== getBillingAlertBillingUrl(billingAlert)
+ const action = buildBillingAlertAction(billingAlert, canAccessBilling)
return {
message: (
@@ -514,11 +531,7 @@ export const projectNoticeLogic = kea<projectNoticeLogicType>([
if (!effectiveBillingAlert) {
return null
}
- const notice = buildBillingAlertNotice(
- effectiveBillingAlert,
- canAccessBilling,
- currentLocation.pathname
- )
+ const notice = buildBillingAlertNotice(effectiveBillingAlert, canAccessBilling, currentLocation)
const canClose = dismiss || notice.onClose
return {
...notice,
diff --git a/frontend/src/scenes/billing/billing-utils.spec.ts b/frontend/src/scenes/billing/billing-utils.spec.ts
index 78b1cc7e83cb..b7816b9afdef 100644
--- a/frontend/src/scenes/billing/billing-utils.spec.ts
+++ b/frontend/src/scenes/billing/billing-utils.spec.ts
@@ -9,7 +9,7 @@ import billingJsonWithFlatFee from '~/mocks/fixtures/_billing_with_flat_fee.json
import {
buildUsageLimitApproachingMessage,
- buildUsageLimitExceededMessage,
+ buildUsageLimitReachedMessage,
canAccessBilling,
canViewUsageAndSpend,
convertAmountToUsage,
@@ -460,74 +460,74 @@ describe('getUsageLimitConsequence', () => {
})
})
-describe('buildUsageLimitExceededMessage', () => {
+describe('buildUsageLimitReachedMessage', () => {
it('should return empty strings for empty array', () => {
- expect(buildUsageLimitExceededMessage([])).toEqual({ title: '', message: '' })
+ expect(buildUsageLimitReachedMessage([])).toEqual({ title: '', message: '' })
})
it('should build message for single subscribed product', () => {
- const result = buildUsageLimitExceededMessage([{ name: 'Session replay', subscribed: true }])
- expect(result.title).toEqual('Usage limit exceeded')
+ const result = buildUsageLimitReachedMessage([{ name: 'Session replay', subscribed: true }])
+ expect(result.title).toEqual('Usage limit reached')
expect(result.message).toEqual(
- 'You have exceeded the usage limit for Session replay. Please increase your billing limit or data loss may occur.'
+ 'You have reached the usage limit for Session replay. Please increase your billing limit or data loss may occur.'
)
})
it('should build message for single unsubscribed product', () => {
- const result = buildUsageLimitExceededMessage([{ name: 'Session replay', subscribed: false }])
+ const result = buildUsageLimitReachedMessage([{ name: 'Session replay', subscribed: false }])
expect(result.message).toContain('upgrade your plan')
})
it('should build message for multiple products with unique consequences', () => {
- const result = buildUsageLimitExceededMessage([
+ const result = buildUsageLimitReachedMessage([
{ name: 'Session replay', subscribed: true },
{ name: 'Feature flags & Experiments', subscribed: true },
])
- expect(result.title).toEqual('Usage limits exceeded')
+ expect(result.title).toEqual('Usage limits reached')
expect(result.message).toEqual(
- 'You have exceeded the usage limit for Session replay and Feature flags & Experiments. Please increase your billing limit or data loss may occur and feature flags will not evaluate.'
+ 'You have reached the usage limit for Session replay and Feature flags & Experiments. Please increase your billing limit or data loss may occur and feature flags will not evaluate.'
)
})
it('should build message for PostHog AI with specific consequence', () => {
- const result = buildUsageLimitExceededMessage([{ name: 'PostHog AI', subscribed: true }])
- expect(result.title).toEqual('Usage limit exceeded')
+ const result = buildUsageLimitReachedMessage([{ name: 'PostHog AI', subscribed: true }])
+ expect(result.title).toEqual('Usage limit reached')
expect(result.message).toEqual(
- 'You have exceeded the usage limit for PostHog AI. Please increase your billing limit or PostHog AI will be unavailable.'
+ 'You have reached the usage limit for PostHog AI. Please increase your billing limit or PostHog AI will be unavailable.'
)
})
it('should build message for Inbox with specific consequence', () => {
- const result = buildUsageLimitExceededMessage([{ name: 'Inbox', subscribed: true }])
- expect(result.title).toEqual('Usage limit exceeded')
+ const result = buildUsageLimitReachedMessage([{ name: 'Inbox', subscribed: true }])
+ expect(result.title).toEqual('Usage limit reached')
expect(result.message).toEqual(
- 'You have exceeded the usage limit for Inbox. Please increase your billing limit or Inbox agents will be paused.'
+ 'You have reached the usage limit for Inbox. Please increase your billing limit or Inbox agents will be paused.'
)
})
it('should build message for PostHog AI with other products', () => {
- const result = buildUsageLimitExceededMessage([
+ const result = buildUsageLimitReachedMessage([
{ name: 'PostHog AI', subscribed: true },
{ name: 'Session replay', subscribed: true },
])
- expect(result.title).toEqual('Usage limits exceeded')
+ expect(result.title).toEqual('Usage limits reached')
expect(result.message).toEqual(
- 'You have exceeded the usage limit for PostHog AI and Session replay. Please increase your billing limit or PostHog AI will be unavailable and data loss may occur.'
+ 'You have reached the usage limit for PostHog AI and Session replay. Please increase your billing limit or PostHog AI will be unavailable and data loss may occur.'
)
})
it('should deduplicate consequences for products with same consequence', () => {
- const result = buildUsageLimitExceededMessage([
+ const result = buildUsageLimitReachedMessage([
{ name: 'Session replay', subscribed: true },
{ name: 'Product analytics', subscribed: true },
])
expect(result.message).toEqual(
- 'You have exceeded the usage limit for Session replay and Product analytics. Please increase your billing limit or data loss may occur.'
+ 'You have reached the usage limit for Session replay and Product analytics. Please increase your billing limit or data loss may occur.'
)
})
it('should use upgrade message when any product is not subscribed', () => {
- const result = buildUsageLimitExceededMessage([
+ const result = buildUsageLimitReachedMessage([
{ name: 'Session replay', subscribed: true },
{ name: 'Feature flags & Experiments', subscribed: false },
])
@@ -558,13 +558,13 @@ describe('buildUsageLimitExceededMessage', () => {
])(
'should use "$expected" when hasBillingAccess=$hasBillingAccess and subscribed=$subscribed',
({ hasBillingAccess, subscribed, expected }) => {
- const result = buildUsageLimitExceededMessage([{ name: 'Session replay', subscribed }], hasBillingAccess)
+ const result = buildUsageLimitReachedMessage([{ name: 'Session replay', subscribed }], hasBillingAccess)
expect(result.message).toContain(expected)
}
)
it('should say "owner" when minimumBillingAccessLevel is Owner and user has no billing access', () => {
- const result = buildUsageLimitExceededMessage(
+ const result = buildUsageLimitReachedMessage(
[{ name: 'Session replay', subscribed: true }],
false,
OrganizationMembershipLevel.Owner
@@ -573,7 +573,7 @@ describe('buildUsageLimitExceededMessage', () => {
})
it('should default to admin message when hasBillingAccess is not provided', () => {
- const result = buildUsageLimitExceededMessage([{ name: 'Session replay', subscribed: true }])
+ const result = buildUsageLimitReachedMessage([{ name: 'Session replay', subscribed: true }])
expect(result.message).toContain('increase your billing limit')
})
})
diff --git a/frontend/src/scenes/billing/billing-utils.ts b/frontend/src/scenes/billing/billing-utils.ts
index 57ef0f0dc5ac..13bb4736c464 100644
--- a/frontend/src/scenes/billing/billing-utils.ts
+++ b/frontend/src/scenes/billing/billing-utils.ts
@@ -690,7 +690,7 @@ export function formatProductNames(names: string[]): string {
}
/**
- * Get the consequence message for a product when it exceeds its usage limit
+ * Get the consequence message for a product when it reaches its usage limit
*/
export function getUsageLimitConsequence(productName: string): string {
if (productName === 'Data warehouse') {
@@ -709,9 +709,9 @@ export function getUsageLimitConsequence(productName: string): string {
}
/**
- * Build a consolidated message for products that have exceeded their usage limits
+ * Build a consolidated message for products that have reached their usage limits
*/
-export function buildUsageLimitExceededMessage(
+export function buildUsageLimitReachedMessage(
products: Array<{ name: string; subscribed: boolean | null }>,
hasBillingAccess: boolean = true,
minimumBillingAccessLevel: OrganizationMembershipLevel = OrganizationMembershipLevel.Admin
@@ -743,8 +743,8 @@ export function buildUsageLimitExceededMessage(
}
return {
- title: products.length === 1 ? 'Usage limit exceeded' : 'Usage limits exceeded',
- message: `You have exceeded the usage limit for ${productListText}. Please ${actionText} or ${consequenceText}.`,
+ title: products.length === 1 ? 'Usage limit reached' : 'Usage limits reached',
+ message: `You have reached the usage limit for ${productListText}. Please ${actionText} or ${consequenceText}.`,
}
}
diff --git a/frontend/src/scenes/billing/billingLogic.test.ts b/frontend/src/scenes/billing/billingLogic.test.ts
index c99823614701..ce001fcb8266 100644
--- a/frontend/src/scenes/billing/billingLogic.test.ts
+++ b/frontend/src/scenes/billing/billingLogic.test.ts
@@ -1,15 +1,58 @@
import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { billingLogic } from 'scenes/billing/billingLogic'
import { organizationLogic } from 'scenes/organizationLogic'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
+import { billingJson } from '~/mocks/fixtures/_billing'
+import preflightJson from '~/mocks/fixtures/_preflight.json'
+import { useMocks } from '~/mocks/jest'
import { ProductKey } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
+import { BillingProductV2Type, BillingType } from '~/types'
+
+const creditOverviewResponse = {
+ eligible: false,
+ estimated_monthly_credit_amount_usd: null,
+ status: 'none',
+ invoice_url: null,
+ collection_method: null,
+ cc_last_four: null,
+ email: null,
+ credit_brackets: [],
+}
+
+const productWithUsage = (
+ percentageUsage: number,
+ overrides: Partial<BillingProductV2Type> = {}
+): BillingProductV2Type => ({
+ ...billingJson.products[0],
+ type: ProductKey.PRODUCT_ANALYTICS,
+ usage_key: 'events',
+ name: 'Product analytics',
+ subscribed: true,
+ percentage_usage: percentageUsage,
+ current_usage: Math.round(percentageUsage * 100),
+ usage_limit: percentageUsage > 0 ? 100 : null,
+ has_exceeded_limit: percentageUsage >= 1,
+ ...overrides,
+})
+
+const billingWithProducts = (
+ products: BillingProductV2Type[],
+ customLimitsUsd: BillingType['custom_limits_usd'] = {}
+): BillingType => ({
+ ...billingJson,
+ products,
+ custom_limits_usd: customLimitsUsd,
+})
type BillingAccessCase = {
name: string
@@ -24,7 +67,17 @@ type BillingAccessCase = {
}
describe('billingLogic', () => {
+ let billingState: BillingType
+
beforeEach(() => {
+ billingState = billingWithProducts([productWithUsage(0.5)])
+ useMocks({
+ get: {
+ '/_preflight': [200, { ...preflightJson, cloud: true }],
+ '/api/billing': () => [200, billingState],
+ '/api/billing/credits/overview': [200, creditOverviewResponse],
+ },
+ })
initKeaTests()
})
@@ -68,6 +121,112 @@ describe('billingLogic', () => {
}
)
+ it('treats exactly 100% usage as a reached limit alert', async () => {
+ billingState = billingWithProducts([productWithUsage(1)])
+ billingLogic.mount()
+ await expectLogic(preflightLogic).toFinishAllListeners()
+
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+
+ expect(billingLogic.values.billingAlert).toMatchObject({
+ status: 'error',
+ title: 'Usage limit reached',
+ message: expect.stringContaining('You have reached the usage limit for Product analytics.'),
+ productKey: ProductKey.PRODUCT_ANALYTICS,
+ })
+ })
+
+ it('clears a stale usage limit alert when refreshed billing data no longer qualifies', async () => {
+ billingState = billingWithProducts([productWithUsage(1)])
+ billingLogic.mount()
+ await expectLogic(preflightLogic).toFinishAllListeners()
+
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+
+ expect(billingLogic.values.billingAlert?.title).toBe('Usage limit reached')
+
+ billingState = billingWithProducts([productWithUsage(0)])
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+
+ expect(billingLogic.values.billingAlert).toBeNull()
+ })
+
+ it('preserves billing error URL alerts when refreshed billing data has no managed alert', async () => {
+ billingState = billingWithProducts([productWithUsage(0)])
+ router.actions.push('/organization/billing', { billing_error: 'Checkout failed' })
+ billingLogic.mount()
+ await expectLogic(preflightLogic).toFinishAllListeners()
+
+ expect(billingLogic.values.billingAlert).toMatchObject({
+ status: 'error',
+ title: 'Error',
+ message: 'Checkout failed',
+ contactSupport: true,
+ })
+
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+
+ expect(billingLogic.values.billingAlert).toMatchObject({
+ status: 'error',
+ title: 'Error',
+ message: 'Checkout failed',
+ contactSupport: true,
+ })
+ })
+
+ it('unregisters removed custom limit analytics properties', async () => {
+ const registerSpy = jest.spyOn(posthog, 'register')
+ const unregisterSpy = jest.spyOn(posthog, 'unregister')
+ jest.spyOn(posthog, 'get_property').mockImplementation((property) =>
+ property === 'custom_limits_usd.product_analytics' ? 100 : undefined
+ )
+ billingState = billingWithProducts([productWithUsage(0.5)], { [ProductKey.PRODUCT_ANALYTICS]: 100 })
+ billingLogic.mount()
+ await expectLogic(preflightLogic).toFinishAllListeners()
+ registerSpy.mockClear()
+ unregisterSpy.mockClear()
+
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+
+ expect(registerSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ 'custom_limits_usd.product_analytics': 100,
+ })
+ )
+
+ billingState = billingWithProducts([])
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+
+ expect(unregisterSpy).toHaveBeenCalledWith('custom_limits_usd.product_analytics')
+ const lastRegisterPayload = registerSpy.mock.calls[registerSpy.mock.calls.length - 1][0]
+ expect(lastRegisterPayload).not.toHaveProperty('custom_limits_usd.product_analytics')
+
+ billingState = billingWithProducts([productWithUsage(0.5)], { [ProductKey.PRODUCT_ANALYTICS]: 100 })
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+ unregisterSpy.mockClear()
+
+ billingState = billingWithProducts([productWithUsage(0.5)], { [ProductKey.PRODUCT_ANALYTICS]: null })
+ await expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+
+ expect(unregisterSpy).toHaveBeenCalledWith('custom_limits_usd.product_analytics')
+ })
+
it.each<BillingAccessCase>([
{
name: 'member with both member-access flags',
diff --git a/frontend/src/scenes/billing/billingLogic.tsx b/frontend/src/scenes/billing/billingLogic.tsx
index 9218fe9ebd1b..43f21e82e14f 100644
--- a/frontend/src/scenes/billing/billingLogic.tsx
+++ b/frontend/src/scenes/billing/billingLogic.tsx
@@ -36,7 +36,7 @@ import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { OrganizationType, PreflightStatus } from '../../types'
import {
buildUsageLimitApproachingMessage,
- buildUsageLimitExceededMessage,
+ buildUsageLimitReachedMessage,
canAccessBilling as canAccessBillingUtil,
canViewUsageAndSpend as canViewUsageAndSpendUtil,
getMinimumBillingAccessLevel,
@@ -60,17 +60,21 @@ const getFirstProductFromProductsParam = (productsParam: unknown): ProductKey |
}
export interface BillingAlertConfig {
+ kind?: 'trial' | 'deactivated' | 'usage_limit'
status: 'info' | 'warning' | 'error'
title: string
message?: string
contactSupport?: boolean
buttonCTA?: string
dismissKey?: string
+ productKey?: ProductKey
action?: LemonBannerAction
pathName?: string
onClose?: () => void
}
+const isManagedBillingAlert = (billingAlert: BillingAlertConfig | null): boolean => billingAlert?.kind !== undefined
+
export enum BillingAPIErrorCodes {
OPEN_INVOICES_ERROR = 'open_invoices_error',
NO_ACTIVE_PAYMENT_METHOD_ERROR = 'no_active_payment_method_error',
@@ -268,6 +272,7 @@ export interface billingLogicValues {
products: BillingProductV2Type[]
productsLoading: boolean
redirectPath: string
+ registeredCustomLimitKeys: string[]
scrollToProductKey: ProductKey | null
showActivateLicenseErrors: boolean
showBillingHero: boolean
@@ -509,6 +514,9 @@ export interface billingLogicActions {
setRedirectPath: (redirectPath: string) => {
redirectPath: string
}
+ setRegisteredCustomLimitKeys: (keys: string[]) => {
+ keys: string[]
+ }
setScrollToProductKey: (scrollToProductKey: ProductKey | null) => {
scrollToProductKey: ProductKey | null
}
@@ -708,6 +716,7 @@ export const billingLogic = kea<billingLogicType>([
toggleCreditCTAHeroDismissed: (isDismissed: boolean) => ({ isDismissed }),
setComputedDiscount: (discount: number) => ({ discount }),
setCreditBrackets: (creditBrackets: any[]) => ({ creditBrackets }),
+ setRegisteredCustomLimitKeys: (keys: string[]) => ({ keys }),
scrollToProduct: (productType: string) => ({ productType }),
setSwitchPlanLoading: (productKey: string | null) => ({ productKey }),
}),
@@ -740,6 +749,12 @@ export const billingLogic = kea<billingLogicType>([
setBillingAlert: (_, { billingAlert }) => billingAlert,
},
],
+ registeredCustomLimitKeys: [
+ [] as string[],
+ {
+ setRegisteredCustomLimitKeys: (_, { keys }) => keys,
+ },
+ ],
scrollToProductKey: [
null as ProductKey | null,
{
@@ -1416,9 +1431,10 @@ export const billingLogic = kea<billingLogicType>([
}
},
determineBillingAlert: () => {
- // If we already have a billing alert, don't show another one
- if (values.billingAlert) {
- return
+ const clearBillingAlert = (): void => {
+ if (values.billingAlert) {
+ actions.setBillingAlert(null)
+ }
}
if (values.productSpecificAlert) {
@@ -1426,7 +1442,12 @@ export const billingLogic = kea<billingLogicType>([
return
}
+ if (values.billingAlert && !isManagedBillingAlert(values.billingAlert)) {
+ return
+ }
+
if (!values.billing || !values.preflight?.cloud) {
+ clearBillingAlert()
return
}
@@ -1434,12 +1455,14 @@ export const billingLogic = kea<billingLogicType>([
if (trial && trial.expires_at && dayjs(trial.expires_at).isAfter(dayjs())) {
if (trial.type === 'autosubscribe' || trial.status !== 'active') {
// Only show for standard ones (managed by sales)
+ clearBillingAlert()
return
}
const remainingDays = dayjs(trial.expires_at).diff(dayjs(), 'days')
const remainingHours = dayjs(trial.expires_at).diff(dayjs(), 'hours')
if (remainingHours > 72) {
+ clearBillingAlert()
return
}
@@ -1449,6 +1472,7 @@ export const billingLogic = kea<billingLogicType>([
remainingHours < 24 ? pluralize(remainingHours, 'hour') : pluralize(remainingDays, 'day')
const planName = capitalizeFirstLetter(trial.target)
actions.setBillingAlert({
+ kind: 'trial',
status: 'info',
title: `Your free trial for the ${planName} plan ends in ${timeRemaining}. Your service will continue without interruption, and you'll be charged for the ${planName} plan.`,
message: `Questions? Reach out to ${contactName} at ${contactEmail}.`,
@@ -1458,6 +1482,7 @@ export const billingLogic = kea<billingLogicType>([
if (values.billing.deactivated) {
actions.setBillingAlert({
+ kind: 'deactivated',
status: 'error',
title: 'Your organization has been temporarily suspended.',
message: 'Please contact support to reactivate it.',
@@ -1468,10 +1493,9 @@ export const billingLogic = kea<billingLogicType>([
const billingPeriodEnd = values.billing.billing_period?.current_period_end?.format('YYYY-MM-DD')
- // Find ALL products over limit, filtering out hidden and dismissed ones
- const productsOverLimit =
+ const productsAtOrOverLimit =
values.billing.products?.filter((x: BillingProductV2Type) => {
- if (x.percentage_usage <= 1 || !x.usage_key) {
+ if (x.percentage_usage < 1 || !x.usage_key) {
return false
}
const hideProductFlag = `billing_hide_product_${x.type}`
@@ -1484,23 +1508,26 @@ export const billingLogic = kea<billingLogicType>([
return true
}) || []
- if (productsOverLimit.length > 0) {
- const { title, message } = buildUsageLimitExceededMessage(
- productsOverLimit,
+ if (productsAtOrOverLimit.length > 0) {
+ const { title, message } = buildUsageLimitReachedMessage(
+ productsAtOrOverLimit,
values.canAccessBilling,
values.minimumBillingAccessLevel
)
actions.setBillingAlert({
+ kind: 'usage_limit',
status: 'error',
title,
message,
dismissKey: 'usage-limit-exceeded',
+ productKey:
+ productsAtOrOverLimit.length === 1 ? (productsAtOrOverLimit[0].type as ProductKey) : undefined,
onClose: () => {
// Store dismissal for all affected products in localStorage
const billingPeriodEnd =
values.billing?.billing_period?.current_period_end?.format('YYYY-MM-DD')
- for (const product of productsOverLimit) {
+ for (const product of productsAtOrOverLimit) {
storeBillingAlertDismissal(values.currentOrganizationId, product.type, billingPeriodEnd)
}
actions.setBillingAlert(null)
@@ -1511,11 +1538,9 @@ export const billingLogic = kea<billingLogicType>([
actions.resetUsageLimitExceededKey()
- // Find ALL products approaching limit (but not yet over), filtering out hidden and dismissed ones
const productsApproachingLimit =
values.billing.products?.filter((x: BillingProductV2Type) => {
- // Only include products approaching but not over the limit
- if (x.percentage_usage <= ALLOCATION_THRESHOLD_ALERT || x.percentage_usage > 1) {
+ if (x.percentage_usage <= ALLOCATION_THRESHOLD_ALERT || x.percentage_usage >= 1) {
return false
}
const hideProductFlag = `billing_hide_product_${x.type}`
@@ -1538,10 +1563,15 @@ export const billingLogic = kea<billingLogicType>([
)
actions.setBillingAlert({
+ kind: 'usage_limit',
status: 'info',
title,
message,
dismissKey: 'usage-limit-approaching',
+ productKey:
+ productsApproachingLimit.length === 1
+ ? (productsApproachingLimit[0].type as ProductKey)
+ : undefined,
onClose: () => {
// Store dismissal for all affected products
const billingPeriodEnd =
@@ -1561,6 +1591,7 @@ export const billingLogic = kea<billingLogicType>([
}
actions.resetUsageLimitApproachingKey()
+ clearBillingAlert()
},
setCreditFormValue: ({ name, value }) => {
if (name === 'creditInput' || (name as FieldNamePath)?.[0] === 'creditInput') {
@@ -1588,12 +1619,36 @@ export const billingLogic = kea<billingLogicType>([
customer_deactivated: values.billing.deactivated,
current_total_amount_usd: values.billing.current_total_amount_usd,
}
- if (values.billing.custom_limits_usd) {
- for (const product of Object.keys(values.billing.custom_limits_usd)) {
- payload[`custom_limits_usd.${product}`] = values.billing.custom_limits_usd[product]
- }
- }
if (values.billing.products) {
+ const customLimitsUsd = values.billing.custom_limits_usd ?? {}
+ const customLimitKeysToSync = new Set<string>([
+ ...values.registeredCustomLimitKeys,
+ ...Object.keys(customLimitsUsd),
+ ])
+ const registeredCustomLimitKeys = new Set<string>()
+ for (const product of values.billing.products) {
+ customLimitKeysToSync.add(product.type)
+ if (product.usage_key) {
+ customLimitKeysToSync.add(product.usage_key)
+ }
+ }
+ for (const product of customLimitKeysToSync) {
+ const customLimitUsd = customLimitsUsd[product]
+ const property = `custom_limits_usd.${product}`
+ if (customLimitUsd === null || customLimitUsd === undefined) {
+ if (
+ values.registeredCustomLimitKeys.includes(product) ||
+ posthog.get_property(property) !== undefined
+ ) {
+ posthog.unregister(property)
+ }
+ } else {
+ registeredCustomLimitKeys.add(product)
+ payload[property] = customLimitUsd
+ }
+ }
+ actions.setRegisteredCustomLimitKeys([...registeredCustomLimitKeys])
+
for (const product of values.billing.products) {
const type = product.type.toLowerCase()
payload[`percentage_usage.${type}`] = product.percentage_usage