: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(billing): prepare billing APIs for MCP (#79047)
Pawel Cebula3d18613e1566
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex 9d8053f34882..2e1e3c102501 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -21,8 +21,9 @@ pnpm --filter=@posthog/mcp run scaffold-yaml -- --product your_product \# 2. Configure the YAML – enable tools, add scopes, annotations, descriptions# Place in products/<product>/mcp/*.yaml (preferred, e.g. actions, cohorts)-# 3. Add a HogQL system table in posthog/hogql/database/schema/system.py-# and a model reference in products/posthog_ai/skills/querying-posthog-data/references/+# 3. For read/list tools backed by PostHog database rows, add a HogQL system table+# in posthog/hogql/database/schema/system.py and a model reference in+# products/posthog_ai/skills/querying-posthog-data/references/# 4. Generate handlers and schemashogli build:openapi@@ -78,9 +79,14 @@ Primarily oriented toward coding agents (PostHog Desktop, PostHog AI, Claude Cod## SQL-first MCP: HogQL system tables-Every list/get endpoint exposed as an MCP tool must have a corresponding HogQL system table.+Most list/get endpoints exposed as MCP tools should have a corresponding HogQL system table.This lets agents query PostHog data via SQL in addition to (or instead of) the REST API tools.+Exceptions are OK when the tool intentionally proxies service-owned data,+aggregates data that is not represented as a team-scoped PostHog table,+or returns a curated API shape that would be awkward or unsafe to rebuild in SQL.+For these tools, keep the surface narrow and document the source and shape in the YAML description.+System tables are defined in [`posthog/hogql/database/schema/system.py`](https://github.com/PostHog/posthog/blob/master/posthog/hogql/database/schema/system.py) as `PostgresTable` instances.Each table must include a `team_id` column for data isolation.@@ -375,6 +381,19 @@ see the [`improving-drf-endpoints` skill](https://github.com/PostHog/posthog/bloand the generated tool gets an empty schema with zero parameters.`ModelViewSet` with `serializer_class` works automatically.+### Root-router viewsets++Viewsets mounted at root URLs (no `team_id`/`project_id` in the path) set+`param_derived_from_user_current_team` and are excluded from the OpenAPI schema by default,+which means they are invisible to frontend type generation and MCP tool scaffolding.+If your viewset is one of these and you want to expose it,+set `force_include_in_api_docs = True` on the class. See `ee/api/billing.py` for an example.+This flag only controls schema inclusion.+Runtime access still comes from the viewset's `scope_object`,+`scope_object_read_actions`, `scope_object_write_actions`,+and any per-action `required_scopes` or `dangerously_get_required_scopes` overrides.+Only mark the actions you actually want PATs, OAuth tokens, and MCP clients to call.+## HogQL query schemas (WIP)[`frontend/src/queries/schema/schema-assistant-queries.ts`](https://github.com/PostHog/posthog/blob/master/frontend/src/queries/schema/schema-assistant-queries.ts) defines structured query typesdiff --git a/ee/api/billing.py b/ee/api/billing.pyindex 8fe66424f8a1..62c77169df9d 100644--- a/ee/api/billing.py+++ b/ee/api/billing.py@@ -7,7 +7,7 @@ from django.shortcuts import redirectimport requestsimport structlogimport posthoganalytics-from drf_spectacular.utils import extend_schema+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_serializerfrom rest_framework import permissions, serializers, status, viewsetsfrom rest_framework.exceptions import NotFound, PermissionDenied, ValidationErrorfrom rest_framework.request import Request@@ -20,7 +20,7 @@ from posthog.event_usage import groupsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Organization, OrganizationIntegration, Team, Userfrom posthog.models.organization import OrganizationMembership-from posthog.permissions import posthog_feature_flag_enabled+from posthog.permissions import get_authenticator_scopes, posthog_feature_flag_enabledfrom posthog.utils import get_trusted_client_ip, relative_date_parsefrom ee.billing.billing_manager import BillingManager@@ -63,6 +63,10 @@ def user_has_billing_access(user: User, organization: Organization) -> bool:return _owner_only_billing_enabled(user, organization) is False+def is_token_auth_request(request: Request) -> bool:+ return get_authenticator_scopes(getattr(request, "successful_authenticator", None)) is not None++class HasBillingAccess(permissions.BasePermission):"""Permission to allow users with Billing access to access Billing endpoints.@@ -87,6 +91,47 @@ class BillingSerializer(serializers.Serializer):billing_limit = serializers.IntegerField()+@extend_schema_serializer(many=False)+class BillingOverviewResponseSerializer(serializers.Serializer):+ customer_id = serializers.CharField(required=False, allow_null=True)+ billing_plan = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ subscription_level = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ has_active_subscription = serializers.BooleanField(required=False)+ deactivated = serializers.BooleanField(required=False)+ is_annual_plan_customer = serializers.BooleanField(required=False)+ free_trial_until = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ current_total_amount_usd = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ current_total_amount_usd_after_discount = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ projected_total_amount_usd = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ projected_total_amount_usd_after_discount = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ projected_total_amount_usd_with_limit = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ projected_total_amount_usd_with_limit_after_discount = serializers.CharField(+ required=False, allow_blank=True, allow_null=True+ )+ discount_amount_usd = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ discount_percent = serializers.FloatField(required=False, allow_null=True)+ amount_off_expires_at = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ startup_program_label = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ startup_program_label_previous = serializers.CharField(required=False, allow_blank=True, allow_null=True)+ stripe_portal_url = serializers.URLField(required=False, allow_blank=True, allow_null=True)+ external_billing_provider_invoices_url = serializers.URLField(required=False, allow_blank=True, allow_null=True)+ products = serializers.ListField(+ child=serializers.DictField(child=serializers.JSONField(allow_null=True)),+ required=False,+ help_text="Subscribed and available products/addons with pricing, plan, limit, usage, and entitlement metadata.",+ )+ available_product_features = serializers.ListField(child=serializers.CharField(), required=False)+ usage_summary = serializers.JSONField(required=False)+ billing_period = serializers.JSONField(required=False, allow_null=True)+ custom_limits_usd = serializers.JSONField(required=False)+ next_period_custom_limits_usd = serializers.JSONField(required=False)+ trial = serializers.JSONField(required=False, allow_null=True)+ license = serializers.JSONField(required=False, allow_null=True)+ account_owner = serializers.JSONField(required=False, allow_null=True)+ customer_trust_scores = serializers.JSONField(required=False)+ never_drop_data = serializers.BooleanField(required=False)++class LicenseKeySerializer(serializers.Serializer):license = serializers.CharField()@@ -140,21 +185,31 @@ class BillingPeriodResponseSerializer(serializers.Serializer):@extend_schema(tags=["billing"])class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer_class = BillingSerializer+ pagination_class = Noneparam_derived_from_user_current_team = "team_id"- scope_object = "INTERNAL"+ scope_object = "billing"+ scope_object_read_actions = ["list", "usage", "spend"]+ scope_object_write_actions: list[str] = []+ # OpenAPI skips root-router viewsets that derive their team from the current user.+ # Billing opts in so generated clients and MCP scaffolding include these read actions.+ force_include_in_api_docs = Truedef get_billing_manager(self) -> BillingManager:license = get_cached_instance_license()user = self.request.user if isinstance(self.request.user, User) and self.request.user.distinct_id else Nonereturn BillingManager(license, user, ip_address=get_trusted_client_ip(self.request))+ @extend_schema(responses={200: OpenApiResponse(response=BillingOverviewResponseSerializer)})def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:license = get_cached_instance_license()if license and not license.is_v2_license:raise NotFound("Billing is not supported for this license type")org = self._get_org()+ if is_token_auth_request(request):+ if not org or not isinstance(request.user, User) or not user_has_billing_access(request.user, org):+ raise PermissionDenied("You do not have access to Billing for this organization.")# If on Cloud and we have the property billing - return 404 as we always use legacy billing it it existsif hasattr(org, "billing"):@@ -682,11 +737,13 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return {}def _get_org(self) -> Optional[Organization]:- # root-router viewset with param_derived_from_user_current_team — no URL-scoped org to mismatch- # nosemgrep: cross-org-bypass-user-organization- org = None if self.request.user.is_anonymous else self.request.user.organization+ if self.request.user.is_anonymous:+ return None- return org+ try:+ return self.team.organization+ except Exception:+ return Nonedef _get_org_required(self) -> Organization:org = self._get_org()diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.pyindex 0844b7f1ce8b..be5ac4b450b0 100644--- a/ee/api/test/test_billing.py+++ b/ee/api/test/test_billing.py@@ -23,7 +23,7 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from ee.api.billing import BillingUsageRequestSerializer+from ee.api.billing import BillingUsageRequestSerializer, BillingViewsetfrom ee.api.test.base import APILicensedTestfrom ee.billing.billing_types import BillingPeriod, CustomerInfo, CustomerProductfrom ee.billing.quota_limiting import QuotaResource@@ -1152,6 +1152,74 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()+ def _personal_api_key_headers(self, scopes: list[str], scoped_teams: list[int] | None = None) -> dict[str, str]:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Test Key",+ user=self.user,+ secure_value=hash_key_value(token),+ scopes=scopes,+ scoped_teams=scoped_teams,+ )+ self.client.logout()+ return {"HTTP_AUTHORIZATION": f"Bearer {token}"}++ def test_scope_actions_are_read_only(self):+ self.assertEqual(BillingViewset.scope_object, "billing")+ self.assertEqual(BillingViewset.scope_object_read_actions, ["list", "usage", "spend"])+ self.assertEqual(BillingViewset.scope_object_write_actions, [])++ @patch("ee.billing.billing_manager.BillingManager.update_billing")+ def test_billing_write_scope_does_not_allow_patch_personal_api_key(self, mock_update_billing):+ headers = self._personal_api_key_headers(["billing:write"], scoped_teams=[self.team.pk])++ response = self.client.patch(+ "/api/billing//",+ data={"custom_limits_usd": {"events": 10}},+ content_type="application/json",+ HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_update_billing.assert_not_called()++ @parameterized.expand(+ [+ ("list", "get", "/api/billing/", None, "ee.billing.billing_manager.BillingManager.get_billing"),+ (+ "usage",+ "get",+ "/api/billing/usage/",+ {"start_date": "2025-01-01"},+ "ee.billing.billing_manager.BillingManager.get_usage_data",+ ),+ (+ "spend",+ "get",+ "/api/billing/spend/",+ {"start_date": "2025-01-01"},+ "ee.billing.billing_manager.BillingManager.get_spend_data",+ ),+ ]+ )+ def test_billing_read_scope_actions_still_require_billing_access(+ self, action_name, method_name, url, data, manager_method_path+ ):+ self.assertIn(action_name, BillingViewset.scope_object_read_actions)+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ headers = self._personal_api_key_headers(["billing:read"], scoped_teams=[self.team.pk])++ with patch(manager_method_path) as mock_manager_method:+ response = getattr(self.client, method_name)(+ url,+ data=data,+ HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_manager_method.assert_not_called()+@patch("ee.billing.billing_manager.BillingManager.get_usage_data")def test_get_usage_success(self, mock_get_usage_data):mock_get_usage_data.return_value = self.MOCK_USAGE_DATA@@ -1185,6 +1253,76 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):self.assertEqual(passed_params["team_ids"], f"[{str(self.team.pk)}]")self.assertEqual(passed_params["teams_map"], {self.team.pk: self.team.name})+ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ def test_get_usage_allows_wildcard_personal_api_key_for_admin(self, mock_get_usage_data):+ mock_get_usage_data.return_value = self.MOCK_USAGE_DATA+ headers = self._personal_api_key_headers(["*"])++ response = self.client.get(+ "/api/billing/usage/",+ {"start_date": "2025-01-01", "team_ids": f"[{self.team.pk}]"},+ HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), self.MOCK_USAGE_DATA)+ mock_get_usage_data.assert_called_once()++ @patch("ee.billing.billing_manager.BillingManager.get_billing")+ def test_list_personal_api_key_uses_resolved_team_org_when_current_org_is_stale(self, mock_get_billing):+ other_org = self.create_organization_with_features([])+ self.create_team_with_organization(other_org)+ OrganizationMembership.objects.create(+ user=self.user,+ organization=other_org,+ level=OrganizationMembership.Level.ADMIN,+ )+ self.user.current_organization = other_org+ self.user.current_team = self.team+ self.user.save(update_fields=["current_organization", "current_team"])+ headers = self._personal_api_key_headers(["billing:read"], scoped_teams=[self.team.pk])+ mock_get_billing.return_value = create_billing_response(customer=create_billing_customer())++ response = self.client.get(+ "/api/billing/",+ HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_get_billing.assert_called_once()+ self.assertEqual(mock_get_billing.call_args.args[0], self.organization)++ @patch("ee.billing.billing_manager.BillingManager.get_billing")+ def test_list_rejects_billing_read_personal_api_key_for_member(self, mock_get_billing):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ headers = self._personal_api_key_headers(["billing:read"], scoped_teams=[self.team.pk])++ response = self.client.get(+ "/api/billing/",+ HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_get_billing.assert_not_called()++ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled", return_value=True)+ def test_owner_only_billing_rejects_admin_personal_api_key_usage_access(+ self, _mock_feature_enabled, mock_get_usage_data+ ):+ mock_get_usage_data.return_value = self.MOCK_USAGE_DATA+ headers = self._personal_api_key_headers(["billing:read"], scoped_teams=[self.team.pk])++ response = self.client.get(+ "/api/billing/usage/",+ {"start_date": "2025-01-01"},+ HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_get_usage_data.assert_not_called()+@patch("ee.billing.billing_manager.BillingManager.get_usage_data")@patch("ee.api.billing.posthog_feature_flag_enabled", return_value=True)def test_owner_only_billing_rejects_admin_usage_access(self, _mock_feature_enabled, mock_get_usage_data):diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.tsindex b26bdfd139d6..eb8069657cb2 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessControlsLogic.ts@@ -397,6 +397,7 @@ export interface accessControlsLogicActions {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -565,6 +566,7 @@ export interface accessControlsLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -709,6 +711,7 @@ export interface accessControlsLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -826,6 +829,7 @@ export interface accessControlsLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.tsindex 87ef1a669aa9..ced36a856e96 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic.ts@@ -219,6 +219,7 @@ export interface accessDetailLogicActions {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.tsindex 7fffd58684d1..f816c79724e5 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/addObjectOverrideModalLogic.ts@@ -69,6 +69,7 @@ export interface addObjectOverrideModalLogicActions {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -184,6 +185,7 @@ export interface addObjectOverrideModalLogicActions {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -320,6 +322,7 @@ export interface addObjectOverrideModalLogicActions {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -440,6 +443,7 @@ export interface addObjectOverrideModalLogicActions {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -559,6 +563,7 @@ export interface addObjectOverrideModalLogicActions {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -699,6 +704,7 @@ export interface addObjectOverrideModalLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.tsindex f869a8d03cad..d1436d7da4d6 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/groupedAccessControlRuleModalLogic.ts@@ -32,6 +32,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -153,6 +154,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -266,6 +268,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -392,6 +395,7 @@ export interface groupedAccessControlRuleModalLogicValues {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -523,6 +527,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -656,6 +661,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -769,6 +775,7 @@ export interface groupedAccessControlRuleModalLogicActions {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -921,6 +928,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -1036,6 +1044,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -1150,6 +1159,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -1264,6 +1274,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -1379,6 +1390,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -1493,6 +1505,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -1618,6 +1631,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -1732,6 +1746,7 @@ export interface groupedAccessControlRuleModalLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.tsindex 1d40906b23e6..47b222b01d74 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/accessControlLogic.ts@@ -323,6 +323,7 @@ export interface accessControlLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -540,6 +541,7 @@ export interface accessControlLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'@@ -654,6 +656,7 @@ export interface accessControlLogicMeta {| 'batch_export'| 'batch_import'| 'batch_import_support'+ | 'billing'| 'business_knowledge'| 'canvas'| 'clickhouse_test_cluster_perf'diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 9135a42e62a4..8b9f15da700d 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -36,6 +36,7 @@ export const API_SCOPES: APIScope[] = [{ key: 'annotation', objectName: 'Annotation', objectPlural: 'annotations' },{ key: 'approvals', objectName: 'Approvals', objectPlural: 'approvals' },{ key: 'batch_export', objectName: 'Batch export', objectPlural: 'batch exports' },+ { key: 'billing', objectName: 'Billing', objectPlural: 'billing' },{ key: 'business_knowledge', objectName: 'Business knowledge', objectPlural: 'business knowledge' },{ key: 'canvas', objectName: 'Canvas', objectPlural: 'canvases' },{ key: 'cohort', objectName: 'Cohort', objectPlural: 'cohorts' },diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 48f82a1839d5..07a2d79edc50 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5766,6 +5766,7 @@ export const API_SCOPE_OBJECTS = ['batch_export','batch_import','batch_import_support',+ 'billing','business_knowledge','canvas','clickhouse_test_cluster_perf',diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8d44925d0d17..0160c74c3725 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2518,6 +2518,8 @@ importers:products/batch_exports: {}+ products/billing: {}+products/billing_alerts:dependencies:'@posthog/icons':diff --git a/posthog/api/documentation.py b/posthog/api/documentation.pyindex 7f4147c34edc..5cab0d7a4d91 100644--- a/posthog/api/documentation.py+++ b/posthog/api/documentation.py@@ -741,7 +741,11 @@ def preprocess_exclude_path_format(endpoints, **kwargs):projects_suffixes: set[tuple[str, str]] = set()for path, path_regex, method, callback in endpoints:- if getattr(callback.cls, "param_derived_from_user_current_team", None):+ force_include = getattr(callback.cls, "force_include_in_api_docs", False)++ if getattr(callback.cls, "param_derived_from_user_current_team", None) and not force_include:+ # Root-router viewsets don't fit the /api/projects/{team_id}/... pattern; opt in via+ # `force_include_in_api_docs = True` to surface in type-gen and MCP scaffolding.continuehas_scope_object = hasattr(callback.cls, "scope_object")# A view with no scope_object is normally excluded - the schema is built arounddiff --git a/posthog/scopes.py b/posthog/scopes.pyindex 0af6f874fc2a..440c42b0a4f6 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -25,6 +25,7 @@ APIScopeObject = Literal["batch_export","batch_import","batch_import_support",+ "billing","business_knowledge","canvas","clickhouse_test_cluster_perf",diff --git a/products/billing/__init__.py b/products/billing/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/billing/frontend/generated/api.schemas.ts b/products/billing/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..db9f3f61bfdd--- /dev/null+++ b/products/billing/frontend/generated/api.schemas.ts@@ -0,0 +1,639 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+export type BillingOverviewResponseApiProductsItem = { [key: string]: unknown }++export interface BillingOverviewResponseApi {+ /** @nullable */+ customer_id?: string | null+ /** @nullable */+ billing_plan?: string | null+ /** @nullable */+ subscription_level?: string | null+ has_active_subscription?: boolean+ deactivated?: boolean+ is_annual_plan_customer?: boolean+ /** @nullable */+ free_trial_until?: string | null+ /** @nullable */+ current_total_amount_usd?: string | null+ /** @nullable */+ current_total_amount_usd_after_discount?: string | null+ /** @nullable */+ projected_total_amount_usd?: string | null+ /** @nullable */+ projected_total_amount_usd_after_discount?: string | null+ /** @nullable */+ projected_total_amount_usd_with_limit?: string | null+ /** @nullable */+ projected_total_amount_usd_with_limit_after_discount?: string | null+ /** @nullable */+ discount_amount_usd?: string | null+ /** @nullable */+ discount_percent?: number | null+ /** @nullable */+ amount_off_expires_at?: string | null+ /** @nullable */+ startup_program_label?: string | null+ /** @nullable */+ startup_program_label_previous?: string | null+ /** @nullable */+ stripe_portal_url?: string | null+ /** @nullable */+ external_billing_provider_invoices_url?: string | null+ /** Subscribed and available products/addons with pricing, plan, limit, usage, and entitlement metadata. */+ products?: BillingOverviewResponseApiProductsItem[]+ available_product_features?: string[]+ usage_summary?: unknown+ billing_period?: unknown+ custom_limits_usd?: unknown+ next_period_custom_limits_usd?: unknown+ trial?: unknown+ license?: unknown+ account_owner?: unknown+ customer_trust_scores?: unknown+ never_drop_data?: boolean+}++export interface PatchedBillingApi {+ /** @maxLength 100 */+ plan?: string+ billing_limit?: number+}++export interface BillingApi {+ /** @maxLength 100 */+ plan: string+ billing_limit: number+}++export interface BillingPeriodResponseApi {+ /**+ * Start of the organization's current billing period, or null when billing has not synced a period.+ * @nullable+ */+ current_period_start: string | null+ /**+ * End of the organization's current billing period, or null when billing has not synced a period.+ * @nullable+ */+ current_period_end: string | null+}++/**+ * * `spend` - Spend+ * * `projected_spend` - Projected spend+ */+export type BillingAlertMetricEnumApi = (typeof BillingAlertMetricEnumApi)[keyof typeof BillingAlertMetricEnumApi]++export const BillingAlertMetricEnumApi = {+ Spend: 'spend',+ ProjectedSpend: 'projected_spend',+} as const++/**+ * * `USD` - USD+ */+export type CurrencyEnumApi = (typeof CurrencyEnumApi)[keyof typeof CurrencyEnumApi]++export const CurrencyEnumApi = {+ Usd: 'USD',+} as const++/**+ * * `relative_increase` - Relative increase+ * * `absolute_value` - Absolute value+ * * `absolute_increase` - Absolute increase+ */+export type ThresholdTypeEnumApi = (typeof ThresholdTypeEnumApi)[keyof typeof ThresholdTypeEnumApi]++export const ThresholdTypeEnumApi = {+ RelativeIncrease: 'relative_increase',+ AbsoluteValue: 'absolute_value',+ AbsoluteIncrease: 'absolute_increase',+} as const++/**+ * * `not_firing` - Not firing+ * * `firing` - Firing+ * * `errored` - Errored+ * * `snoozed` - Snoozed+ * * `broken` - Broken+ */+export type BillingAlertStateEnumApi = (typeof BillingAlertStateEnumApi)[keyof typeof BillingAlertStateEnumApi]++export const BillingAlertStateEnumApi = {+ NotFiring: 'not_firing',+ Firing: 'firing',+ Errored: 'errored',+ Snoozed: 'snoozed',+ Broken: 'broken',+} as const++/**+ * * `slack` - slack+ * * `webhook` - webhook+ * * `teams` - teams+ */+export type NotificationDestinationTypeEnumApi =+ (typeof NotificationDestinationTypeEnumApi)[keyof typeof NotificationDestinationTypeEnumApi]++export const NotificationDestinationTypeEnumApi = {+ Slack: 'slack',+ Webhook: 'webhook',+ Teams: 'teams',+} as const++export interface BillingAlertDestinationSummaryApi {+ type: NotificationDestinationTypeEnumApi+ hog_function_ids: string[]+}++export interface BillingAlertDestinationCreateDataApi {+ /** Destination type.+ *+ * * `slack` - slack+ * * `webhook` - webhook+ * * `teams` - teams */+ type: NotificationDestinationTypeEnumApi+ /** Slack integration ID in the alert execution project. */+ slack_workspace_id?: number+ /** Slack channel ID for alert delivery. */+ slack_channel_id?: string+ /** Optional Slack channel name shown in the UI. */+ slack_channel_name?: string+ /** HTTPS webhook URL for webhook or Microsoft Teams delivery. */+ webhook_url?: string+}++export interface BillingAlertDestinationChangesApi {+ /**+ * @items.minItems 4+ * @items.maxItems 4+ */+ delete?: string[][]+ create?: BillingAlertDestinationCreateDataApi[]+}++export interface BillingAlertConfigurationApi {+ /** Unique identifier for this billing alert. */+ readonly id: string+ /** Organization this billing alert belongs to. */+ readonly organization_id: string+ /**+ * Team used as the execution context for internal notification destinations.+ * @nullable+ */+ readonly execution_team_id: number | null+ /**+ * User ID that created this alert.+ * @nullable+ */+ readonly created_by_id: number | null+ /**+ * User ID that last updated this alert.+ * @nullable+ */+ readonly updated_by_id: number | null+ /**+ * Display name for this billing alert.+ * @maxLength 160+ */+ name: string+ /** Optional internal description. */+ description?: string+ /** Whether scheduled checks should evaluate this alert. */+ enabled?: boolean+ /** Billing-period total to evaluate: current spend so far, or projected period-end spend.+ *+ * * `spend` - Spend+ * * `projected_spend` - Projected spend */+ metric?: BillingAlertMetricEnumApi+ /** Server-controlled currency for spend values.+ *+ * * `USD` - USD */+ readonly currency: CurrencyEnumApi+ /** Revision incremented whenever evaluation behavior changes. */+ readonly configuration_revision: number+ /** Threshold rule type. The first version supports absolute value only.+ *+ * * `relative_increase` - Relative increase+ * * `absolute_value` - Absolute value+ * * `absolute_increase` - Absolute increase */+ threshold_type?: ThresholdTypeEnumApi+ /**+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.+ * @nullable+ * @pattern ^-?\d{0,6}(?:\.\d{0,2})?$+ */+ threshold_percentage?: string | null+ /**+ * Absolute value or absolute increase that triggers absolute threshold alerts.+ * @nullable+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$+ */+ threshold_value?: string | null+ /**+ * Minimum current value before the alert can fire.+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$+ */+ minimum_value?: string+ /**+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.+ * @minimum 1+ * @maximum 90+ */+ baseline_window_days?: number+ /**+ * Hours after a UTC billing date ends before it becomes eligible for evaluation.+ * @minimum 0+ * @maximum 72+ */+ evaluation_delay_hours?: number+ /** Current lifecycle state of this alert.+ *+ * * `not_firing` - Not firing+ * * `firing` - Firing+ * * `errored` - Errored+ * * `snoozed` - Snoozed+ * * `broken` - Broken */+ readonly state: BillingAlertStateEnumApi+ /**+ * Minimum hours between repeated firing notifications.+ * @minimum 0+ * @maximum 720+ */+ cooldown_hours?: number+ /**+ * ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.+ * @nullable+ */+ snoozed_until?: string | null+ /**+ * When the next scheduled evaluation is due.+ * @nullable+ */+ readonly next_check_at: string | null+ /**+ * When this alert was last evaluated.+ * @nullable+ */+ readonly last_checked_at: string | null+ /**+ * When notifications were last delivered for this alert.+ * @nullable+ */+ readonly last_notified_at: string | null+ /** Number of consecutive failed evaluations. */+ readonly consecutive_failures: number+ /** Notification destination groups configured for this alert, including their shared HogFunctions. */+ readonly destinations: readonly BillingAlertDestinationSummaryApi[]+ /** Destination groups to create or delete in the same transaction as this configuration write. */+ destination_changes?: BillingAlertDestinationChangesApi+ /** When this alert was created. */+ readonly created_at: string+ /**+ * When this alert was last updated.+ * @nullable+ */+ readonly updated_at: string | null+}++export interface PaginatedBillingAlertConfigurationListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: BillingAlertConfigurationApi[]+}++export interface PatchedBillingAlertConfigurationApi {+ /** Unique identifier for this billing alert. */+ readonly id?: string+ /** Organization this billing alert belongs to. */+ readonly organization_id?: string+ /**+ * Team used as the execution context for internal notification destinations.+ * @nullable+ */+ readonly execution_team_id?: number | null+ /**+ * User ID that created this alert.+ * @nullable+ */+ readonly created_by_id?: number | null+ /**+ * User ID that last updated this alert.+ * @nullable+ */+ readonly updated_by_id?: number | null+ /**+ * Display name for this billing alert.+ * @maxLength 160+ */+ name?: string+ /** Optional internal description. */+ description?: string+ /** Whether scheduled checks should evaluate this alert. */+ enabled?: boolean+ /** Billing-period total to evaluate: current spend so far, or projected period-end spend.+ *+ * * `spend` - Spend+ * * `projected_spend` - Projected spend */+ metric?: BillingAlertMetricEnumApi+ /** Server-controlled currency for spend values.+ *+ * * `USD` - USD */+ readonly currency?: CurrencyEnumApi+ /** Revision incremented whenever evaluation behavior changes. */+ readonly configuration_revision?: number+ /** Threshold rule type. The first version supports absolute value only.+ *+ * * `relative_increase` - Relative increase+ * * `absolute_value` - Absolute value+ * * `absolute_increase` - Absolute increase */+ threshold_type?: ThresholdTypeEnumApi+ /**+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.+ * @nullable+ * @pattern ^-?\d{0,6}(?:\.\d{0,2})?$+ */+ threshold_percentage?: string | null+ /**+ * Absolute value or absolute increase that triggers absolute threshold alerts.+ * @nullable+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$+ */+ threshold_value?: string | null+ /**+ * Minimum current value before the alert can fire.+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$+ */+ minimum_value?: string+ /**+ * Reserved for future increase-over-baseline rules. Not used by absolute value alerts.+ * @minimum 1+ * @maximum 90+ */+ baseline_window_days?: number+ /**+ * Hours after a UTC billing date ends before it becomes eligible for evaluation.+ * @minimum 0+ * @maximum 72+ */+ evaluation_delay_hours?: number+ /** Current lifecycle state of this alert.+ *+ * * `not_firing` - Not firing+ * * `firing` - Firing+ * * `errored` - Errored+ * * `snoozed` - Snoozed+ * * `broken` - Broken */+ readonly state?: BillingAlertStateEnumApi+ /**+ * Minimum hours between repeated firing notifications.+ * @minimum 0+ * @maximum 720+ */+ cooldown_hours?: number+ /**+ * ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.+ * @nullable+ */+ snoozed_until?: string | null+ /**+ * When the next scheduled evaluation is due.+ * @nullable+ */+ readonly next_check_at?: string | null+ /**+ * When this alert was last evaluated.+ * @nullable+ */+ readonly last_checked_at?: string | null+ /**+ * When notifications were last delivered for this alert.+ * @nullable+ */+ readonly last_notified_at?: string | null+ /** Number of consecutive failed evaluations. */+ readonly consecutive_failures?: number+ /** Notification destination groups configured for this alert, including their shared HogFunctions. */+ readonly destinations?: readonly BillingAlertDestinationSummaryApi[]+ /** Destination groups to create or delete in the same transaction as this configuration write. */+ destination_changes?: BillingAlertDestinationChangesApi+ /** When this alert was created. */+ readonly created_at?: string+ /**+ * When this alert was last updated.+ * @nullable+ */+ readonly updated_at?: string | null+}++/**+ * * `check` - Check+ * * `firing` - Firing+ * * `resolved` - Resolved+ * * `errored` - Errored+ * * `broken_config` - Broken config+ */+export type BillingAlertEventKindEnumApi =+ (typeof BillingAlertEventKindEnumApi)[keyof typeof BillingAlertEventKindEnumApi]++export const BillingAlertEventKindEnumApi = {+ Check: 'check',+ Firing: 'firing',+ Resolved: 'resolved',+ Errored: 'errored',+ BrokenConfig: 'broken_config',+} as const++/**+ * * `scheduled` - Scheduled+ * * `manual` - Manual+ */+export type BillingAlertEventSourceEnumApi =+ (typeof BillingAlertEventSourceEnumApi)[keyof typeof BillingAlertEventSourceEnumApi]++export const BillingAlertEventSourceEnumApi = {+ Scheduled: 'scheduled',+ Manual: 'manual',+} as const++export interface BillingAlertEventApi {+ /** Unique identifier for this billing alert event. */+ readonly id: string+ /** Event kind for a check, state transition, or delivery-worthy alert event.+ *+ * * `check` - Check+ * * `firing` - Firing+ * * `resolved` - Resolved+ * * `errored` - Errored+ * * `broken_config` - Broken config */+ readonly kind: BillingAlertEventKindEnumApi+ /** Whether this evaluation was scheduled or manually requested.+ *+ * * `scheduled` - Scheduled+ * * `manual` - Manual */+ readonly source: BillingAlertEventSourceEnumApi+ /** Attempt number for this billing date and configuration revision. */+ readonly attempt_number: number+ /** When this event was recorded. */+ readonly created_at: string+ /**+ * Billing data date evaluated by this event.+ * @nullable+ */+ readonly evaluation_date: string | null+ /** Configuration revision used for this evaluation. */+ readonly configuration_revision: number+ /**+ * Start of the evaluated billing period.+ * @nullable+ */+ readonly period_start: string | null+ /**+ * End of the evaluated billing period.+ * @nullable+ */+ readonly period_end: string | null+ /** Billing metric evaluated by this event.+ *+ * * `spend` - Spend+ * * `projected_spend` - Projected spend */+ readonly metric: BillingAlertMetricEnumApi+ /**+ * Metric value for the evaluated billing date.+ * @nullable+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$+ */+ readonly current_value: string | null+ /**+ * Average metric value across the baseline window.+ * @nullable+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$+ */+ readonly baseline_value: string | null+ /**+ * Current value minus the baseline value.+ * @nullable+ * @pattern ^-?\d{0,14}(?:\.\d{0,6})?$+ */+ readonly absolute_delta: string | null+ /**+ * Percentage change against the baseline value.+ * @nullable+ * @pattern ^-?\d{0,22}(?:\.\d{0,6})?$+ */+ readonly relative_delta_percentage: string | null+ /** Whether the evaluated value breached the configured threshold. */+ readonly threshold_breached: boolean+ /** Alert state before this event was applied.+ *+ * * `not_firing` - Not firing+ * * `firing` - Firing+ * * `errored` - Errored+ * * `snoozed` - Snoozed+ * * `broken` - Broken */+ readonly state_before: BillingAlertStateEnumApi | null+ /** Alert state after this event was applied.+ *+ * * `not_firing` - Not firing+ * * `firing` - Firing+ * * `errored` - Errored+ * * `snoozed` - Snoozed+ * * `broken` - Broken */+ readonly state_after: BillingAlertStateEnumApi | null+ /**+ * When notifications for this event were delivered.+ * @nullable+ */+ readonly notification_sent_at: string | null+ /** Notification targets recorded for this event. */+ readonly targets_notified: unknown+ /**+ * Milliseconds spent fetching billing data for this evaluation.+ * @nullable+ */+ readonly query_duration_ms: number | null+ /**+ * Exception class name recorded when the evaluation failed.+ * @nullable+ */+ readonly error_code: string | null+ /**+ * Failure description recorded when the evaluation failed.+ * @nullable+ */+ readonly error_message: string | null+ /** Human-readable explanation of the evaluation outcome. */+ readonly reason: string+}++export interface BillingAlertCheckNowResponseApi {+ /** Evaluation event recorded by the manual check, or null for a paused preview. */+ event?: BillingAlertEventApi | null+ /** Number of destination HogFunctions queued. */+ dispatched_destinations: number+ /** True when the alert is paused: it was evaluated but no notifications were sent. */+ preview: boolean+ /** Whether the evaluated billing-period total breached the configured threshold. */+ threshold_breached: boolean+ /**+ * Evaluated billing-period total, or null when billing data was not available.+ * @nullable+ */+ current_value?: string | null+}++export interface BillingAlertDestinationResponseApi {+ hog_function_ids: string[]+}++export interface BillingAlertDeleteDestinationApi {+ /**+ * HogFunction IDs to delete as one atomic destination group.+ * @minItems 4+ * @maxItems 4+ */+ hog_function_ids: string[]+}++export interface PaginatedBillingAlertEventListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: BillingAlertEventApi[]+}++export type BillingAlertsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type BillingAlertsEventsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}diff --git a/products/billing/frontend/generated/api.ts b/products/billing/frontend/generated/api.tsnew file mode 100644index 000000000000..30408c7810e8--- /dev/null+++ b/products/billing/frontend/generated/api.ts@@ -0,0 +1,510 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type {+ BillingAlertCheckNowResponseApi,+ BillingAlertConfigurationApi,+ BillingAlertDeleteDestinationApi,+ BillingAlertDestinationCreateDataApi,+ BillingAlertDestinationResponseApi,+ BillingAlertsEventsListParams,+ BillingAlertsListParams,+ BillingApi,+ BillingOverviewResponseApi,+ BillingPeriodResponseApi,+ PaginatedBillingAlertConfigurationListApi,+ PaginatedBillingAlertEventListApi,+ PatchedBillingAlertConfigurationApi,+ PatchedBillingApi,+} from './api.schemas'++// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B++type WritableKeys<T> = {+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>+}[keyof T]++type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never++type Writable<T> = Pick<T, WritableKeys<T>>+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]+ ? {+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]+ }+ : DistributeReadOnlyOverUnions<T>++export const getBillingListUrl = () => {+ return `/api/billing/`+}++export const billingList = async (options?: RequestInit): Promise<BillingOverviewResponseApi> => {+ return apiMutator<BillingOverviewResponseApi>(getBillingListUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getBillingPartialUpdateUrl = () => {+ return `/api/billing///`+}++export const billingPartialUpdate = async (+ patchedBillingApi?: PatchedBillingApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getBillingPartialUpdateUrl(), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedBillingApi),+ })+}++export const getBillingActivateCreateUrl = () => {+ return `/api/billing/activate/`+}++export const billingActivateCreate = async (billingApi: BillingApi, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingActivateCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingApi),+ })+}++export const getBillingActivateAuthorizeCreateUrl = () => {+ return `/api/billing/activate/authorize/`+}++export const billingActivateAuthorizeCreate = async (billingApi: BillingApi, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingActivateAuthorizeCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingApi),+ })+}++export const getBillingActivateAuthorizeStatusCreateUrl = () => {+ return `/api/billing/activate/authorize/status/`+}++export const billingActivateAuthorizeStatusCreate = async (+ billingApi: BillingApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getBillingActivateAuthorizeStatusCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingApi),+ })+}++export const getBillingCouponsClaimCreateUrl = () => {+ return `/api/billing/coupons/claim/`+}++export const billingCouponsClaimCreate = async (billingApi: BillingApi, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingCouponsClaimCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingApi),+ })+}++export const getBillingCouponsOverviewRetrieveUrl = () => {+ return `/api/billing/coupons/overview/`+}++export const billingCouponsOverviewRetrieve = async (options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingCouponsOverviewRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getBillingCreditsOverviewRetrieveUrl = () => {+ return `/api/billing/credits/overview/`+}++export const billingCreditsOverviewRetrieve = async (options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingCreditsOverviewRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getBillingCreditsPurchaseCreateUrl = () => {+ return `/api/billing/credits/purchase/`+}++export const billingCreditsPurchaseCreate = async (billingApi: BillingApi, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingCreditsPurchaseCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingApi),+ })+}++export const getBillingDeactivateCreateUrl = () => {+ return `/api/billing/deactivate/`+}++export const billingDeactivateCreate = async (billingApi: BillingApi, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingDeactivateCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingApi),+ })+}++export const getBillingGetInvoicesRetrieveUrl = () => {+ return `/api/billing/get_invoices/`+}++export const billingGetInvoicesRetrieve = async (options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingGetInvoicesRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getBillingLicensePartialUpdateUrl = () => {+ return `/api/billing/license/`+}++export const billingLicensePartialUpdate = async (+ patchedBillingApi?: PatchedBillingApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getBillingLicensePartialUpdateUrl(), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedBillingApi),+ })+}++export const getBillingPeriodRetrieveUrl = () => {+ return `/api/billing/period/`+}++/**+ * @summary Get the current organization billing period+ */+export const billingPeriodRetrieve = async (options?: RequestInit): Promise<BillingPeriodResponseApi> => {+ return apiMutator<BillingPeriodResponseApi>(getBillingPeriodRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getBillingPortalRetrieveUrl = () => {+ return `/api/billing/portal/`+}++export const billingPortalRetrieve = async (options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingPortalRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getBillingSpendRetrieveUrl = () => {+ return `/api/billing/spend/`+}++/**+ * Endpoint to fetch spend data (proxy to billing service).+ */+export const billingSpendRetrieve = async (options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingSpendRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getBillingStartupsApplyCreateUrl = () => {+ return `/api/billing/startups/apply/`+}++export const billingStartupsApplyCreate = async (billingApi: BillingApi, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingStartupsApplyCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingApi),+ })+}++export const getBillingSubscriptionSwitchPlanCreateUrl = () => {+ return `/api/billing/subscription/switch-plan/`+}++export const billingSubscriptionSwitchPlanCreate = async (+ billingApi: BillingApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getBillingSubscriptionSwitchPlanCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingApi),+ })+}++export const getBillingTrialsActivateCreateUrl = () => {+ return `/api/billing/trials/activate/`+}++export const billingTrialsActivateCreate = async (billingApi: BillingApi, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingTrialsActivateCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingApi),+ })+}++export const getBillingTrialsCancelCreateUrl = () => {+ return `/api/billing/trials/cancel/`+}++export const billingTrialsCancelCreate = async (billingApi: BillingApi, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingTrialsCancelCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingApi),+ })+}++export const getBillingUsageRetrieveUrl = () => {+ return `/api/billing/usage/`+}++export const billingUsageRetrieve = async (options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getBillingUsageRetrieveUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getBillingAlertsListUrl = (organizationId: string, params?: BillingAlertsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/organizations/${organizationId}/billing/alerts/?${stringifiedParams}`+ : `/api/organizations/${organizationId}/billing/alerts/`+}++export const billingAlertsList = async (+ organizationId: string,+ params?: BillingAlertsListParams,+ options?: RequestInit+): Promise<PaginatedBillingAlertConfigurationListApi> => {+ return apiMutator<PaginatedBillingAlertConfigurationListApi>(getBillingAlertsListUrl(organizationId, params), {+ ...options,+ method: 'GET',+ })+}++export const getBillingAlertsCreateUrl = (organizationId: string) => {+ return `/api/organizations/${organizationId}/billing/alerts/`+}++export const billingAlertsCreate = async (+ organizationId: string,+ billingAlertConfigurationApi: NonReadonly<BillingAlertConfigurationApi>,+ options?: RequestInit+): Promise<BillingAlertConfigurationApi> => {+ return apiMutator<BillingAlertConfigurationApi>(getBillingAlertsCreateUrl(organizationId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingAlertConfigurationApi),+ })+}++export const getBillingAlertsRetrieveUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/billing/alerts/${id}/`+}++export const billingAlertsRetrieve = async (+ organizationId: string,+ id: string,+ options?: RequestInit+): Promise<BillingAlertConfigurationApi> => {+ return apiMutator<BillingAlertConfigurationApi>(getBillingAlertsRetrieveUrl(organizationId, id), {+ ...options,+ method: 'GET',+ })+}++export const getBillingAlertsUpdateUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/billing/alerts/${id}/`+}++export const billingAlertsUpdate = async (+ organizationId: string,+ id: string,+ billingAlertConfigurationApi: NonReadonly<BillingAlertConfigurationApi>,+ options?: RequestInit+): Promise<BillingAlertConfigurationApi> => {+ return apiMutator<BillingAlertConfigurationApi>(getBillingAlertsUpdateUrl(organizationId, id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingAlertConfigurationApi),+ })+}++export const getBillingAlertsPartialUpdateUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/billing/alerts/${id}/`+}++export const billingAlertsPartialUpdate = async (+ organizationId: string,+ id: string,+ patchedBillingAlertConfigurationApi?: NonReadonly<PatchedBillingAlertConfigurationApi>,+ options?: RequestInit+): Promise<BillingAlertConfigurationApi> => {+ return apiMutator<BillingAlertConfigurationApi>(getBillingAlertsPartialUpdateUrl(organizationId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedBillingAlertConfigurationApi),+ })+}++export const getBillingAlertsDestroyUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/billing/alerts/${id}/`+}++export const billingAlertsDestroy = async (+ organizationId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getBillingAlertsDestroyUrl(organizationId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getBillingAlertsCheckNowCreateUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/billing/alerts/${id}/check_now/`+}++/**+ * Evaluate this billing alert immediately against real billing spend data. An enabled alert can send notifications when the evaluation records a dispatchable event. A paused alert is evaluated as a preview only: it reports the current spend and would-be outcome without sending notifications or recording an evaluation.+ */+export const billingAlertsCheckNowCreate = async (+ organizationId: string,+ id: string,+ options?: RequestInit+): Promise<BillingAlertCheckNowResponseApi> => {+ return apiMutator<BillingAlertCheckNowResponseApi>(getBillingAlertsCheckNowCreateUrl(organizationId, id), {+ ...options,+ method: 'POST',+ })+}++export const getBillingAlertsDestinationsCreateUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/billing/alerts/${id}/destinations/`+}++/**+ * Create a notification destination for this alert. One HogFunction is created per alert event kind.+ */+export const billingAlertsDestinationsCreate = async (+ organizationId: string,+ id: string,+ billingAlertDestinationCreateDataApi: BillingAlertDestinationCreateDataApi,+ options?: RequestInit+): Promise<BillingAlertDestinationResponseApi> => {+ return apiMutator<BillingAlertDestinationResponseApi>(getBillingAlertsDestinationsCreateUrl(organizationId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingAlertDestinationCreateDataApi),+ })+}++export const getBillingAlertsDestinationsDeleteCreateUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/billing/alerts/${id}/destinations/delete/`+}++/**+ * Delete a notification destination by deleting its HogFunction group atomically.+ */+export const billingAlertsDestinationsDeleteCreate = async (+ organizationId: string,+ id: string,+ billingAlertDeleteDestinationApi: BillingAlertDeleteDestinationApi,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getBillingAlertsDestinationsDeleteCreateUrl(organizationId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(billingAlertDeleteDestinationApi),+ })+}++export const getBillingAlertsEventsListUrl = (+ organizationId: string,+ id: string,+ params?: BillingAlertsEventsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/organizations/${organizationId}/billing/alerts/${id}/events/?${stringifiedParams}`+ : `/api/organizations/${organizationId}/billing/alerts/${id}/events/`+}++/**+ * List evaluation and notification events for this billing alert, newest first.+ */+export const billingAlertsEventsList = async (+ organizationId: string,+ id: string,+ params?: BillingAlertsEventsListParams,+ options?: RequestInit+): Promise<PaginatedBillingAlertEventListApi> => {+ return apiMutator<PaginatedBillingAlertEventListApi>(getBillingAlertsEventsListUrl(organizationId, id, params), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/billing/frontend/generated/api.zod.ts b/products/billing/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..d402a1368892--- /dev/null+++ b/products/billing/frontend/generated/api.zod.ts@@ -0,0 +1,456 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++export const billingPartialUpdateBodyPlanMax = 100++export const BillingPartialUpdateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingPartialUpdateBodyPlanMax).optional(),+ billing_limit: zod.number().optional(),+})++export const billingActivateCreateBodyPlanMax = 100++export const BillingActivateCreateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingActivateCreateBodyPlanMax),+ billing_limit: zod.number(),+})++export const billingActivateAuthorizeCreateBodyPlanMax = 100++export const BillingActivateAuthorizeCreateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingActivateAuthorizeCreateBodyPlanMax),+ billing_limit: zod.number(),+})++export const billingActivateAuthorizeStatusCreateBodyPlanMax = 100++export const BillingActivateAuthorizeStatusCreateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingActivateAuthorizeStatusCreateBodyPlanMax),+ billing_limit: zod.number(),+})++export const billingCouponsClaimCreateBodyPlanMax = 100++export const BillingCouponsClaimCreateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingCouponsClaimCreateBodyPlanMax),+ billing_limit: zod.number(),+})++export const billingCreditsPurchaseCreateBodyPlanMax = 100++export const BillingCreditsPurchaseCreateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingCreditsPurchaseCreateBodyPlanMax),+ billing_limit: zod.number(),+})++export const billingDeactivateCreateBodyPlanMax = 100++export const BillingDeactivateCreateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingDeactivateCreateBodyPlanMax),+ billing_limit: zod.number(),+})++export const billingLicensePartialUpdateBodyPlanMax = 100++export const BillingLicensePartialUpdateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingLicensePartialUpdateBodyPlanMax).optional(),+ billing_limit: zod.number().optional(),+})++export const billingStartupsApplyCreateBodyPlanMax = 100++export const BillingStartupsApplyCreateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingStartupsApplyCreateBodyPlanMax),+ billing_limit: zod.number(),+})++export const billingSubscriptionSwitchPlanCreateBodyPlanMax = 100++export const BillingSubscriptionSwitchPlanCreateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingSubscriptionSwitchPlanCreateBodyPlanMax),+ billing_limit: zod.number(),+})++export const billingTrialsActivateCreateBodyPlanMax = 100++export const BillingTrialsActivateCreateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingTrialsActivateCreateBodyPlanMax),+ billing_limit: zod.number(),+})++export const billingTrialsCancelCreateBodyPlanMax = 100++export const BillingTrialsCancelCreateBody = /* @__PURE__ */ zod.object({+ plan: zod.string().max(billingTrialsCancelCreateBodyPlanMax),+ billing_limit: zod.number(),+})++export const billingAlertsCreateBodyNameMax = 160++export const billingAlertsCreateBodyThresholdPercentageRegExp = new RegExp('^-?\\d{0,6}(?:\\.\\d{0,2})?$')+export const billingAlertsCreateBodyThresholdValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')+export const billingAlertsCreateBodyMinimumValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')+export const billingAlertsCreateBodyBaselineWindowDaysMax = 90++export const billingAlertsCreateBodyEvaluationDelayHoursMin = 0+export const billingAlertsCreateBodyEvaluationDelayHoursMax = 72++export const billingAlertsCreateBodyCooldownHoursMin = 0+export const billingAlertsCreateBodyCooldownHoursMax = 720++export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMin = 4+export const billingAlertsCreateBodyDestinationChangesOneDeleteItemMax = 4++export const BillingAlertsCreateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(billingAlertsCreateBodyNameMax).describe('Display name for this billing alert.'),+ description: zod.string().optional().describe('Optional internal description.'),+ enabled: zod.boolean().optional().describe('Whether scheduled checks should evaluate this alert.'),+ metric: zod+ .enum(['spend', 'projected_spend'])+ .describe('\* `spend` - Spend\n\* `projected_spend` - Projected spend')+ .optional()+ .describe(+ 'Billing-period total to evaluate: current spend so far, or projected period-end spend.\n\n\* `spend` - Spend\n\* `projected_spend` - Projected spend'+ ),+ threshold_type: zod+ .enum(['relative_increase', 'absolute_value', 'absolute_increase'])+ .describe(+ '\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'+ )+ .optional()+ .describe(+ 'Threshold rule type. The first version supports absolute value only.\n\n\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'+ ),+ threshold_percentage: zod+ .stringFormat('decimal', billingAlertsCreateBodyThresholdPercentageRegExp)+ .nullish()+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),+ threshold_value: zod+ .stringFormat('decimal', billingAlertsCreateBodyThresholdValueRegExp)+ .nullish()+ .describe('Absolute value or absolute increase that triggers absolute threshold alerts.'),+ minimum_value: zod+ .stringFormat('decimal', billingAlertsCreateBodyMinimumValueRegExp)+ .optional()+ .describe('Minimum current value before the alert can fire.'),+ baseline_window_days: zod+ .number()+ .min(1)+ .max(billingAlertsCreateBodyBaselineWindowDaysMax)+ .optional()+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),+ evaluation_delay_hours: zod+ .number()+ .min(billingAlertsCreateBodyEvaluationDelayHoursMin)+ .max(billingAlertsCreateBodyEvaluationDelayHoursMax)+ .optional()+ .describe('Hours after a UTC billing date ends before it becomes eligible for evaluation.'),+ cooldown_hours: zod+ .number()+ .min(billingAlertsCreateBodyCooldownHoursMin)+ .max(billingAlertsCreateBodyCooldownHoursMax)+ .optional()+ .describe('Minimum hours between repeated firing notifications.'),+ snoozed_until: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.'),+ destination_changes: zod+ .object({+ delete: zod+ .array(+ zod+ .array(zod.uuid())+ .min(billingAlertsCreateBodyDestinationChangesOneDeleteItemMin)+ .max(billingAlertsCreateBodyDestinationChangesOneDeleteItemMax)+ )+ .optional(),+ create: zod+ .array(+ zod.object({+ type: zod+ .enum(['slack', 'webhook', 'teams'])+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')+ .describe(+ 'Destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'+ ),+ slack_workspace_id: zod+ .number()+ .optional()+ .describe('Slack integration ID in the alert execution project.'),+ slack_channel_id: zod.string().optional().describe('Slack channel ID for alert delivery.'),+ slack_channel_name: zod+ .string()+ .optional()+ .describe('Optional Slack channel name shown in the UI.'),+ webhook_url: zod+ .url()+ .optional()+ .describe('HTTPS webhook URL for webhook or Microsoft Teams delivery.'),+ })+ )+ .optional(),+ })+ .optional()+ .describe('Destination groups to create or delete in the same transaction as this configuration write.'),+})++export const billingAlertsUpdateBodyNameMax = 160++export const billingAlertsUpdateBodyThresholdPercentageRegExp = new RegExp('^-?\\d{0,6}(?:\\.\\d{0,2})?$')+export const billingAlertsUpdateBodyThresholdValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')+export const billingAlertsUpdateBodyMinimumValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')+export const billingAlertsUpdateBodyBaselineWindowDaysMax = 90++export const billingAlertsUpdateBodyEvaluationDelayHoursMin = 0+export const billingAlertsUpdateBodyEvaluationDelayHoursMax = 72++export const billingAlertsUpdateBodyCooldownHoursMin = 0+export const billingAlertsUpdateBodyCooldownHoursMax = 720++export const billingAlertsUpdateBodyDestinationChangesOneDeleteItemMin = 4+export const billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax = 4++export const BillingAlertsUpdateBody = /* @__PURE__ */ zod.object({+ name: zod.string().max(billingAlertsUpdateBodyNameMax).describe('Display name for this billing alert.'),+ description: zod.string().optional().describe('Optional internal description.'),+ enabled: zod.boolean().optional().describe('Whether scheduled checks should evaluate this alert.'),+ metric: zod+ .enum(['spend', 'projected_spend'])+ .describe('\* `spend` - Spend\n\* `projected_spend` - Projected spend')+ .optional()+ .describe(+ 'Billing-period total to evaluate: current spend so far, or projected period-end spend.\n\n\* `spend` - Spend\n\* `projected_spend` - Projected spend'+ ),+ threshold_type: zod+ .enum(['relative_increase', 'absolute_value', 'absolute_increase'])+ .describe(+ '\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'+ )+ .optional()+ .describe(+ 'Threshold rule type. The first version supports absolute value only.\n\n\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'+ ),+ threshold_percentage: zod+ .stringFormat('decimal', billingAlertsUpdateBodyThresholdPercentageRegExp)+ .nullish()+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),+ threshold_value: zod+ .stringFormat('decimal', billingAlertsUpdateBodyThresholdValueRegExp)+ .nullish()+ .describe('Absolute value or absolute increase that triggers absolute threshold alerts.'),+ minimum_value: zod+ .stringFormat('decimal', billingAlertsUpdateBodyMinimumValueRegExp)+ .optional()+ .describe('Minimum current value before the alert can fire.'),+ baseline_window_days: zod+ .number()+ .min(1)+ .max(billingAlertsUpdateBodyBaselineWindowDaysMax)+ .optional()+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),+ evaluation_delay_hours: zod+ .number()+ .min(billingAlertsUpdateBodyEvaluationDelayHoursMin)+ .max(billingAlertsUpdateBodyEvaluationDelayHoursMax)+ .optional()+ .describe('Hours after a UTC billing date ends before it becomes eligible for evaluation.'),+ cooldown_hours: zod+ .number()+ .min(billingAlertsUpdateBodyCooldownHoursMin)+ .max(billingAlertsUpdateBodyCooldownHoursMax)+ .optional()+ .describe('Minimum hours between repeated firing notifications.'),+ snoozed_until: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.'),+ destination_changes: zod+ .object({+ delete: zod+ .array(+ zod+ .array(zod.uuid())+ .min(billingAlertsUpdateBodyDestinationChangesOneDeleteItemMin)+ .max(billingAlertsUpdateBodyDestinationChangesOneDeleteItemMax)+ )+ .optional(),+ create: zod+ .array(+ zod.object({+ type: zod+ .enum(['slack', 'webhook', 'teams'])+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')+ .describe(+ 'Destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'+ ),+ slack_workspace_id: zod+ .number()+ .optional()+ .describe('Slack integration ID in the alert execution project.'),+ slack_channel_id: zod.string().optional().describe('Slack channel ID for alert delivery.'),+ slack_channel_name: zod+ .string()+ .optional()+ .describe('Optional Slack channel name shown in the UI.'),+ webhook_url: zod+ .url()+ .optional()+ .describe('HTTPS webhook URL for webhook or Microsoft Teams delivery.'),+ })+ )+ .optional(),+ })+ .optional()+ .describe('Destination groups to create or delete in the same transaction as this configuration write.'),+})++export const billingAlertsPartialUpdateBodyNameMax = 160++export const billingAlertsPartialUpdateBodyThresholdPercentageRegExp = new RegExp('^-?\\d{0,6}(?:\\.\\d{0,2})?$')+export const billingAlertsPartialUpdateBodyThresholdValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')+export const billingAlertsPartialUpdateBodyMinimumValueRegExp = new RegExp('^-?\\d{0,14}(?:\\.\\d{0,6})?$')+export const billingAlertsPartialUpdateBodyBaselineWindowDaysMax = 90++export const billingAlertsPartialUpdateBodyEvaluationDelayHoursMin = 0+export const billingAlertsPartialUpdateBodyEvaluationDelayHoursMax = 72++export const billingAlertsPartialUpdateBodyCooldownHoursMin = 0+export const billingAlertsPartialUpdateBodyCooldownHoursMax = 720++export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin = 4+export const billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax = 4++export const BillingAlertsPartialUpdateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(billingAlertsPartialUpdateBodyNameMax)+ .optional()+ .describe('Display name for this billing alert.'),+ description: zod.string().optional().describe('Optional internal description.'),+ enabled: zod.boolean().optional().describe('Whether scheduled checks should evaluate this alert.'),+ metric: zod+ .enum(['spend', 'projected_spend'])+ .describe('\* `spend` - Spend\n\* `projected_spend` - Projected spend')+ .optional()+ .describe(+ 'Billing-period total to evaluate: current spend so far, or projected period-end spend.\n\n\* `spend` - Spend\n\* `projected_spend` - Projected spend'+ ),+ threshold_type: zod+ .enum(['relative_increase', 'absolute_value', 'absolute_increase'])+ .describe(+ '\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'+ )+ .optional()+ .describe(+ 'Threshold rule type. The first version supports absolute value only.\n\n\* `relative_increase` - Relative increase\n\* `absolute_value` - Absolute value\n\* `absolute_increase` - Absolute increase'+ ),+ threshold_percentage: zod+ .stringFormat('decimal', billingAlertsPartialUpdateBodyThresholdPercentageRegExp)+ .nullish()+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),+ threshold_value: zod+ .stringFormat('decimal', billingAlertsPartialUpdateBodyThresholdValueRegExp)+ .nullish()+ .describe('Absolute value or absolute increase that triggers absolute threshold alerts.'),+ minimum_value: zod+ .stringFormat('decimal', billingAlertsPartialUpdateBodyMinimumValueRegExp)+ .optional()+ .describe('Minimum current value before the alert can fire.'),+ baseline_window_days: zod+ .number()+ .min(1)+ .max(billingAlertsPartialUpdateBodyBaselineWindowDaysMax)+ .optional()+ .describe('Reserved for future increase-over-baseline rules. Not used by absolute value alerts.'),+ evaluation_delay_hours: zod+ .number()+ .min(billingAlertsPartialUpdateBodyEvaluationDelayHoursMin)+ .max(billingAlertsPartialUpdateBodyEvaluationDelayHoursMax)+ .optional()+ .describe('Hours after a UTC billing date ends before it becomes eligible for evaluation.'),+ cooldown_hours: zod+ .number()+ .min(billingAlertsPartialUpdateBodyCooldownHoursMin)+ .max(billingAlertsPartialUpdateBodyCooldownHoursMax)+ .optional()+ .describe('Minimum hours between repeated firing notifications.'),+ snoozed_until: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('ISO 8601 timestamp until which evaluation and notifications are snoozed, or null to resume.'),+ destination_changes: zod+ .object({+ delete: zod+ .array(+ zod+ .array(zod.uuid())+ .min(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMin)+ .max(billingAlertsPartialUpdateBodyDestinationChangesOneDeleteItemMax)+ )+ .optional(),+ create: zod+ .array(+ zod.object({+ type: zod+ .enum(['slack', 'webhook', 'teams'])+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')+ .describe(+ 'Destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'+ ),+ slack_workspace_id: zod+ .number()+ .optional()+ .describe('Slack integration ID in the alert execution project.'),+ slack_channel_id: zod.string().optional().describe('Slack channel ID for alert delivery.'),+ slack_channel_name: zod+ .string()+ .optional()+ .describe('Optional Slack channel name shown in the UI.'),+ webhook_url: zod+ .url()+ .optional()+ .describe('HTTPS webhook URL for webhook or Microsoft Teams delivery.'),+ })+ )+ .optional(),+ })+ .optional()+ .describe('Destination groups to create or delete in the same transaction as this configuration write.'),+})++/**+ * Create a notification destination for this alert. One HogFunction is created per alert event kind.+ */+export const BillingAlertsDestinationsCreateBody = /* @__PURE__ */ zod.object({+ type: zod+ .enum(['slack', 'webhook', 'teams'])+ .describe('\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams')+ .describe('Destination type.\n\n\* `slack` - slack\n\* `webhook` - webhook\n\* `teams` - teams'),+ slack_workspace_id: zod.number().optional().describe('Slack integration ID in the alert execution project.'),+ slack_channel_id: zod.string().optional().describe('Slack channel ID for alert delivery.'),+ slack_channel_name: zod.string().optional().describe('Optional Slack channel name shown in the UI.'),+ webhook_url: zod.url().optional().describe('HTTPS webhook URL for webhook or Microsoft Teams delivery.'),+})++/**+ * Delete a notification destination by deleting its HogFunction group atomically.+ */+export const billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMin = 4+export const billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax = 4++export const BillingAlertsDestinationsDeleteCreateBody = /* @__PURE__ */ zod.object({+ hog_function_ids: zod+ .array(zod.uuid())+ .min(billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMin)+ .max(billingAlertsDestinationsDeleteCreateBodyHogFunctionIdsMax)+ .describe('HogFunction IDs to delete as one atomic destination group.'),+})diff --git a/products/billing/mcp/tools.yaml b/products/billing/mcp/tools.yamlnew file mode 100644index 000000000000..f20a54e70db9--- /dev/null+++ b/products/billing/mcp/tools.yaml@@ -0,0 +1,101 @@+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.+# The tool list and operation IDs are kept in sync automatically:+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all+#+# To enable a tool, set enabled: true and add required scopes + annotations.+# All other fields (title, description, enrich_url, etc.) are yours to configure.+category: Billing+feature: billing+url_prefix: /billing+ui_apps: {}+tools:+ billing-activate-authorize-create:+ operation: billing_activate_authorize_create+ enabled: false+ billing-activate-authorize-status-create:+ operation: billing_activate_authorize_status_create+ enabled: false+ billing-activate-create:+ operation: billing_activate_create+ enabled: false+ billing-alerts-check-now-create:+ operation: billing_alerts_check_now_create+ enabled: false+ billing-alerts-create:+ operation: billing_alerts_create+ enabled: false+ billing-alerts-destinations-create:+ operation: billing_alerts_destinations_create+ enabled: false+ billing-alerts-destinations-delete-create:+ operation: billing_alerts_destinations_delete_create+ enabled: false+ billing-alerts-destroy:+ operation: billing_alerts_destroy+ enabled: false+ billing-alerts-events-list:+ operation: billing_alerts_events_list+ enabled: false+ billing-alerts-list:+ operation: billing_alerts_list+ enabled: false+ billing-alerts-partial-update:+ operation: billing_alerts_partial_update+ enabled: false+ billing-alerts-retrieve:+ operation: billing_alerts_retrieve+ enabled: false+ billing-alerts-update:+ operation: billing_alerts_update+ enabled: false+ billing-coupons-claim-create:+ operation: billing_coupons_claim_create+ enabled: false+ billing-coupons-overview-retrieve:+ operation: billing_coupons_overview_retrieve+ enabled: false+ billing-credits-overview-retrieve:+ operation: billing_credits_overview_retrieve+ enabled: false+ billing-credits-purchase-create:+ operation: billing_credits_purchase_create+ enabled: false+ billing-deactivate-create:+ operation: billing_deactivate_create+ enabled: false+ billing-get-invoices-retrieve:+ operation: billing_get_invoices_retrieve+ enabled: false+ billing-license-partial-update:+ operation: billing_license_partial_update+ enabled: false+ billing-list:+ operation: billing_list+ enabled: false+ billing-partial-update:+ operation: billing_partial_update+ enabled: false+ billing-period-retrieve:+ operation: billing_period_retrieve+ enabled: false+ billing-portal-retrieve:+ operation: billing_portal_retrieve+ enabled: false+ billing-spend-retrieve:+ operation: billing_spend_retrieve+ enabled: false+ billing-startups-apply-create:+ operation: billing_startups_apply_create+ enabled: false+ billing-subscription-switch-plan-create:+ operation: billing_subscription_switch_plan_create+ enabled: false+ billing-trials-activate-create:+ operation: billing_trials_activate_create+ enabled: false+ billing-trials-cancel-create:+ operation: billing_trials_cancel_create+ enabled: false+ billing-usage-retrieve:+ operation: billing_usage_retrieve+ enabled: falsediff --git a/products/billing/package.json b/products/billing/package.jsonnew file mode 100644index 000000000000..1cfec0eb3cf6--- /dev/null+++ b/products/billing/package.json@@ -0,0 +1,3 @@+{+ "name": "@posthog/products-billing"+}diff --git a/products/billing/product.yaml b/products/billing/product.yamlnew file mode 100644index 000000000000..64c88ce70429--- /dev/null+++ b/products/billing/product.yaml@@ -0,0 +1,3 @@+name: Billing+owners:+ - team-billingdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 434e948ddd74..6e2b79a10fa7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13049,6 +13049,12 @@ export namespace Schemas {BigQuery: 'BigQuery',} as const;+ export interface Billing {+ /** @maxLength 100 */+ plan: string;+ billing_limit: number;+ }+/*** * `check` - Check* * `firing` - Firing@@ -13455,6 +13461,60 @@ export namespace Schemas {PosthogSystem: 'posthog_system',} as const;+ export type BillingOverviewResponseProductsItem = {[key: string]: unknown};++ export interface BillingOverviewResponse {+ /** @nullable */+ customer_id?: string | null;+ /** @nullable */+ billing_plan?: string | null;+ /** @nullable */+ subscription_level?: string | null;+ has_active_subscription?: boolean;+ deactivated?: boolean;+ is_annual_plan_customer?: boolean;+ /** @nullable */+ free_trial_until?: string | null;+ /** @nullable */+ current_total_amount_usd?: string | null;+ /** @nullable */+ current_total_amount_usd_after_discount?: string | null;+ /** @nullable */+ projected_total_amount_usd?: string | null;+ /** @nullable */+ projected_total_amount_usd_after_discount?: string | null;+ /** @nullable */+ projected_total_amount_usd_with_limit?: string | null;+ /** @nullable */+ projected_total_amount_usd_with_limit_after_discount?: string | null;+ /** @nullable */+ discount_amount_usd?: string | null;+ /** @nullable */+ discount_percent?: number | null;+ /** @nullable */+ amount_off_expires_at?: string | null;+ /** @nullable */+ startup_program_label?: string | null;+ /** @nullable */+ startup_program_label_previous?: string | null;+ /** @nullable */+ stripe_portal_url?: string | null;+ /** @nullable */+ external_billing_provider_invoices_url?: string | null;+ /** Subscribed and available products/addons with pricing, plan, limit, usage, and entitlement metadata. */+ products?: BillingOverviewResponseProductsItem[];+ available_product_features?: string[];+ usage_summary?: unknown;+ billing_period?: unknown;+ custom_limits_usd?: unknown;+ next_period_custom_limits_usd?: unknown;+ trial?: unknown;+ license?: unknown;+ account_owner?: unknown;+ customer_trust_scores?: unknown;+ never_drop_data?: boolean;+ }+/*** * `excluded` - Excluded* * `credited` - Credited@@ -13467,6 +13527,19 @@ export namespace Schemas {Credited: 'credited',} as const;+ export interface BillingPeriodResponse {+ /**+ * Start of the organization's current billing period, or null when billing has not synced a period.+ * @nullable+ */+ current_period_start: string | null;+ /**+ * End of the organization's current billing period, or null when billing has not synced a period.+ * @nullable+ */+ current_period_end: string | null;+ }+/*** * `team_retention` - team_retention* * `byte_budget` - byte_budget@@ -56150,6 +56223,12 @@ export namespace Schemas {readonly import_config?: unknown;}+ export interface PatchedBilling {+ /** @maxLength 100 */+ plan?: string;+ billing_limit?: number;+ }+export interface PatchedBillingAlertConfiguration {/** Unique identifier for this billing alert. */readonly id?: string;diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex 7bdd1ed5ce98..fae772467fca 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -29,6 +29,8 @@ export const OAUTH_SCOPES_SUPPORTED = ['batch_export:write','batch_import:read','batch_import:write',+ 'billing:read',+ 'billing:write','business_knowledge:read','business_knowledge:write','canvas:read',