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.

feat(billing): add billing alert management (#72260)

willwearing8cc589bdf5de
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml
index 705fce5f803e..2899c311ef55 100644
--- a/.github/workflows/ci-mcp.yml
+++ b/.github/workflows/ci-mcp.yml
@@ -326,7 +326,7 @@ jobs:
DISABLE_SECURE_SSL_REDIRECT: 'True'
CLICKHOUSE_LOGS_CLUSTER_SECURE: 'False'
CELERY_METRICS_PORT: 8999
- POSTHOG_FEATURE_FLAGS_FORCE_ENABLED: 'logs-alerting,dashboard-widgets,product-business-knowledge'
+ POSTHOG_FEATURE_FLAGS_FORCE_ENABLED: 'logs-alerting,dashboard-widgets,product-business-knowledge,billing-alerts'
# Required for the feature_flags test_evaluation endpoint, which authenticates
# historical-flag override requests to the Rust flags service. Any non-empty
# value is fine for CI — the Rust service in the test stack accepts it.
diff --git a/frontend/package.json b/frontend/package.json
index 1d517b3f3b9c..35975091dd3d 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -88,6 +88,7 @@
"@posthog/products-annotations": "workspace:*",
"@posthog/products-apm": "workspace:*",
"@posthog/products-batch-exports": "workspace:*",
+ "@posthog/products-billing-alerts": "workspace:*",
"@posthog/products-business-knowledge": "workspace:*",
"@posthog/products-canvas": "workspace:*",
"@posthog/products-cohorts": "workspace:*",
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2df8f7416249..bce66e72fdb7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1057,9 +1057,9 @@ snapshots:
components-hogcharts-timeserieslinechart--date-axis--light:
hash: v1.k794b7964.dc5c22ca390b56a959e433a282804008a2b4c807cbac4f7c0b480f6d84572352.7o9nzEjQIRHr34Wj8ZPILiWhbETStNhUK9QndRCltag
components-hogcharts-timeserieslinechart--drag-to-zoom--dark:
- hash: v1.k794b7964.c5a1a997378245bd048d35ff7ab54694c9e333ff6369e5c30d40357df99842fa.xXPbAc4NqAr0LvV-0z_5t3MYqgWR7l0eVtIt35KNfhE
+ hash: v1.k794b7964.e4e717b64c2b6bff54884958b0c1aca7bb96065de08f6ef672e28aac62ddffa4.sHLYgTgGvG5EhnN9HPxEUg9a5Z-Q4q5orLpcAux_PxY
components-hogcharts-timeserieslinechart--drag-to-zoom--light:
- hash: v1.k794b7964.7d8de1c664f78dad36682304cd25c746266b6fb509d28bcaf2d8ae629a808284.eGlPABfqYjC1-H2VGiv5lJxfPOXP5U2fpK2cr7CtOT4
+ hash: v1.k794b7964.9cb34678aa2989c4af6d10cdf453f05bc5dc893a8514bc087c605c536c116ed0.RLTJiNFv1whT6hqgdTMM67WIi8HqLu8mg_mx3WdkGrI
components-hogcharts-timeserieslinechart--dual-y-axis--dark:
hash: v1.k794b7964.4c7f12507323cced93e68edfca7f76e2bf9f23f94ce89411b2339bf05bae2954.LrKKPYkdPf9_SbJg711wjVuanmojl04C8xYBYM6erlw
components-hogcharts-timeserieslinechart--dual-y-axis--light:
@@ -4725,9 +4725,9 @@ snapshots:
products-alerts-shared-components--editor-loading--light:
hash: v1.k794b7964.5e3a2827ace05ced5a178649d4d511fde78fbd2efc102c1fd3d5cacc229b8395.GsnqMnxDeg6gkEjtWsWDcrdQRmw4OdCs2s4rfF0WdN4
products-alerts-shared-components--evaluation-history--dark:
- hash: v1.k794b7964.453165acd1cbb101c12b290fe168d0fe04ae0f626fdae715e79f68fe69475caf.isZqjBZXk31Z7iMmwiTrmIFhJp6MdOLTWGJMtT6yUtQ
+ hash: v1.k794b7964.4c73cdf98a02e35050526eb3d8dbeb6290352aec664d5efeb427061b90ad3805.agcaltLoWhqx3J3mCJW_kDgM2eR3Z8Q1rLkTRISqmS4
products-alerts-shared-components--evaluation-history--light:
- hash: v1.k794b7964.4d156162bbf222b25d0bcea9f4be1c23c8c787a360b4b0bef507de7f361e8025.25EdkHo5WY5JPgsCWiwy4a_UjKJ594t0qnizfl_KW8A
+ hash: v1.k794b7964.c1926b36680c9eb9131bf374492a31d897583cc0219e0c12e31c57406ba42284.6e5ldiw6-7Xry45ZfkhsNoDiozPOldPRDzQ2Y3pFjYk
products-alerts-shared-components--notifications--dark:
hash: v1.k794b7964.81ff4b2654d65e3866f9dd9e04dfcedb6d1dbbb45fcdf73acfd60153ba263480.Zq6Us8BfcBnrdUHjpISWQFYe5836RgaIlc6eoFwpshE
products-alerts-shared-components--notifications--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 3821efeb299a..55d939fd649d 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -267,6 +267,7 @@ export const FEATURE_FLAGS = {
APPROVALS: 'approvals', // owner: @yasen-posthog #team-platform-features
AVERAGE_PAGE_VIEW_COLUMN: 'average-page-view-column', // owner: @jordanm-posthog #team-web-analytics
BACKFILL_WORKFLOWS_DESTINATION: 'backfill-workflows-destination', // owner: #team-batch-exports
+ BILLING_ALERTS: 'billing-alerts', // owner: #team-billing, gates the Billing > Alerts tab
CDP_ACTIVITY_LOG_NOTIFICATIONS: 'cdp-activity-log-notifications', // owner: #team-workflows-cdp
CDP_DWH_TABLE_SOURCE: 'cdp-dwh-table-source', // owner: #team-workflows-cdp
CDP_HOG_SOURCES: 'cdp-hog-sources', // owner #team-workflows-cdp
diff --git a/frontend/src/scenes/billing/BillingSection.tsx b/frontend/src/scenes/billing/BillingSection.tsx
index 2191e6483fe4..93f10fceed2f 100644
--- a/frontend/src/scenes/billing/BillingSection.tsx
+++ b/frontend/src/scenes/billing/BillingSection.tsx
@@ -2,9 +2,12 @@ import './Billing.scss'
import { useValues } from 'kea'
import { router } from 'kea-router'
+import { Suspense, lazy, useEffect } from 'react'
-import { LemonTabs } from '@posthog/lemon-ui'
+import { LemonTabs, Spinner } from '@posthog/lemon-ui'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -14,25 +17,46 @@ import { BillingSpendView } from './BillingSpendView'
import { BillingUsage } from './BillingUsage'
import { BillingSectionId } from './types'
+const BillingAlerts = lazy(() =>
+ import('@posthog/products-billing-alerts/frontend/BillingAlerts').then((module) => ({
+ default: module.BillingAlerts,
+ }))
+)
+
export const scene: SceneExport = {
component: BillingSection,
logic: billingLogic,
}
-const tabs: { key: BillingSectionId; label: string }[] = [
+const allTabs: { key: BillingSectionId; label: string }[] = [
{ key: 'overview', label: 'Overview' },
{ key: 'usage', label: 'Usage' },
{ key: 'spend', label: 'Spend' },
+ { key: 'alerts', label: 'Alerts' },
]
export function BillingSection(): JSX.Element {
const { location, searchParams } = useValues(router)
+ const { featureFlags, receivedFeatureFlags } = useValues(featureFlagLogic)
+ const billingAlertsEnabled = !!featureFlags[FEATURE_FLAGS.BILLING_ALERTS]
+ const alertsRequested = location.pathname.includes('alerts')
+ const billingAlertsPending = alertsRequested && !receivedFeatureFlags
+ const tabs = billingAlertsEnabled || billingAlertsPending ? allTabs : allTabs.filter((tab) => tab.key !== 'alerts')
const section = location.pathname.includes('spend')
? 'spend'
: location.pathname.includes('usage')
? 'usage'
- : 'overview'
+ : alertsRequested && (billingAlertsEnabled || billingAlertsPending)
+ ? 'alerts'
+ : 'overview'
+
+ useEffect(() => {
+ // Wait for feature flags before redirecting an alerts deep link away.
+ if (alertsRequested && receivedFeatureFlags && !billingAlertsEnabled) {
+ router.actions.replace(urls.organizationBillingSection('overview'))
+ }
+ }, [alertsRequested, billingAlertsEnabled, receivedFeatureFlags])
const handleTabChange = (key: BillingSectionId): void => {
const newUrl = urls.organizationBillingSection(key)
@@ -68,6 +92,11 @@ export function BillingSection(): JSX.Element {
{section === 'overview' && <Billing />}
{section === 'usage' && <BillingUsage />}
{section === 'spend' && <BillingSpendView />}
+ {section === 'alerts' && (
+ <Suspense fallback={<Spinner className="text-3xl mx-auto my-8" />}>
+ {billingAlertsPending ? <Spinner className="text-3xl mx-auto my-8" /> : <BillingAlerts />}
+ </Suspense>
+ )}
</div>
)
}
diff --git a/frontend/src/scenes/billing/types.ts b/frontend/src/scenes/billing/types.ts
index 9c1c978f79a3..fa27bda014cc 100644
--- a/frontend/src/scenes/billing/types.ts
+++ b/frontend/src/scenes/billing/types.ts
@@ -12,7 +12,7 @@ export type BillingGaugeItemType = {
value: number
}
-export type BillingSectionId = 'overview' | 'usage' | 'spend'
+export type BillingSectionId = 'overview' | 'usage' | 'spend' | 'alerts'
export type SeatStatus = 'active' | 'canceling' | 'pending' | 'pending_payment' | 'expired' | 'withdrawn'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0e76e6e62153..f46aab784c53 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -659,6 +659,9 @@ importers:
'@posthog/products-batch-exports':
specifier: workspace:*
version: link:../products/batch_exports
+ '@posthog/products-billing-alerts':
+ specifier: workspace:*
+ version: link:../products/billing_alerts
'@posthog/products-business-knowledge':
specifier: workspace:*
version: link:../products/business_knowledge
@@ -2512,7 +2515,32 @@ importers:
products/batch_exports: {}
- products/billing_alerts: {}
+ products/billing_alerts:
+ dependencies:
+ '@posthog/icons':
+ specifier: '*'
+ '@posthog/lemon-ui':
+ specifier: '*'
+ version: 0.0.0([email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])))([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))([email protected]([email protected]))([email protected])
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
+ kea-forms:
+ specifier: 'catalog:'
+ version: 3.2.0([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ kea-loaders:
+ specifier: 'catalog:'
+ version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
+ typescript:
+ specifier: 6.0.3
+ version: 6.0.3
products/business_knowledge:
dependencies:
diff --git a/products/alerts/frontend/components/AlertComponents.stories.tsx b/products/alerts/frontend/components/AlertComponents.stories.tsx
index 6a0f80360466..713995707ad0 100644
--- a/products/alerts/frontend/components/AlertComponents.stories.tsx
+++ b/products/alerts/frontend/components/AlertComponents.stories.tsx
@@ -160,7 +160,10 @@ function NotificationsStory(): JSX.Element {
title: 'Slack: #product-alerts',
tags: [{ label: 'Active', type: 'success' }],
viewAction: { kind: 'button', label: 'View', url: '#destination' },
- onDelete: () => setExistingDestinations([]),
+ onDelete: () =>
+ setExistingDestinations((destinations) =>
+ destinations.map((destination) => ({ ...destination, deleting: true }))
+ ),
},
])
const [pendingDestinations, setPendingDestinations] = useState<PendingAlertNotificationDestinationView[]>([
@@ -360,7 +363,7 @@ const HISTORY_POINTS: AlertEvaluationHistoryPoint[] = [
{ label: '11:30', value: 71, firedAtTime: true },
{ label: '11:45', value: 64, firedAtTime: true },
{ label: '12:00', value: 53, firedAtTime: false },
- { label: '12:15', value: 38, firedAtTime: false },
+ { label: '12:15', value: 68, firedAtTime: false, wouldFireUnderCurrentConfiguration: true },
{ label: '12:30', value: 76, firedAtTime: true },
]
@@ -377,6 +380,7 @@ function EvaluationHistoryStory(): JSX.Element {
evaluationsTotal={47}
evaluationNoun="evaluation"
tableAvailable
+ formatValue={(value) => `$${value.toFixed(2)}`}
/>
</div>
)
diff --git a/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsx b/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsx
index a7a424967ad8..40537d4b2850 100644
--- a/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsx
+++ b/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsx
@@ -16,6 +16,12 @@ export interface AlertEvaluationHistoryPoint {
label: string
value: number
firedAtTime?: boolean
+ /**
+ * Caller-computed classification against the CURRENT alert configuration.
+ * `undefined`: the chart infers from `thresholds`. `null`: unclassifiable (e.g. the point
+ * predates the current configuration revision), never flagged. `true`/`false`: explicit.
+ */
+ wouldFireUnderCurrentConfiguration?: boolean | null
}
export interface AlertEvaluationThreshold {
@@ -33,6 +39,7 @@ interface AlertEvaluationHistoryChartProps {
evaluationNoun?: string
tableAvailable?: boolean
classifyUnusualWithoutThresholds?: boolean
+ formatValue?: (value: number) => string
}
function rollingMean(values: number[], window: number): number[] {
@@ -108,6 +115,7 @@ export function AlertEvaluationHistoryChart({
evaluationNoun = 'check',
tableAvailable = false,
classifyUnusualWithoutThresholds = false,
+ formatValue = humanFriendlyNumber,
}: AlertEvaluationHistoryChartProps): JSX.Element {
const chartSeries = useMemo(
() => ({
@@ -128,6 +136,9 @@ export function AlertEvaluationHistoryChart({
if (point.firedAtTime) {
return 'historical'
}
+ if (point.wouldFireUnderCurrentConfiguration !== undefined) {
+ return point.wouldFireUnderCurrentConfiguration ? 'currentOnly' : 'none'
+ }
return matchesThreshold(point.value, thresholds) ? 'currentOnly' : 'none'
})
}
@@ -246,7 +257,7 @@ export function AlertEvaluationHistoryChart({
} else if (classification === 'currentOnly') {
suffix = ' (would trigger the alert now)'
}
- return `${valueLabel}: ${humanFriendlyNumber(value)}${suffix}`
+ return `${valueLabel}: ${formatValue(value)}${suffix}`
},
},
},
@@ -263,14 +274,21 @@ export function AlertEvaluationHistoryChart({
ticks: {
maxTicksLimit: 5,
font: { size: 10 },
- callback: (value: string | number) => humanFriendlyNumber(Number(value)),
+ callback: (value: string | number) => formatValue(Number(value)),
},
grid: { color: 'rgba(0,0,0,0.06)' },
},
},
},
}),
- deps: [chartSeries, valueLabel, thresholdAnnotations, pointClassifications, hasHistoricalFiringState],
+ deps: [
+ chartSeries,
+ valueLabel,
+ thresholdAnnotations,
+ pointClassifications,
+ hasHistoricalFiringState,
+ formatValue,
+ ],
})
const historicalCount = pointClassifications.filter((classification) => classification === 'historical').length
diff --git a/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx b/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx
index ecb7e4715c89..fd7b3aef3fbd 100644
--- a/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx
+++ b/products/alerts/frontend/components/AlertNotificationDestinationEditor.tsx
@@ -39,6 +39,7 @@ export interface AlertNotificationDestinationView {
tags?: { label: string; type?: LemonTagType }[]
viewAction?: AlertNotificationDestinationIconAction | AlertNotificationDestinationButtonAction
onDelete: () => void
+ deleting?: boolean
}
export interface PendingAlertNotificationDestinationView {
@@ -65,6 +66,8 @@ interface AlertNotificationDestinationEditorProps<NotificationType extends strin
options: LemonSelectOptions<NotificationType>
value: NotificationType
onChange: (type: NotificationType) => void
+ /** Where the type dropdown opens. Set 'top-start' when the editor sits near the bottom of the page. */
+ dropdownPlacement?: 'top-start' | 'bottom-start'
}
slack: {
notificationType: NotificationType
@@ -167,6 +170,8 @@ function ExistingDestinations({
size="xsmall"
status="danger"
onClick={destination.onDelete}
+ loading={destination.deleting}
+ disabledReason={destination.deleting ? 'Deleting notification.' : undefined}
tooltip="Delete notification"
/>
</div>
@@ -307,6 +312,7 @@ export function AlertNotificationDestinationEditor<NotificationType extends stri
<div className="space-y-3 max-w-xl">
<LemonSelect
fullWidth
+ dropdownPlacement={notificationType.dropdownPlacement}
options={notificationType.options}
value={notificationType.value}
onChange={notificationType.onChange}
diff --git a/products/billing_alerts/README.md b/products/billing_alerts/README.md
index aa1d6cd5968b..64d7620082d4 100644
--- a/products/billing_alerts/README.md
+++ b/products/billing_alerts/README.md
@@ -9,3 +9,7 @@ Scheduled evaluation follows the shared alert delivery barrier: evaluate and pro
Billing follows the Logs alerting pattern: billing owns its evaluation rules, persistence adapter, and lifecycle message definitions. The shared alerting infrastructure handles lifecycle decisions, scheduling, grouped destination persistence, and event delivery.
The MCP server exposes atomic create and partial-update tools for billing alert configuration. They use the existing organization write scope and retain the API's organization Admin or Owner permission check.
+
+Billing alerts evaluate one UTC billing date every 24 hours. Alert configuration and destination changes are committed atomically through the generated billing API, while the shared alerting backend owns destination persistence and delivery.
+
+The Billing tab uses the shared alert editor, destination editor, advanced options, next-evaluation status, and evaluation-history chart from `products/alerts`. Billing supplies its own form, threshold labels, value formatting, API calls, and notification destination payloads.
diff --git a/products/billing_alerts/backend/alert_destinations.py b/products/billing_alerts/backend/alert_destinations.py
index b038ae9d2e3d..0aacf7bf7ff0 100644
--- a/products/billing_alerts/backend/alert_destinations.py
+++ b/products/billing_alerts/backend/alert_destinations.py
@@ -27,7 +27,7 @@ _BASE_DATA = {
"relative_delta_percentage": "{event.properties.relative_delta_percentage}",
"evaluation_date": "{event.properties.evaluation_date}",
"reason": "{event.properties.reason}",
- "alert_url": "{project.url}/organization/billing",
+ "alert_url": "{event.properties.alert_url}",
}
@@ -50,7 +50,7 @@ def _spec(
display_kind=display_kind,
header=header,
details=details,
- primary_action_url="{project.url}/organization/billing",
+ primary_action_url="{event.properties.alert_url}",
primary_action_label="View billing alert",
webhook_body={
"id": "{event.uuid}",
diff --git a/products/billing_alerts/backend/logic/notifications.py b/products/billing_alerts/backend/logic/notifications.py
index 978b8b139ca8..89597a5505bd 100644
--- a/products/billing_alerts/backend/logic/notifications.py
+++ b/products/billing_alerts/backend/logic/notifications.py
@@ -9,6 +9,7 @@ from django.utils import timezone
import structlog
from posthog.kafka_client.client import ProduceResult
+from posthog.utils import absolute_uri
from products.alerts.backend.destinations import (
alert_internal_event_delivered,
@@ -97,6 +98,7 @@ def _properties(event: BillingAlertEvent, now: datetime, *, consecutive_failures
return {
"alert_id": str(alert.id),
"alert_name": alert.name,
+ "alert_url": absolute_uri("/organization/billing/alerts"),
"metric": event.metric,
"threshold_type": alert.threshold_type,
"threshold_percentage": str(event.threshold_percentage_snapshot)
diff --git a/products/billing_alerts/backend/presentation/views.py b/products/billing_alerts/backend/presentation/views.py
index 6e79f41fbf5d..6dd866078ab4 100644
--- a/products/billing_alerts/backend/presentation/views.py
+++ b/products/billing_alerts/backend/presentation/views.py
@@ -15,7 +15,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.event_usage import report_user_action
from posthog.models.team.team import Team
from posthog.models.user import User
-from posthog.permissions import OrganizationAdminReadPermissions
+from posthog.permissions import OrganizationAdminReadPermissions, PostHogFeatureFlagPermission
from products.billing_alerts.backend.facade import api as billing_alerts_api
from products.billing_alerts.backend.facade.api import BillingAlertConfiguration
@@ -36,7 +36,10 @@ class BillingAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
queryset = BillingAlertConfiguration.objects.all()
serializer_class = BillingAlertConfigurationSerializer
lookup_field = "id"
- permission_classes = [OrganizationAdminReadPermissions]
+ # Server-side rollout boundary: gate the API behind the `billing-alerts` flag so the flag is a
+ # hard boundary, not just a UI toggle. Appended to the mixin's default permissions.
+ posthog_feature_flag = "billing-alerts"
+ permission_classes = [OrganizationAdminReadPermissions, PostHogFeatureFlagPermission]
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
return queryset.filter(organization_id=self.organization.id).order_by("-created_at")
diff --git a/products/billing_alerts/backend/test/test_alert_destinations.py b/products/billing_alerts/backend/test/test_alert_destinations.py
index 8e2b40acf724..4438e40f512f 100644
--- a/products/billing_alerts/backend/test/test_alert_destinations.py
+++ b/products/billing_alerts/backend/test/test_alert_destinations.py
@@ -7,7 +7,7 @@ from rest_framework import status
from posthog.models.organization import OrganizationMembership
-from products.billing_alerts.backend.alert_destinations import BILLING_ALERT_EVENT_IDS
+from products.billing_alerts.backend.alert_destinations import BILLING_ALERT_EVENT_IDS, EVENT_KIND_CONFIG
from products.billing_alerts.backend.models import BillingAlertConfiguration
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -19,6 +19,10 @@ class TestBillingAlertDestinations(APIBaseTest):
self.url = f"/api/organizations/{self.organization.id}/billing/alerts/"
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
+ # The API is gated behind the `billing-alerts` flag; enable it for the default test org.
+ ff_patcher = patch("posthoganalytics.feature_enabled", return_value=True)
+ ff_patcher.start()
+ self.addCleanup(ff_patcher.stop)
def _alert(self, name: str = "Period spend cap") -> BillingAlertConfiguration:
return BillingAlertConfiguration.objects.create(
@@ -172,6 +176,10 @@ class TestBillingAlertDestinations(APIBaseTest):
assert BillingAlertConfiguration.objects.filter(name="Atomic rollback").exists() is False
assert HogFunction.objects.filter(name__contains="Atomic rollback").exists() is False
+ def test_destination_links_use_the_organization_root_url_from_the_event(self) -> None:
+ assert all(config.primary_action_url == "{event.properties.alert_url}" for config in EVENT_KIND_CONFIG.values())
+ assert all("project.url}/organization" not in str(config) for config in EVENT_KIND_CONFIG.values())
+
def test_create_destination_rejects_duplicate_type(self) -> None:
self._sync_webhook_template()
alert = self._alert()
diff --git a/products/billing_alerts/backend/test/test_api.py b/products/billing_alerts/backend/test/test_api.py
index f0b76be7dcb3..9b785a981b6b 100644
--- a/products/billing_alerts/backend/test/test_api.py
+++ b/products/billing_alerts/backend/test/test_api.py
@@ -34,6 +34,10 @@ class TestBillingAlertAPI(APIBaseTest):
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
self.url = f"/api/organizations/{self.organization.id}/billing/alerts/"
+ # The API is gated behind the `billing-alerts` flag; enable it for the default test org.
+ ff_patcher = patch("posthoganalytics.feature_enabled", return_value=True)
+ ff_patcher.start()
+ self.addCleanup(ff_patcher.stop)
def _payload(self, **overrides) -> dict:
payload = {
@@ -323,6 +327,15 @@ class TestBillingAlertAPI(APIBaseTest):
assert len(data[1]["destinations"][0]["hog_function_ids"]) == len(EVENT_KIND_CONFIG)
assert data[2]["destinations"] == []
+ def test_api_is_gated_behind_billing_alerts_flag(self) -> None:
+ with patch("posthoganalytics.feature_enabled", return_value=False):
+ listed = self.client.get(self.url)
+ created = self.client.post(self.url, self._payload(), format="json")
+
+ assert listed.status_code == status.HTTP_403_FORBIDDEN
+ assert created.status_code == status.HTTP_403_FORBIDDEN
+ assert not BillingAlertConfiguration.objects.exists()
+
def test_non_admin_cannot_create(self) -> None:
self.organization_membership.level = OrganizationMembership.Level.MEMBER
self.organization_membership.save()
diff --git a/products/billing_alerts/backend/test/test_notifications.py b/products/billing_alerts/backend/test/test_notifications.py
index 062d6513fee8..faf90429560a 100644
--- a/products/billing_alerts/backend/test/test_notifications.py
+++ b/products/billing_alerts/backend/test/test_notifications.py
@@ -4,6 +4,8 @@ from decimal import Decimal
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
+from posthog.utils import absolute_uri
+
from products.billing_alerts.backend.alert_destinations import EVENT_KIND_CONFIG, EventKind
from products.billing_alerts.backend.logic.notifications import (
commit_pending_billing_alert_dispatch,
@@ -111,6 +113,7 @@ class TestBillingAlertNotifications(BaseTest):
assert event.targets_notified == {"hog_functions": [str(destination.id)]}
assert produce.call_args.kwargs["event_name"] == EVENT_KIND_CONFIG["firing"].event_id
assert produce.call_args.kwargs["uuid"] == str(event.claim.delivery_uuid)
+ assert produce.call_args.kwargs["properties"]["alert_url"] == absolute_uri("/organization/billing/alerts")
assert "billing_alert_destination_ids" not in produce.call_args.kwargs["properties"]
flush.assert_called_once()
delivered.assert_called_once_with(
diff --git a/products/billing_alerts/frontend/BillingAlertEditor.tsx b/products/billing_alerts/frontend/BillingAlertEditor.tsx
new file mode 100644
index 000000000000..457d71f0f242
--- /dev/null
+++ b/products/billing_alerts/frontend/BillingAlertEditor.tsx
@@ -0,0 +1,189 @@
+import { BindLogic, useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { IconPlay } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonSelect, LemonTextArea } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { AlertAdvancedOptions } from 'products/alerts/frontend/components/AlertAdvancedOptions'
+import { AlertDefinitionRow, AlertNextEvaluationStatus } from 'products/alerts/frontend/components/AlertDefinition'
+import {
+ AlertEditor,
+ AlertEditorFormDetails,
+ AlertEditorSection,
+} from 'products/alerts/frontend/components/AlertEditor'
+
+import { ADVANCED_OPTION_DEFAULTS, billingAlertFormLogic, BillingAlertFormLogicProps } from './billingAlertFormLogic'
+import { BillingAlertHistory } from './BillingAlertHistory'
+import { billingAlertNotificationLogic } from './billingAlertNotificationLogic'
+import { BillingAlertNotifications } from './BillingAlertNotifications'
+import { billingAlertsLogic } from './billingAlertsLogic'
+
+export function BillingAlertEditor(props: BillingAlertFormLogicProps): JSX.Element {
+ const notificationProps = { alert: props.alert }
+
+ return (
+ <BindLogic logic={billingAlertFormLogic} props={props}>
+ <BindLogic logic={billingAlertNotificationLogic} props={notificationProps}>
+ <BillingAlertEditorContent {...props} />
+ </BindLogic>
+ </BindLogic>
+ )
+}
+
+function BillingAlertEditorContent(props: BillingAlertFormLogicProps): JSX.Element {
+ const { alertForm, alertFormChanged, isAlertFormSubmitting } = useValues(billingAlertFormLogic)
+ const { setAlertFormValue } = useActions(billingAlertFormLogic)
+ const { pendingDestinations } = useValues(billingAlertNotificationLogic)
+ const { closeEditor, checkNow } = useActions(billingAlertsLogic)
+ const { checkingAlertId } = useValues(billingAlertsLogic)
+ const enabledAdvancedOptionsCount =
+ Number(alertForm.minimumValue > ADVANCED_OPTION_DEFAULTS.minimumValue) +
+ Number(alertForm.evaluationDelayHours !== ADVANCED_OPTION_DEFAULTS.evaluationDelayHours) +
+ Number(alertForm.cooldownHours !== ADVANCED_OPTION_DEFAULTS.cooldownHours)
+ const isPaused = props.alert !== null && !props.alert.enabled
+
+ return (
+ <Form
+ logic={billingAlertFormLogic}
+ props={props}
+ formKey="alertForm"
+ enableFormOnSubmit
+ data-attr="billing-alert-shared-editor-form"
+ >
+ <AlertEditor
+ title={props.alert ? 'Edit billing alert' : 'New billing alert'}
+ description="Billing alerts check your organization's billing-period spend once a day against a configured threshold."
+ onBack={closeEditor}
+ isEditing={props.alert !== null}
+ isSubmitting={isAlertFormSubmitting}
+ hasChanges={alertFormChanged}
+ hasPendingChanges={pendingDestinations.length > 0}
+ leadingActions={
+ props.alert ? (
+ <LemonButton
+ type="secondary"
+ icon={<IconPlay />}
+ onClick={() => checkNow(props.alert!)}
+ loading={checkingAlertId === props.alert.id}
+ tooltip={
+ isPaused
+ ? 'This alert is paused, so the check runs as a preview and does not send notifications.'
+ : undefined
+ }
+ disabledReason={
+ alertFormChanged || pendingDestinations.length > 0
+ ? 'Save your changes before checking.'
+ : isAlertFormSubmitting
+ ? 'Wait for the alert to finish saving.'
+ : undefined
+ }
+ data-attr="billing-alert-check-now"
+ >
+ {isPaused ? 'Preview check' : 'Check now'}
+ </LemonButton>
+ ) : undefined
+ }
+ contentClassName="space-y-6"
+ >
+ <div className="space-y-6 max-w-2xl" data-attr="billing-alert-shared-editor">
+ <AlertEditorFormDetails
+ enabled={{ checked: alertForm.enabled, dataAttr: 'billing-alert-enabled' }}
+ nameDataAttr="billing-alert-name"
+ />
+ <LemonField name="description" label="Internal note">
+ <LemonTextArea placeholder="Only visible in PostHog." />
+ </LemonField>
+
+ <AlertEditorSection
+ title="Definition"
+ description="You can choose when the daily check runs, but the underlying billing data updates once a day and usually settles around 8-10am UTC."
+ >
+ <div className="space-y-4" data-attr="billing-alert-definition">
+ <AlertDefinitionRow label="Alert on">
+ <LemonSelect
+ value={alertForm.metric}
+ onChange={(metric) => setAlertFormValue('metric', metric)}
+ options={[
+ { value: 'spend', label: 'Current period spend' },
+ { value: 'projected_spend', label: 'Projected period spend' },
+ ]}
+ size="small"
+ data-attr="billing-alert-metric"
+ />
+ <span className="text-sm">when it goes above</span>
+ <LemonField name="thresholdValue">
+ <LemonInput
+ type="number"
+ min={0}
+ value={alertForm.thresholdValue ?? undefined}
+ onChange={(value) => setAlertFormValue('thresholdValue', value ?? null)}
+ prefix={<span>$</span>}
+ className="w-32"
+ size="small"
+ data-attr="billing-alert-threshold-value"
+ />
+ </LemonField>
+ </AlertDefinitionRow>
+ <div className="text-xs text-secondary">
+ {alertForm.metric === 'projected_spend'
+ ? 'Projected period spend estimates what this billing period will cost by its end, after discounts.'
+ : 'Current period spend is what this billing period has cost so far, after discounts.'}
+ </div>
+ <AlertNextEvaluationStatus loading={false}>
+ {props.alert?.next_check_at
+ ? dayjs.utc(props.alert.next_check_at).format('MMM D, HH:mm [UTC]')
+ : 'after the alert is created'}
+ </AlertNextEvaluationStatus>
+ </div>
+ </AlertEditorSection>
+
+ <AlertEditorSection title="Notifications">
+ <BillingAlertNotifications alert={props.alert} />
+ </AlertEditorSection>
+
+ <AlertAdvancedOptions enabledCount={enabledAdvancedOptionsCount}>
+ <div
+ className="grid grid-cols-1 md:grid-cols-2 gap-3"
+ data-attr="billing-alert-advanced-options"
+ >
+ <LemonField name="minimumValue" label="Minimum current value">
+ <LemonInput
+ type="number"
+ min={0}
+ value={alertForm.minimumValue}
+ onChange={(value) => setAlertFormValue('minimumValue', value ?? 0)}
+ prefix={<span>$</span>}
+ />
+ </LemonField>
+ <LemonField name="evaluationDelayHours" label="Evaluation delay">
+ <LemonInput
+ type="number"
+ min={0}
+ max={72}
+ value={alertForm.evaluationDelayHours}
+ onChange={(value) => setAlertFormValue('evaluationDelayHours', value ?? 0)}
+ suffix={<span>hours</span>}
+ />
+ </LemonField>
+ <LemonField name="cooldownHours" label="Notification cooldown">
+ <LemonInput
+ type="number"
+ min={0}
+ max={720}
+ value={alertForm.cooldownHours}
+ onChange={(value) => setAlertFormValue('cooldownHours', value ?? 0)}
+ suffix={<span>hours</span>}
+ />
+ </LemonField>
+ </div>
+ </AlertAdvancedOptions>
+
+ {props.alert ? <BillingAlertHistory alert={props.alert} /> : null}
+ </div>
+ </AlertEditor>
+ </Form>
+ )
+}
diff --git a/products/billing_alerts/frontend/BillingAlertHistory.test.ts b/products/billing_alerts/frontend/BillingAlertHistory.test.ts
new file mode 100644
index 000000000000..06e8fd1c395d
--- /dev/null
+++ b/products/billing_alerts/frontend/BillingAlertHistory.test.ts
@@ -0,0 +1,80 @@
+import { eventValue, historyPoint, wouldFire } from './BillingAlertHistory'
+import type { BillingAlertConfigurationApi, BillingAlertEventApi } from './generated/api.schemas'
+
+function alert(
+ thresholdType: BillingAlertConfigurationApi['threshold_type'],
+ minimumValue = '0'
+): BillingAlertConfigurationApi {
+ return {
+ threshold_type: thresholdType,
+ threshold_percentage: '50',
+ threshold_value: '100',
+ minimum_value: minimumValue,
+ configuration_revision: 2,
+ } as unknown as BillingAlertConfigurationApi
+}
+
+function event(overrides: Partial<BillingAlertEventApi>): BillingAlertEventApi {
+ return {
+ current_value: '150',
+ absolute_delta: '100',
+ relative_delta_percentage: '75',
+ kind: 'check',
+ created_at: '2026-07-21T08:00:00Z',
+ configuration_revision: 2,
+ ...overrides,
+ } as BillingAlertEventApi
+}
+
+describe('billing alert history classification', () => {
+ it('does not chart missing values as zero', () => {
+ expect(eventValue(alert('relative_increase'), event({ relative_delta_percentage: null }))).toBeNull()
+ expect(eventValue(alert('absolute_value'), event({ current_value: null }))).toBeNull()
+ })
+
+ it('does not classify an incomplete baseline as firing', () => {
+ expect(
+ wouldFire(
+ { ...alert('absolute_increase'), threshold_value: '0' },
+ event({ current_value: '150', absolute_delta: null })
+ )
+ ).toBe(false)
+ })
+
+ it.each([
+ ['relative_increase', { current_value: '99', relative_delta_percentage: '500' }],
+ ['absolute_value', { current_value: '99' }],
+ ['absolute_increase', { current_value: '99', absolute_delta: '500' }],
+ ] as const)('applies the minimum current value to %s alerts', (thresholdType, values) => {
+ expect(wouldFire(alert(thresholdType, '100'), event(values))).toBe(false)
+ })
+
+ it('classifies a complete value that clears both gates', () => {
+ expect(wouldFire(alert('relative_increase', '100'), event({ current_value: '150' }))).toBe(true)
+ })
+
+ it.each(['check', 'errored'] as const)('does not mark %s events as firing edges', (kind) => {
+ expect(historyPoint(alert('relative_increase'), event({ kind, state_after: 'firing' }))?.firedAtTime).toBe(
+ false
+ )
+ })
+
+ it('marks only firing events as firing edges', () => {
+ expect(historyPoint(alert('relative_increase'), event({ kind: 'firing' }))?.firedAtTime).toBe(true)
+ })
+
+ it('classifies against the current rule only for the same configuration revision', () => {
+ expect(
+ historyPoint(
+ alert('relative_increase'),
+ event({ configuration_revision: 2 } as Partial<BillingAlertEventApi>)
+ )?.wouldFireUnderCurrentConfiguration
+ ).toBe(true)
+ expect(
+ historyPoint(
+ alert('relative_increase'),
+ event({ configuration_revision: 1 } as Partial<BillingAlertEventApi>)
+ )?.wouldFireUnderCurrentConfiguration
+ ).toBeNull()
+ })
+})
diff --git a/products/billing_alerts/frontend/BillingAlertHistory.tsx b/products/billing_alerts/frontend/BillingAlertHistory.tsx
new file mode 100644
index 000000000000..ffe29950a218
--- /dev/null
+++ b/products/billing_alerts/frontend/BillingAlertHistory.tsx
@@ -0,0 +1,161 @@
+import { BindLogic, useActions, useValues } from 'kea'
+
+import { LemonTable, LemonTableColumns, LemonTag, LemonTagType } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs } from 'lib/dayjs'
+
+import { AlertEditorSection } from 'products/alerts/frontend/components/AlertEditor'
+import {
+ AlertEvaluationHistoryChart,
+ AlertEvaluationHistoryPoint,
+ AlertEvaluationThreshold,
+} from 'products/alerts/frontend/components/AlertEvaluationHistoryChart'
+
+import { formatBillingValue, thresholdView } from './billingAlertDisplay'
+import { billingAlertHistoryLogic, HISTORY_PAGE_SIZE } from './billingAlertHistoryLogic'
+import type { BillingAlertConfigurationApi, BillingAlertEventApi } from './generated/api.schemas'
+
+export function eventValue(alert: BillingAlertConfigurationApi, event: BillingAlertEventApi): number | null {
+ return thresholdView(alert).pickEventValue(event)
+}
+
+export function wouldFire(alert: BillingAlertConfigurationApi, event: BillingAlertEventApi): boolean {
+ if (event.current_value === null || event.current_value === undefined) {
+ return false
+ }
+ const current = Number(event.current_value)
+ const minimum = Number(alert.minimum_value ?? 0)
+ if (!Number.isFinite(current) || current < minimum) {
+ return false
+ }
+ const view = thresholdView(alert)
+ const value = view.pickEventValue(event)
+ if (value === null || view.thresholdValue === null) {
+ return false
+ }
+ return value >= view.thresholdValue
+}
+
+function chartThreshold(alert: BillingAlertConfigurationApi): AlertEvaluationThreshold[] {
+ const view = thresholdView(alert)
+ if (view.thresholdValue === null) {
+ return []
+ }
+ return [{ direction: 'upper', value: view.thresholdValue, label: view.thresholdLabel }]
+}
+
+export function historyPoint(
+ alert: BillingAlertConfigurationApi,
+ event: BillingAlertEventApi
+): AlertEvaluationHistoryPoint | null {
+ const value = eventValue(alert, event)
+ if (value === null) {
+ return null
+ }
+ return {
+ label: dayjs(event.created_at).format('MMM D, HH:mm'),
+ value,
+ firedAtTime: event.kind === 'firing',
+ wouldFireUnderCurrentConfiguration:
+ event.configuration_revision === alert.configuration_revision ? wouldFire(alert, event) : null,
+ }
+}
+
+function chartPoints(
+ alert: BillingAlertConfigurationApi,
+ events: BillingAlertEventApi[]
+): AlertEvaluationHistoryPoint[] {
+ return events
+ .slice()
+ .sort((left, right) => left.created_at.localeCompare(right.created_at))
+ .map((event) => historyPoint(alert, event))
+ .filter((point): point is AlertEvaluationHistoryPoint => point !== null)
+}
+
+function eventTag(event: BillingAlertEventApi): { label: string; type: LemonTagType } {
+ if (event.kind === 'firing') {
+ return { label: 'Fired', type: 'danger' }
+ }
+ if (event.kind === 'resolved') {
+ return { label: 'Resolved', type: 'success' }
+ }
+ if (event.kind === 'errored' || event.kind === 'broken_config') {
+ return { label: event.kind === 'errored' ? 'Errored' : 'Auto-disabled', type: 'warning' }
+ }
+ return { label: 'Check', type: 'default' }
+}
+
+export function BillingAlertHistory({ alert }: { alert: BillingAlertConfigurationApi }): JSX.Element {
+ return (
+ <BindLogic logic={billingAlertHistoryLogic} props={{ alertId: alert.id }}>
+ <BillingAlertHistoryContent alert={alert} />
+ </BindLogic>
+ )
+}
+
+function BillingAlertHistoryContent({ alert }: { alert: BillingAlertConfigurationApi }): JSX.Element {
+ const { currentPage, eventsPage, eventsPageLoading } = useValues(billingAlertHistoryLogic)
+ const { loadMoreEvents, loadPreviousEvents } = useActions(billingAlertHistoryLogic)
+ const view = thresholdView(alert)
+ // The chart claims to show the most recent evaluations, so only render it from first-page data.
+ const points = currentPage === 1 ? chartPoints(alert, eventsPage.results) : []
+ const columns: LemonTableColumns<BillingAlertEventApi> = [
+ {
+ title: 'Event',
+ render: (_, event) => {
+ const tag = eventTag(event)
+ return <LemonTag type={tag.type}>{tag.label}</LemonTag>
+ },
+ },
+ {
+ title: 'When',
+ render: (_, event) => <TZLabel time={event.created_at} formatDate="MMM D" formatTime="HH:mm:ss" />,
+ },
+ {
+ title: 'Value',
+ render: (_, event) => formatBillingValue(event.current_value, event.metric, alert.currency),
+ },
+ {
+ title: 'Reason',
+ render: (_, event) => <span className="text-xs text-secondary">{event.reason}</span>,
+ },
+ ]
+
+ return (
+ <AlertEditorSection title="History" description="Evaluations, transitions, errors, and notifications.">
+ <div data-attr="billing-alert-history" className="space-y-4">
+ {points.length > 0 ? (
+ <AlertEvaluationHistoryChart
+ points={points}
+ valueLabel={view.valueLabel}
+ thresholds={chartThreshold(alert)}
+ historyLimit={HISTORY_PAGE_SIZE}
+ evaluationsTotal={eventsPage.count}
+ evaluationNoun="evaluation"
+ tableAvailable
+ formatValue={view.format}
+ />
+ ) : null}
+ <LemonTable
+ columns={columns}
+ dataSource={eventsPage.results}
+ rowKey="id"
+ loading={eventsPageLoading}
+ size="small"
+ emptyState="No evaluations yet."
+ nouns={['evaluation', 'evaluations']}
+ pagination={{
+ controlled: true,
+ hideOnSinglePage: false,
+ currentPage,
+ pageSize: HISTORY_PAGE_SIZE,
+ entryCount: eventsPage.count,
+ onForward: eventsPage.next ? () => loadMoreEvents(undefined) : undefined,
+ onBackward: eventsPage.previous ? () => loadPreviousEvents(undefined) : undefined,
+ }}
+ />
+ </div>
+ </AlertEditorSection>
+ )
+}
diff --git a/products/billing_alerts/frontend/BillingAlertNotifications.tsx b/products/billing_alerts/frontend/BillingAlertNotifications.tsx
new file mode 100644
index 000000000000..1bfd213892fb
--- /dev/null
+++ b/products/billing_alerts/frontend/BillingAlertNotifications.tsx
@@ -0,0 +1,110 @@
+import { useActions, useValues } from 'kea'
+
+import {
+ AlertNotificationDestinationEditor,
+ AlertNotificationDestinationView,
+ PendingAlertNotificationDestinationView,
+} from 'products/alerts/frontend/components/AlertNotificationDestinationEditor'
+
+import { destinationLabel } from './billingAlertDisplay'
+import {
+ BillingAlertNotificationLogicProps,
+ BillingAlertNotificationType,
+ billingAlertNotificationLogic,
+} from './billingAlertNotificationLogic'
+import { destinationKey } from './billingAlertUtils'
+
+const DESTINATION_OPTIONS = [
+ { value: 'slack' as const, label: 'Slack' },
+ { value: 'teams' as const, label: 'Microsoft Teams' },
+ { value: 'webhook' as const, label: 'Webhook' },
+]
+
+export function BillingAlertNotifications(props: BillingAlertNotificationLogicProps): JSX.Element {
+ const logic = billingAlertNotificationLogic(props)
+ const {
+ pendingDestinations,
+ selectedType,
+ integrationsLoading,
+ integrationsFailed,
+ slackIntegrations,
+ selectedSlackIntegration,
+ slackChannel,
+ webhookUrl,
+ addDisabledReason,
+ deletingDestinationKeys,
+ } = useValues(logic)
+ const {
+ setSelectedType,
+ setSelectedIntegrationId,
+ setSlackChannel,
+ setWebhookUrl,
+ addSelectedDestination,
+ removePendingDestination,
+ deleteDestination,
+ loadIntegrations,
+ } = useActions(logic)
+
+ const existingDestinations: AlertNotificationDestinationView[] = (props.alert?.destinations ?? []).map(
+ (destination) => ({
+ key: destinationKey(destination),
+ title: destinationLabel(destination.type),
+ detail: 'Firing, resolved, errored, and auto-disabled notifications',
+ tags: [{ label: 'Active', type: 'success' }],
+ onDelete: () => deleteDestination(destination),
+ deleting: deletingDestinationKeys.has(destinationKey(destination)),
+ })
+ )
+ const pendingViews: PendingAlertNotificationDestinationView[] = pendingDestinations.map((destination) => ({
+ key: destination.key,
+ title: destination.label,
+ detail: 'Save the alert to apply this notification',
+ onRemove: () => removePendingDestination(destination.key),
+ }))
+
+ return (
+ <div data-attr="billing-alert-notifications">
+ <AlertNotificationDestinationEditor<BillingAlertNotificationType>
+ description="Each destination receives firing, resolved, errored, and auto-disabled notifications."
+ destinations={{
+ showExisting: true,
+ existingLoading: false,
+ existing: existingDestinations,
+ pending: pendingViews,
+ }}
+ notificationType={{
+ options: DESTINATION_OPTIONS,
+ value: selectedType,
+ onChange: setSelectedType,
+ dropdownPlacement: 'top-start',
+ }}
+ slack={{
+ notificationType: 'slack',
+ integrationsLoading,
+ integrationsFailed,
+ onRetryIntegrations: loadIntegrations,
+ integrations: slackIntegrations,
+ integration: selectedSlackIntegration,
+ onIntegrationChange: setSelectedIntegrationId,
+ channelValue: slackChannel,
+ onChannelValueChange: setSlackChannel,
+ }}
+ url={
+ selectedType === 'slack'
+ ? undefined
+ : {
+ input: {
+ placeholder:
+ selectedType === 'teams'
+ ? 'https://<region>.logic.azure.com/...'
+ : 'https://example.com/webhook',
+ },
+ value: webhookUrl,
+ onChange: setWebhookUrl,
+ }
+ }
+ add={{ onClick: addSelectedDestination, disabledReason: addDisabledReason }}
+ />
+ </div>
+ )
+}
diff --git a/products/billing_alerts/frontend/BillingAlerts.tsx b/products/billing_alerts/frontend/BillingAlerts.tsx
new file mode 100644
index 000000000000..9345fdd854ec
--- /dev/null
+++ b/products/billing_alerts/frontend/BillingAlerts.tsx
@@ -0,0 +1,17 @@
+import { useValues } from 'kea'
+
+import { BillingAlertEditor } from './BillingAlertEditor'
+import { BillingAlertsList } from './BillingAlertsList'
+import { billingAlertsLogic } from './billingAlertsLogic'
+
+export function BillingAlerts(): JSX.Element {
+ const { canAccessBilling, selectedAlert, isEditorOpen } = useValues(billingAlertsLogic)
+
+ if (!canAccessBilling) {
+ return <div>You need billing access to manage billing alerts.</div>
+ }
+ if (isEditorOpen) {
+ return <BillingAlertEditor alert={selectedAlert} />
+ }
+ return <BillingAlertsList />
+}
diff --git a/products/billing_alerts/frontend/BillingAlertsList.tsx b/products/billing_alerts/frontend/BillingAlertsList.tsx
new file mode 100644
index 000000000000..9788eacee316
--- /dev/null
+++ b/products/billing_alerts/frontend/BillingAlertsList.tsx
@@ -0,0 +1,128 @@
+import { useActions, useValues } from 'kea'
+
+import { IconBell, IconPlay, IconPlus } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonTable, LemonTag } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { More } from 'lib/lemon-ui/LemonButton/More'
+import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'
+import type { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
+
+import { destinationLabel, metricLabel, stateLabel, stateTagType, thresholdDescription } from './billingAlertDisplay'
+import { billingAlertsLogic } from './billingAlertsLogic'
+import type { BillingAlertConfigurationApi } from './generated/api.schemas'
+
+export function BillingAlertsList(): JSX.Element {
+ const { alerts, alertsPage, alertsPageLoading, checkingAlertId, deletingAlertIds } = useValues(billingAlertsLogic)
+ const { createAlert, editAlert, checkNow, deleteAlert, loadMoreAlerts } = useActions(billingAlertsLogic)
+ const columns: LemonTableColumns<BillingAlertConfigurationApi> = [
+ {
+ title: 'Alert',
+ render: (_, alert) => (
+ <LemonTableLink
+ title={alert.name}
+ description={`${metricLabel(alert.metric)} · ${thresholdDescription(alert)}`}
+ onClick={() => editAlert(alert)}
+ />
+ ),
+ },
+ {
+ title: 'Destinations',
+ render: (_, alert) =>
+ alert.destinations.length > 0 ? (
+ <div className="flex gap-1 flex-wrap">
+ {alert.destinations.map((destination) => (
+ <LemonTag key={destination.type} size="small">
+ {destinationLabel(destination.type)}
+ </LemonTag>
+ ))}
+ </div>
+ ) : (
+ 'None'
+ ),
+ },
+ {
+ title: 'Last checked',
+ render: (_, alert) => (alert.last_checked_at ? dayjs(alert.last_checked_at).fromNow() : 'Never'),
+ },
+ {
+ title: 'Status',
+ render: (_, alert) => <LemonTag type={stateTagType(alert)}>{stateLabel(alert)}</LemonTag>,
+ },
+ {
+ width: 0,
+ render: (_, alert) => (
+ <More
+ overlay={
+ <LemonMenuOverlay
+ items={[
+ { label: 'Edit', onClick: () => editAlert(alert) },
+ {
+ label: 'Check now',
+ icon: <IconPlay />,
+ disabledReason: checkingAlertId
+ ? checkingAlertId === alert.id
+ ? 'Check in progress.'
+ : 'Another alert is checking.'
+ : undefined,
+ onClick: () => checkNow(alert),
+ },
+ {
+ label: 'Delete',
+ status: 'danger',
+ disabledReason: deletingAlertIds.has(alert.id) ? 'Deleting.' : undefined,
+ onClick: () =>
+ LemonDialog.open({
+ title: 'Delete billing alert?',
+ description: `This deletes “${alert.name}” and its notification destinations.`,
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deleteAlert(alert),
+ },
+ secondaryButton: { children: 'Cancel' },
+ }),
+ },
+ ]}
+ />
+ }
+ />
+ ),
+ },
+ ]
+
+ return (
+ <div className="space-y-4" data-attr="billing-alerts-view">
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <h2 className="m-0 flex items-center gap-2">
+ <IconBell /> Billing alerts
+ </h2>
+ <p className="text-secondary mb-0 mt-1">
+ Get notified when organization spend crosses a threshold.
+ </p>
+ </div>
+ <LemonButton type="primary" icon={<IconPlus />} onClick={createAlert} data-attr="new-billing-alert">
+ New alert
+ </LemonButton>
+ </div>
+ <LemonTable
+ dataSource={alerts}
+ columns={columns}
+ rowKey="id"
+ loading={alertsPageLoading}
+ nouns={['billing alert', 'billing alerts']}
+ emptyState="No billing alerts yet."
+ data-attr="billing-alerts-table"
+ />
+ {alertsPage.next ? (
+ <div className="flex justify-center">
+ <LemonButton type="secondary" loading={alertsPageLoading} onClick={loadMoreAlerts}>
+ Load more alerts
+ </LemonButton>
+ </div>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/billing_alerts/frontend/billingAlertDisplay.ts b/products/billing_alerts/frontend/billingAlertDisplay.ts
new file mode 100644
index 000000000000..dd1ffa7975e0
--- /dev/null
+++ b/products/billing_alerts/frontend/billingAlertDisplay.ts
@@ -0,0 +1,120 @@
+import type {
+ BillingAlertConfigurationApi,
+ BillingAlertEventApi,
+ BillingAlertMetricEnumApi,
+ NotificationDestinationTypeEnumApi,
+} from './generated/api.schemas'
+
+export function metricLabel(metric: BillingAlertMetricEnumApi | undefined): string {
+ return metric === 'projected_spend' ? 'Projected period spend' : 'Current period spend'
+}
+
+export function formatBillingValue(
+ value: string | number | null | undefined,
+ metric: BillingAlertMetricEnumApi | undefined,
+ currency = 'USD'
+): string {
+ if (value === null || value === undefined) {
+ return '–'
+ }
+ const number = Number(value)
+ if (!Number.isFinite(number)) {
+ return String(value)
+ }
+ if (metric === 'spend' || metric === 'projected_spend') {
+ return new Intl.NumberFormat(undefined, {
+ style: 'currency',
+ currency,
+ maximumFractionDigits: 2,
+ }).format(number)
+ }
+ return number.toLocaleString(undefined, { maximumFractionDigits: 2 })
+}
+
+export function thresholdDescription(alert: BillingAlertConfigurationApi): string {
+ if (alert.threshold_type === 'relative_increase') {
+ return `${alert.threshold_percentage ?? 0}% over the ${alert.baseline_window_days ?? 7}-day baseline`
+ }
+ const value = formatBillingValue(alert.threshold_value, alert.metric, alert.currency)
+ return alert.threshold_type === 'absolute_increase' ? `${value} above baseline` : `Above ${value}`
+}
+
+export function stateLabel(alert: BillingAlertConfigurationApi): string {
+ if (alert.state === 'broken') {
+ return 'Auto-disabled'
+ }
+ if (!alert.enabled) {
+ return 'Paused'
+ }
+ return alert.state.replaceAll('_', ' ')
+}
+
+export function stateTagType(alert: BillingAlertConfigurationApi): 'success' | 'danger' | 'warning' | 'muted' {
+ if (alert.state === 'broken' || alert.state === 'firing') {
+ return 'danger'
+ }
+ if (!alert.enabled) {
+ return 'muted'
+ }
+ if (alert.state === 'errored' || alert.state === 'snoozed') {
+ return 'warning'
+ }
+ return 'success'
+}
+
+export interface BillingAlertThresholdView {
+ /** Numeric threshold under the current configuration, or null when unparsable. */
+ thresholdValue: number | null
+ thresholdLabel: string
+ valueLabel: string
+ pickEventValue: (event: BillingAlertEventApi) => number | null
+ format: (value: number) => string
+}
+
+/** Single home for threshold-type dispatch: which event field to plot, how to label and format it. */
+export function thresholdView(alert: BillingAlertConfigurationApi): BillingAlertThresholdView {
+ const isRelative = alert.threshold_type === 'relative_increase'
+ const rawThreshold = Number(isRelative ? alert.threshold_percentage : alert.threshold_value)
+ // Label off the guarded value so an unparsable threshold reads as "–" rather than "NaN".
+ const thresholdValue = Number.isFinite(rawThreshold) ? rawThreshold : null
+ return {
+ thresholdValue,
+ thresholdLabel:
+ thresholdValue === null
+ ? '–'
+ : isRelative
+ ? `${thresholdValue}% increase`
+ : formatBillingValue(thresholdValue, alert.metric, alert.currency),
+ valueLabel: isRelative
+ ? 'Increase'
+ : alert.threshold_type === 'absolute_increase'
+ ? 'Increase over baseline'
+ : metricLabel(alert.metric),
+ pickEventValue: (event: BillingAlertEventApi): number | null => {
+ const value = isRelative
+ ? event.relative_delta_percentage
+ : alert.threshold_type === 'absolute_increase'
+ ? event.absolute_delta
+ : event.current_value
+ if (value === null || value === undefined) {
+ return null
+ }
+ const parsed = Number(value)
+ return Number.isFinite(parsed) ? parsed : null
+ },
+ format: (value: number): string =>
+ isRelative
+ ? `${value.toLocaleString(undefined, { maximumFractionDigits: 2 })}%`
+ : formatBillingValue(value, alert.metric, alert.currency),
+ }
+}
+
+export function destinationLabel(type: NotificationDestinationTypeEnumApi): string {
+ if (type === 'slack') {
+ return 'Slack'
+ }
+ if (type === 'teams') {
+ return 'Microsoft Teams'
+ }
+ return 'Webhook'
+}
diff --git a/products/billing_alerts/frontend/billingAlertFormLogic.test.ts b/products/billing_alerts/frontend/billingAlertFormLogic.test.ts
new file mode 100644
index 000000000000..d34a1fb9b67b
--- /dev/null
+++ b/products/billing_alerts/frontend/billingAlertFormLogic.test.ts
@@ -0,0 +1,56 @@
+import { ApiError } from 'lib/api'
+
+import { billingAlertSaveErrorMessage, billingAlertWritePayload, formErrorsFromApiError } from './billingAlertFormLogic'
+
+describe('billing alert form server errors', () => {
+ it('maps DRF field errors onto the form', () => {
+ const error = new ApiError('Bad request', 400, undefined, {
+ name: ['Ensure this field has no more than 160 characters.'],
+ threshold_value: ['A valid number is required.'],
+ })
+
+ expect(formErrorsFromApiError(error)).toEqual({
+ name: 'Ensure this field has no more than 160 characters.',
+ thresholdValue: 'A valid number is required.',
+ })
+ })
+
+ it('sends pending destinations in the atomic configuration write', () => {
+ const payload = billingAlertWritePayload(
+ {
+ name: 'Period spend cap',
+ description: '',
+ enabled: true,
+ metric: 'projected_spend',
+ thresholdValue: 100,
+ minimumValue: 0,
+ evaluationDelayHours: 6,
+ cooldownHours: 24,
+ },
+ [
+ {
+ key: 'webhook',
+ label: 'Webhook',
+ payload: { type: 'webhook', webhook_url: 'https://example.com/alerts' },
+ },
+ ]
+ )
+
+ expect(payload.enabled).toBe(true)
+ expect(payload.metric).toBe('projected_spend')
+ expect(payload.threshold_type).toBe('absolute_value')
+ expect(payload.destination_changes).toEqual({
+ create: [{ type: 'webhook', webhook_url: 'https://example.com/alerts' }],
+ })
+ })
+
+ it('surfaces nested destination validation instead of a generic transport error', () => {
+ const error = new ApiError('Bad request', 400, undefined, {
+ destination_changes: {
+ create: [{ webhook_url: ['Enter a supported Microsoft Teams webhook URL.'] }],
+ },
+ })
+
+ expect(billingAlertSaveErrorMessage(error)).toBe('Enter a supported Microsoft Teams webhook URL.')
+ })
+})
diff --git a/products/billing_alerts/frontend/billingAlertFormLogic.ts b/products/billing_alerts/frontend/billingAlertFormLogic.ts
new file mode 100644
index 000000000000..1806ad913e68
--- /dev/null
+++ b/products/billing_alerts/frontend/billingAlertFormLogic.ts
@@ -0,0 +1,293 @@
+import { MakeLogicType, afterMount, connect, kea, key, path, props } from 'kea'
+import { forms } from 'kea-forms'
+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { ApiError } from 'lib/api'
+import { billingLogic } from 'scenes/billing/billingLogic'
+
+import type { OrganizationType } from '~/types'
+
+import { billingAlertNotificationLogic } from './billingAlertNotificationLogic'
+import type { PendingBillingAlertDestination } from './billingAlertNotificationLogic'
+import { billingAlertsLogic } from './billingAlertsLogic'
+import { billingAlertRequestError } from './billingAlertUtils'
+import { billingAlertsCreate, billingAlertsPartialUpdate } from './generated/api'
+import type {
+ BillingAlertConfigurationApi,
+ BillingAlertMetricEnumApi,
+ PatchedBillingAlertConfigurationApi,
+} from './generated/api.schemas'
+
+export interface BillingAlertFormValues {
+ name: string
+ description: string
+ enabled: boolean
+ metric: BillingAlertMetricEnumApi
+ /** null while the input is cleared, so an empty threshold fails validation instead of saving as 0. */
+ thresholdValue: number | null
+ minimumValue: number
+ evaluationDelayHours: number
+ cooldownHours: number
+}
+
+export interface BillingAlertFormLogicProps {
+ alert: BillingAlertConfigurationApi | null
+}
+
+const API_FIELD_TO_FORM_FIELD: Record<string, keyof BillingAlertFormValues> = {
+ name: 'name',
+ description: 'description',
+ enabled: 'enabled',
+ metric: 'metric',
+ threshold_value: 'thresholdValue',
+ minimum_value: 'minimumValue',
+ evaluation_delay_hours: 'evaluationDelayHours',
+ cooldown_hours: 'cooldownHours',
+}
+
+function firstErrorMessage(value: unknown): string | undefined {
+ if (typeof value === 'string') {
+ return value
+ }
+ if (Array.isArray(value)) {
+ return value.map(firstErrorMessage).find(Boolean)
+ }
+ if (value && typeof value === 'object') {
+ return Object.values(value).map(firstErrorMessage).find(Boolean)
+ }
+ return undefined
+}
+
+export function formErrorsFromApiError(error: unknown): Record<string, string> {
+ if (!(error instanceof ApiError) || !error.data || typeof error.data !== 'object' || Array.isArray(error.data)) {
+ return {}
+ }
+ return Object.fromEntries(
+ Object.entries(error.data)
+ .map(([field, value]) => {
+ const formField = API_FIELD_TO_FORM_FIELD[field]
+ const message = firstErrorMessage(value)
+ return formField && message ? [formField, message] : null
+ })
+ .filter((entry): entry is [string, string] => entry !== null)
+ )
+}
+
+export function billingAlertSaveErrorMessage(error: unknown): string {
+ if (error instanceof ApiError && !error.detail) {
+ const fieldMessage = firstErrorMessage(error.data)
+ if (fieldMessage) {
+ return fieldMessage
+ }
+ }
+ return billingAlertRequestError(error, 'Failed to save billing alert.')
+}
+
+function numberValue(value: string | null | undefined, fallback: number): number {
+ const parsed = Number(value)
+ return Number.isFinite(parsed) ? parsed : fallback
+}
+
+// Shared with the editor's advanced-options badge, which counts fields diverging from these.
+export const ADVANCED_OPTION_DEFAULTS = {
+ minimumValue: 0,
+ evaluationDelayHours: 6,
+ cooldownHours: 24,
+} as const
+
+function formDefaults(alert: BillingAlertConfigurationApi | null): BillingAlertFormValues {
+ return {
+ name: alert?.name ?? '',
+ description: alert?.description ?? '',
+ enabled: alert?.enabled ?? true,
+ metric: alert?.metric ?? 'spend',
+ thresholdValue: numberValue(alert?.threshold_value, 100),
+ minimumValue: numberValue(alert?.minimum_value, ADVANCED_OPTION_DEFAULTS.minimumValue),
+ evaluationDelayHours: alert?.evaluation_delay_hours ?? ADVANCED_OPTION_DEFAULTS.evaluationDelayHours,
+ cooldownHours: alert?.cooldown_hours ?? ADVANCED_OPTION_DEFAULTS.cooldownHours,
+ }
+}
+
+export function billingAlertWritePayload(
+ form: BillingAlertFormValues,
+ pending: PendingBillingAlertDestination[]
+): PatchedBillingAlertConfigurationApi {
+ return {
+ name: form.name.trim(),
+ description: form.description.trim(),
+ enabled: form.enabled,
+ metric: form.metric,
+ threshold_type: 'absolute_value',
+ // Validation rejects a null threshold before submit, so fall back to 0 only for typing.
+ threshold_value: String(form.thresholdValue ?? 0),
+ minimum_value: String(form.minimumValue),
+ evaluation_delay_hours: form.evaluationDelayHours,
+ cooldown_hours: form.cooldownHours,
+ ...(pending.length > 0 ? { destination_changes: { create: pending.map(({ payload }) => payload) } } : {}),
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface billingAlertFormLogicValues {
+ pendingDestinations: PendingBillingAlertDestination[] // billingAlertNotificationLogic
+ currentOrganization: OrganizationType | null // billingLogic
+ alertForm: BillingAlertFormValues
+ alertFormAllErrors: Record<string, any>
+ alertFormChanged: boolean
+ alertFormErrors: DeepPartialMap<BillingAlertFormValues, ValidationErrorType>
+ alertFormHasErrors: boolean
+ alertFormManualErrors: Record<string, any>
+ alertFormTouched: boolean
+ alertFormTouches: Record<string, boolean>
+ alertFormValidationErrors: DeepPartialMap<BillingAlertFormValues, ValidationErrorType>
+ isAlertFormSubmitting: boolean
+ isAlertFormValid: boolean
+ showAlertFormErrors: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface billingAlertFormLogicActions {
+ clearCreatedDestinations: (keys: string[]) => {
+ keys: string[]
+ } // billingAlertNotificationLogic
+ closeEditor: () => {
+ value: true
+ } // billingAlertsLogic
+ loadAlerts: () => void // billingAlertsLogic
+ resetAlertForm: (values?: BillingAlertFormValues) => {
+ values?: BillingAlertFormValues
+ }
+ setAlertFormManualErrors: (errors: Record<string, any>) => {
+ errors: Record<string, any>
+ }
+ setAlertFormValue: (
+ key: FieldName,
+ value: any
+ ) => {
+ name: FieldName
+ value: any
+ }
+ setAlertFormValues: (values: DeepPartial<BillingAlertFormValues>) => {
+ values: DeepPartial<BillingAlertFormValues>
+ }
+ submitAlertForm: () => {
+ value: boolean
+ }
+ submitAlertFormFailure: (
+ error: Error,
+ errors: Record<string, any>
+ ) => {
+ error: Error
+ errors: Record<string, any>
+ }
+ submitAlertFormRequest: (alertForm: BillingAlertFormValues) => {
+ alertForm: BillingAlertFormValues
+ }
+ submitAlertFormSuccess: (alertForm: BillingAlertFormValues) => {
+ alertForm: BillingAlertFormValues
+ }
+ touchAlertFormField: (key: string) => {
+ key: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface billingAlertFormLogicMeta {
+ key: string
+}
+
+export type billingAlertFormLogicType = MakeLogicType<
+ billingAlertFormLogicValues,
+ billingAlertFormLogicActions,
+ BillingAlertFormLogicProps,
+ billingAlertFormLogicMeta
+>
+
+export const billingAlertFormLogic = kea<billingAlertFormLogicType>([
+ path(['products', 'billingAlerts', 'frontend', 'billingAlertFormLogic']),
+ props({} as BillingAlertFormLogicProps),
+ key(({ alert }) => alert?.id ?? 'new'),
+ // The notification logic shares this logic's key, so both connect to the same instance
+ // BindLogic mounts in BillingAlertEditor.
+ connect((props: BillingAlertFormLogicProps) => ({
+ values: [billingLogic, ['currentOrganization'], billingAlertNotificationLogic(props), ['pendingDestinations']],
+ actions: [
+ billingAlertsLogic,
+ ['loadAlerts', 'closeEditor'],
+ billingAlertNotificationLogic(props),
+ ['clearCreatedDestinations'],
+ ],
+ })),
+ afterMount(({ actions, props }) => {
+ actions.resetAlertForm(formDefaults(props.alert))
+ }),
+ forms(({ props, values, actions }) => ({
+ alertForm: {
+ defaults: formDefaults(props.alert),
+ errors: (form) => ({
+ name: form.name.trim() ? undefined : 'Name is required.',
+ thresholdValue:
+ form.thresholdValue === null
+ ? 'Enter a threshold.'
+ : form.thresholdValue < 0
+ ? 'Enter a value of 0 or more.'
+ : undefined,
+ minimumValue: form.minimumValue < 0 ? 'Enter a value of 0 or more.' : undefined,
+ evaluationDelayHours:
+ form.evaluationDelayHours < 0 || form.evaluationDelayHours > 72
+ ? 'Use a delay between 0 and 72 hours.'
+ : undefined,
+ cooldownHours:
+ form.cooldownHours < 0 || form.cooldownHours > 720
+ ? 'Use a cooldown between 0 and 720 hours.'
+ : undefined,
+ }),
+ submit: async (form) => {
+ const organizationId = values.currentOrganization?.id
+ if (!organizationId) {
+ throw new Error('No organization selected.')
+ }
+
+ const pending = values.pendingDestinations
+ if (!props.alert && pending.length === 0) {
+ lemonToast.error('Add at least one notification destination.')
+ throw new Error('A notification destination is required.')
+ }
+
+ try {
+ const pendingKeys = pending.map(({ key }) => key)
+ const formPayload = billingAlertWritePayload(form, pending)
+ if (props.alert) {
+ await billingAlertsPartialUpdate(organizationId, props.alert.id, formPayload)
+ } else {
+ await billingAlertsCreate(
+ organizationId,
+ formPayload as Parameters<typeof billingAlertsCreate>[1]
+ )
+ }
+ // The org may have switched while the write was in flight; skip the success
+ // toast, refetch, and editor close so they don't fire against the new tenant.
+ if (values.currentOrganization?.id !== organizationId) {
+ return form
+ }
+ actions.clearCreatedDestinations(pendingKeys)
+
+ lemonToast.success(props.alert ? 'Billing alert updated.' : 'Billing alert created.')
+ actions.loadAlerts()
+ actions.closeEditor()
+ return form
+ } catch (error) {
+ const fieldErrors = formErrorsFromApiError(error)
+ if (Object.keys(fieldErrors).length > 0) {
+ actions.setAlertFormManualErrors(fieldErrors)
+ }
+ const message = billingAlertSaveErrorMessage(error)
+ lemonToast.error(message)
+ throw error
+ }
+ },
+ },
+ })),
+])
diff --git a/products/billing_alerts/frontend/billingAlertHistoryLogic.ts b/products/billing_alerts/frontend/billingAlertHistoryLogic.ts
new file mode 100644
index 000000000000..95b77a921f4c
--- /dev/null
+++ b/products/billing_alerts/frontend/billingAlertHistoryLogic.ts
@@ -0,0 +1,156 @@
+import { MakeLogicType, afterMount, connect, kea, key, path, props, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { billingLogic } from 'scenes/billing/billingLogic'
+
+import type { OrganizationType } from '~/types'
+
+import { offsetFromPageLink } from './billingAlertUtils'
+import { billingAlertsEventsList } from './generated/api'
+import type { PaginatedBillingAlertEventListApi } from './generated/api.schemas'
+
+export interface BillingAlertHistoryLogicProps {
+ alertId: string
+}
+
+const EMPTY_PAGE: PaginatedBillingAlertEventListApi = {
+ count: 0,
+ next: null,
+ previous: null,
+ results: [],
+}
+
+export const HISTORY_PAGE_SIZE = 50
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface billingAlertHistoryLogicValues {
+ currentOrganization: OrganizationType | null // billingLogic
+ currentPage: number
+ eventsPage: PaginatedBillingAlertEventListApi
+ eventsPageLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface billingAlertHistoryLogicActions {
+ loadEvents: (_: any) => any
+ loadEventsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadEventsSuccess: (
+ eventsPage: PaginatedBillingAlertEventListApi,
+ payload?: any
+ ) => {
+ eventsPage: PaginatedBillingAlertEventListApi
+ payload?: any
+ }
+ loadMoreEvents: (_: any) => any
+ loadMoreEventsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadMoreEventsSuccess: (
+ eventsPage: PaginatedBillingAlertEventListApi,
+ payload?: any
+ ) => {
+ eventsPage: PaginatedBillingAlertEventListApi
+ payload?: any
+ }
+ loadPreviousEvents: (_: any) => any
+ loadPreviousEventsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPreviousEventsSuccess: (
+ eventsPage: PaginatedBillingAlertEventListApi,
+ payload?: any
+ ) => {
+ eventsPage: PaginatedBillingAlertEventListApi
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface billingAlertHistoryLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ currentPage: (eventsPage: PaginatedBillingAlertEventListApi) => number
+ }
+}
+
+export type billingAlertHistoryLogicType = MakeLogicType<
+ billingAlertHistoryLogicValues,
+ billingAlertHistoryLogicActions,
+ BillingAlertHistoryLogicProps,
+ billingAlertHistoryLogicMeta
+>
+
+export const billingAlertHistoryLogic = kea<billingAlertHistoryLogicType>([
+ path(['products', 'billingAlerts', 'frontend', 'billingAlertHistoryLogic']),
+ props({} as BillingAlertHistoryLogicProps),
+ key(({ alertId }) => alertId),
+ connect({
+ values: [billingLogic, ['currentOrganization']],
+ }),
+ loaders(({ props, values }) => ({
+ eventsPage: [
+ EMPTY_PAGE,
+ {
+ loadEvents: async (_, breakpoint) => {
+ if (!values.currentOrganization?.id) {
+ return EMPTY_PAGE
+ }
+ await breakpoint()
+ const page = await billingAlertsEventsList(values.currentOrganization.id, props.alertId, {
+ limit: HISTORY_PAGE_SIZE,
+ })
+ await breakpoint()
+ return page
+ },
+ loadMoreEvents: async (_, breakpoint) => {
+ if (!values.currentOrganization?.id || !values.eventsPage.next) {
+ return values.eventsPage
+ }
+ await breakpoint()
+ const nextPage = await billingAlertsEventsList(values.currentOrganization.id, props.alertId, {
+ limit: HISTORY_PAGE_SIZE,
+ offset: offsetFromPageLink(values.eventsPage.next),
+ })
+ await breakpoint()
+ return nextPage
+ },
+ loadPreviousEvents: async (_, breakpoint) => {
+ if (!values.currentOrganization?.id || !values.eventsPage.previous) {
+ return values.eventsPage
+ }
+ await breakpoint()
+ const previousPage = await billingAlertsEventsList(values.currentOrganization.id, props.alertId, {
+ limit: HISTORY_PAGE_SIZE,
+ offset: offsetFromPageLink(values.eventsPage.previous),
+ })
+ await breakpoint()
+ return previousPage
+ },
+ },
+ ],
+ })),
+ selectors({
+ currentPage: [
+ (selectors) => [selectors.eventsPage],
+ (eventsPage: PaginatedBillingAlertEventListApi): number =>
+ eventsPage.previous ? offsetFromPageLink(eventsPage.previous) / HISTORY_PAGE_SIZE + 2 : 1,
+ ],
+ }),
+ afterMount(({ actions }) => {
+ actions.loadEvents(undefined)
+ }),
+])
diff --git a/products/billing_alerts/frontend/billingAlertNotificationLogic.test.ts b/products/billing_alerts/frontend/billingAlertNotificationLogic.test.ts
new file mode 100644
index 000000000000..6a324d3fb430
--- /dev/null
+++ b/products/billing_alerts/frontend/billingAlertNotificationLogic.test.ts
@@ -0,0 +1,10 @@
+import { isHttpsUrl } from './billingAlertNotificationLogic'
+
+describe('billing alert notification input validation', () => {
+ it('keeps browser validation to HTTPS completeness and leaves destination policy to the server', () => {
+ expect(isHttpsUrl('https://example.com/webhook')).toBe(true)
+ expect(isHttpsUrl('https://example.com:444/webhook')).toBe(true)
+ expect(isHttpsUrl('http://example.com/webhook')).toBe(false)
+ expect(isHttpsUrl('not a URL')).toBe(false)
+ })
+})
diff --git a/products/billing_alerts/frontend/billingAlertNotificationLogic.ts b/products/billing_alerts/frontend/billingAlertNotificationLogic.ts
new file mode 100644
index 000000000000..8fc899cf5432
--- /dev/null
+++ b/products/billing_alerts/frontend/billingAlertNotificationLogic.ts
@@ -0,0 +1,293 @@
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { billingLogic } from 'scenes/billing/billingLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import type { IntegrationType, OrganizationType } from '~/types'
+
+import { billingAlertsLogic } from './billingAlertsLogic'
+import { billingAlertRequestError, destinationKey } from './billingAlertUtils'
+import { billingAlertsDestinationsDeleteCreate } from './generated/api'
+import type {
+ BillingAlertConfigurationApi,
+ BillingAlertDestinationCreateDataApi,
+ BillingAlertDestinationSummaryApi,
+} from './generated/api.schemas'
+
+export type BillingAlertNotificationType = 'slack' | 'teams' | 'webhook'
+
+export interface PendingBillingAlertDestination {
+ key: string
+ label: string
+ payload: BillingAlertDestinationCreateDataApi
+}
+
+export interface BillingAlertNotificationLogicProps {
+ alert: BillingAlertConfigurationApi | null
+}
+
+export function isHttpsUrl(value: string): boolean {
+ const trimmed = value.trim()
+ if (!trimmed) {
+ return false
+ }
+ try {
+ return new URL(trimmed).protocol === 'https:'
+ } catch {
+ return false
+ }
+}
+
+export interface billingAlertNotificationLogicValues {
+ currentOrganization: OrganizationType | null
+ currentTeamId: number | null
+ integrations: IntegrationType[] | null
+ integrationsLoading: boolean
+ integrationsFailed: boolean
+ slackIntegrations: IntegrationType[]
+ selectedSlackIntegration: IntegrationType | undefined
+ pendingDestinations: PendingBillingAlertDestination[]
+ selectedType: BillingAlertNotificationType
+ selectedIntegrationId: number | null
+ slackChannel: string | null
+ webhookUrl: string
+ addDisabledReason: string | undefined
+ executionTeamMismatch: boolean
+ deletingDestinationKeys: Set<string>
+}
+
+export interface billingAlertNotificationLogicActions {
+ setSelectedType: (selectedType: BillingAlertNotificationType) => { selectedType: BillingAlertNotificationType }
+ setSelectedIntegrationId: (integrationId: number | null) => { integrationId: number | null }
+ setSlackChannel: (slackChannel: string | null) => { slackChannel: string | null }
+ setWebhookUrl: (webhookUrl: string) => { webhookUrl: string }
+ addSelectedDestination: () => { value: true }
+ addPendingDestination: (destination: PendingBillingAlertDestination) => {
+ destination: PendingBillingAlertDestination
+ }
+ removePendingDestination: (key: string) => { key: string }
+ clearCreatedDestinations: (keys: string[]) => { keys: string[] }
+ setDestinationDeleting: (key: string, deleting: boolean) => { key: string; deleting: boolean }
+ deleteDestination: (destination: BillingAlertDestinationSummaryApi) => {
+ destination: BillingAlertDestinationSummaryApi
+ }
+ loadAlerts: () => void
+ alertUpdated: (alert: BillingAlertConfigurationApi) => { alert: BillingAlertConfigurationApi }
+ loadIntegrations: () => void
+ loadIntegrationsFailure: (error: string) => { error: string }
+ loadIntegrationsSuccess: (integrations: IntegrationType[] | null) => {
+ integrations: IntegrationType[] | null
+ }
+}
+
+export type billingAlertNotificationLogicType = MakeLogicType<
+ billingAlertNotificationLogicValues,
+ billingAlertNotificationLogicActions,
+ BillingAlertNotificationLogicProps
+>
+
+export const billingAlertNotificationLogic = kea<billingAlertNotificationLogicType>([
+ path(['products', 'billingAlerts', 'frontend', 'billingAlertNotificationLogic']),
+ props({} as BillingAlertNotificationLogicProps),
+ key(({ alert }) => alert?.id ?? 'new'),
+ connect({
+ values: [
+ billingLogic,
+ ['currentOrganization'],
+ teamLogic,
+ ['currentTeamId'],
+ integrationsLogic,
+ ['integrations', 'integrationsLoading'],
+ ],
+ actions: [
+ billingAlertsLogic,
+ ['loadAlerts', 'alertUpdated'],
+ integrationsLogic,
+ ['loadIntegrations', 'loadIntegrationsFailure', 'loadIntegrationsSuccess'],
+ ],
+ }),
+ actions({
+ setSelectedType: (selectedType: BillingAlertNotificationType) => ({ selectedType }),
+ setSelectedIntegrationId: (integrationId: number | null) => ({ integrationId }),
+ setSlackChannel: (slackChannel: string | null) => ({ slackChannel }),
+ setWebhookUrl: (webhookUrl: string) => ({ webhookUrl }),
+ addSelectedDestination: true,
+ addPendingDestination: (destination: PendingBillingAlertDestination) => ({ destination }),
+ removePendingDestination: (key: string) => ({ key }),
+ clearCreatedDestinations: (keys: string[]) => ({ keys }),
+ deleteDestination: (destination: BillingAlertDestinationSummaryApi) => ({ destination }),
+ setDestinationDeleting: (key: string, deleting: boolean) => ({ key, deleting }),
+ }),
+ reducers({
+ pendingDestinations: [
+ [] as PendingBillingAlertDestination[],
+ {
+ addPendingDestination: (state, { destination }) => [...state, destination],
+ removePendingDestination: (state, { key }) => state.filter((destination) => destination.key !== key),
+ clearCreatedDestinations: (state, { keys }) =>
+ state.filter((destination) => !keys.includes(destination.key)),
+ },
+ ],
+ selectedType: [
+ 'slack' as BillingAlertNotificationType,
+ { setSelectedType: (_, { selectedType }) => selectedType },
+ ],
+ integrationsFailed: [
+ false,
+ {
+ loadIntegrations: () => false,
+ loadIntegrationsFailure: () => true,
+ loadIntegrationsSuccess: () => false,
+ },
+ ],
+ // null means "no explicit choice": selectedSlackIntegration falls back to the first workspace.
+ selectedIntegrationId: [
+ null as number | null,
+ {
+ setSelectedIntegrationId: (_, { integrationId }) => integrationId,
+ },
+ ],
+ slackChannel: [
+ null as string | null,
+ {
+ setSlackChannel: (_, { slackChannel }) => slackChannel,
+ setSelectedIntegrationId: () => null,
+ },
+ ],
+ webhookUrl: [
+ '',
+ {
+ setWebhookUrl: (_, { webhookUrl }) => webhookUrl,
+ },
+ ],
+ deletingDestinationKeys: [
+ new Set<string>(),
+ {
+ setDestinationDeleting: (state, { key, deleting }) =>
+ deleting ? new Set([...state, key]) : new Set([...state].filter((candidate) => candidate !== key)),
+ },
+ ],
+ }),
+ selectors({
+ slackIntegrations: [
+ (selectors) => [selectors.integrations],
+ (integrations: IntegrationType[] | null): IntegrationType[] =>
+ integrations?.filter((integration) => integration.kind === 'slack') ?? [],
+ ],
+ selectedSlackIntegration: [
+ (selectors) => [selectors.slackIntegrations, selectors.selectedIntegrationId],
+ (integrations: IntegrationType[], integrationId: number | null): IntegrationType | undefined =>
+ integrations.find((integration) => integration.id === integrationId) ?? integrations[0],
+ ],
+ executionTeamMismatch: [
+ (selectors) => [(_, props) => props.alert, selectors.currentTeamId],
+ (alert: BillingAlertConfigurationApi | null, currentTeamId: number | null): boolean =>
+ Boolean(alert && currentTeamId && alert.execution_team_id !== currentTeamId),
+ ],
+ addDisabledReason: [
+ (selectors) => [
+ selectors.selectedType,
+ selectors.selectedSlackIntegration,
+ selectors.slackChannel,
+ selectors.webhookUrl,
+ selectors.pendingDestinations,
+ (_, props) => props.alert,
+ selectors.executionTeamMismatch,
+ ],
+ (
+ selectedType: BillingAlertNotificationType,
+ integration: IntegrationType | undefined,
+ slackChannel: string | null,
+ webhookUrl: string,
+ pending: PendingBillingAlertDestination[],
+ alert: BillingAlertConfigurationApi | null,
+ executionTeamMismatch: boolean
+ ): string | undefined => {
+ if (alert?.destinations.some((destination) => destination.type === selectedType)) {
+ return 'This alert already has that destination type.'
+ }
+ if (pending.some((destination) => destination.payload.type === selectedType)) {
+ return 'That destination is already pending.'
+ }
+ if (selectedType === 'slack') {
+ if (executionTeamMismatch) {
+ return "Switch to this alert's execution project to use its Slack integrations."
+ }
+ if (!integration) {
+ return 'Connect Slack first.'
+ }
+ return slackChannel ? undefined : 'Select a Slack channel.'
+ }
+ return isHttpsUrl(webhookUrl) ? undefined : 'Enter a valid HTTPS webhook URL.'
+ },
+ ],
+ }),
+ listeners(({ actions, values, props }) => ({
+ addSelectedDestination: () => {
+ if (values.addDisabledReason) {
+ return
+ }
+ let pending: PendingBillingAlertDestination
+ if (values.selectedType === 'slack' && values.selectedSlackIntegration && values.slackChannel) {
+ const [channelId, channelLabel] = values.slackChannel.split('|')
+ pending = {
+ key: `slack-${values.selectedSlackIntegration.id}-${channelId}`,
+ label: `Slack: ${channelLabel || channelId}`,
+ payload: {
+ type: 'slack',
+ slack_workspace_id: values.selectedSlackIntegration.id,
+ slack_channel_id: channelId,
+ slack_channel_name: channelLabel?.replace(/^#/, '') || channelId,
+ },
+ }
+ actions.setSlackChannel(null)
+ } else {
+ const url = values.webhookUrl.trim()
+ pending = {
+ key: `${values.selectedType}-${url}`,
+ label: `${values.selectedType === 'teams' ? 'Microsoft Teams' : 'Webhook'}: ${url}`,
+ payload: { type: values.selectedType, webhook_url: url },
+ }
+ actions.setWebhookUrl('')
+ }
+ actions.addPendingDestination(pending)
+ },
+ deleteDestination: async ({ destination }) => {
+ const organizationId = values.currentOrganization?.id
+ if (!organizationId || !props.alert) {
+ return
+ }
+ const key = destinationKey(destination)
+ if (values.deletingDestinationKeys.has(key)) {
+ return
+ }
+ actions.setDestinationDeleting(key, true)
+ try {
+ await billingAlertsDestinationsDeleteCreate(organizationId, props.alert.id, {
+ hog_function_ids: [...destination.hog_function_ids],
+ })
+ // The org may have switched while the request was in flight; don't leak the
+ // success toast or a refetch into the new tenant's view.
+ if (values.currentOrganization?.id !== organizationId) {
+ return
+ }
+ lemonToast.success('Destination removed.')
+ const destinations = props.alert.destinations.filter((candidate) => destinationKey(candidate) !== key)
+ actions.alertUpdated({
+ ...props.alert,
+ destinations,
+ })
+ actions.loadAlerts()
+ } catch (error) {
+ if (values.currentOrganization?.id === organizationId) {
+ lemonToast.error(billingAlertRequestError(error))
+ }
+ } finally {
+ actions.setDestinationDeleting(key, false)
+ }
+ },
+ })),
+])
diff --git a/products/billing_alerts/frontend/billingAlertUtils.ts b/products/billing_alerts/frontend/billingAlertUtils.ts
new file mode 100644
index 000000000000..c738b00d8f0b
--- /dev/null
+++ b/products/billing_alerts/frontend/billingAlertUtils.ts
@@ -0,0 +1,29 @@
+import { ApiError } from 'lib/api'
+
+import type { BillingAlertDestinationSummaryApi } from './generated/api.schemas'
+
+export function offsetFromPageLink(link: string | null | undefined, fallback = 0): number {
+ if (!link) {
+ return fallback
+ }
+ try {
+ const offset = Number(new URL(link, 'https://app.posthog.com').searchParams.get('offset'))
+ return Number.isSafeInteger(offset) && offset >= 0 ? offset : fallback
+ } catch {
+ return fallback
+ }
+}
+
+export function billingAlertRequestError(error: unknown, fallback = 'Request failed.'): string {
+ if (error instanceof ApiError) {
+ return error.detail || fallback
+ }
+ return error instanceof Error ? error.message : fallback
+}
+
+/** Identity of a destination group, shared by delete-in-flight tracking and list rendering. */
+export function destinationKey(
+ destination: Pick<BillingAlertDestinationSummaryApi, 'type' | 'hog_function_ids'>
+): string {
+ return `${destination.type}-${destination.hog_function_ids.join('-')}`
+}
diff --git a/products/billing_alerts/frontend/billingAlertsLogic.test.ts b/products/billing_alerts/frontend/billingAlertsLogic.test.ts
new file mode 100644
index 000000000000..97bc116fd980
--- /dev/null
+++ b/products/billing_alerts/frontend/billingAlertsLogic.test.ts
@@ -0,0 +1,113 @@
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { OrganizationMembershipLevel } from 'lib/constants'
+import { billingLogic } from 'scenes/billing/billingLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import { initKeaTests } from '~/test/init'
+import { expectLogic } from '~/test/keaTestUtils'
+import type { OrganizationType } from '~/types'
+
+import {
+ CHECK_NOW_CONFIRMATION_DESCRIPTION,
+ billingAlertsLogic,
+ mergeUniqueAlerts,
+ openBillingAlertCheckNowConfirmation,
+} from './billingAlertsLogic'
+import * as generatedApi from './generated/api'
+import type { BillingAlertConfigurationApi, PaginatedBillingAlertConfigurationListApi } from './generated/api.schemas'
+
+const alert = (id: string): BillingAlertConfigurationApi => ({ id }) as BillingAlertConfigurationApi
+const organization = (id: string): OrganizationType =>
+ ({ id, membership_level: OrganizationMembershipLevel.Owner }) as OrganizationType
+const page = (alerts: BillingAlertConfigurationApi[]): PaginatedBillingAlertConfigurationListApi => ({
+ count: alerts.length,
+ next: null,
+ previous: null,
+ results: alerts,
+})
+
+describe('billing alerts logic', () => {
+ it('deduplicates alerts when a later page overlaps after a live insert', () => {
+ expect(
+ mergeUniqueAlerts([alert('a'), alert('b')], [alert('b'), alert('c'), alert('c')]).map(({ id }) => id)
+ ).toEqual(['a', 'b', 'c'])
+ })
+
+ it('confirms live notification side effects before checking', () => {
+ const onConfirm = jest.fn()
+ const dialog = jest.spyOn(LemonDialog, 'open').mockImplementation(jest.fn())
+
+ openBillingAlertCheckNowConfirmation(onConfirm)
+
+ expect(dialog).toHaveBeenCalledWith(
+ expect.objectContaining({
+ description: CHECK_NOW_CONFIRMATION_DESCRIPTION,
+ primaryButton: expect.objectContaining({ children: 'Check now' }),
+ })
+ )
+ expect(onConfirm).not.toHaveBeenCalled()
+ dialog.mock.calls[0][0].primaryButton?.onClick?.({} as never)
+ expect(onConfirm).toHaveBeenCalledTimes(1)
+ })
+
+ describe('organization changes', () => {
+ let unmountOrganization: () => void
+ let unmountBilling: () => void
+ let unmountAlerts: () => void
+
+ beforeEach(() => {
+ initKeaTests()
+ unmountOrganization = organizationLogic.mount()
+ unmountBilling = billingLogic.mount()
+ organizationLogic.actions.loadCurrentOrganizationSuccess(organization('org-a'))
+ })
+
+ afterEach(() => {
+ unmountAlerts?.()
+ unmountBilling?.()
+ unmountOrganization?.()
+ jest.restoreAllMocks()
+ })
+
+ it('clears organization-scoped rows and editor state before loading the next organization', async () => {
+ const list = jest.spyOn(generatedApi, 'billingAlertsList').mockResolvedValue(page([alert('a')]))
+ unmountAlerts = billingAlertsLogic.mount()
+ await expectLogic(billingAlertsLogic).toFinishAllListeners()
+
+ billingAlertsLogic.actions.editAlert(alert('a'))
+ billingAlertsLogic.actions.setCheckingAlertId('a')
+ billingAlertsLogic.actions.setDeletingAlertId('a', true)
+ organizationLogic.actions.loadCurrentOrganizationSuccess(organization('org-b'))
+
+ expect(billingAlertsLogic.values.alertsPage).toEqual(page([]))
+ expect(billingAlertsLogic.values.selectedAlert).toBeNull()
+ expect(billingAlertsLogic.values.isEditorOpen).toBe(false)
+ expect(billingAlertsLogic.values.checkingAlertId).toBeNull()
+ expect(billingAlertsLogic.values.deletingAlertIds.size).toBe(0)
+
+ await expectLogic(billingAlertsLogic).toFinishAllListeners()
+ expect(list).toHaveBeenLastCalledWith('org-b', { limit: 30 })
+ })
+
+ it('does not let a late response from the previous organization overwrite the new page', async () => {
+ let resolveOrgA: (value: PaginatedBillingAlertConfigurationListApi) => void = () => undefined
+ const orgAResponse = new Promise<PaginatedBillingAlertConfigurationListApi>((resolve) => {
+ resolveOrgA = resolve
+ })
+ jest.spyOn(generatedApi, 'billingAlertsList').mockImplementation((organizationId) =>
+ organizationId === 'org-a' ? orgAResponse : Promise.resolve(page([alert('b')]))
+ )
+
+ unmountAlerts = billingAlertsLogic.mount()
+ organizationLogic.actions.loadCurrentOrganizationSuccess(organization('org-b'))
+ await expectLogic(billingAlertsLogic).toFinishAllListeners()
+ expect(billingAlertsLogic.values.alerts.map(({ id }) => id)).toEqual(['b'])
+
+ resolveOrgA(page([alert('a')]))
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(billingAlertsLogic.values.alerts.map(({ id }) => id)).toEqual(['b'])
+ })
+ })
+})
diff --git a/products/billing_alerts/frontend/billingAlertsLogic.ts b/products/billing_alerts/frontend/billingAlertsLogic.ts
new file mode 100644
index 000000000000..23095665f35e
--- /dev/null
+++ b/products/billing_alerts/frontend/billingAlertsLogic.ts
@@ -0,0 +1,271 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
+
+import { billingLogic } from 'scenes/billing/billingLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import type { OrganizationType } from '~/types'
+
+import { formatBillingValue, metricLabel } from './billingAlertDisplay'
+import { billingAlertRequestError, offsetFromPageLink } from './billingAlertUtils'
+import { billingAlertsCheckNowCreate, billingAlertsDestroy, billingAlertsList } from './generated/api'
+import type { BillingAlertConfigurationApi, PaginatedBillingAlertConfigurationListApi } from './generated/api.schemas'
+
+const EMPTY_ALERTS_PAGE: PaginatedBillingAlertConfigurationListApi = {
+ count: 0,
+ next: null,
+ previous: null,
+ results: [],
+}
+
+export function mergeUniqueAlerts(
+ current: BillingAlertConfigurationApi[],
+ incoming: BillingAlertConfigurationApi[]
+): BillingAlertConfigurationApi[] {
+ const knownIds = new Set(current.map((alert) => alert.id))
+ return [
+ ...current,
+ ...incoming.filter((alert) => {
+ if (knownIds.has(alert.id)) {
+ return false
+ }
+ knownIds.add(alert.id)
+ return true
+ }),
+ ]
+}
+
+export const CHECK_NOW_CONFIRMATION_DESCRIPTION =
+ 'This evaluates live billing data and may send Slack, Microsoft Teams, or webhook notifications.'
+
+export const PREVIEW_CHECK_CONFIRMATION_DESCRIPTION =
+ 'This alert is paused. The check evaluates live billing data as a preview and does not send notifications or record an evaluation.'
+
+export function openBillingAlertCheckNowConfirmation(onConfirm: () => void, options?: { preview?: boolean }): void {
+ LemonDialog.open({
+ title: options?.preview ? 'Preview billing alert check?' : 'Check billing alert now?',
+ description: options?.preview ? PREVIEW_CHECK_CONFIRMATION_DESCRIPTION : CHECK_NOW_CONFIRMATION_DESCRIPTION,
+ primaryButton: {
+ children: options?.preview ? 'Preview check' : 'Check now',
+ onClick: onConfirm,
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+}
+
+export interface billingAlertsLogicValues {
+ canAccessBilling: boolean
+ currentOrganization: OrganizationType | null
+ alertsPage: PaginatedBillingAlertConfigurationListApi
+ alertsPageLoading: boolean
+ alerts: BillingAlertConfigurationApi[]
+ selectedAlert: BillingAlertConfigurationApi | null
+ isEditorOpen: boolean
+ checkingAlertId: string | null
+ deletingAlertIds: Set<string>
+}
+
+export interface billingAlertsLogicActions {
+ loadAlerts: () => void
+ loadAlertsSuccess: (alertsPage: PaginatedBillingAlertConfigurationListApi) => {
+ alertsPage: PaginatedBillingAlertConfigurationListApi
+ }
+ loadAlertsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }
+ loadMoreAlerts: () => void
+ loadMoreAlertsSuccess: (alertsPage: PaginatedBillingAlertConfigurationListApi) => {
+ alertsPage: PaginatedBillingAlertConfigurationListApi
+ }
+ loadMoreAlertsFailure: (error: string, errorObject?: unknown) => { error: string; errorObject?: unknown }
+ createAlert: () => { value: true }
+ editAlert: (alert: BillingAlertConfigurationApi) => { alert: BillingAlertConfigurationApi }
+ alertUpdated: (alert: BillingAlertConfigurationApi) => { alert: BillingAlertConfigurationApi }
+ closeEditor: () => { value: true }
+ checkNow: (alert: BillingAlertConfigurationApi) => { alert: BillingAlertConfigurationApi }
+ runCheckNow: (alert: BillingAlertConfigurationApi) => { alert: BillingAlertConfigurationApi }
+ deleteAlert: (alert: BillingAlertConfigurationApi) => { alert: BillingAlertConfigurationApi }
+ setCheckingAlertId: (alertId: string | null) => { alertId: string | null }
+ setDeletingAlertId: (alertId: string, deleting: boolean) => { alertId: string; deleting: boolean }
+ resetOrganizationState: () => { value: true }
+ loadCurrentOrganizationSuccess: (
+ currentOrganization: OrganizationType | null,
+ payload?: any
+ ) => {
+ currentOrganization: OrganizationType | null
+ payload?: any
+ }
+}
+
+export type billingAlertsLogicType = MakeLogicType<billingAlertsLogicValues, billingAlertsLogicActions>
+
+export const billingAlertsLogic = kea<billingAlertsLogicType>([
+ path(['products', 'billingAlerts', 'frontend', 'billingAlertsLogic']),
+ connect({
+ values: [billingLogic, ['canAccessBilling', 'currentOrganization']],
+ actions: [organizationLogic, ['loadCurrentOrganizationSuccess']],
+ }),
+ actions({
+ createAlert: true,
+ editAlert: (alert: BillingAlertConfigurationApi) => ({ alert }),
+ alertUpdated: (alert: BillingAlertConfigurationApi) => ({ alert }),
+ closeEditor: true,
+ checkNow: (alert: BillingAlertConfigurationApi) => ({ alert }),
+ runCheckNow: (alert: BillingAlertConfigurationApi) => ({ alert }),
+ deleteAlert: (alert: BillingAlertConfigurationApi) => ({ alert }),
+ setCheckingAlertId: (alertId: string | null) => ({ alertId }),
+ setDeletingAlertId: (alertId: string, deleting: boolean) => ({ alertId, deleting }),
+ resetOrganizationState: true,
+ }),
+ reducers({
+ selectedAlert: [
+ null as BillingAlertConfigurationApi | null,
+ {
+ createAlert: () => null,
+ editAlert: (_, { alert }) => alert,
+ alertUpdated: (state, { alert }) => (state?.id === alert.id ? alert : state),
+ resetOrganizationState: () => null,
+ },
+ ],
+ isEditorOpen: [
+ false,
+ {
+ createAlert: () => true,
+ editAlert: () => true,
+ closeEditor: () => false,
+ resetOrganizationState: () => false,
+ },
+ ],
+ checkingAlertId: [
+ null as string | null,
+ { setCheckingAlertId: (_, { alertId }) => alertId, resetOrganizationState: () => null },
+ ],
+ deletingAlertIds: [
+ new Set<string>(),
+ {
+ setDeletingAlertId: (state, { alertId, deleting }) =>
+ deleting ? new Set([...state, alertId]) : new Set([...state].filter((id) => id !== alertId)),
+ resetOrganizationState: () => new Set(),
+ },
+ ],
+ }),
+ loaders(({ values }) => ({
+ alertsPage: [
+ EMPTY_ALERTS_PAGE,
+ {
+ loadAlerts: async (_, breakpoint) => {
+ if (!values.currentOrganization?.id || !values.canAccessBilling) {
+ return EMPTY_ALERTS_PAGE
+ }
+ await breakpoint()
+ const page = await billingAlertsList(values.currentOrganization.id, { limit: 30 })
+ await breakpoint()
+ return page
+ },
+ loadMoreAlerts: async (_, breakpoint) => {
+ if (!values.currentOrganization?.id || !values.alertsPage.next) {
+ return values.alertsPage
+ }
+ await breakpoint()
+ const nextPage = await billingAlertsList(values.currentOrganization.id, {
+ limit: 30,
+ offset: offsetFromPageLink(values.alertsPage.next, values.alertsPage.results.length),
+ })
+ await breakpoint()
+ return {
+ ...nextPage,
+ results: mergeUniqueAlerts(values.alertsPage.results, nextPage.results),
+ }
+ },
+ },
+ ],
+ })),
+ selectors({
+ alerts: [
+ (selectors) => [selectors.alertsPage],
+ (alertsPage: PaginatedBillingAlertConfigurationListApi): BillingAlertConfigurationApi[] =>
+ alertsPage.results,
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ loadAlertsFailure: ({ error, errorObject }) => {
+ lemonToast.error(billingAlertRequestError(errorObject ?? error))
+ },
+ loadMoreAlertsFailure: ({ error, errorObject }) => {
+ lemonToast.error(billingAlertRequestError(errorObject ?? error))
+ },
+ loadCurrentOrganizationSuccess: () => {
+ actions.resetOrganizationState()
+ actions.loadAlertsSuccess(EMPTY_ALERTS_PAGE)
+ actions.loadAlerts()
+ },
+ checkNow: ({ alert }) => {
+ openBillingAlertCheckNowConfirmation(() => actions.runCheckNow(alert), { preview: !alert.enabled })
+ },
+ runCheckNow: async ({ alert }) => {
+ const organizationId = values.currentOrganization?.id
+ if (!organizationId || values.checkingAlertId) {
+ return
+ }
+ actions.setCheckingAlertId(alert.id)
+ try {
+ const result = await billingAlertsCheckNowCreate(organizationId, alert.id)
+ if (values.currentOrganization?.id !== organizationId) {
+ return
+ }
+ if (result.preview) {
+ const value =
+ result.current_value !== null && result.current_value !== undefined
+ ? formatBillingValue(result.current_value, alert.metric, alert.currency)
+ : 'not available yet'
+ lemonToast.success(
+ result.threshold_breached
+ ? `Preview: ${metricLabel(alert.metric)} is ${value}, above the threshold. No notifications were sent.`
+ : `Preview: ${metricLabel(alert.metric)} is ${value}, below the threshold.`
+ )
+ } else {
+ lemonToast.success(
+ result.event?.kind === 'firing' ? 'Billing alert fired.' : 'Billing alert checked.'
+ )
+ }
+ actions.closeEditor()
+ actions.loadAlerts()
+ } catch (error) {
+ if (values.currentOrganization?.id === organizationId) {
+ lemonToast.error(billingAlertRequestError(error))
+ }
+ } finally {
+ if (values.currentOrganization?.id === organizationId && values.checkingAlertId === alert.id) {
+ actions.setCheckingAlertId(null)
+ }
+ }
+ },
+ deleteAlert: async ({ alert }) => {
+ const organizationId = values.currentOrganization?.id
+ if (!organizationId || values.deletingAlertIds.has(alert.id)) {
+ return
+ }
+ actions.setDeletingAlertId(alert.id, true)
+ try {
+ await billingAlertsDestroy(organizationId, alert.id)
+ if (values.currentOrganization?.id !== organizationId) {
+ return
+ }
+ lemonToast.success('Billing alert deleted.')
+ actions.closeEditor()
+ actions.loadAlerts()
+ } catch (error) {
+ if (values.currentOrganization?.id === organizationId) {
+ lemonToast.error(billingAlertRequestError(error))
+ }
+ } finally {
+ if (values.currentOrganization?.id === organizationId) {
+ actions.setDeletingAlertId(alert.id, false)
+ }
+ }
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadAlerts()
+ }),
+])
diff --git a/products/billing_alerts/package.json b/products/billing_alerts/package.json
index d2c2bbd5d878..804f13fb12c1 100644
--- a/products/billing_alerts/package.json
+++ b/products/billing_alerts/package.json
@@ -2,5 +2,17 @@
"name": "@posthog/products-billing-alerts",
"scripts": {
"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short || test $? -eq 5"
+ },
+ "dependencies": {
+ "kea": "catalog:",
+ "kea-forms": "catalog:",
+ "kea-loaders": "catalog:"
+ },
+ "peerDependencies": {
+ "@posthog/icons": "*",
+ "@posthog/lemon-ui": "*",
+ "@types/react": "*",
+ "react": "*",
+ "typescript": "catalog:*"
}
}
diff --git a/products/billing_alerts/tsconfig.json b/products/billing_alerts/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/billing_alerts/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}