: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): member read-only access to usage and spend tabs (#69406)
Luke Baber725f61872ce4
diff --git a/ee/api/billing.py b/ee/api/billing.pyindex 5031a6cbc4cf..e85826ab90a7 100644--- a/ee/api/billing.py+++ b/ee/api/billing.py@@ -1,4 +1,5 @@import json+from collections.abc import Callable, Sequencefrom typing import Any, Optionalfrom zoneinfo import ZoneInfo@@ -22,7 +23,13 @@ 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 get_authenticator_scopes, posthog_feature_flag_enabled+from posthog.permissions import (+ get_authenticator_scoped_team_ids,+ get_authenticator_scopes,+ posthog_feature_flag_enabled,+)+from posthog.rbac.user_access_control import UserAccessControl, visible_teams_for_user+from posthog.user_permissions import UserPermissionsfrom posthog.utils import get_trusted_client_ip, relative_date_parsefrom ee.billing.billing_manager import BillingManager@@ -34,6 +41,7 @@ logger = structlog.get_logger(__name__)BILLING_SERVICE_JWT_AUD = "posthog:license-key"OWNER_ONLY_BILLING_FLAG = "owner-only-billing"+MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG = "member-billing-usage-spend-read-access"def _owner_only_billing_enabled(user: User, organization: Organization) -> Optional[bool]:@@ -66,6 +74,45 @@ def user_has_billing_access(user: User, organization: Organization) -> bool:return _owner_only_billing_enabled(user, organization) is False+def _member_billing_usage_spend_read_access_enabled(user: User, organization: Organization) -> bool:+ if not user.distinct_id:+ return False++ try:+ return (+ posthog_feature_flag_enabled(+ MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG,+ str(user.distinct_id),+ organization_id=organization.id,+ )+ is True+ )+ except Exception as e:+ capture_exception(e, {"organization_id": organization.id, "flag": MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG})+ return False+++def user_has_billing_usage_spend_read_access(user: User, organization: Organization) -> bool:+ membership = OrganizationMembership.objects.filter(user=user, organization=organization).only("level").first()+ if not membership:+ return False++ if membership.level >= OrganizationMembership.Level.OWNER:+ return True++ # Only a confirmed disabled flag lets non-owners through. Unknown flag state fails closed to owners.+ if _owner_only_billing_enabled(user, organization) is not False:+ return False++ if membership.level >= OrganizationMembership.Level.ADMIN:+ return True++ if membership.level < OrganizationMembership.Level.MEMBER:+ return False++ return _member_billing_usage_spend_read_access_enabled(user, organization)++def is_token_auth_request(request: Request) -> bool:return get_authenticator_scopes(getattr(request, "successful_authenticator", None)) is not None@@ -89,6 +136,27 @@ class HasBillingAccess(permissions.BasePermission):return user_has_billing_access(request.user, org)+class HasBillingUsageSpendReadAccess(permissions.BasePermission):+ """+ Permission for read-only billing usage/spend endpoints. The frontend additionally requires+ usage-spend-dashboards before honoring the member grant, but that flag is not an authorization+ input here or in the billing service.+ """++ message = "You do not have access to billing usage and spend data for this organization."++ def has_permission(self, request: Request, view: Any) -> bool:+ try:+ org = view._get_org_required()+ except Exception:+ return False++ if not isinstance(request.user, User):+ return False++ return user_has_billing_usage_spend_read_access(request.user, org)++class BillingSerializer(serializers.Serializer):plan = serializers.CharField(max_length=100)billing_limit = serializers.IntegerField()@@ -163,7 +231,9 @@ class BillingUsageRequestSerializer(serializers.Serializer):allow_null=True,help_text=("JSON-encoded array of numeric team/project IDs to filter on, "- "for example [1,2]. Omit for all teams in the organization."+ "for example [1,2]. Omit for all projects available to the caller. Full billing-access callers can read "+ "all organization projects; member read-only callers are limited to visible projects and any project "+ "scope on their token."),)breakdowns = serializers.CharField(@@ -752,71 +822,59 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):methods=["GET"],detail=False,url_path="usage",- permission_classes=[permissions.IsAuthenticated, HasBillingAccess],+ permission_classes=[permissions.IsAuthenticated, HasBillingUsageSpendReadAccess],responses={200: BillingTimeSeriesResponseSerializer},)def usage(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:- organization = self._get_org_required()-- billing_manager = self.get_billing_manager()-- serializer = BillingUsageRequestSerializer(data=request.GET)- serializer.is_valid(raise_exception=True)- self._check_requested_team_ids_belong_to_org(organization, serializer.validated_data.get("team_ids"))-- teams_map = self._get_teams_map(organization)-- try:- params_to_pass = {k: v for k, v in serializer.validated_data.items() if v is not None}- params_to_pass["teams_map"] = teams_map- res = billing_manager.get_usage_data(organization, params_to_pass)- return Response(res, status=status.HTTP_200_OK)- except Exception as e:- if len(e.args) > 2:- detail_object = e.args[2]- if not isinstance(detail_object, dict):- raise- return Response(- {- "statusText": e.args[0],- "detail": detail_object.get("error_message", detail_object),- "code": detail_object.get("code"),- },- status=status.HTTP_400_BAD_REQUEST,- )- else:- raise+ return self._usage_or_spend_response(request, self.get_billing_manager().get_usage_data)@extend_schema(parameters=[BillingUsageRequestSerializer])@action(methods=["GET"],detail=False,url_path="spend",- permission_classes=[permissions.IsAuthenticated, HasBillingAccess],+ permission_classes=[permissions.IsAuthenticated, HasBillingUsageSpendReadAccess],responses={200: BillingTimeSeriesResponseSerializer},)def spend(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:"""Endpoint to fetch spend data (proxy to billing service)."""- organization = self._get_org_required()-- billing_manager = self.get_billing_manager()+ return self._usage_or_spend_response(request, self.get_billing_manager().get_spend_data)+ def _usage_or_spend_response(+ self,+ request: Request,+ billing_data_getter: Callable[[Organization, dict[str, Any]], Any],+ ) -> HttpResponse:+ organization = self._get_org_required()serializer = BillingUsageRequestSerializer(data=request.GET)serializer.is_valid(raise_exception=True)self._check_requested_team_ids_belong_to_org(organization, serializer.validated_data.get("team_ids"))- teams_map = self._get_teams_map(organization)-try:params_to_pass = {k: v for k, v in serializer.validated_data.items() if v is not None}+ scoped_team_ids = self._scoped_team_ids_for_usage_spend_request(request, organization, params_to_pass)+ teams_map = self._get_teams_map(organization, scoped_team_ids)params_to_pass["teams_map"] = teams_map- res = billing_manager.get_spend_data(organization, params_to_pass)++ if scoped_team_ids is not None:+ params_to_pass["team_ids"] = json.dumps(scoped_team_ids)++ res = billing_data_getter(organization, params_to_pass)+ if scoped_team_ids is not None and isinstance(res, dict) and "team_id_options" in res:+ scoped_team_id_set = set(scoped_team_ids)+ res["team_id_options"] = [+ team_id for team_id in (res.get("team_id_options") or []) if team_id in scoped_team_id_set+ ]return Response(res, status=status.HTTP_200_OK)except Exception as e:if len(e.args) > 2:detail_object = e.args[2]if not isinstance(detail_object, dict):raise+ if detail_object.get("code") == "permission_denied":+ # billing evaluates the same permission from its own cache, so flag rollout+ # windows can still return a downstream permission denial.+ raise PermissionDenied(HasBillingUsageSpendReadAccess.message)return Response({"statusText": e.args[0],@@ -828,12 +886,61 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):else:raise- def _get_teams_map(self, organization: Organization) -> dict[int, str]:+ def _scoped_team_ids_for_usage_spend_request(+ self, request: Request, organization: Organization, params_to_pass: dict[str, Any]+ ) -> Optional[Sequence[int]]:+ if not isinstance(request.user, User) or user_has_billing_access(request.user, organization):+ return None++ accessible_team_ids = self._team_ids_visible_to_user_in_org(request.user, organization)+ token_scoped_team_ids = get_authenticator_scoped_team_ids(getattr(request, "successful_authenticator", None))+ if token_scoped_team_ids is not None:+ accessible_team_ids = sorted(set(accessible_team_ids).intersection(token_scoped_team_ids))++ if not accessible_team_ids:+ raise PermissionDenied(HasBillingUsageSpendReadAccess.message)++ requested_team_ids = self._parse_team_ids(params_to_pass.get("team_ids"))+ if not requested_team_ids:+ return accessible_team_ids++ scoped_team_ids = sorted(set(requested_team_ids).intersection(accessible_team_ids))+ if not scoped_team_ids:+ raise PermissionDenied(HasBillingUsageSpendReadAccess.message)++ return scoped_team_ids++ def _team_ids_visible_to_user_in_org(self, user: User, organization: Organization) -> Sequence[int]:+ return list(+ visible_teams_for_user(+ organization,+ UserAccessControl(user=user, organization_id=str(organization.id)),+ UserPermissions(user=user),+ )+ .order_by("id")+ .values_list("id", flat=True)+ )++ def _parse_team_ids(self, team_ids: Optional[str]) -> Sequence[int]:+ if not team_ids:+ return []++ parsed_team_ids = json.loads(team_ids)+ if not isinstance(parsed_team_ids, list):+ raise ValidationError({"team_ids": "Value must be a JSON array of numeric team IDs."})++ return [team_id for team_id in parsed_team_ids if isinstance(team_id, int) and not isinstance(team_id, bool)]++ def _get_teams_map(self, organization: Organization, team_ids: Optional[Sequence[int]] = None) -> dict[int, str]:"""- Safely build a mapping of team.id to team.name for the org. Return empty dict on failure.+ Safely build a mapping of team.id to team.name for the org, optionally limited to team_ids.+ Return empty dict on failure."""try:- return {team.id: team.name for team in Team.objects.filter(organization=organization)}+ teams = Team.objects.filter(organization=organization)+ if team_ids is not None:+ teams = teams.filter(id__in=team_ids)+ return {team.id: team.name for team in teams}except Exception as e:capture_exception(e, {"organization_id": organization.id})return {}diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.pyindex e0098853b186..663e4aa399d9 100644--- a/ee/api/test/test_billing.py+++ b/ee/api/test/test_billing.py@@ -7,7 +7,7 @@ from zoneinfo import ZoneInfofrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, _create_event, flush_persons_and_eventsfrom unittest import TestCase-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, PropertyMock, patchfrom django.utils.timezone import now@@ -18,18 +18,27 @@ from requests import Response, getfrom rest_framework import statusfrom posthog.cloud_utils import TEST_clear_instance_license_cache, get_cached_instance_license+from posthog.constants import AvailableFeaturefrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Team+from posthog.models.user import Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from ee.api.billing import BillingUsageRequestSerializer, BillingViewset+from ee.api.billing import (+ MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG,+ OWNER_ONLY_BILLING_FLAG,+ BillingUsageRequestSerializer,+ BillingViewset,+ HasBillingUsageSpendReadAccess,+)from ee.api.test.base import APILicensedTestfrom ee.billing.billing_types import USAGE_TYPE_OPTIONS, BillingPeriod, CustomerInfo, CustomerProduct, UsageTypefrom ee.billing.quota_limiting import QuotaResourcefrom ee.billing.test.test_billing_manager import create_default_products_responsefrom ee.models.license import License+from ee.models.rbac.access_control import AccessControldef create_usage_summary(**kwargs) -> dict[str, Any]:@@ -1217,6 +1226,15 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):self.client.logout()return {"HTTP_AUTHORIZATION": f"Bearer {token}"}+ def _token_headers(+ self, token_type: str, scopes: list[str], scoped_teams: list[int] | None = None+ ) -> dict[str, str]:+ if token_type == "personal":+ return self._personal_api_key_headers(scopes, scoped_teams=scoped_teams)+ if token_type == "oauth":+ return self._oauth_token_headers(scopes, scoped_teams=scoped_teams)+ raise AssertionError(f"Unknown token type: {token_type}")+def test_scope_actions_are_read_only(self):self.assertEqual(BillingViewset.scope_object, "billing")self.assertEqual(BillingViewset.scope_object_read_actions, ["list", "usage", "spend"])@@ -1255,8 +1273,9 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):),])+ @patch("ee.api.billing.posthog_feature_flag_enabled", return_value=False)def test_billing_read_scope_actions_still_require_billing_access(- self, action_name, method_name, url, data, manager_method_path+ self, action_name, method_name, url, data, manager_method_path, _mock_feature_enabled):self.assertIn(action_name, BillingViewset.scope_object_read_actions)self.organization_membership.level = OrganizationMembership.Level.MEMBER@@ -1417,6 +1436,76 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ @parameterized.expand([("usage", "get_usage_data"), ("spend", "get_spend_data")])+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_billing_read_personal_api_key_can_read_usage_and_spend_when_flag_allows(+ self, endpoint: str, manager_method: str, mock_feature_enabled: MagicMock+ ):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ mock_feature_enabled.side_effect = self._member_access_flags+ headers = self._personal_api_key_headers(["billing:read"], scoped_teams=[self.team.pk])++ with patch(f"ee.billing.billing_manager.BillingManager.{manager_method}") as mock_fetch:+ mock_fetch.return_value = self.MOCK_USAGE_DATA if endpoint == "usage" else self.MOCK_SPEND_DATA+ response = self.client.get(+ f"/api/billing/{endpoint}/",+ {"start_date": "2025-01-01"},+ HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_fetch.assert_called_once()+ passed_params = mock_fetch.call_args[0][1]+ self.assertEqual(json.loads(passed_params["team_ids"]), [self.team.pk])+ self.assertEqual(passed_params["teams_map"], {self.team.pk: self.team.name})++ @parameterized.expand([("personal",), ("oauth",)])+ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_token_scope_limits_injected_team_ids(+ self, token_type: str, mock_feature_enabled: MagicMock, mock_get_usage_data: MagicMock+ ):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ other_team = Team.objects.create(organization=self.organization, name="Other visible project")+ mock_feature_enabled.side_effect = self._member_access_flags+ mock_get_usage_data.return_value = self.MOCK_USAGE_DATA+ headers = self._token_headers(token_type, ["billing:read"], scoped_teams=[self.team.pk])++ response = self.client.get(+ "/api/billing/usage/",+ HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_get_usage_data.assert_called_once()+ passed_params = mock_get_usage_data.call_args[0][1]+ self.assertEqual(json.loads(passed_params["team_ids"]), [self.team.pk])+ self.assertEqual(passed_params["teams_map"], {self.team.pk: self.team.name})+ self.assertNotIn(other_team.pk, passed_params["teams_map"])++ @parameterized.expand([("personal",), ("oauth",)])+ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_token_scope_rejects_requested_team_outside_token_scope(+ self, token_type: str, mock_feature_enabled: MagicMock, mock_get_usage_data: MagicMock+ ):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ other_team = Team.objects.create(organization=self.organization, name="Other visible project")+ mock_feature_enabled.side_effect = self._member_access_flags+ headers = self._token_headers(token_type, ["billing:read"], scoped_teams=[self.team.pk])++ response = self.client.get(+ "/api/billing/usage/",+ {"team_ids": f"[{other_team.pk}]"},+ 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_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([])@@ -1442,9 +1531,11 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):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):+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_list_rejects_billing_read_personal_api_key_for_member(self, mock_feature_enabled, mock_get_billing):self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()+ mock_feature_enabled.side_effect = self._member_access_flagsheaders = self._personal_api_key_headers(["billing:read"], scoped_teams=[self.team.pk])response = self.client.get(@@ -1491,8 +1582,11 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):self.assertEqual(response.status_code, status.HTTP_200_OK)mock_get_usage_data.assert_called_once()- mock_feature_enabled.assert_called_once()- self.assertEqual(mock_feature_enabled.call_args.args[0], "owner-only-billing")+ mock_feature_enabled.assert_any_call(+ OWNER_ONLY_BILLING_FLAG,+ str(self.user.distinct_id),+ organization_id=self.organization.id,+ )@patch("ee.billing.billing_manager.BillingManager.get_usage_data")@patch("ee.api.billing.posthog_feature_flag_enabled", return_value=None)@@ -1578,6 +1672,119 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):response = self.client.get("/api/billing/spend/")self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ @parameterized.expand(+ [+ ("usage", True, False, status.HTTP_200_OK),+ ("spend", True, False, status.HTTP_200_OK),+ ("usage", True, True, status.HTTP_403_FORBIDDEN),+ ("spend", True, True, status.HTTP_403_FORBIDDEN),+ ("usage", False, False, status.HTTP_403_FORBIDDEN),+ ("spend", False, False, status.HTTP_403_FORBIDDEN),+ ]+ )+ @patch("ee.billing.billing_manager.BillingManager.get_spend_data")+ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_access_gated_by_flags(+ self,+ endpoint: str,+ member_access_flag: bool,+ owner_only_flag: bool,+ expected_status: int,+ mock_flag_eval: MagicMock,+ mock_get_usage_data: MagicMock,+ mock_get_spend_data: MagicMock,+ ):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ mock_flag_eval.side_effect = lambda key, *args, **kwargs: {+ MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG: member_access_flag,+ OWNER_ONLY_BILLING_FLAG: owner_only_flag,+ }[key]+ mock_get_usage_data.return_value = self.MOCK_USAGE_DATA+ mock_get_spend_data.return_value = self.MOCK_SPEND_DATA++ response = self.client.get(f"/api/billing/{endpoint}/")++ self.assertEqual(response.status_code, expected_status)+ if expected_status == status.HTTP_403_FORBIDDEN:+ mock_get_usage_data.assert_not_called()+ mock_get_spend_data.assert_not_called()+ else:+ expected_data = self.MOCK_USAGE_DATA if endpoint == "usage" else self.MOCK_SPEND_DATA+ self.assertEqual(response.json(), expected_data)++ @patch("ee.api.billing.capture_exception")+ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_access_denies_when_member_flag_check_raises(+ self,+ mock_feature_enabled: MagicMock,+ mock_get_usage_data: MagicMock,+ mock_capture_exception: MagicMock,+ ):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()++ def flag_response(key: str, *args: Any, **kwargs: Any) -> bool:+ if key == OWNER_ONLY_BILLING_FLAG:+ return False+ if key == MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG:+ raise Exception("flag lookup failed")+ raise AssertionError(f"Unexpected flag: {key}")++ mock_feature_enabled.side_effect = flag_response++ response = self.client.get("/api/billing/usage/")++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ mock_get_usage_data.assert_not_called()+ mock_capture_exception.assert_called_once()++ @parameterized.expand(+ [+ ("usage", OrganizationMembership.Level.ADMIN, False, status.HTTP_200_OK),+ ("spend", OrganizationMembership.Level.ADMIN, False, status.HTTP_200_OK),+ ("usage", OrganizationMembership.Level.ADMIN, True, status.HTTP_403_FORBIDDEN),+ ("spend", OrganizationMembership.Level.ADMIN, True, status.HTTP_403_FORBIDDEN),+ ("usage", OrganizationMembership.Level.OWNER, True, status.HTTP_200_OK),+ ("spend", OrganizationMembership.Level.OWNER, True, status.HTTP_200_OK),+ ]+ )+ @patch("ee.billing.billing_manager.BillingManager.get_spend_data")+ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_admin_and_owner_access_gated_only_by_owner_only_billing(+ self,+ endpoint: str,+ level: OrganizationMembership.Level,+ owner_only_flag: bool,+ expected_status: int,+ mock_flag_eval: MagicMock,+ mock_get_usage_data: MagicMock,+ mock_get_spend_data: MagicMock,+ ):+ self.organization_membership.level = level+ self.organization_membership.save()+ mock_flag_eval.side_effect = lambda key, *args, **kwargs: {+ MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG: False,+ OWNER_ONLY_BILLING_FLAG: owner_only_flag,+ }[key]+ mock_get_usage_data.return_value = self.MOCK_USAGE_DATA+ mock_get_spend_data.return_value = self.MOCK_SPEND_DATA++ response = self.client.get(f"/api/billing/{endpoint}/")++ self.assertEqual(response.status_code, expected_status)+ if expected_status == status.HTTP_403_FORBIDDEN:+ mock_get_usage_data.assert_not_called()+ mock_get_spend_data.assert_not_called()+ # The member read-access flag must never be consulted for admins and owners+ self.assertNotIn(+ MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG,+ [call.args[0] for call in mock_flag_eval.call_args_list],+ )+@patch("ee.billing.billing_manager.BillingManager.get_usage_data")@patch("ee.api.billing.BillingViewset._get_teams_map")def test_get_usage_empty_teams_map_graceful_handling(self, mock_get_teams_map, mock_get_usage_data):@@ -1608,6 +1815,207 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):self.assertEqual(passed_params["teams_map"], {})mock_get_teams_map.assert_called_once()+ @staticmethod+ def _member_access_flags(key: str, *args: Any, **kwargs: Any) -> bool:+ return key == MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG++ def _make_team_private(self, team: Team) -> None:+ AccessControl.objects.create(+ team=team,+ resource="project",+ resource_id=str(team.id),+ access_level="none",+ organization_member=None,+ role=None,+ )++ def _setup_member_with_private_team(self) -> Team:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ private_team = Team.objects.create(organization=self.organization, name="Private Team")+ self._make_team_private(private_team)+ return private_team++ @parameterized.expand([("usage",), ("spend",)])+ @patch("ee.billing.billing_manager.BillingManager.get_spend_data")+ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_team_ids_intersected_with_accessible_teams(+ self,+ endpoint: str,+ mock_flag_eval: MagicMock,+ mock_get_usage_data: MagicMock,+ mock_get_spend_data: MagicMock,+ ):+ private_team = self._setup_member_with_private_team()+ mock_flag_eval.side_effect = self._member_access_flags+ mock_get_usage_data.return_value = self.MOCK_USAGE_DATA+ mock_get_spend_data.return_value = self.MOCK_SPEND_DATA++ response = self.client.get(f"/api/billing/{endpoint}/?team_ids=[{self.team.pk},{private_team.pk}]")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_fetch = mock_get_usage_data if endpoint == "usage" else mock_get_spend_data+ mock_fetch.assert_called_once()+ passed_params = mock_fetch.call_args[0][1]+ self.assertEqual(json.loads(passed_params["team_ids"]), [self.team.pk])+ self.assertEqual(passed_params["teams_map"], {self.team.pk: self.team.name})++ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_without_team_ids_gets_accessible_teams_injected(+ self, mock_flag_eval: MagicMock, mock_get_usage_data: MagicMock+ ):+ self._setup_member_with_private_team()+ mock_flag_eval.side_effect = self._member_access_flags+ mock_get_usage_data.return_value = self.MOCK_USAGE_DATA++ response = self.client.get("/api/billing/usage/?start_date=2025-01-01")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_get_usage_data.assert_called_once()+ passed_params = mock_get_usage_data.call_args[0][1]+ self.assertEqual(json.loads(passed_params["team_ids"]), [self.team.pk])+ self.assertEqual(passed_params["teams_map"], {self.team.pk: self.team.name})++ @parameterized.expand([("usage",), ("spend",)])+ @patch("ee.billing.billing_manager.BillingManager.get_spend_data")+ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_requesting_only_inaccessible_teams_gets_403(+ self,+ endpoint: str,+ mock_flag_eval: MagicMock,+ mock_get_usage_data: MagicMock,+ mock_get_spend_data: MagicMock,+ ):+ private_team = self._setup_member_with_private_team()+ mock_flag_eval.side_effect = self._member_access_flags++ response = self.client.get(f"/api/billing/{endpoint}/?team_ids=[{private_team.pk}]")++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ # An empty team_ids list means "all teams" to the billing service, so it must never be called here+ mock_get_usage_data.assert_not_called()+ mock_get_spend_data.assert_not_called()++ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_with_zero_accessible_teams_never_calls_billing(+ self, mock_flag_eval: MagicMock, mock_get_usage_data: MagicMock+ ):+ self._setup_member_with_private_team()+ self._make_team_private(self.team)+ mock_flag_eval.side_effect = self._member_access_flags++ response = self.client.get("/api/billing/usage/")++ # TeamMemberAccessPermission rejects a member whose current team is private; the in-view+ # zero-accessible-teams guard backstops it. Either way billing must never be called, since+ # an absent or empty team_ids means "all teams" to the billing service.+ 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")+ def test_member_response_team_id_options_filtered(self, mock_flag_eval: MagicMock, mock_get_usage_data: MagicMock):+ private_team = self._setup_member_with_private_team()+ mock_flag_eval.side_effect = self._member_access_flags+ deleted_team_id = 999999+ mock_get_usage_data.return_value = {+ "results": [{"data": [1, 2], "count": 2}],+ "team_id_options": [self.team.pk, private_team.pk, deleted_team_id],+ }++ response = self.client.get("/api/billing/usage/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(data["team_id_options"], [self.team.pk])+ self.assertEqual(data["results"], [{"data": [1, 2], "count": 2}])++ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_scoping_does_not_depend_on_user_teams_first_org(+ self, mock_flag_eval: MagicMock, mock_get_usage_data: MagicMock+ ):+ private_team = self._setup_member_with_private_team()+ mock_flag_eval.side_effect = self._member_access_flags+ mock_get_usage_data.return_value = {+ "results": [],+ "team_id_options": [self.team.pk, private_team.pk],+ }++ # User.teams gates private-project filtering on the features of the user's *first* org.+ # Simulate the multi-org case where that first org lacks ACCESS_CONTROL, making User.teams+ # leak this org's private team: the endpoint must not use it as the security boundary.+ leaky_teams = Team.objects.filter(organization=self.organization)+ with patch.object(User, "teams", new_callable=PropertyMock, return_value=leaky_teams):+ response = self.client.get("/api/billing/usage/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_get_usage_data.assert_called_once()+ passed_params = mock_get_usage_data.call_args[0][1]+ self.assertEqual(json.loads(passed_params["team_ids"]), [self.team.pk])+ self.assertEqual(passed_params["teams_map"], {self.team.pk: self.team.name})+ self.assertEqual(response.json()["team_id_options"], [self.team.pk])++ @parameterized.expand([("not-json",), ('["a"]',)])+ @patch("ee.billing.billing_manager.BillingManager.get_usage_data")+ @patch("ee.api.billing.posthog_feature_flag_enabled")+ def test_member_malformed_team_ids_returns_400(+ self, raw_team_ids: str, mock_flag_eval: MagicMock, mock_get_usage_data: MagicMock+ ):+ self._setup_member_with_private_team()+ mock_flag_eval.side_effect = self._member_access_flags++ response = self.client.get(f"/api/billing/usage/?team_ids={raw_team_ids}")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ mock_get_usage_data.assert_not_called()++ @parameterized.expand([("usage",), ("spend",)])+ def test_billing_service_permission_denied_returns_403(self, endpoint: str):+ # The billing service gates these endpoints on the same flags we do, from its own cache, so a+ # flag rollout can leave it denying a request we allowed. That must read as a permission+ # denial, not as a generic failure.+ with patch(f"ee.billing.billing_manager.BillingManager.get_{endpoint}_data") as mock_fetch:+ mock_fetch.side_effect = Exception(+ "Billing service returned bad status code: 403",+ "body:",+ {+ "type": "authentication_error",+ "code": "permission_denied",+ "detail": "You do not have permission to perform this action.",+ "attr": None,+ },+ )++ response = self.client.get(f"/api/billing/{endpoint}/")++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["detail"], HasBillingUsageSpendReadAccess.message)++ @parameterized.expand([("usage",), ("spend",)])+ def test_billing_service_other_error_still_returns_400(self, endpoint: str):+ with patch(f"ee.billing.billing_manager.BillingManager.get_{endpoint}_data") as mock_fetch:+ mock_fetch.side_effect = Exception(+ "Billing service returned bad status code: 400",+ "body:",+ {"code": "invalid_input", "error_message": "start_date is invalid"},+ )++ response = self.client.get(f"/api/billing/{endpoint}/")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ data = response.json()+ self.assertEqual(data["code"], "invalid_input")+ self.assertEqual(data["detail"], "start_date is invalid")+class TestBillingPeriodAPI(APILicensedTest):def test_member_can_read_synced_organization_period(self):@@ -1690,6 +2098,8 @@ class TestBillingPermissionDeniedForMembers(APILicensedTest):@patch("ee.api.billing.requests.get")def test_list_still_accessible(self, mock_request):+ # Session-authenticated members can still read the historical billing overview payload.+ # MCP/token reads are separately gated by billing access.mock_request.return_value.status_code = 200mock_request.return_value.json.return_value = create_billing_response(customer=create_billing_customer(),diff --git a/frontend/src/lib/components/Account/AccountMenu.tsx b/frontend/src/lib/components/Account/AccountMenu.tsxindex 1e2432a77d40..a2da2ae1026e 100644--- a/frontend/src/lib/components/Account/AccountMenu.tsx+++ b/frontend/src/lib/components/Account/AccountMenu.tsx@@ -143,7 +143,7 @@ export function AccountMenu({ trigger, ...props }: AccountMenuProps): JSX.Elemenconst { currentOrganization } = useValues(organizationLogic)const { isCloudOrDev, isCloud, preflight } = useValues(preflightLogic)const { featureFlags } = useValues(featureFlagLogic)- const { billing, canAccessBilling } = useValues(billingLogic)+ const { billing, billingEntryUrl } = useValues(billingLogic)const { showInviteModal } = useActions(inviteLogic)const { reportInviteMembersButtonClicked } = useActions(eventUsageLogic)const { reportAccountOwnerClicked } = useActions(eventUsageLogic)@@ -187,14 +187,10 @@ export function AccountMenu({ trigger, ...props }: AccountMenuProps): JSX.Elemen</div></Link></DropdownMenuItem>- {isCloudOrDev && canAccessBilling ? (+ {isCloudOrDev && billingEntryUrl ? (<DropdownMenuItem asChild><Link- to={- featureFlags[FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]- ? urls.organizationBillingSection('overview')- : urls.organizationBilling()- }+ to={billingEntryUrl}buttonProps={{className: 'flex items-center gap-2',menuItem: true,diff --git a/frontend/src/lib/components/Account/NewAccountMenu.tsx b/frontend/src/lib/components/Account/NewAccountMenu.tsxindex bf0ffc658b14..73e77e2a4f99 100644--- a/frontend/src/lib/components/Account/NewAccountMenu.tsx+++ b/frontend/src/lib/components/Account/NewAccountMenu.tsx@@ -65,7 +65,7 @@ export function NewAccountMenu({ isLayoutNavCollapsed }: AccountMenuProps): JSX.const hasPendingInvites = pendingInvites.length > 0const { preflight } = useValues(preflightLogic)const { currentOrganization } = useValues(organizationLogic)- const { canAccessBilling } = useValues(billingLogic)+ const { billingEntryUrl } = useValues(billingLogic)const { guardAvailableFeature } = useValues(upgradeModalLogic)const { showCreateProjectModal } = useActions(globalModalsLogic)const { showCreateOrganizationModal } = useActions(globalModalsLogic)@@ -307,16 +307,12 @@ export function NewAccountMenu({ isLayoutNavCollapsed }: AccountMenuProps): JSX.</Menu.Portal></Menu.SubmenuRoot>- {isCloudOrDev && canAccessBilling ? (+ {isCloudOrDev && billingEntryUrl ? (<Menu.Itemrender={(props) => (<Link{...props}- to={- featureFlags[FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]- ? urls.organizationBillingSection('overview')- : urls.organizationBilling()- }+ to={billingEntryUrl}buttonProps={{className: 'flex items-center gap-2',menuItem: true,diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsxindex 3dc3a80d8d27..3f07d40bf727 100644--- a/frontend/src/lib/components/Search/searchLogic.tsx+++ b/frontend/src/lib/components/Search/searchLogic.tsx@@ -14,6 +14,7 @@ import { GroupQueryResult, mapGroupQueryResponse } from 'lib/utils/groups'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { newInternalTab } from 'lib/utils/newInternalTab'import { toSentenceCase } from 'lib/utils/strings'+import { billingLogic } from 'scenes/billing/billingLogic'import { organizationIntegrationsLogic } from 'scenes/settings/organization/organizationIntegrationsLogic'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -170,6 +171,7 @@ export interface SettingsSectionSummary {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface searchLogicValues {+ billingEntryUrl: string | null // billingLogicisCommandOpen: boolean // commandLogicfeatureFlags: FeatureFlagsSet // featureFlagLogicaggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel@@ -417,7 +419,8 @@ export interface searchLogicMeta {settingsItems: (featureFlags: FeatureFlagsSet,organizationIntegrations: IntegrationType[] | null,- settingsSections: SettingsSectionSummary[]+ settingsSections: SettingsSectionSummary[],+ billingEntryUrl: string | null) => SearchItem[]unifiedSearchItems: (unifiedSearchResults: SearchResponse | null) => Record<string, SearchItem[]>loadingStates: (@@ -499,6 +502,8 @@ export const searchLogic = kea<searchLogicType>([['shortcutData as cachedStarred', 'shortcutDataHasLoaded', 'groupItems as treeGroupItems'],organizationIntegrationsLogic,['organizationIntegrations'],+ billingLogic,+ ['billingEntryUrl'],],})),actions({@@ -1133,11 +1138,12 @@ export const searchLogic = kea<searchLogicType>([],],settingsItems: [- (s) => [s.featureFlags, s.organizationIntegrations, s.settingsSections],+ (s) => [s.featureFlags, s.organizationIntegrations, s.settingsSections, s.billingEntryUrl],(featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet,organizationIntegrations: import('~/types').IntegrationType[] | null,- settingsSections: SettingsSectionSummary[]+ settingsSections: SettingsSectionSummary[],+ billingEntryUrl: string | null): SearchItem[] => {const checkFlag = (flagKey: Pick<Setting, 'flag'>['flag']): boolean =>matchesFlagDefinition(flagKey, featureFlags)@@ -1162,6 +1168,17 @@ export const searchLogic = kea<searchLogicType>([continue}+ // Mirror the sidebar's billing gate. billingEntryUrl is null when the user has no+ // billing access, and for view-only members it points at Usage, which keeps them+ // off the admin-only Overview and the restricted state it renders first.+ let billingHref: string | null = null+ if (section.id === 'organization-billing') {+ if (!billingEntryUrl) {+ continue+ }+ billingHref = billingEntryUrl+ }+// Map environment sections to project levelconst effectiveLevel = section.level === 'environment' ? 'project' : section.levelconst effectiveSectionId = (@@ -1206,7 +1223,7 @@ export const searchLogic = kea<searchLogicType>([name: `${levelPrefix}: ${displayName} (${settings})`,displayName: `${displayName}${displayNameSuffix}`,category: 'settings',- href: section.to || urls.settings(effectiveSectionId),+ href: billingHref || section.to || urls.settings(effectiveSectionId),itemType: 'settings',record: {type: 'settings',diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex cc258b5c9e57..c38a561667ed 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -401,6 +401,7 @@ export const FEATURE_FLAGS = {MCP_ANALYTICS: 'mcp-analytics', // owner: #project-mcp-analyticsMCP_ANALYTICS_INTENT_ROUTING: 'mcp-analytics-intent-routing', // owner: #project-mcp-analyticsMCP_GATEWAY: 'mcp-gateway', // owner: #team-self-driving — gates the MCP gateway UI AND backend enforcement of built-in agent MCP access (delegated-only installs + restricted sandbox token scope); roll out by organization+ MEMBER_BILLING_USAGE_SPEND_READ_ACCESS: 'member-billing-usage-spend-read-access', // owner: @pawelcebula #team-billing, grants members read-only access to billing usage/spend tabs; owner-only-billing takes precedenceMESSAGING_SES: 'messaging-ses', // owner #team-workflowsMETRICS: 'metrics', // owner: #team-apm (@jonmcwest, @frankh)NEW_TAB_PROJECT_EXPLORER: 'new-tab-project-explorer', // owner: #team-platform-uxdiff --git a/frontend/src/scenes/billing/Billing.tsx b/frontend/src/scenes/billing/Billing.tsxindex 37afd03fdec2..bdf0cc2658f5 100644--- a/frontend/src/scenes/billing/Billing.tsx+++ b/frontend/src/scenes/billing/Billing.tsx@@ -59,6 +59,7 @@ export function Billing(): JSX.Element {showCreditCTAHero,showBillingHero,minimumBillingAccessLevel,+ canOnlyViewUsageAndSpend,hasSupportAddonPlan,} = useValues(billingLogic)const { reportBillingShown } = useActions(billingLogic)@@ -76,10 +77,14 @@ export function Billing(): JSX.Element {useEffect(() => {if (location.pathname === urls.organizationBilling() && featureFlags[FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]) {- router.actions.replace(urls.organizationBillingSection('overview'), searchParams)+ // View-only members can't see the Overview tab, so land them on Usage instead+ router.actions.replace(+ urls.organizationBillingSection(canOnlyViewUsageAndSpend ? 'usage' : 'overview'),+ searchParams+ )return}- }, [featureFlags, location.pathname, searchParams])+ }, [featureFlags, location.pathname, searchParams, canOnlyViewUsageAndSpend])useEffect(() => {if (billing) {diff --git a/frontend/src/scenes/billing/BillingSection.tsx b/frontend/src/scenes/billing/BillingSection.tsxindex 93f10fceed2f..07351fe91960 100644--- a/frontend/src/scenes/billing/BillingSection.tsx+++ b/frontend/src/scenes/billing/BillingSection.tsx@@ -38,6 +38,7 @@ const allTabs: { key: BillingSectionId; label: string }[] = [export function BillingSection(): JSX.Element {const { location, searchParams } = useValues(router)const { featureFlags, receivedFeatureFlags } = useValues(featureFlagLogic)+ const { canAccessBilling, canViewUsageAndSpend, canOnlyViewUsageAndSpend } = useValues(billingLogic)const billingAlertsEnabled = !!featureFlags[FEATURE_FLAGS.BILLING_ALERTS]const alertsRequested = location.pathname.includes('alerts')const billingAlertsPending = alertsRequested && !receivedFeatureFlags@@ -58,6 +59,20 @@ export function BillingSection(): JSX.Element {}}, [alertsRequested, billingAlertsEnabled, receivedFeatureFlags])+ // View-only members have no access to the Overview tab, so send them to Usage instead.+ // canOnlyViewUsageAndSpend is only true once org membership and flags are loaded, so admins never bounce.+ useEffect(() => {+ if (section === 'overview' && canOnlyViewUsageAndSpend) {+ router.actions.replace(urls.organizationBillingSection('usage'))+ }+ }, [section, canOnlyViewUsageAndSpend])++ // Usage and Spend are the read-only surfaces. Overview and Alerts stay admin-only, since both+ // can change what the organization is billed.+ const visibleTabs = tabs.filter((tab) =>+ tab.key === 'usage' || tab.key === 'spend' ? canViewUsageAndSpend : canAccessBilling+ )+const handleTabChange = (key: BillingSectionId): void => {const newUrl = urls.organizationBillingSection(key)@@ -87,7 +102,7 @@ export function BillingSection(): JSX.Element {return (<div className="flex flex-col">- <LemonTabs activeKey={section} onChange={handleTabChange} tabs={tabs} />+ {visibleTabs.length > 0 && <LemonTabs activeKey={section} onChange={handleTabChange} tabs={visibleTabs} />}{section === 'overview' && <Billing />}{section === 'usage' && <BillingUsage />}diff --git a/frontend/src/scenes/billing/BillingSpendView.tsx b/frontend/src/scenes/billing/BillingSpendView.tsxindex b945882234ec..e7d12c4a77c8 100644--- a/frontend/src/scenes/billing/BillingSpendView.tsx+++ b/frontend/src/scenes/billing/BillingSpendView.tsx@@ -26,9 +26,9 @@ import { BillingNoAccess } from './BillingNoAccess'import { billingSpendLogic } from './billingSpendLogic'export function BillingSpendView(): JSX.Element {- const { minimumBillingAccessLevel } = useValues(billingLogic)+ const { minimumUsageSpendReadAccessLevel } = useValues(billingLogic)const restrictionReason = useRestrictedArea({- minimumAccessLevel: minimumBillingAccessLevel,+ minimumAccessLevel: minimumUsageSpendReadAccessLevel,scope: RestrictionScope.Organization,})const logic = billingSpendLogic({ syncWithUrl: true })diff --git a/frontend/src/scenes/billing/BillingUsage.tsx b/frontend/src/scenes/billing/BillingUsage.tsxindex 931eafbc50f8..802ee70ce57b 100644--- a/frontend/src/scenes/billing/BillingUsage.tsx+++ b/frontend/src/scenes/billing/BillingUsage.tsx@@ -25,9 +25,9 @@ import { BillingNoAccess } from './BillingNoAccess'import { billingUsageLogic } from './billingUsageLogic'export function BillingUsage(): JSX.Element {- const { minimumBillingAccessLevel } = useValues(billingLogic)+ const { minimumUsageSpendReadAccessLevel } = useValues(billingLogic)const restrictionReason = useRestrictedArea({- minimumAccessLevel: minimumBillingAccessLevel,+ minimumAccessLevel: minimumUsageSpendReadAccessLevel,scope: RestrictionScope.Organization,})const logic = billingUsageLogic({ syncWithUrl: true })diff --git a/frontend/src/scenes/billing/billing-utils.spec.ts b/frontend/src/scenes/billing/billing-utils.spec.tsindex 6a28758e7b4e..78b1cc7e83cb 100644--- a/frontend/src/scenes/billing/billing-utils.spec.ts+++ b/frontend/src/scenes/billing/billing-utils.spec.ts@@ -1,7 +1,8 @@import tk from 'timekeeper'-import { OrganizationMembershipLevel } from 'lib/constants'+import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'import { dayjs } from 'lib/dayjs'+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { billingJson } from '~/mocks/fixtures/_billing'import billingJsonWithFlatFee from '~/mocks/fixtures/_billing_with_flat_fee.json'@@ -10,6 +11,7 @@ import {buildUsageLimitApproachingMessage,buildUsageLimitExceededMessage,canAccessBilling,+ canViewUsageAndSpend,convertAmountToUsage,convertLargeNumberToWords,convertUsageToAmount,@@ -17,8 +19,10 @@ import {formatProductNames,formatWithDecimals,getMinimumBillingAccessLevel,+ getMinimumUsageSpendReadAccessLevel,getProration,getUsageLimitConsequence,+ isMemberUsageSpendReadAccessEnabled,projectUsage,summarizeUsage,} from './billing-utils'@@ -679,3 +683,69 @@ describe('canAccessBilling', () => {expect(canAccessBilling(level, ownerOnly)).toBe(expected)})})++describe('getMinimumUsageSpendReadAccessLevel', () => {+ it.each([+ { memberAccess: false, ownerOnly: false, expected: OrganizationMembershipLevel.Admin },+ { memberAccess: true, ownerOnly: false, expected: OrganizationMembershipLevel.Member },+ { memberAccess: false, ownerOnly: true, expected: OrganizationMembershipLevel.Owner },+ // owner-only-billing wins over member-billing-usage-spend-read-access+ { memberAccess: true, ownerOnly: true, expected: OrganizationMembershipLevel.Owner },+ ])(+ 'returns $expected for memberAccess=$memberAccess, ownerOnly=$ownerOnly',+ ({ memberAccess, ownerOnly, expected }) => {+ expect(getMinimumUsageSpendReadAccessLevel(memberAccess, ownerOnly)).toBe(expected)+ }+ )+})++describe('canViewUsageAndSpend', () => {+ it.each([+ { level: OrganizationMembershipLevel.Member, memberAccess: true, ownerOnly: false, expected: true },+ { level: OrganizationMembershipLevel.Member, memberAccess: true, ownerOnly: true, expected: false },+ { level: OrganizationMembershipLevel.Member, memberAccess: false, ownerOnly: false, expected: false },+ { level: OrganizationMembershipLevel.Admin, memberAccess: false, ownerOnly: false, expected: true },+ { level: OrganizationMembershipLevel.Admin, memberAccess: true, ownerOnly: true, expected: false },+ { level: OrganizationMembershipLevel.Owner, memberAccess: false, ownerOnly: true, expected: true },+ { level: null, memberAccess: true, ownerOnly: false, expected: false },+ ])(+ 'returns $expected for level=$level, memberAccess=$memberAccess, ownerOnly=$ownerOnly',+ ({ level, memberAccess, ownerOnly, expected }) => {+ expect(canViewUsageAndSpend(level, memberAccess, ownerOnly)).toBe(expected)+ }+ )+})++describe('isMemberUsageSpendReadAccessEnabled', () => {+ // Dropping the usage-spend-dashboards half of this lets a view-only member reach Usage and Spend+ // by URL while the account menu and settings sidebar hide Billing from them entirely.+ it.each<{ case: string; featureFlags: FeatureFlagsSet; expected: boolean }>([+ {+ case: 'both flags are on',+ featureFlags: {+ [FEATURE_FLAGS.MEMBER_BILLING_USAGE_SPEND_READ_ACCESS]: true,+ [FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]: true,+ },+ expected: true,+ },+ {+ case: 'the grant is on but there are no dashboards to reach',+ featureFlags: {+ [FEATURE_FLAGS.MEMBER_BILLING_USAGE_SPEND_READ_ACCESS]: true,+ [FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]: false,+ },+ expected: false,+ },+ {+ case: 'the dashboards are on but the grant is not',+ featureFlags: {+ [FEATURE_FLAGS.MEMBER_BILLING_USAGE_SPEND_READ_ACCESS]: false,+ [FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]: true,+ },+ expected: false,+ },+ { case: 'neither flag is present', featureFlags: {}, expected: false },+ ])('returns $expected when $case', ({ featureFlags, expected }) => {+ expect(isMemberUsageSpendReadAccessEnabled(featureFlags)).toBe(expected)+ })+})diff --git a/frontend/src/scenes/billing/billing-utils.ts b/frontend/src/scenes/billing/billing-utils.tsindex e732e1e912a0..57ef0f0dc5ac 100644--- a/frontend/src/scenes/billing/billing-utils.ts+++ b/frontend/src/scenes/billing/billing-utils.ts@@ -5,6 +5,7 @@ import Papa from 'papaparse'import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'import { dayjs } from 'lib/dayjs'+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { dateStringToDayJs } from 'lib/utils/dateFilters'import { compactNumber } from 'lib/utils/numbers'import { membershipLevelToName } from 'lib/utils/permissioning'@@ -448,6 +449,49 @@ export function canAccessBilling(membershipLevel: number | null | undefined, ownreturn membershipLevel >= getMinimumBillingAccessLevel(ownerOnlyBilling)}+/**+ * Whether the member-level read grant for usage and spend is in effect.+ *+ * The grant requires usage-spend-dashboards as well, because the tabbed dashboards are the only+ * member-facing usage/spend surface. Honoring the grant without them would leave Usage and Spend+ * reachable by URL while the account menu and settings sidebar hide Billing entirely. Admins reach+ * usage and spend either way, so the second flag only ever narrows members.+ */+export function isMemberUsageSpendReadAccessEnabled(featureFlags: FeatureFlagsSet): boolean {+ return (+ !!featureFlags[FEATURE_FLAGS.MEMBER_BILLING_USAGE_SPEND_READ_ACCESS] &&+ !!featureFlags[FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]+ )+}++/**+ * Returns the minimum membership level required for read-only access to the billing usage/spend tabs.+ * The member-billing-usage-spend-read-access feature flag lowers it to Member, but owner-only-billing takes precedence.+ */+export function getMinimumUsageSpendReadAccessLevel(+ memberUsageSpendReadAccess: boolean,+ ownerOnlyBilling: boolean+): OrganizationMembershipLevel {+ if (ownerOnlyBilling) {+ return OrganizationMembershipLevel.Owner+ }+ return memberUsageSpendReadAccess ? OrganizationMembershipLevel.Member : OrganizationMembershipLevel.Admin+}++/**+ * Determines if the user can view the read-only billing usage/spend tabs based on their org membership level.+ */+export function canViewUsageAndSpend(+ membershipLevel: number | null | undefined,+ memberUsageSpendReadAccess: boolean,+ ownerOnlyBilling: boolean+): boolean {+ if (!membershipLevel) {+ return false+ }+ return membershipLevel >= getMinimumUsageSpendReadAccessLevel(memberUsageSpendReadAccess, ownerOnlyBilling)+}+/*** Synchronizes URL search parameters with billing filter state.* Returns the appropriate router action format for kea-router.diff --git a/frontend/src/scenes/billing/billingLogic.test.ts b/frontend/src/scenes/billing/billingLogic.test.tsindex 271cff5cc9c9..c99823614701 100644--- a/frontend/src/scenes/billing/billingLogic.test.ts+++ b/frontend/src/scenes/billing/billingLogic.test.ts@@ -1,10 +1,28 @@+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'+import { router } from 'kea-router'+import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { billingLogic } from 'scenes/billing/billingLogic'+import { organizationLogic } from 'scenes/organizationLogic'+import { urls } from 'scenes/urls'import { ProductKey } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'+type BillingAccessCase = {+ name: string+ membershipLevel: OrganizationMembershipLevel+ flags: Record<string, string | boolean>+ expected: {+ canAccessBilling: boolean+ canViewUsageAndSpend: boolean+ canOnlyViewUsageAndSpend: boolean+ billingEntryUrl: string | null+ }+}+describe('billingLogic', () => {beforeEach(() => {initKeaTests()@@ -49,4 +67,97 @@ describe('billingLogic', () => {expect(billingLogic.values.scrollToProductKey).toBe(null)})++ it.each<BillingAccessCase>([+ {+ name: 'member with both member-access flags',+ membershipLevel: OrganizationMembershipLevel.Member,+ flags: {+ [FEATURE_FLAGS.MEMBER_BILLING_USAGE_SPEND_READ_ACCESS]: true,+ [FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]: true,+ },+ expected: {+ canAccessBilling: false,+ canViewUsageAndSpend: true,+ canOnlyViewUsageAndSpend: true,+ billingEntryUrl: urls.organizationBillingSection('usage'),+ },+ },+ {+ name: 'member without the dashboards flag',+ membershipLevel: OrganizationMembershipLevel.Member,+ flags: {+ [FEATURE_FLAGS.MEMBER_BILLING_USAGE_SPEND_READ_ACCESS]: true,+ [FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]: false,+ },+ expected: {+ canAccessBilling: false,+ canViewUsageAndSpend: false,+ canOnlyViewUsageAndSpend: false,+ billingEntryUrl: null,+ },+ },+ {+ name: 'admin when owner-only billing is off',+ membershipLevel: OrganizationMembershipLevel.Admin,+ flags: {+ [FEATURE_FLAGS.OWNER_ONLY_BILLING]: false,+ [FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]: true,+ },+ expected: {+ canAccessBilling: true,+ canViewUsageAndSpend: true,+ canOnlyViewUsageAndSpend: false,+ billingEntryUrl: urls.organizationBillingSection('overview'),+ },+ },+ {+ name: 'admin when owner-only billing is on',+ membershipLevel: OrganizationMembershipLevel.Admin,+ flags: {+ [FEATURE_FLAGS.OWNER_ONLY_BILLING]: true,+ [FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]: true,+ },+ expected: {+ canAccessBilling: false,+ canViewUsageAndSpend: false,+ canOnlyViewUsageAndSpend: false,+ billingEntryUrl: null,+ },+ },+ {+ name: 'owner when owner-only billing is on',+ membershipLevel: OrganizationMembershipLevel.Owner,+ flags: {+ [FEATURE_FLAGS.OWNER_ONLY_BILLING]: true,+ [FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]: true,+ },+ expected: {+ canAccessBilling: true,+ canViewUsageAndSpend: true,+ canOnlyViewUsageAndSpend: false,+ billingEntryUrl: urls.organizationBillingSection('overview'),+ },+ },+ ])('sets billing access selectors for $name', ({ membershipLevel, flags, expected }) => {+ featureFlagLogic.mount()+ organizationLogic.mount()+ billingLogic.mount()++ organizationLogic.actions.loadCurrentOrganizationSuccess({+ ...MOCK_DEFAULT_ORGANIZATION,+ membership_level: membershipLevel,+ })+ featureFlagLogic.actions.setFeatureFlags(+ Object.entries(flags)+ .filter(([, value]) => value)+ .map(([key]) => key),+ flags+ )++ expect(billingLogic.values.canAccessBilling).toBe(expected.canAccessBilling)+ expect(billingLogic.values.canViewUsageAndSpend).toBe(expected.canViewUsageAndSpend)+ expect(billingLogic.values.canOnlyViewUsageAndSpend).toBe(expected.canOnlyViewUsageAndSpend)+ expect(billingLogic.values.billingEntryUrl).toBe(expected.billingEntryUrl)+ })})diff --git a/frontend/src/scenes/billing/billingLogic.tsx b/frontend/src/scenes/billing/billingLogic.tsxindex 8112d9ada5f9..9218fe9ebd1b 100644--- a/frontend/src/scenes/billing/billingLogic.tsx+++ b/frontend/src/scenes/billing/billingLogic.tsx@@ -18,6 +18,7 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { pluralize } from 'lib/utils/strings'import { organizationLogic } from 'scenes/organizationLogic'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { ProductKey } from '~/queries/schema/schema-general'@@ -37,7 +38,10 @@ import {buildUsageLimitApproachingMessage,buildUsageLimitExceededMessage,canAccessBilling as canAccessBillingUtil,+ canViewUsageAndSpend as canViewUsageAndSpendUtil,getMinimumBillingAccessLevel,+ getMinimumUsageSpendReadAccessLevel,+ isMemberUsageSpendReadAccessEnabled,} from './billing-utils'import { DEFAULT_ESTIMATED_MONTHLY_CREDIT_AMOUNT_USD } from './CreditCTAHero'@@ -196,12 +200,15 @@ export interface billingLogicValues {>billing: BillingType | nullbillingAlert: BillingAlertConfig | null+ billingEntryUrl: string | nullbillingError: BillingError | nullbillingErrorLoading: booleanbillingLoading: booleanbillingPeriodUTC: BillingPeriodbillingPlan: BillingPlan | nullcanAccessBilling: boolean+ canOnlyViewUsageAndSpend: boolean+ canViewUsageAndSpend: booleancomputedDiscount: number | nullcreditBrackets: any[]creditDiscount: number@@ -255,6 +262,7 @@ export interface billingLogicValues {isPurchaseCreditsModalOpen: booleanisUnlicensedDebug: booleanminimumBillingAccessLevel: OrganizationMembershipLevel+ minimumUsageSpendReadAccessLevel: OrganizationMembershipLevelplatformAddons: BillingProductV2AddonType[]productSpecificAlert: BillingAlertConfig | nullproducts: BillingProductV2Type[]@@ -610,6 +618,14 @@ export interface billingLogicMeta {__keaTypeGenInternalSelectorTypes: {minimumBillingAccessLevel: (featureFlags: FeatureFlagsSet) => OrganizationMembershipLevelcanAccessBilling: (currentOrganization: OrganizationType | null, featureFlags: FeatureFlagsSet) => boolean+ minimumUsageSpendReadAccessLevel: (featureFlags: FeatureFlagsSet) => OrganizationMembershipLevel+ canViewUsageAndSpend: (currentOrganization: OrganizationType | null, featureFlags: FeatureFlagsSet) => boolean+ canOnlyViewUsageAndSpend: (canViewUsageAndSpend: boolean, canAccessBilling: boolean) => boolean+ billingEntryUrl: (+ canAccessBilling: boolean,+ canOnlyViewUsageAndSpend: boolean,+ featureFlags: FeatureFlagsSet+ ) => string | nullupgradeLink: (preflight: PreflightStatus | null) => stringisUnlicensedDebug: (preflight: PreflightStatus | null, billing: BillingType | null) => booleansupportPlans: (billing: BillingType | null) => BillingPlanType[]@@ -1050,6 +1066,46 @@ export const billingLogic = kea<billingLogicType>([!!featureFlags[FEATURE_FLAGS.OWNER_ONLY_BILLING]),],+ minimumUsageSpendReadAccessLevel: [+ (s) => [s.featureFlags],+ (featureFlags: FeatureFlagsSet): OrganizationMembershipLevel =>+ getMinimumUsageSpendReadAccessLevel(+ isMemberUsageSpendReadAccessEnabled(featureFlags),+ !!featureFlags[FEATURE_FLAGS.OWNER_ONLY_BILLING]+ ),+ ],+ canViewUsageAndSpend: [+ (s) => [s.currentOrganization, s.featureFlags],+ (currentOrganization: OrganizationType | null, featureFlags: FeatureFlagsSet): boolean =>+ canViewUsageAndSpendUtil(+ currentOrganization?.membership_level,+ isMemberUsageSpendReadAccessEnabled(featureFlags),+ !!featureFlags[FEATURE_FLAGS.OWNER_ONLY_BILLING]+ ),+ ],+ canOnlyViewUsageAndSpend: [+ (s) => [s.canViewUsageAndSpend, s.canAccessBilling],+ (canViewUsageAndSpend: boolean, canAccessBilling: boolean): boolean =>+ canViewUsageAndSpend && !canAccessBilling,+ ],+ billingEntryUrl: [+ (s) => [s.canAccessBilling, s.canOnlyViewUsageAndSpend, s.featureFlags],+ (+ canAccessBilling: boolean,+ canOnlyViewUsageAndSpend: boolean,+ featureFlags: FeatureFlagsSet+ ): string | null => {+ if (canAccessBilling) {+ return featureFlags[FEATURE_FLAGS.USAGE_SPEND_DASHBOARDS]+ ? urls.organizationBillingSection('overview')+ : urls.organizationBilling()+ }+ if (canOnlyViewUsageAndSpend) {+ return urls.organizationBillingSection('usage')+ }+ return null+ },+ ],upgradeLink: [(s) => [s.preflight], (): string => '/organization/billing'],isUnlicensedDebug: [(s) => [s.preflight, s.billing],diff --git a/frontend/src/scenes/billing/billingSpendLogic.ts b/frontend/src/scenes/billing/billingSpendLogic.tsindex 6b280fce34f6..ab88c59bb56c 100644--- a/frontend/src/scenes/billing/billingSpendLogic.ts+++ b/frontend/src/scenes/billing/billingSpendLogic.ts@@ -2,6 +2,7 @@ import { deepEqual as equal } from 'fast-equals'import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'+import { subscriptions } from 'kea-subscriptions'import difference from 'lodash.difference'import sortBy from 'lodash.sortby'@@ -74,7 +75,7 @@ export interface BillingSpendLogicProps {export interface billingSpendLogicValues {billing: BillingType | null // billingLogicbillingPeriodUTC: BillingPeriod // billingLogic- canAccessBilling: boolean // billingLogic+ canViewUsageAndSpend: boolean // billingLogiccurrentOrganization: OrganizationType | null // billingLogicisHobby: boolean // preflightLogicbillingPeriodMarkers: BillingPeriodMarker[]@@ -246,7 +247,7 @@ export const billingSpendLogic = kea<billingSpendLogicType>([connect(() => ({values: [billingLogic,- ['billing', 'billingPeriodUTC', 'canAccessBilling', 'currentOrganization'],+ ['billing', 'billingPeriodUTC', 'canViewUsageAndSpend', 'currentOrganization'],preflightLogic,['isHobby'],],@@ -273,7 +274,7 @@ export const billingSpendLogic = kea<billingSpendLogicType>([null as BillingSpendResponse | null,{loadBillingSpend: async () => {- if (!values.canAccessBilling || values.isHobby) {+ if (!values.canViewUsageAndSpend || values.isHobby) {return null}const { usage_types, team_ids, breakdowns, interval } = values.filters@@ -622,6 +623,18 @@ export const billingSpendLogic = kea<billingSpendLogicType>([actions.loadBillingSpend()},})),+ subscriptions(({ actions, values }) => ({+ canViewUsageAndSpend: (canViewUsageAndSpend: boolean, previousCanViewUsageAndSpend: boolean | undefined) => {+ if (canViewUsageAndSpend && previousCanViewUsageAndSpend === false && !values.isHobby) {+ actions.loadBillingSpend()+ }+ },+ isHobby: (isHobby: boolean, previousIsHobby: boolean | undefined) => {+ if (!isHobby && previousIsHobby === true && values.canViewUsageAndSpend) {+ actions.loadBillingSpend()+ }+ },+ })),afterMount((logic: billingSpendLogicType) => {logic.actions.loadBillingSpend()}),diff --git a/frontend/src/scenes/billing/billingUsageLogic.ts b/frontend/src/scenes/billing/billingUsageLogic.tsindex facd9d97a789..44723e65e874 100644--- a/frontend/src/scenes/billing/billingUsageLogic.ts+++ b/frontend/src/scenes/billing/billingUsageLogic.ts@@ -2,6 +2,7 @@ import { deepEqual as equal } from 'fast-equals'import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'+import { subscriptions } from 'kea-subscriptions'import difference from 'lodash.difference'import sortBy from 'lodash.sortby'@@ -105,7 +106,7 @@ export interface BillingUsageLogicProps {export interface billingUsageLogicValues {billing: BillingType | null // billingLogicbillingPeriodUTC: BillingPeriod // billingLogic- canAccessBilling: boolean // billingLogic+ canViewUsageAndSpend: boolean // billingLogiccurrentOrganization: OrganizationType | null // billingLogicisHobby: boolean // preflightLogicbillingPeriodMarkers: BillingPeriodMarker[]@@ -277,7 +278,7 @@ export const billingUsageLogic = kea<billingUsageLogicType>([connect(() => ({values: [billingLogic,- ['billing', 'billingPeriodUTC', 'canAccessBilling', 'currentOrganization'],+ ['billing', 'billingPeriodUTC', 'canViewUsageAndSpend', 'currentOrganization'],preflightLogic,['isHobby'],],@@ -304,7 +305,7 @@ export const billingUsageLogic = kea<billingUsageLogicType>([null as BillingUsageResponse | null,{loadBillingUsage: async () => {- if (!values.canAccessBilling || values.isHobby) {+ if (!values.canViewUsageAndSpend || values.isHobby) {return null}const { usage_types, team_ids, breakdowns, interval } = values.filters@@ -653,6 +654,18 @@ export const billingUsageLogic = kea<billingUsageLogicType>([actions.loadBillingUsage()},})),+ subscriptions(({ actions, values }) => ({+ canViewUsageAndSpend: (canViewUsageAndSpend: boolean, previousCanViewUsageAndSpend: boolean | undefined) => {+ if (canViewUsageAndSpend && previousCanViewUsageAndSpend === false && !values.isHobby) {+ actions.loadBillingUsage()+ }+ },+ isHobby: (isHobby: boolean, previousIsHobby: boolean | undefined) => {+ if (!isHobby && previousIsHobby === true && values.canViewUsageAndSpend) {+ actions.loadBillingUsage()+ }+ },+ })),afterMount(({ actions }: billingUsageLogicType) => {actions.loadBillingUsage()}),diff --git a/frontend/src/scenes/settings/settingsLogic.ts b/frontend/src/scenes/settings/settingsLogic.tsindex b086493afbb0..a5c1911b3a79 100644--- a/frontend/src/scenes/settings/settingsLogic.ts+++ b/frontend/src/scenes/settings/settingsLogic.ts@@ -79,7 +79,7 @@ const getSectionStringValue = (section: SettingSection): string => {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface settingsLogicValues {- canAccessBilling: boolean // billingLogic+ billingEntryUrl: string | null // billingLogicfeatureFlags: FeatureFlagsSet // featureFlagLogicorganizationIntegrations: IntegrationType[] | null // organizationIntegrationsLogiccurrentOrganization: OrganizationType | null // organizationLogic@@ -196,7 +196,7 @@ export interface settingsLogicMeta {currentOrganization: OrganizationType | null,organizationIntegrations: IntegrationType[] | null,preflight: PreflightStatus | null,- canAccessBilling: boolean,+ billingEntryUrl: string | null,isAdminOrOwner: boolean | null) => SettingSection[]selectedLevel: (@@ -274,7 +274,7 @@ export const settingsLogic = kea<settingsLogicType>([organizationIntegrationsLogic,['organizationIntegrations'],billingLogic,- ['canAccessBilling'],+ ['billingEntryUrl'],],})),@@ -444,7 +444,7 @@ export const settingsLogic = kea<settingsLogicType>([s.currentOrganization,s.organizationIntegrations,s.preflight,- s.canAccessBilling,+ s.billingEntryUrl,s.isAdminOrOwner,],(@@ -454,7 +454,7 @@ export const settingsLogic = kea<settingsLogicType>([currentOrganization: null | import('../../types').OrganizationType,organizationIntegrations: import('../../types').IntegrationType[] | null,preflight: null | import('../../types').PreflightStatus,- canAccessBilling: boolean,+ billingEntryUrl: string | null,isAdminOrOwner: boolean | null): SettingSection[] => {const isSettingVisible = (setting: Setting): boolean => {@@ -482,7 +482,7 @@ export const settingsLogic = kea<settingsLogicType>([}// Explicit gates to avoid showing this in the sidebar when the use doesn't have access to it- if (section.id === 'organization-billing' && !canAccessBilling) {+ if (section.id === 'organization-billing' && !billingEntryUrl) {return false}if (section.id === 'organization-legal-documents' && !isAdminOrOwner) {diff --git a/products/billing/frontend/generated/api.schemas.ts b/products/billing/frontend/generated/api.schemas.tsindex 4aa8b12289cb..b76298b04ed6 100644--- a/products/billing/frontend/generated/api.schemas.ts+++ b/products/billing/frontend/generated/api.schemas.ts@@ -666,7 +666,7 @@ export type BillingSpendRetrieveParams = {*/start_date?: string | null/**- * JSON-encoded array of numeric team/project IDs to filter on, for example [1,2]. Omit for all teams in the organization.+ * JSON-encoded array of numeric team/project IDs to filter on, for example [1,2]. Omit for all projects available to the caller. Full billing-access callers can read all organization projects; member read-only callers are limited to visible projects and any project scope on their token.* @nullable*/team_ids?: string | null@@ -696,7 +696,7 @@ export type BillingUsageRetrieveParams = {*/start_date?: string | null/**- * JSON-encoded array of numeric team/project IDs to filter on, for example [1,2]. Omit for all teams in the organization.+ * JSON-encoded array of numeric team/project IDs to filter on, for example [1,2]. Omit for all projects available to the caller. Full billing-access callers can read all organization projects; member read-only callers are limited to visible projects and any project scope on their token.* @nullable*/team_ids?: string | nulldiff --git a/products/billing/mcp/tools.yaml b/products/billing/mcp/tools.yamlindex 8bd0ee51376e..cf27d54ac876 100644--- a/products/billing/mcp/tools.yaml+++ b/products/billing/mcp/tools.yaml@@ -138,9 +138,11 @@ tools:title: Get spend breakdowndescription: >Fetch time-series spend (cost in USD) breakdowns for the organization across a date range. Same dimensional- parameters as billing-usage-get, but values are dollar amounts rather than usage volumes. Requires org- admin-level access. Use this to investigate cost spikes, compare spend across periods, or attribute spend to- specific products or teams.+ parameters as billing-usage-get, but values are dollar amounts rather than usage volumes. Requires billing+ usage/spend read access: owners always, admins when owner-only billing is off, or members only when+ owner-only billing is off and the org has the member read-only billing usage/spend flag enabled. This member+ grant applies only to usage/spend, not billing-overview-get or billing admin actions. Use this to+ investigate cost spikes, compare spend across periods, or attribute spend to specific products or teams.param_overrides:start_date:description: >@@ -153,7 +155,8 @@ tools:team_ids:description: >JSON-encoded array of numeric team (project) IDs to filter by, NOT a comma-separated string. Pass as- e.g. `[1,2]`. Omit for all teams in the org.+ e.g. `[1,2]`. Omit for every project this request can see: all org teams for full billing-access+ callers, or the member's visible/project-scoped teams for member read-only callers.usage_types:description: >JSON-encoded array of usage type identifiers to filter on, NOT a comma-separated string. Pass as@@ -200,9 +203,12 @@ tools:title: Get usage breakdowndescription: >Fetch time-series usage breakdowns for the organization across a date range. Supports per-team (project) and- per-usage-type dimensions. Requires org admin-level access. Use this to investigate usage spikes, compare- periods, or attribute usage to specific projects. For a single-snapshot aggregate view call- billing-overview-get; for cost (spend) breakdowns call billing-spend-get.+ per-usage-type dimensions. Requires billing usage/spend read access: owners always, admins when owner-only+ billing is off, or members only when owner-only billing is off and the org has the member read-only billing+ usage/spend flag enabled. This member grant applies only to usage/spend, not billing-overview-get or billing+ admin actions. Use this to investigate usage spikes, compare periods, or attribute usage to specific+ projects. For a single-snapshot aggregate view call billing-overview-get when the caller has full billing+ access; for cost (spend) breakdowns call billing-spend-get.param_overrides:start_date:description: >@@ -215,7 +221,8 @@ tools:team_ids:description: >JSON-encoded array of numeric team (project) IDs to filter by, NOT a comma-separated string. Pass as- e.g. `[1,2]`. Omit for all teams in the org.+ e.g. `[1,2]`. Omit for every project this request can see: all org teams for full billing-access+ callers, or the member's visible/project-scoped teams for member read-only callers.usage_types:description: >JSON-encoded array of usage type identifiers to filter on, NOT a comma-separated string. Pass asdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 498c9ac414b1..97ded5ec6180 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -937,7 +937,7 @@"feature_flag": "billing-mcp-read-tools"},"billing-spend-get": {- "description": "Fetch time-series spend (cost in USD) breakdowns for the organization across a date range. Same dimensional parameters as billing-usage-get, but values are dollar amounts rather than usage volumes. Requires org admin-level access. Use this to investigate cost spikes, compare spend across periods, or attribute spend to specific products or teams.",+ "description": "Fetch time-series spend (cost in USD) breakdowns for the organization across a date range. Same dimensional parameters as billing-usage-get, but values are dollar amounts rather than usage volumes. Requires billing usage/spend read access: owners always, admins when owner-only billing is off, or members only when owner-only billing is off and the org has the member read-only billing usage/spend flag enabled. This member grant applies only to usage/spend, not billing-overview-get or billing admin actions. Use this to investigate cost spikes, compare spend across periods, or attribute spend to specific products or teams.","category": "Billing","feature": "billing","summary": "Get spend breakdown",@@ -952,7 +952,7 @@"feature_flag": "billing-mcp-read-tools"},"billing-usage-get": {- "description": "Fetch time-series usage breakdowns for the organization across a date range. Supports per-team (project) and per-usage-type dimensions. Requires org admin-level access. Use this to investigate usage spikes, compare periods, or attribute usage to specific projects. For a single-snapshot aggregate view call billing-overview-get; for cost (spend) breakdowns call billing-spend-get.",+ "description": "Fetch time-series usage breakdowns for the organization across a date range. Supports per-team (project) and per-usage-type dimensions. Requires billing usage/spend read access: owners always, admins when owner-only billing is off, or members only when owner-only billing is off and the org has the member read-only billing usage/spend flag enabled. This member grant applies only to usage/spend, not billing-overview-get or billing admin actions. Use this to investigate usage spikes, compare periods, or attribute usage to specific projects. For a single-snapshot aggregate view call billing-overview-get when the caller has full billing access; for cost (spend) breakdowns call billing-spend-get.","category": "Billing","feature": "billing","summary": "Get usage breakdown",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 042b1f75cccd..62bf7c9e6fd2 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -952,7 +952,7 @@"feature_flag": "billing-mcp-read-tools"},"billing-spend-get": {- "description": "Fetch time-series spend (cost in USD) breakdowns for the organization across a date range. Same dimensional parameters as billing-usage-get, but values are dollar amounts rather than usage volumes. Requires org admin-level access. Use this to investigate cost spikes, compare spend across periods, or attribute spend to specific products or teams.",+ "description": "Fetch time-series spend (cost in USD) breakdowns for the organization across a date range. Same dimensional parameters as billing-usage-get, but values are dollar amounts rather than usage volumes. Requires billing usage/spend read access: owners always, admins when owner-only billing is off, or members only when owner-only billing is off and the org has the member read-only billing usage/spend flag enabled. This member grant applies only to usage/spend, not billing-overview-get or billing admin actions. Use this to investigate cost spikes, compare spend across periods, or attribute spend to specific products or teams.","category": "Billing","feature": "billing","summary": "Get spend breakdown",@@ -967,7 +967,7 @@"feature_flag": "billing-mcp-read-tools"},"billing-usage-get": {- "description": "Fetch time-series usage breakdowns for the organization across a date range. Supports per-team (project) and per-usage-type dimensions. Requires org admin-level access. Use this to investigate usage spikes, compare periods, or attribute usage to specific projects. For a single-snapshot aggregate view call billing-overview-get; for cost (spend) breakdowns call billing-spend-get.",+ "description": "Fetch time-series usage breakdowns for the organization across a date range. Supports per-team (project) and per-usage-type dimensions. Requires billing usage/spend read access: owners always, admins when owner-only billing is off, or members only when owner-only billing is off and the org has the member read-only billing usage/spend flag enabled. This member grant applies only to usage/spend, not billing-overview-get or billing admin actions. Use this to investigate usage spikes, compare periods, or attribute usage to specific projects. For a single-snapshot aggregate view call billing-overview-get when the caller has full billing access; for cost (spend) breakdowns call billing-spend-get.","category": "Billing","feature": "billing","summary": "Get usage breakdown",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e83c32e69c36..4ad01ffc6e6e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -83773,7 +83773,7 @@ export namespace Schemas {*/start_date?: string | null;/**- * JSON-encoded array of numeric team/project IDs to filter on, for example [1,2]. Omit for all teams in the organization.+ * JSON-encoded array of numeric team/project IDs to filter on, for example [1,2]. Omit for all projects available to the caller. Full billing-access callers can read all organization projects; member read-only callers are limited to visible projects and any project scope on their token.* @nullable*/team_ids?: string | null;@@ -83803,7 +83803,7 @@ export namespace Schemas {*/start_date?: string | null;/**- * JSON-encoded array of numeric team/project IDs to filter on, for example [1,2]. Omit for all teams in the organization.+ * JSON-encoded array of numeric team/project IDs to filter on, for example [1,2]. Omit for all projects available to the caller. Full billing-access callers can read all organization projects; member read-only callers are limited to visible projects and any project scope on their token.* @nullable*/team_ids?: string | null;diff --git a/services/mcp/src/generated/billing/api.ts b/services/mcp/src/generated/billing/api.tsindex cba81d83dfb5..0e84294dc5fe 100644--- a/services/mcp/src/generated/billing/api.ts+++ b/services/mcp/src/generated/billing/api.ts@@ -25,7 +25,7 @@ export const BillingSpendRetrieveQueryParams = /* @__PURE__ */ zod.object({.string().nullish().describe(- 'JSON-encoded array of numeric team\/project IDs to filter on, for example [1,2]. Omit for all teams in the organization.'+ 'JSON-encoded array of numeric team\/project IDs to filter on, for example [1,2]. Omit for all projects available to the caller. Full billing-access callers can read all organization projects; member read-only callers are limited to visible projects and any project scope on their token.'),usage_types: zod.string()@@ -49,7 +49,7 @@ export const BillingUsageRetrieveQueryParams = /* @__PURE__ */ zod.object({.string().nullish().describe(- 'JSON-encoded array of numeric team\/project IDs to filter on, for example [1,2]. Omit for all teams in the organization.'+ 'JSON-encoded array of numeric team\/project IDs to filter on, for example [1,2]. Omit for all projects available to the caller. Full billing-access callers can read all organization projects; member read-only callers are limited to visible projects and any project scope on their token.'),usage_types: zod.string()diff --git a/services/mcp/src/tools/generated/billing.ts b/services/mcp/src/tools/generated/billing.tsindex 7fe47c4a1956..5beb58680347 100644--- a/services/mcp/src/tools/generated/billing.ts+++ b/services/mcp/src/tools/generated/billing.ts@@ -58,7 +58,7 @@ const BillingSpendGetSchema = BillingSpendRetrieveQueryParams.extend({"End date (YYYY-MM-DD), inclusive. Pass this whenever start_date is set; use today's date if the user did not name one."),team_ids: BillingSpendRetrieveQueryParams.shape['team_ids'].describe(- 'JSON-encoded array of numeric team (project) IDs to filter by, NOT a comma-separated string. Pass as e.g. `[1,2]`. Omit for all teams in the org.'+ "JSON-encoded array of numeric team (project) IDs to filter by, NOT a comma-separated string. Pass as e.g. `[1,2]`. Omit for every project this request can see: all org teams for full billing-access callers, or the member's visible/project-scoped teams for member read-only callers."),usage_types: BillingSpendRetrieveQueryParams.shape['usage_types'].describe('JSON-encoded array of usage type identifiers to filter on, NOT a comma-separated string. Pass as e.g. `["event_count_in_period"]` or `["event_count_in_period","recording_count_in_period"]`. Omit for all usage types.'@@ -106,7 +106,7 @@ const BillingUsageGetSchema = BillingUsageRetrieveQueryParams.extend({"End date (YYYY-MM-DD), inclusive. Pass this whenever start_date is set; use today's date if the user did not name one."),team_ids: BillingUsageRetrieveQueryParams.shape['team_ids'].describe(- 'JSON-encoded array of numeric team (project) IDs to filter by, NOT a comma-separated string. Pass as e.g. `[1,2]`. Omit for all teams in the org.'+ "JSON-encoded array of numeric team (project) IDs to filter by, NOT a comma-separated string. Pass as e.g. `[1,2]`. Omit for every project this request can see: all org teams for full billing-access callers, or the member's visible/project-scoped teams for member read-only callers."),usage_types: BillingUsageRetrieveQueryParams.shape['usage_types'].describe('JSON-encoded array of usage type identifiers to filter on, NOT a comma-separated string. Pass as e.g. `["event_count_in_period"]` or `["event_count_in_period","recording_count_in_period"]`. Omit for all usage types.'diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.jsonindex 18a5ed036ffc..50a80508c0a5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-spend-get.json@@ -54,7 +54,7 @@"type": "null"}],- "description": "JSON-encoded array of numeric team (project) IDs to filter by, NOT a comma-separated string. Pass as e.g. `[1,2]`. Omit for all teams in the org."+ "description": "JSON-encoded array of numeric team (project) IDs to filter by, NOT a comma-separated string. Pass as e.g. `[1,2]`. Omit for every project this request can see: all org teams for full billing-access callers, or the member's visible/project-scoped teams for member read-only callers."},"usage_types": {"anyOf": [diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.jsonindex 18a5ed036ffc..50a80508c0a5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/billing-usage-get.json@@ -54,7 +54,7 @@"type": "null"}],- "description": "JSON-encoded array of numeric team (project) IDs to filter by, NOT a comma-separated string. Pass as e.g. `[1,2]`. Omit for all teams in the org."+ "description": "JSON-encoded array of numeric team (project) IDs to filter by, NOT a comma-separated string. Pass as e.g. `[1,2]`. Omit for every project this request can see: all org teams for full billing-access callers, or the member's visible/project-scoped teams for member read-only callers."},"usage_types": {"anyOf": [