Skip to content

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

149 KB
Raw Blame
import gzip
import json
from collections.abc import Sequence
from datetime import datetime, timedelta
from typing import Any, cast, get_args
from uuid import uuid4
from zoneinfo import ZoneInfo

import time_machine
from posthog.test.base import APIBaseTest, _create_event, flush_persons_and_events
from unittest import TestCase
from unittest.mock import MagicMock, PropertyMock, patch

from django.core.cache import cache
from django.test import SimpleTestCase
from django.utils.timezone import now

import jwt
from asgiref.sync import async_to_sync
from dateutil.relativedelta import relativedelta
from parameterized import parameterized
from requests import Response, get
from rest_framework import status
from rest_framework.exceptions import ValidationError

from posthog.auth import ProjectSecretAPIKeyUser
from posthog.cloud_utils import TEST_clear_instance_license_cache, get_cached_instance_license
from posthog.constants import AvailableFeature
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_integration import OrganizationIntegration
from posthog.models.organization_provisioning import OrganizationProvisioning
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.project_secret_api_key import ProjectSecretAPIKey
from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal, hash_key_value

from products.access_control.backend.models.access_control import AccessControl

from ee.api.billing import (
    _EXPORT_STREAMS,
    BILLING_ACCESS_DENIED_MESSAGE,
    BILLING_PROJECT_ACCESS_DENIED_MESSAGE,
    BillingDateRangeTooLong,
    BillingExportThrottle,
    BillingNotManagedByPartner,
    BillingQueryRejected,
    BillingQueryTooLarge,
    BillingUsageRequestSerializer,
    BillingViewset,
    HasBillingAccess,
    HasBillingUsageSpendReadAccess,
    _gzip_stream,
    _resolve_team_labels,
    _rewrite_csv_labels,
    _stream_chunks,
)
from ee.api.test.base import APILicensedTest
from ee.billing.billing_manager import BillingManager, BillingServiceResponseError
from ee.billing.billing_types import USAGE_TYPE_OPTIONS, BillingPeriod, CustomerInfo, CustomerProduct, UsageType
from ee.billing.exports import _release_export_stream_slot, _take_export_stream_slot
from ee.billing.grants import (
    BILLING_LIMIT_TODAYS_USAGE_FLAG,
    MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG,
    OWNER_ONLY_BILLING_FLAG,
)
from ee.billing.quota_limiting import QuotaResource
from ee.billing.test.test_billing_manager import create_default_products_response
from ee.models.license import License

VERCEL_BILLING_REFUSAL = {
    "error": "Billing for this organization is managed by Vercel",
    "code": "billing_managed_by_provider",
}
VERCEL_BILLING_REFUSAL_RESPONSE = {
    "type": "invalid_request",
    "code": "billing_managed_by_provider",
    "detail": "Billing for this organization is managed by Vercel",
    "attr": None,
}


def create_usage_summary(**kwargs) -> dict[str, Any]:
    data: dict[str, Any] = {
        "period": ["2022-10-07T11:12:48", "2022-11-07T11:12:48"],
    }
    for resource in QuotaResource:
        data[resource.value] = {"limit": None, "usage": 0, "todays_usage": 0}

    data.update(kwargs)
    return data


def create_billing_response(**kwargs) -> dict[str, Any]:
    data: Any = {"license": {"type": "cloud"}}
    data.update(kwargs)
    return data


def create_missing_billing_customer(**kwargs) -> CustomerInfo:
    data: dict[str, Any] = {
        "customer_id": "cus_123",
        "custom_limits_usd": {},
        "has_active_subscription": False,
        "current_total_amount_usd": "0.00",
        "current_total_amount_usd_after_discount": "0.00",
        "discount_percent": None,
        "discount_amount_usd": None,
        "customer_trust_scores": {},
        "products": None,
        "billing_period": BillingPeriod(
            current_period_start="2022-10-07T11:12:48",
            current_period_end="2022-11-07T11:12:48",
            interval="month",
        ),
        "usage_summary": create_usage_summary(),
        "free_trial_until": None,
        "available_product_features": [],
    }
    data.update(kwargs)
    return cast(CustomerInfo, data)


def create_billing_customer(**kwargs) -> CustomerInfo:
    data: dict[str, Any] = {
        "customer_id": "cus_123",
        "custom_limits_usd": {},
        "has_active_subscription": True,
        "current_total_amount_usd": "100.00",
        "current_total_amount_usd_after_discount": "100.00",
        "discount_percent": None,
        "discount_amount_usd": None,
        "products": [
            {
                "name": "Product OS",
                "description": "Product Analytics, event pipelines, data warehousing",
                "price_description": None,
                "type": "product_analytics",
                "image_url": "https://posthog.com/static/images/product-os.png",
                "free_allocation": 10000,
                "tiers": [
                    {"unit_amount_usd": "0.00", "up_to": 1000000, "current_amount_usd": "0.00"},
                    {"unit_amount_usd": "0.00045", "up_to": 2000000, "current_amount_usd": "0.00"},
                ],
                "tiered": True,
                "unit_amount_usd": "0.00",
                "current_amount_usd": "0.00",
                "current_usage": 0,
                "usage_limit": None,
                "has_exceeded_limit": False,
                "percentage_usage": 0,
                "projected_usage": 0,
                "projected_amount_usd": "0.00",
                "projected_amount_usd_with_limit": "0.00",
                "usage_key": "events",
                "addons": [
                    {
                        "name": "Addon",
                        "description": "Test Addon",
                        "price_description": None,
                        "type": "addon",
                        "image_url": "https://posthog.com/static/images/product-os.png",
                        "free_allocation": 10000,
                        "tiers": [
                            {"unit_amount_usd": "0.00", "up_to": 1000000, "current_amount_usd": "0.00"},
                            {"unit_amount_usd": "0.0000135", "up_to": 2000000, "current_amount_usd": "0.00"},
                        ],
                        "tiered": True,
                        "unit_amount_usd": "0.00",
                        "current_amount_usd": "0.00",
                        "current_usage": 0,
                        "usage_limit": None,
                        "has_exceeded_limit": False,
                        "percentage_usage": 0,
                        "projected_usage": 0,
                        "projected_amount_usd": "0.00",
                        "usage_key": "events",
                        "subscribed": True,
                    }
                ],
            }
        ],
        "customer_trust_scores": {
            "surveys": 15,
            "feature_flags": 15,
            "data_warehouse": 15,
            "session_replay": 15,
            "product_analytics": 15,
        },
        "billing_period": BillingPeriod(
            current_period_start="2022-10-07T11:12:48",
            current_period_end="2022-11-07T11:12:48",
            interval="month",
        ),
        "usage_summary": create_usage_summary(),
        "free_trial_until": None,
        "available_product_features": [],
    }
    data.update(kwargs)
    return cast(CustomerInfo, data)


def create_billing_products_response(**kwargs) -> dict[str, list[CustomerProduct]]:
    data: Any = {
        "products": [
            {
                "name": "Product OS",
                "description": "Product Analytics, event pipelines, data warehousing",
                "price_description": None,
                "type": "events",
                "image_url": "https://posthog.com/static/images/product-os.png",
                "free_allocation": 10000,
                "tiers": [
                    {
                        "unit_amount_usd": "0.00",
                        "up_to": 1000000,
                        "current_amount_usd": "0.00",
                        "current_usage": 0,
                        "flat_amount_usd": "0",
                        "projected_amount_usd": "None",
                        "projected_usage": None,
                    },
                    {
                        "unit_amount_usd": "0.00045",
                        "up_to": 2000000,
                        "current_amount_usd": "0.00",
                        "current_usage": 0,
                        "flat_amount_usd": "0",
                        "projected_amount_usd": "None",
                        "projected_usage": None,
                    },
                ],
                "addons": [
                    {
                        "current_amount_usd": 0.0,
                        "current_usage": 0,
                        "description": "Test Addon",
                        "free_allocation": 10000,
                        "has_exceeded_limit": False,
                        "image_url": "https://posthog.com/static/images/product-os.png",
                        "name": "Addon",
                        "percentage_usage": 0,
                        "price_description": None,
                        "projected_amount_usd": "0.00",
                        "projected_usage": 0,
                        "subscribed": True,
                        "tiered": True,
                        "tiers": [
                            {
                                "current_amount_usd": "0.00",
                                "current_usage": 0,
                                "flat_amount_usd": "0",
                                "projected_amount_usd": "None",
                                "projected_usage": None,
                                "unit_amount_usd": "0.00",
                                "up_to": 1000000,
                            },
                            {
                                "current_amount_usd": "0.00",
                                "current_usage": 0,
                                "flat_amount_usd": "0",
                                "projected_amount_usd": "None",
                                "projected_usage": None,
                                "unit_amount_usd": "0.0000135",
                                "up_to": 2000000,
                            },
                        ],
                        "type": "events",
                        "unit_amount_usd": "0.00",
                        "usage_key": "events",
                        "usage_limit": None,
                    },
                ],
                "tiered": True,
                "unit_amount_usd": "0.00",
                "current_amount_usd": 0.0,
                "current_usage": 0,
                "usage_limit": None,
                "has_exceeded_limit": False,
                "percentage_usage": 0,
                "projected_usage": 0,
                "projected_amount": 0,
                "projected_amount_usd": 0.00,
                "projected_amount_usd_with_limit": 0.00,
                "usage_key": "events",
            }
        ]
    }
    data.update(kwargs)
    return cast(dict[str, list[CustomerProduct]], data)


class TestUnlicensedBillingAPI(APIBaseTest):
    @patch("ee.billing.billing_manager.http_session.get")
    @time_machine.travel("2022-01-01", tick=False)
    def test_billing_calls_the_service_without_token(self, mock_request):
        def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
            mock = MagicMock()
            mock.status_code = 404

            if "api/billing/portal" in url:
                mock.status_code = 200
                mock.json.return_value = {"url": "https://billing.stripe.com/p/session/test_1234"}
            elif "api/billing" in url:
                mock.status_code = 401
                mock.json.return_value = {"detail": "Authorization is missing."}
            elif "api/products" in url:
                mock.status_code = 200
                mock.json.return_value = create_default_products_response()

            return mock

        mock_request.side_effect = mock_implementation

        TEST_clear_instance_license_cache()
        res = self.client.get("/api/billing")
        assert res.status_code == 200
        assert res.json() == {
            "available_product_features": [],
            "products": create_default_products_response()["products"],
            "billing_managed_by_partner": None,
        }

    def test_license_patch_denied_for_members(self):
        # Unlicensed instance, so the permission layer (not the "license already exists"
        # guard) decides the outcome. Setting the instance-wide license key is an
        # admin-only action.
        TEST_clear_instance_license_cache()
        self.organization_membership.level = OrganizationMembership.Level.MEMBER
        self.organization_membership.save()
        response = self.client.patch("/api/billing/license", {}, content_type="application/json")
        assert response.status_code == status.HTTP_403_FORBIDDEN


class TestBillingAPI(APILicensedTest):
    def test_billing_fails_for_old_license_type(self):
        self.license.key = "test_key"
        self.license.save()
        TEST_clear_instance_license_cache()

        res = self.client.get("/api/billing")
        assert res.status_code == 404
        assert res.json()["detail"] == "Billing is not supported for this license type"

    @patch("ee.billing.billing_manager.http_session.get")
    @time_machine.travel("2022-01-01", tick=False)
    def test_billing_calls_the_service_with_appropriate_token(self, mock_request):
        def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
            mock = MagicMock()
            mock.status_code = 404

            if "api/billing/portal" in url:
                mock.status_code = 200
                mock.json.return_value = {"url": "https://billing.stripe.com/p/session/test_1234"}
            elif "api/billing" in url:
                mock.status_code = 200
                mock.json.return_value = create_billing_response(customer=create_billing_customer())

            return mock

        mock_request.side_effect = mock_implementation

        TEST_clear_instance_license_cache()

        self.client.get("/api/billing")
        assert mock_request.call_args_list[0].args[0].endswith("/api/billing")
        token = mock_request.call_args_list[0].kwargs["headers"]["Authorization"].split(" ")[1]

        secret = self.license.key.split("::")[1]

        decoded_token = jwt.decode(
            token,
            secret,
            algorithms=["HS256"],
            audience="posthog:license-key",
            options={"verify_aud": True},
        )

        assert decoded_token == {
            "aud": "posthog:license-key",
            "distinct_id": str(self.user.distinct_id),
            "email": self.user.email,
            "exp": 1640996100,
            "id": self.license.key.split("::")[0],
            "organization_id": str(self.organization.id),
            "organization_name": "Test",
            "organization_role": "member",
        }

    @patch("ee.billing.billing_manager.http_session.get")
    def test_billing_returns_if_billing_exists(self, mock_request):
        def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
            mock = MagicMock()
            mock.status_code = 404

            if "api/billing/portal" in url:
                mock.status_code = 200
                mock.json.return_value = {"url": "https://billing.stripe.com/p/session/test_1234"}
            elif "api/billing" in url:
                mock.status_code = 200
                mock.json.return_value = create_billing_response(customer=create_billing_customer())

            return mock

        mock_request.side_effect = mock_implementation

        TEST_clear_instance_license_cache()
        response = self.client.get("/api/billing")
        assert response.status_code == status.HTTP_200_OK

        assert response.json() == {
            "customer_id": "cus_123",
            "customer_trust_scores": {
                "data_warehouse": 15,
                "feature_flags": 15,
                "product_analytics": 15,
                "session_replay": 15,
                "surveys": 15,
            },
            "license": {"plan": "cloud"},
            "available_product_features": [],
            "custom_limits_usd": {},
            "has_active_subscription": True,
            "stripe_portal_url": "http://localhost:8010/api/billing/portal",
            "current_total_amount_usd": "100.00",
            "current_total_amount_usd_after_discount": "100.00",
            "discount_percent": None,
            "discount_amount_usd": None,
            "products": [
                {
                    "name": "Product OS",
                    "description": "Product Analytics, event pipelines, data warehousing",
                    "price_description": None,
                    "type": "product_analytics",
                    "image_url": "https://posthog.com/static/images/product-os.png",
                    "free_allocation": 10000,
                    "tiers": [
                        {
                            "unit_amount_usd": "0.00",
                            "up_to": 1000000,
                            "current_amount_usd": "0.00",
                        },
                        {
                            "unit_amount_usd": "0.00045",
                            "up_to": 2000000,
                            "current_amount_usd": "0.00",
                        },
                    ],
                    "tiered": True,
                    "current_amount_usd": "0.00",
                    "current_usage": 0,
                    "usage_limit": None,
                    "percentage_usage": 0,
                    "has_exceeded_limit": False,
                    "unit_amount_usd": "0.00",
                    "projected_amount_usd": "0.00",
                    "projected_amount_usd_with_limit": "0.00",
                    "projected_usage": 0,
                    "usage_key": "events",
                    "addons": [
                        {
                            "current_amount_usd": "0.00",
                            "current_usage": 0,
                            "description": "Test Addon",
                            "free_allocation": 10000,
                            "has_exceeded_limit": False,
                            "image_url": "https://posthog.com/static/images/product-os.png",
                            "name": "Addon",
                            "percentage_usage": 0,
                            "price_description": None,
                            "projected_amount_usd": "0.00",
                            "projected_usage": 0,
                            "subscribed": True,
                            "tiered": True,
                            "tiers": [
                                {
                                    "current_amount_usd": "0.00",
                                    "unit_amount_usd": "0.00",
                                    "up_to": 1000000,
                                },
                                {
                                    "current_amount_usd": "0.00",
                                    "unit_amount_usd": "0.0000135",
                                    "up_to": 2000000,
                                },
                            ],
                            "type": "addon",
                            "unit_amount_usd": "0.00",
                            "usage_key": "events",
                            "usage_limit": None,
                        },
                    ],
                },
            ],
            "billing_period": {
                "current_period_start": "2022-10-07T11:12:48",
                "current_period_end": "2022-11-07T11:12:48",
                "interval": "month",
            },
            "usage_summary": create_usage_summary(),
            "free_trial_until": None,
            "billing_managed_by_partner": None,
        }

    @patch("ee.billing.billing_manager.http_session.get")
    def test_billing_returns_if_doesnt_exist(self, mock_request):
        def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
            mock = MagicMock()
            mock.status_code = 404

            if "api/billing/portal" in url:
                mock.status_code = 200
                mock.json.return_value = {"url": "https://billing.stripe.com/p/session/test_1234"}
            elif "api/billing" in url:
                mock.status_code = 200
                mock.json.return_value = create_billing_response(customer=create_missing_billing_customer())
            elif "api/products" in url:
                mock.status_code = 200
                mock.json.return_value = create_billing_products_response()

            return mock

        mock_request.side_effect = mock_implementation

        response = self.client.get("/api/billing")
        assert response.status_code == status.HTTP_200_OK
        assert response.json() == {
            "customer_id": "cus_123",
            "customer_trust_scores": {},
            "license": {"plan": "cloud"},
            "custom_limits_usd": {},
            "has_active_subscription": False,
            "available_product_features": [],
            "products": [
                {
                    "name": "Product OS",
                    "description": "Product Analytics, event pipelines, data warehousing",
                    "price_description": None,
                    "type": "events",
                    "free_allocation": 10000,
                    "tiers": [
                        {
                            "unit_amount_usd": "0.00",
                            "up_to": 1000000,
                            "current_amount_usd": "0.00",
                            "current_usage": 0,
                            "flat_amount_usd": "0",
                            "projected_amount_usd": "None",
                            "projected_usage": None,
                        },
                        {
                            "unit_amount_usd": "0.00045",
                            "up_to": 2000000,
                            "current_amount_usd": "0.00",
                            "current_usage": 0,
                            "flat_amount_usd": "0",
                            "projected_amount_usd": "None",
                            "projected_usage": None,
                        },
                    ],
                    "current_usage": 0,
                    "percentage_usage": 0,
                    "current_amount_usd": 0.0,
                    "has_exceeded_limit": False,
                    "projected_amount": 0,
                    "projected_amount_usd": 0.0,
                    "projected_amount_usd_with_limit": 0.0,
                    "projected_usage": 0,
                    "tiered": True,
                    "unit_amount_usd": "0.00",
                    "usage_limit": None,
                    "image_url": "https://posthog.com/static/images/product-os.png",
                    "usage_key": "events",
                    "addons": [
                        {
                            "current_amount_usd": 0.0,
                            "current_usage": 0,
                            "description": "Test Addon",
                            "free_allocation": 10000,
                            "has_exceeded_limit": False,
                            "image_url": "https://posthog.com/static/images/product-os.png",
                            "name": "Addon",
                            "percentage_usage": 0,
                            "price_description": None,
                            "projected_amount_usd": "0.00",
                            "projected_usage": 0,
                            "subscribed": True,
                            "tiered": True,
                            "tiers": [
                                {
                                    "current_amount_usd": "0.00",
                                    "current_usage": 0,
                                    "flat_amount_usd": "0",
                                    "projected_amount_usd": "None",
                                    "projected_usage": None,
                                    "unit_amount_usd": "0.00",
                                    "up_to": 1000000,
                                },
                                {
                                    "current_amount_usd": "0.00",
                                    "current_usage": 0,
                                    "flat_amount_usd": "0",
                                    "projected_amount_usd": "None",
                                    "projected_usage": None,
                                    "unit_amount_usd": "0.0000135",
                                    "up_to": 2000000,
                                },
                            ],
                            "type": "events",
                            "unit_amount_usd": "0.00",
                            "usage_key": "events",
                            "usage_limit": None,
                        },
                    ],
                }
            ],
            "billing_period": {
                "current_period_start": "2022-10-07T11:12:48",
                "current_period_end": "2022-11-07T11:12:48",
                "interval": "month",
            },
            "usage_summary": create_usage_summary(),
            "free_trial_until": None,
            "current_total_amount_usd": "0.00",
            "current_total_amount_usd_after_discount": "0.00",
            "discount_percent": None,
            "discount_amount_usd": None,
            "stripe_portal_url": "http://localhost:8010/api/billing/portal",
            "billing_managed_by_partner": None,
        }

    @patch("ee.billing.billing_manager.http_session.get")
    def test_billing_stores_valid_license(self, mock_request):
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()
        self.license.delete()

        mock_request.return_value.status_code = 200
        mock_request.return_value.json.return_value = {
            "license": {
                "type": "scale",
            }
        }
        response = self.client.patch(
            "/api/billing/license",
            {
                "license": "test::test",
            },
        )

        assert response.status_code == status.HTTP_200_OK
        assert response.json() == {"success": True}
        license = License.objects.first_valid()
        assert license
        assert license.key == "test::test"
        assert license.plan == "scale"

    @patch("ee.billing.billing_manager.http_session.get")
    def test_billing_ignores_invalid_license(self, mock_request):
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()
        self.license.delete()

        mock_request.return_value.status_code = 403
        mock_request.return_value.json.return_value = {}
        response = self.client.patch(
            "/api/billing/license",
            {
                "license": "test::test",
            },
        )

        assert response.status_code == status.HTTP_400_BAD_REQUEST
        assert response.json() == {
            "attr": "license",
            "code": "invalid_input",
            "detail": "License could not be activated. Please contact support. (BillingService status 403)",
            "type": "validation_error",
        }

    @time_machine.travel("2022-01-01T12:00:00Z", tick=False)
    @patch("ee.billing.billing_manager.http_session.get")
    def test_license_is_updated_on_billing_load(self, mock_request):
        mock_request.return_value.status_code = 200
        mock_request.return_value.json.return_value = {
            "license": {
                "type": "scale",
            },
            "customer": create_billing_customer(),
        }

        assert self.license.plan == "enterprise"
        self.client.get("/api/billing")
        self.license.refresh_from_db()

        self.license.valid_until = datetime(2022, 1, 2, 0, 0, 0, tzinfo=ZoneInfo("UTC"))
        self.license.save()
        assert self.license.plan == "scale"
        TEST_clear_instance_license_cache()
        license = get_cached_instance_license()
        assert license is not None
        assert license.plan == "scale"
        assert license.valid_until == datetime(2022, 1, 2, 0, 0, 0, tzinfo=ZoneInfo("UTC"))

        mock_request.return_value.json.return_value = {
            "license": {
                "type": "enterprise",
            },
            "customer": create_billing_customer(),
        }

        self.client.get("/api/billing")
        license = get_cached_instance_license()
        assert license is not None
        assert license.plan == "enterprise"
        # Should be extended by 30 days
        assert license.valid_until == datetime(2022, 1, 31, 12, 0, 0, tzinfo=ZoneInfo("UTC"))

    @patch("ee.billing.billing_manager.http_session.get")
    def test_organization_available_product_features_updated_if_different(self, mock_request):
        def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
            mock = MagicMock()
            mock.status_code = 404

            if "api/billing/portal" in url:
                mock.status_code = 200
                mock.json.return_value = {"url": "https://billing.stripe.com/p/session/test_1234"}
            elif "api/billing" in url:
                mock.status_code = 200
                mock.json.return_value = create_billing_response(
                    customer=create_billing_customer(
                        available_product_features=[
                            {"key": "feature1", "name": "feature1"},
                            {"key": "feature2", "name": "feature2"},
                        ]
                    )
                )

            return mock

        mock_request.side_effect = mock_implementation

        self.organization.available_product_features = []
        self.organization.save()

        assert self.organization.available_product_features == []
        self.client.get("/api/billing")
        self.organization.refresh_from_db()
        assert self.organization.available_product_features == [
            {
                "key": "feature1",
                "name": "feature1",
            },
            {"key": "feature2", "name": "feature2"},
        ]

    @patch("ee.billing.billing_manager.http_session.get")
    def test_organization_update_usage(self, mock_request):
        self.organization.customer_id = None
        self.organization.usage = None
        self.organization.save()

        def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
            mock = MagicMock()
            mock.status_code = 404

            if "api/billing/portal" in url:
                mock.status_code = 200
                mock.json.return_value = {"url": "https://billing.stripe.com/p/session/test_1234"}
            elif "api/billing" in url:
                mock.status_code = 200
                mock.json.return_value = create_billing_response(
                    customer=create_billing_customer(has_active_subscription=True),
                )
                mock.json.return_value["customer"]["usage_summary"]["events"]["usage"] = 1000
            elif "api/products" in url:
                mock.status_code = 200
                mock.json.return_value = create_billing_products_response()

            return mock

        mock_request.side_effect = mock_implementation

        self.assertIsNone(self.organization.usage)
        res = self.client.get("/api/billing")
        assert res.status_code == 200
        organization = Team.objects.get(pk=self.team.pk).organization
        assert organization.usage is not None
        TestCase().assertDictEqual(
            organization.usage,
            create_usage_summary(events={"usage": 1000, "limit": None, "todays_usage": 0}),
        )

        self.organization.usage = {"events": {"limit": None, "usage": 1000, "todays_usage": 1100000}}
        self.organization.save()

        res = self.client.get("/api/billing")
        assert res.status_code == 200
        res_json = res.json()
        # Should update product usage to reflect today's usage
        assert res_json["products"][0]["current_usage"] == 1101000
        assert res_json["products"][0]["current_amount_usd"] == "0.00"
        assert res_json["products"][0]["tiers"][0]["current_amount_usd"] == "0.00"
        assert res_json["products"][0]["tiers"][1]["current_amount_usd"] == "0.00"

        assert res_json["products"][0]["addons"][0]["current_usage"] == 0
        assert res_json["products"][0]["addons"][0]["current_amount_usd"] == "0.00"
        assert res_json["products"][0]["addons"][0]["tiers"][0]["current_amount_usd"] == "0.00"
        assert res_json["products"][0]["addons"][0]["tiers"][1]["current_amount_usd"] == "0.00"

    @patch("posthog.tasks.demo_create_data.create_data_for_demo_team.delay")
    @patch("ee.billing.billing_manager.http_session.get")
    def test_organization_usage_count_with_demo_project(self, mock_request, *args):
        def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock | Response:
            mock = MagicMock()
            if "api/billing/portal" in url:
                mock.status_code = 200
                mock.json.return_value = {"url": "https://billing.stripe.com/p/session/test_1234"}
                return mock
            elif "api/billing" in url:
                mock.status_code = 200
                mock.json.return_value = create_billing_response(
                    # Set usage to none so it is calculated from scratch
                    customer=create_billing_customer(has_active_subscription=False, usage=None)
                )
                return mock
            else:
                return get(url, headers=headers, params=params)

        mock_request.side_effect = mock_implementation

        self.organization.customer_id = None
        self.organization.usage = None
        self.organization.save()
        # Create a demo project
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()
        self.assertEqual(Team.objects.count(), 1)
        response = self.client.post("/api/projects/", {"name": "Test", "is_demo": True})
        self.assertEqual(response.status_code, 201)
        self.assertEqual(Team.objects.count(), 2)

        demo_team = Team.objects.get(organization=self.organization, is_demo=True)

        # We create some events for the demo project
        with self.settings(USE_TZ=False):
            distinct_id = str(uuid4())
            for _ in range(0, 10):
                _create_event(
                    distinct_id=distinct_id,
                    event="$demo-event",
                    properties={"$lib": "$mobile"},
                    timestamp=now() - relativedelta(hours=12),
                    team=demo_team,
                )
            flush_persons_and_events()

        assert not self.organization.usage
        res = self.client.get("/api/billing")
        assert res.status_code == 200
        self.organization.refresh_from_db()
        assert self.organization.usage == create_usage_summary()

    @patch("ee.billing.billing_manager.http_session.get")
    def test_org_trust_score_updated(self, mock_request):
        def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
            mock = MagicMock()
            mock.status_code = 404

            if "api/billing/portal" in url:
                mock.status_code = 200
                mock.json.return_value = {"url": "https://billing.stripe.com/p/session/test_1234"}
            elif "api/billing" in url:
                mock.status_code = 200
                mock.json.return_value = create_billing_response(
                    # Set usage to none so it is calculated from scratch
                    customer=create_billing_customer(has_active_subscription=False, usage=None)
                )

            return mock

        mock_request.side_effect = mock_implementation

        self.organization.customer_id = None
        # For key values check: QuotaResource values
        self.organization.customer_trust_scores = {
            "events": 0,
            "exceptions": 0,
            "recordings": 0,
            "rows_synced": 0,
            "feature_flags": 0,
            "api_queries_read_bytes": 17,
            "surveys": 0,
        }
        self.organization.save()

        res = self.client.get("/api/billing")
        assert res.status_code == 200
        self.organization.refresh_from_db()

        assert self.organization.customer_trust_scores == {
            "events": 15,
            "exceptions": 0,
            "recordings": 0,
            "rows_synced": 0,
            "feature_flags": 0,
            "api_queries_read_bytes": 17,
            "surveys": 0,
        }

    @parameterized.expand(
        [
            (None, {}),
            ("true", {"include_forecasting": "true"}),
            ("false", {"include_forecasting": "false"}),
            ("1", {"include_forecasting": "true"}),
            ("0", {"include_forecasting": "false"}),
        ]
    )
    @patch("ee.billing.billing_manager.http_session.get")
    def test_billing_with_supported_params(
        self, include_forecasting: str | None, expected_params: dict[str, str], mock_get: MagicMock
    ) -> None:
        """Normalize explicit forecasting values and preserve the downstream default when omitted."""

        def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
            mock = MagicMock()
            mock.status_code = 200

            if "api/billing/portal" in url:
                mock.json.return_value = {"url": "https://billing.stripe.com/p/session/test_1234"}
            elif "api/billing" in url:
                mock.json.return_value = create_billing_response(
                    customer=create_billing_customer(has_active_subscription=True)
                )

            return mock

        mock_get.side_effect = mock_implementation

        params = {} if include_forecasting is None else {"include_forecasting": include_forecasting}
        response = self.client.get("/api/billing/", params)
        assert response.status_code == 200

        # Verify the billing service was called with the correct query param
        billing_calls = [
            call
            for call in mock_get.call_args_list
            if "api/billing" in call[0][0] and "api/billing/portal" not in call[0][0]
        ]
        assert len(billing_calls) == 1
        assert billing_calls[0].kwargs["params"] == expected_params

    @patch("ee.billing.billing_manager.BillingManager.get_billing")
    def test_billing_rejects_malformed_forecasting_param(self, mock_get_billing: MagicMock) -> None:
        response = self.client.get("/api/billing/", {"include_forecasting": "invalid"})

        assert response.status_code == status.HTTP_400_BAD_REQUEST
        mock_get_billing.assert_not_called()

    @patch("ee.billing.billing_manager.BillingManager.get_billing")
    @patch("ee.billing.billing_manager.BillingManager.update_billing")
    @patch("ee.billing.grants.posthog_feature_flag_enabled")
    def test_patch_sends_todays_usage_when_enabled(self, mock_feature_enabled, mock_update_billing, mock_get_billing):
        mock_feature_enabled.side_effect = lambda key, *_args, **_kwargs: key == BILLING_LIMIT_TODAYS_USAGE_FLAG
        self.organization_membership.level = OrganizationMembership.Level.OWNER
        self.organization_membership.save()
        self.organization.usage = create_usage_summary(
            events={"usage": 100, "todays_usage": 20, "limit": None},
            posthog_code_credits={"usage": 1200, "todays_usage": 3400, "limit": 5000},
            posthog_code_token_credits={"usage": 999, "todays_usage": 1, "limit": None},
        )
        self.organization.save()
        mock_get_billing.return_value = create_billing_response(customer=create_billing_customer())

        response = self.client.patch(
            "/api/billing//",
            data={"custom_limits_usd": {"posthog_code_usage": 50}},
            content_type="application/json",
        )

        assert response.status_code == status.HTTP_200_OK
        mock_update_billing.assert_called_once()
        assert mock_update_billing.call_args.args[1] == {
            "custom_limits_usd": {"posthog_code_usage": 50},
            "todays_usage_by_usage_key": {"posthog_code_credits": 3400},
        }
        mock_feature_enabled.assert_any_call(
            BILLING_LIMIT_TODAYS_USAGE_FLAG,
            str(self.user.distinct_id),
            organization_id=self.organization.id,
        )

    @patch("ee.billing.billing_manager.BillingManager.get_billing")
    @patch("ee.billing.billing_manager.BillingManager.update_billing")
    @patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=False)
    def test_patch_does_not_send_todays_usage_when_disabled(
        self, _mock_feature_enabled, mock_update_billing, mock_get_billing
    ):
        self.organization_membership.level = OrganizationMembership.Level.OWNER
        self.organization_membership.save()
        self.organization.usage = create_usage_summary(
            posthog_code_credits={"usage": 1200, "todays_usage": 3400, "limit": 5000}
        )
        self.organization.save()
        mock_get_billing.return_value = create_billing_response(customer=create_billing_customer())

        response = self.client.patch(
            "/api/billing//",
            data={"custom_limits_usd": {"posthog_code_usage": 50}},
            content_type="application/json",
        )

        assert response.status_code == status.HTTP_200_OK
        mock_update_billing.assert_called_once()
        assert mock_update_billing.call_args.args[1] == {"custom_limits_usd": {"posthog_code_usage": 50}}


class TestPortalBillingAPI(APILicensedTest):
    def setUp(self):
        super().setUp()
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()

    @patch("ee.billing.billing_manager.http_session.get")
    def test_portal_success(self, mock_request):
        mock_request.return_value.status_code = 200
        mock_request.return_value.json.return_value = {"url": "https://billing.stripe.com/p/session/test_1234"}

        response = self.client.get("/api/billing/portal")

        self.assertEqual(response.status_code, status.HTTP_302_FOUND)
        self.assertIn("https://billing.stripe.com/p/session/test_1234", cast(Any, response).url)

    @patch("ee.billing.billing_manager.http_session.get")
    def test_portal_sends_a_vercel_billed_organization_to_its_vercel_invoices(self, mock_request):
        mock_request.return_value.status_code = 400
        mock_request.return_value.json.return_value = VERCEL_BILLING_REFUSAL

        without_invoices_page = self.client.get("/api/billing/portal")
        OrganizationIntegration.objects.create(
            organization=self.organization,
            kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,
            integration_id="icfg_example",
            config={"account": {"url": "https://vercel.com/example-team/~/integrations/posthog/icfg_example"}},
        )
        with_invoices_page = self.client.get("/api/billing/portal")

        assert without_invoices_page.status_code == status.HTTP_400_BAD_REQUEST
        assert without_invoices_page.json() == VERCEL_BILLING_REFUSAL_RESPONSE
        assert with_invoices_page.status_code == status.HTTP_302_FOUND
        assert (
            cast(Any, with_invoices_page).url
            == "https://vercel.com/example-team/~/integrations/posthog/icfg_example/invoices"
        )


class TestActivateBillingAPI(APILicensedTest):
    def setUp(self):
        super().setUp()
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()

    @patch("ee.billing.billing_manager.BillingManager.activate_subscription")
    def test_activate_post_success(self, mock_activate_subscription):
        mock_activate_subscription.return_value = {"success": True, "products": ["product_analytics"]}

        url = "/api/billing/activate"
        data = {"organization_id": str(self.organization.id), "products": "all_products:"}

        response = self.client.post(url, data, content_type="application/json")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json(), {"success": True, "products": ["product_analytics"]})
        mock_activate_subscription.assert_called_once_with(self.organization, {"products": "all_products:"})

    @parameterized.expand(
        [
            ("billing_refusal", 400, status.HTTP_400_BAD_REQUEST, "payment_authorization_rejected"),
            ("billing_unauthorized", 401, status.HTTP_400_BAD_REQUEST, "payment_authorization_rejected"),
            ("billing_not_found", 404, status.HTTP_400_BAD_REQUEST, "payment_authorization_rejected"),
            ("billing_failure", 500, status.HTTP_502_BAD_GATEWAY, "billing_service_error"),
        ]
    )
    @patch("ee.billing.billing_manager.http_session.post")
    def test_authorize_hides_the_billing_error_body(
        self, _name: str, upstream_status: int, expected_status: int, expected_code: str, mock_post
    ):
        mock_post.return_value = MagicMock(
            status_code=upstream_status,
            json=lambda: {"detail": "duplicate key value violates unique constraint"},
            text="duplicate key value violates unique constraint",
        )

        response = self.client.post(
            "/api/billing/activate/authorize",
            {"organization_id": str(self.organization.id)},
            content_type="application/json",
        )

        self.assertEqual(response.status_code, expected_status)
        self.assertEqual(response.json()["code"], expected_code)
        self.assertNotIn("duplicate key", response.content.decode())

    def test_activate_get_returns_405(self):
        url = "/api/billing/activate"
        response = self.client.get(url, {"products": "product_1:plan_1"})
        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)

    @parameterized.expand(
        [
            ("activate", "/api/billing/activate", "activate_subscription"),
            ("authorize", "/api/billing/activate/authorize", "authorize"),
        ]
    )
    def test_only_a_vercel_refusal_from_billing_reaches_the_caller(
        self, _name: str, url: str, manager_method: str
    ) -> None:
        refusals = [
            BillingServiceResponseError(400, VERCEL_BILLING_REFUSAL),
            BillingServiceResponseError(400, {"error": "Your card was declined.", "code": "card_declined"}),
        ]

        payment_request = {"organization_id": str(self.organization.id)}

        with patch.object(BillingManager, manager_method, side_effect=refusals):
            vercel_refusal = self.client.post(url, payment_request, content_type="application/json")
            other_refusal = self.client.post(url, payment_request, content_type="application/json")

        assert vercel_refusal.status_code == status.HTTP_400_BAD_REQUEST
        assert vercel_refusal.json() == VERCEL_BILLING_REFUSAL_RESPONSE
        assert "Your card was declined." not in other_refusal.content.decode()

    @parameterized.expand(
        [
            ("activate", "activate_subscription"),
            ("activate/authorize", "authorize"),
            ("activate/authorize/status", "authorize_status"),
        ]
    )
    @patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=False)
    def test_payment_targets_explicit_organization_after_current_team_changes(
        self, action: str, manager_method: str, _flag: MagicMock
    ) -> None:
        other_org = Organization.objects.create(name="Another organization")
        other_team = Team.objects.create(organization=other_org, name="Another project")
        OrganizationMembership.objects.create(
            organization=other_org, user=self.user, level=OrganizationMembership.Level.ADMIN
        )
        self.user.current_organization = other_org
        self.user.current_team = other_team
        self.user.save()
        with patch.object(BillingManager, manager_method, return_value={"success": True}) as manager:
            response = self.client.post(
                f"/api/billing/{action}",
                {
                    "organization_id": str(self.organization.id),
                    "products": "all_products:",
                    "payment_intent_id": "pi_test",
                },
                content_type="application/json",
            )
        assert response.status_code == status.HTTP_200_OK
        assert manager.call_args.args[0] == self.organization

    @parameterized.expand(
        [
            (action, manager_method, level, owner_only, expected)
            for action, manager_method in [
                ("activate", "activate_subscription"),
                ("activate/authorize", "authorize"),
                ("activate/authorize/status", "authorize_status"),
            ]
            for level, owner_only, expected in [
                (OrganizationMembership.Level.MEMBER, False, 403),
                (OrganizationMembership.Level.ADMIN, False, 200),
                (OrganizationMembership.Level.ADMIN, True, 403),
                (OrganizationMembership.Level.ADMIN, None, 403),
                (OrganizationMembership.Level.OWNER, True, 200),
            ]
        ]
    )
    def test_payment_respects_requested_organization_billing_access(
        self, action: str, manager_method: str, level: int, owner_only: bool | None, expected: int
    ) -> None:
        self.organization_membership.level = level
        self.organization_membership.save()
        with (
            patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=owner_only),
            patch.object(BillingManager, manager_method, return_value={"success": True}) as manager,
        ):
            response = self.client.post(
                f"/api/billing/{action}",
                {"organization_id": str(self.organization.id)},
                content_type="application/json",
            )
        assert response.status_code == expected
        assert manager.call_count == (1 if expected == 200 else 0)

    @parameterized.expand(
        [
            (action, value)
            for action in ["activate", "activate/authorize", "activate/authorize/status"]
            for value in [None, "", "@current", "invalid", 123]
        ]
    )
    def test_payment_requires_concrete_organization_id(self, action: str, value: Any) -> None:
        with patch("ee.api.billing.BillingManager") as manager:
            data = {} if value is None else {"organization_id": value}
            response = self.client.post(f"/api/billing/{action}", data, content_type="application/json")
        assert response.status_code == status.HTTP_400_BAD_REQUEST
        manager.assert_not_called()

    @parameterized.expand(["activate", "activate/authorize", "activate/authorize/status"])
    def test_payment_denies_foreign_organization(self, action: str) -> None:
        organization = Organization.objects.create(name="Foreign organization")
        with patch("ee.api.billing.BillingManager") as manager:
            response = self.client.post(
                f"/api/billing/{action}", {"organization_id": str(organization.id)}, content_type="application/json"
            )
        assert response.status_code == status.HTTP_403_FORBIDDEN
        manager.assert_not_called()

    @parameterized.expand(["activate", "activate/authorize", "activate/authorize/status"])
    def test_payment_denies_member_of_target_when_admin_of_current_organization(self, action: str) -> None:
        organization = Organization.objects.create(name="Member organization")
        OrganizationMembership.objects.create(
            organization=organization, user=self.user, level=OrganizationMembership.Level.MEMBER
        )
        with patch("ee.api.billing.BillingManager") as manager:
            response = self.client.post(
                f"/api/billing/{action}", {"organization_id": str(organization.id)}, content_type="application/json"
            )
        assert response.status_code == status.HTTP_403_FORBIDDEN
        manager.assert_not_called()

    @parameterized.expand(
        [
            ("activate", "activate_subscription"),
            ("activate/authorize", "authorize"),
            ("activate/authorize/status", "authorize_status"),
        ]
    )
    @patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=False)
    def test_payment_preserves_token_access_restrictions(
        self, action: str, manager_method: str, _flag: MagicMock
    ) -> None:
        token = generate_random_token_personal()
        PersonalAPIKey.objects.create(
            label="Payment test",
            user=self.user,
            secure_value=hash_key_value(token),
            scopes=["*"],
            scoped_organizations=[str(self.organization.id)],
        )
        self.client.logout()
        with patch.object(BillingManager, manager_method, return_value={"success": True}) as manager:
            response = self.client.post(
                f"/api/billing/{action}",
                {"organization_id": str(self.organization.id)},
                content_type="application/json",
                HTTP_AUTHORIZATION=f"Bearer {token}",
            )
        assert response.status_code == status.HTTP_403_FORBIDDEN
        assert response.json()["detail"] == "This action does not support personal API key access"
        manager.assert_not_called()

    @patch("ee.billing.billing_manager.BillingManager.get_billing")
    def test_payment_refresh_reads_original_organization_after_current_team_changes(self, manager: MagicMock) -> None:
        organization = Organization.objects.create(name="Another organization")
        team = Team.objects.create(organization=organization, name="Another project")
        OrganizationMembership.objects.create(
            organization=organization, user=self.user, level=OrganizationMembership.Level.ADMIN
        )
        self.user.current_team = team
        self.user.current_organization = organization
        self.user.save()
        manager.return_value = {"products": [], "available_product_features": []}
        response = self.client.get("/api/billing", {"organization_id": str(self.organization.id)})
        assert response.status_code == status.HTTP_200_OK
        manager.assert_called_once_with(self.organization, {})

    @parameterized.expand(["", "@current", "invalid"])
    def test_explicit_billing_refresh_rejects_invalid_organization(self, organization_id: str) -> None:
        with patch("ee.api.billing.BillingManager") as manager:
            response = self.client.get("/api/billing", {"organization_id": organization_id})
        assert response.status_code == status.HTTP_400_BAD_REQUEST
        manager.assert_not_called()

    @patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=False)
    def test_explicit_billing_refresh_enforces_token_organization_scope(self, _flag: MagicMock) -> None:
        organization = Organization.objects.create(name="Other permitted organization")
        OrganizationMembership.objects.create(
            organization=organization, user=self.user, level=OrganizationMembership.Level.ADMIN
        )
        token = generate_random_token_personal()
        PersonalAPIKey.objects.create(
            label="Scoped billing",
            user=self.user,
            secure_value=hash_key_value(token),
            scopes=["billing:read"],
            scoped_organizations=[str(self.organization.id)],
        )
        self.client.logout()
        with patch.object(
            BillingManager, "get_billing", return_value={"products": [], "available_product_features": []}
        ) as manager:
            allowed = self.client.get(
                "/api/billing", {"organization_id": str(self.organization.id)}, HTTP_AUTHORIZATION=f"Bearer {token}"
            )
            refused = self.client.get(
                "/api/billing", {"organization_id": str(organization.id)}, HTTP_AUTHORIZATION=f"Bearer {token}"
            )
        assert allowed.status_code == status.HTTP_200_OK
        assert refused.status_code == status.HTTP_403_FORBIDDEN
        manager.assert_called_once_with(self.organization, {})

    @patch("ee.billing.billing_manager.BillingManager.deactivate_products")
    @patch("ee.billing.billing_manager.BillingManager.get_billing")
    def test_deactivate_success(self, mock_get_billing, mock_deactivate_products):
        mock_deactivate_products.return_value = MagicMock()
        mock_get_billing.return_value = {
            "available_features": [],
            "products": [],
        }

        url = "/api/billing/deactivate"
        data = {"products": "product_1"}

        response = self.client.post(url, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        mock_deactivate_products.assert_called_once_with(self.organization, "product_1")
        mock_get_billing.assert_called_once_with(self.organization, {})

    def test_deactivate_failure(self):
        url = "/api/billing/deactivate"
        data = {"none": "nothing"}

        response = self.client.post(url, data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)


class TestStartupApplicationBillingAPI(APILicensedTest):
    def setUp(self):
        super().setUp()
        # Set user as admin/owner by default
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()

        self.url = "/api/billing/startups/apply"
        self.data = {"organization_id": str(self.organization.id)}

    @patch("ee.billing.billing_manager.BillingManager.apply_startup_program")
    def test_startup_apply_owner_success(self, mock_apply_startup_program):
        mock_apply_startup_program.return_value = {"success": True}

        response = self.client.post(self.url, self.data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json(), {"success": True})
        mock_apply_startup_program.assert_called_once()

    def test_startup_apply_non_admin_failure(self):
        self.organization_membership.level = OrganizationMembership.Level.MEMBER
        self.organization_membership.save()

        response = self.client.post(self.url, self.data)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_startup_apply_missing_org_id(self):
        empty_data: dict[str, Any] = {}

        response = self.client.post(self.url, empty_data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(
            response.json(),
            {
                "type": "validation_error",
                "code": "invalid_input",
                "detail": "This field is required.",
                "attr": "organization_id",
            },
        )

    @patch("ee.billing.billing_manager.BillingManager.apply_startup_program")
    def test_startup_apply_passes_user_info(self, mock_apply_startup_program):
        mock_apply_startup_program.return_value = {"success": True}

        # Set user properties
        self.user.email = "[email protected]"
        self.user.first_name = "Test"
        self.user.last_name = "User"
        self.user.save()

        # Add additional data fields
        data = {
            **self.data,
            "raised": "1000000",
            "incorporation_date": "2023-01-01",
        }

        response = self.client.post(self.url, data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        expected_data = {
            "organization_id": str(self.organization.id),
            "raised": "1000000",
            "incorporation_date": "2023-01-01",
            "email": "[email protected]",
            "first_name": "Test",
            "last_name": "User",
        }

        # Check that apply_startup_program was called with the organization and the expected data
        mock_apply_startup_program.assert_called_once()
        _, call_args, _ = mock_apply_startup_program.mock_calls[0]
        self.assertEqual(call_args[0], self.organization)
        self.assertEqual(call_args[1], expected_data)


class TestCouponClaimBillingAPI(APILicensedTest):
    def setUp(self):
        super().setUp()
        # Set user as admin by default
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()

        self.url = "/api/billing/coupons/claim"
        self.data = {"code": "TEST-CODE-123"}

    @patch("ee.billing.billing_manager.BillingManager.claim_coupon")
    def test_claim_coupon_success(self, mock_claim_coupon):
        mock_claim_coupon.return_value = {
            "success": True,
            "code": "TEST-CODE-123",
            "expires_at": "2026-01-01T00:00:00Z",
        }

        response = self.client.post(self.url, self.data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json()["success"], True)
        self.assertEqual(response.json()["code"], "TEST-CODE-123")
        mock_claim_coupon.assert_called_once_with(self.organization, {"code": "TEST-CODE-123"})

    def test_claim_coupon_non_admin_failure(self):
        self.organization_membership.level = OrganizationMembership.Level.MEMBER
        self.organization_membership.save()

        response = self.client.post(self.url, self.data)

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    def test_claim_coupon_missing_code(self):
        empty_data: dict[str, Any] = {}

        response = self.client.post(self.url, empty_data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(
            response.json(),
            {
                "type": "validation_error",
                "code": "invalid_input",
                "detail": "This field is required.",
                "attr": "code",
            },
        )

    @patch("ee.billing.billing_manager.BillingManager.claim_coupon")
    def test_claim_coupon_billing_error_with_detail(self, mock_claim_coupon):
        # DRF validation error
        mock_claim_coupon.side_effect = Exception(
            "Billing service returned bad status code: 400",
            "body:",
            {"detail": "Customer has already claimed a coupon from this campaign."},
        )

        response = self.client.post(self.url, self.data)

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        response_json = response.json()
        self.assertEqual(response_json["detail"], "Customer has already claimed a coupon from this campaign.")


class TestPartnerManagedBillingAPI(APILicensedTest):
    def setUp(self) -> None:
        super().setUp()
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()

    def _provision(
        self, pays_for_customers: bool | None, partner_name: str = "Example Partner"
    ) -> OAuthApplication | None:
        if pays_for_customers is None:
            OrganizationProvisioning.objects.create(
                organization=self.organization, partner=OrganizationProvisioning.Partner.VERCEL
            )
            return None
        application = OAuthApplication.objects.create(
            client_id="example-partner",
            name=partner_name,
            client_secret="",
            client_type=OAuthApplication.CLIENT_PUBLIC,
            authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
            redirect_uris="https://partner.example.com/callback",
            algorithm="RS256",
            is_provisioning_partner=True,
        )
        application.update_provisioning(pays_for_customers=pays_for_customers)
        OrganizationProvisioning.objects.create(
            organization=self.organization,
            partner=OrganizationProvisioning.Partner.PROVISIONING_API,
            application=application,
        )
        return application

    @parameterized.expand(
        [
            ("activate", "post", "/api/billing/activate", "activate_subscription", status.HTTP_200_OK),
            ("switch_plan", "post", "/api/billing/subscription/switch-plan", "switch_plan", status.HTTP_200_OK),
            ("portal", "get", "/api/billing/portal", "_get_stripe_portal_url", status.HTTP_302_FOUND),
            ("purchase_credits", "post", "/api/billing/credits/purchase", "purchase_credits", status.HTTP_200_OK),
            ("activate_trial", "post", "/api/billing/trials/activate", "activate_trial", status.HTTP_200_OK),
            ("authorize", "post", "/api/billing/activate/authorize", "authorize", status.HTTP_200_OK),
            (
                "activate_for_unnamed_partner",
                "post",
                "/api/billing/activate",
                "activate_subscription",
                status.HTTP_200_OK,
                "",
                "your partner",
            ),
        ]
    )
    def test_self_serve_billing_action_is_refused_while_the_partner_pays_and_the_org_has_no_stripe_customer(
        self,
        _name: str,
        method: str,
        url: str,
        manager_method: str,
        allowed_status: int,
        partner_name: str = "Example Partner",
        named_as: str = "Example Partner",
    ) -> None:
        application = self._provision(pays_for_customers=False, partner_name=partner_name)
        assert application is not None
        manager_result = "https://billing.stripe.com/p/session/test_1234" if method == "get" else {"success": True}

        with patch.object(BillingManager, manager_method, return_value=manager_result) as mock_manager_method:
            data = (
                {"organization_id": str(self.organization.id)}
                if _name.startswith("activate") or _name == "authorize"
                else {}
            )
            allowed = getattr(self.client, method)(url, data)
            application.update_provisioning(pays_for_customers=True)
            refused = getattr(self.client, method)(url, data)
            self.organization.customer_id = "cus_example"
            self.organization.save(update_fields=["customer_id"])
            self_billed = getattr(self.client, method)(url, data)

        assert (allowed.status_code, refused.status_code, self_billed.status_code) == (
            allowed_status,
            status.HTTP_403_FORBIDDEN,
            allowed_status,
        )
        assert refused.json()["detail"] == (
            f"Billing for this organization is managed by {named_as}. "
            f"Contact {named_as} to change your plan or payment details."
        )
        assert mock_manager_method.call_count == 2

    @parameterized.expand(
        [
            ("paying_partner", True, None, {"partner_name": "Example Partner"}),
            ("paying_partner_org_with_own_stripe_customer", True, "cus_example", None),
            ("non_paying_partner", False, None, None),
            ("partner_without_application", None, None, None),
        ]
    )
    @patch("ee.billing.billing_manager.BillingManager.get_billing")
    def test_billing_overview_names_the_paying_partner(
        self,
        _name: str,
        pays_for_customers: bool | None,
        customer_id: str | None,
        expected: dict[str, str] | None,
        mock_get_billing: MagicMock,
    ) -> None:
        mock_get_billing.return_value = {"available_product_features": [], "products": []}
        self._provision(pays_for_customers)
        self.organization.customer_id = customer_id
        self.organization.save(update_fields=["customer_id"])

        response = self.client.get("/api/billing")

        assert response.status_code == status.HTTP_200_OK
        assert response.json()["billing_managed_by_partner"] == expected


def _billing_action_permission_classes() -> dict[str, Sequence[object]]:
    viewset_default = BillingViewset.permission_classes
    declared_permissions: dict[str, Sequence[object]] = {
        action.__name__: getattr(action, "kwargs", {}).get("permission_classes", viewset_default)
        for action in BillingViewset.get_extra_actions()
    }
    for standard_action in ("list", "create", "retrieve", "update", "partial_update", "destroy"):
        if hasattr(BillingViewset, standard_action):
            declared_permissions[standard_action] = viewset_default
    return declared_permissions


class TestPartnerBillingLockCoverage(SimpleTestCase):
    READ_ONLY_ACTIONS = {
        "list",
        "period",
        "get_invoices",
        "credits_overview",
        "coupons_overview",
        "usage",
        "usage_team_options",
        "spend",
        "usage_export",
        "spend_export",
    }
    UNLOCKED_WRITE_ACTIONS = {
        "deactivate",
        "cancel_trial",
        "patch",
        "license",
        "authorize_status",
        "apply_startup_program",
        "claim_coupon",
    }

    def test_every_billing_action_is_partner_locked_or_explicitly_exempt(self) -> None:
        declared_permissions = _billing_action_permission_classes()
        unlocked = {name for name, classes in declared_permissions.items() if BillingNotManagedByPartner not in classes}

        assert unlocked == self.READ_ONLY_ACTIONS | self.UNLOCKED_WRITE_ACTIONS


class TestBillingAccessCoverage(SimpleTestCase):
    MEMBER_READ_ACTIONS = {"list", "period", "get_invoices", "credits_overview", "coupons_overview"}
    USAGE_SPEND_READ_ACTIONS = {"usage", "usage_team_options", "spend", "usage_export", "spend_export"}
    CHECKS_ACCESS_IN_METHOD_ACTIONS = {"apply_startup_program"}

    def test_every_billing_action_requires_billing_access_or_is_explicitly_exempt(self) -> None:
        without_access = {
            name for name, classes in _billing_action_permission_classes().items() if HasBillingAccess not in classes
        }
        exempt = self.MEMBER_READ_ACTIONS | self.USAGE_SPEND_READ_ACTIONS | self.CHECKS_ACCESS_IN_METHOD_ACTIONS

        assert without_access <= exempt, f"Add HasBillingAccess to {sorted(without_access - exempt)} or list as exempt"
        assert exempt <= without_access, f"Remove {sorted(exempt - without_access)} from the exempt sets"


class TestBillingUsageRequestSerializer(SimpleTestCase):
    def test_valid_dates(self):
        serializer = BillingUsageRequestSerializer(data={"start_date": "2025-01-01", "end_date": "2025-01-31"})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertEqual(serializer.validated_data["start_date"], "2025-01-01")
        self.assertEqual(serializer.validated_data["end_date"], "2025-01-31")

    @time_machine.travel("2025-02-15", tick=False)
    def test_relative_dates(self):
        serializer = BillingUsageRequestSerializer(data={"start_date": "-7d", "end_date": "-1d"})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertEqual(serializer.validated_data["start_date"], "2025-02-08")
        self.assertEqual(serializer.validated_data["end_date"], "2025-02-14")

    @time_machine.travel("2025-02-15", tick=False)
    def test_start_date_all_defaults_end_date_to_today(self):
        serializer = BillingUsageRequestSerializer(data={"start_date": "all"})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertEqual(serializer.validated_data["start_date"], "2020-01-01")
        self.assertEqual(serializer.validated_data["end_date"], "2025-02-15")

    @time_machine.travel("2025-02-15", tick=False)
    def test_start_date_without_end_date_defaults_end_date_to_today(self):
        serializer = BillingUsageRequestSerializer(data={"start_date": "2025-01-01"})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertEqual(serializer.validated_data["start_date"], "2025-01-01")
        self.assertEqual(serializer.validated_data["end_date"], "2025-02-15")

    def test_passthrough_fields(self):
        data = {
            "usage_types": '["event_count_in_period","recording_count_in_period"]',
            "team_ids": "[1,2,3]",
            "breakdowns": '["type","team"]',
            "interval": "week",
        }
        serializer = BillingUsageRequestSerializer(data=data)
        self.assertTrue(serializer.is_valid(), serializer.errors)
        for key, value in data.items():
            self.assertEqual(serializer.validated_data[key], value)

    def test_usage_type_options_match_usage_type_literal(self):
        self.assertEqual(
            {option["value"] for option in USAGE_TYPE_OPTIONS},
            set(get_args(UsageType)),
        )

    @parameterized.expand(
        [
            ("usage_types_comma_separated", "usage_types", "event_count_in_period, recording_count_in_period"),
            ("usage_types_json_non_array", "usage_types", '"event_count_in_period"'),
            ("team_ids_comma_separated", "team_ids", "1,2,3"),
            ("team_ids_json_string_values", "team_ids", '["1","2"]'),
            ("breakdowns_comma_separated", "breakdowns", "type,team"),
            ("breakdowns_unknown_values", "breakdowns", '["type","project"]'),
        ]
    )
    def test_rejects_invalid_json_array_fields(self, _case_name: str, field_name: str, value: str):
        serializer = BillingUsageRequestSerializer(data={field_name: value})
        self.assertFalse(serializer.is_valid())
        self.assertIn(field_name, serializer.errors)

    @parameterized.expand(
        [
            ("none", "[]"),
            ("by_product", '["type"]'),
            ("by_product_and_project", '["type","team"]'),
            # Spend adds across products, so this one is a number that means something and the
            # spend read serves it. The usage series has its own serializer that refuses it.
            ("by_project_alone", '["team"]'),
        ]
    )
    def test_accepts_every_breakdown_the_spend_read_serves(self, _case_name: str, value: str):
        serializer = BillingUsageRequestSerializer(data={"breakdowns": value})
        self.assertTrue(serializer.is_valid(), serializer.errors)

    @parameterized.expand(
        [
            ("missing", {}),
            ("empty", {"start_date": "", "end_date": ""}),
            ("null", {"start_date": None, "end_date": None}),
            ("empty_start", {"start_date": ""}),
            ("null_end", {"end_date": None}),
        ]
    )
    @time_machine.travel("2025-02-15T00:30:00+14:00", tick=False)
    def test_missing_empty_and_null_dates_default_to_last_30_complete_utc_days(
        self, _case_name: str, data: dict[str, str | None]
    ) -> None:
        serializer = BillingUsageRequestSerializer(data=data)
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertEqual(serializer.validated_data["start_date"], "2025-01-15")
        self.assertEqual(serializer.validated_data["end_date"], "2025-02-13")

    @time_machine.travel("2025-02-15", tick=False)
    def test_end_date_without_start_date_is_preserved(self) -> None:
        serializer = BillingUsageRequestSerializer(data={"end_date": "2025-02-14"})
        self.assertTrue(serializer.is_valid(), serializer.errors)
        self.assertNotIn("start_date", serializer.validated_data)
        self.assertEqual(serializer.validated_data["end_date"], "2025-02-14")


class TestBillingUpstreamValidationErrors(SimpleTestCase):
    @parameterized.expand(
        [
            ("start_date", "required", "This field is required."),
            ("usage_types", "invalid_input", "Invalid value. Check this parameter's format and allowed values."),
            ("interval", "invalid_choice", "Select a valid option for this parameter."),
        ]
    )
    def test_preserves_safe_field_and_code(self, field: str, code: str, detail: str) -> None:
        error = Exception(
            "Billing service returned bad status code: 400",
            "body:",
            {
                "type": "validation_error",
                "code": code,
                "attr": field,
                "detail": "Rejected [email protected]",
                "extra": {"private": "upstream context"},
            },
        )

        with self.assertRaises(ValidationError) as raised:
            BillingViewset._raise_billing_error(error, Organization(id=uuid4()))

        self.assertEqual(raised.exception.detail, {field: [detail]})
        self.assertEqual(raised.exception.get_codes(), {field: [code]})

    @parameterized.expand(
        [
            ("unknown_field", "validation_error", "private_field", "invalid_input"),
            ("unknown_code", "validation_error", "start_date", "private_code"),
            ("wrong_type", "server_error", "start_date", "required"),
            ("missing_field", "validation_error", None, "invalid_input"),
            ("malformed_field", "validation_error", ["start_date"], "required"),
            ("malformed_code", "validation_error", "start_date", ["required"]),
        ]
    )
    def test_masks_unrecognized_validation_errors(
        self, _name: str, error_type: str, field: object, code: object
    ) -> None:
        error = Exception(
            "Billing service returned bad status code: 400",
            "body:",
            {"type": error_type, "code": code, "attr": field, "detail": "Private upstream context"},
        )

        with self.assertRaises(BillingQueryRejected) as raised:
            BillingViewset._raise_billing_error(error, Organization(id=uuid4()))

        self.assertEqual(
            str(raised.exception.detail), "Billing could not answer this request. Adjust the filters and try again."
        )


class TestBillingUsageAndSpendAPI(APILicensedTest):
    MOCK_USAGE_DATA = {"results": [{"data": [1, 2], "count": 2}]}
    MOCK_SPEND_DATA = {"results": [{"spend": 100.0, "usage": 10000}]}

    def setUp(self):
        super().setUp()
        # Ensure the user is an admin for these tests by default
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.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 _oauth_token_headers(self, scopes: list[str], scoped_teams: list[int] | None = None) -> dict[str, str]:
        oauth_application = OAuthApplication.objects.create(
            name="Billing MCP Test OAuth App",
            client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
            authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
            redirect_uris="https://example.com/callback",
            algorithm="RS256",
            organization=self.organization,
            user=self.user,
        )
        token = f"pha_billing_mcp_test_{uuid4().hex}"
        OAuthAccessToken.objects.create(
            user=self.user,
            application=oauth_application,
            token=token,
            expires=now() + timedelta(hours=1),
            scope=" ".join(scopes),
            scoped_teams=scoped_teams,
        )
        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", "usage_export", "spend_export", "usage_team_options"],
        )
        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",
            ),
        ]
    )
    @patch("ee.billing.grants.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, _mock_feature_enabled
    ):
        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)
        expected_detail = (
            BILLING_ACCESS_DENIED_MESSAGE if action_name == "list" else HasBillingUsageSpendReadAccess.message
        )
        self.assertEqual(response.json()["detail"], expected_detail)
        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

        response = self.client.get(f"/api/billing/usage/?start_date=2025-01-01&team_ids=[{self.team.pk}]")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json(), self.MOCK_USAGE_DATA)
        mock_get_usage_data.assert_called_once()
        call_args = mock_get_usage_data.call_args[0]
        self.assertEqual(call_args[0], self.organization)  # First arg is organization
        passed_params = call_args[1]  # Second arg is params dict
        self.assertEqual(passed_params["start_date"], "2025-01-01")
        self.assertEqual(passed_params["team_ids"], f"[{str(self.team.pk)}]")
        # No teams_map: names are put into the response on the way out.
        self.assertNotIn("teams_map", passed_params)

    @parameterized.expand([("usage",), ("spend",)])
    @time_machine.travel("2025-02-15T00:30:00+14:00", tick=False)
    def test_usage_and_spend_default_date_range_is_sent_to_billing(self, endpoint: str) -> None:
        manager_method = f"ee.billing.billing_manager.BillingManager.get_{endpoint}_data"
        mock_data = self.MOCK_USAGE_DATA if endpoint == "usage" else self.MOCK_SPEND_DATA

        with patch(manager_method, return_value=mock_data) as mock_fetch:
            response = self.client.get(f"/api/billing/{endpoint}/")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        mock_fetch.assert_called_once()
        passed_params = mock_fetch.call_args[0][1]
        self.assertEqual(passed_params["start_date"], "2025-01-15")
        self.assertEqual(passed_params["end_date"], "2025-02-13")

    @staticmethod
    def _billing_refusal(upstream_status: int, body: object) -> Exception:
        # The shape handle_billing_service_error raises: the status in the message, the parsed body third.
        return Exception(f"Billing service returned bad status code: {upstream_status}", "body:", body)

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    def test_a_guidance_code_from_billing_becomes_the_pages_own_sentence(self, mock_get_usage_data):
        mock_get_usage_data.side_effect = self._billing_refusal(
            400, {"type": "server_error", "code": "usage_breakdown_too_large", "detail": "Ask for it a page at a time."}
        )

        response = self.client.get("/api/billing/usage/?start_date=2025-01-01")

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.json()["code"], "usage_breakdown_too_large")
        self.assertEqual(response.json()["detail"], BillingQueryTooLarge.default_detail)
        self.assertNotIn("page at a time", response.content.decode())

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    def test_an_unknown_refusal_from_billing_is_a_400_without_its_body(self, mock_get_usage_data):
        mock_get_usage_data.side_effect = self._billing_refusal(
            400, {"detail": "KeyError: 'org_usage_summary' at managers.py:512", "code": "internal"}
        )

        response = self.client.get("/api/billing/usage/?start_date=2025-01-01")

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.json()["code"], "billing_query_rejected")
        self.assertEqual(response.json()["detail"], BillingQueryRejected.default_detail)
        self.assertNotIn("managers.py", response.content.decode())

    @parameterized.expand([("usage",), ("spend",)])
    def test_billing_validation_errors_use_standard_response(self, endpoint: str) -> None:
        with patch(f"ee.billing.billing_manager.BillingManager.get_{endpoint}_data") as mock_fetch:
            mock_fetch.side_effect = self._billing_refusal(
                400,
                {
                    "type": "validation_error",
                    "code": "required",
                    "attr": "start_date",
                    "detail": "Rejected [email protected]",
                    "extra": {"private": "upstream context"},
                },
            )

            response = self.client.get(f"/api/billing/{endpoint}/")

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(
            response.json(),
            {"type": "validation_error", "code": "required", "attr": "start_date", "detail": "This field is required."},
        )

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    def test_a_failure_inside_billing_is_a_502_without_its_body(self, mock_get_usage_data):
        mock_get_usage_data.side_effect = self._billing_refusal(500, "<html>Internal Server Error: stack trace</html>")

        response = self.client.get("/api/billing/usage/?start_date=2025-01-01")

        self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY)
        self.assertEqual(response.json()["code"], "billing_service_error")
        self.assertNotIn("stack trace", response.content.decode())

    @patch("ee.billing.billing_manager.BillingManager.get_usage_csv")
    def test_an_export_refused_by_billing_is_guidance_not_a_500(self, mock_get_usage_csv):
        mock_get_usage_csv.side_effect = self._billing_refusal(
            400, {"code": "usage_date_range_too_long", "detail": "The date range covers 400 days."}
        )

        response = self.client.get("/api/billing/usage/export/?start_date=2025-01-01&end_date=2026-02-04")

        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.json()["code"], "usage_date_range_too_long")
        self.assertEqual(response.json()["detail"], BillingDateRangeTooLong.default_detail)

    @patch("ee.billing.billing_manager.BillingManager.get_spend_data")
    def test_get_spend_success(self, mock_get_spend_data):
        mock_get_spend_data.return_value = self.MOCK_SPEND_DATA

        response = self.client.get(
            "/api/billing/spend/",
            {
                "start_date": "2025-01-01",
                "usage_types": '["event_count_in_period"]',
                "team_ids": f"[{self.team.pk}]",
            },
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json(), self.MOCK_SPEND_DATA)
        mock_get_spend_data.assert_called_once()
        call_args = mock_get_spend_data.call_args[0]
        self.assertEqual(call_args[0], self.organization)
        passed_params = call_args[1]
        self.assertEqual(passed_params["start_date"], "2025-01-01")
        self.assertEqual(json.loads(passed_params["usage_types"]), ["event_count_in_period"])
        self.assertEqual(passed_params["team_ids"], f"[{str(self.team.pk)}]")
        # No teams_map: names are put into the response on the way out.
        self.assertNotIn("teams_map", passed_params)

    @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_usage_data")
    def test_get_usage_allows_project_scoped_billing_read_personal_api_key_for_org_billing(self, mock_get_usage_data):
        mock_get_usage_data.return_value = self.MOCK_USAGE_DATA
        other_team = Team.objects.create(organization=self.organization, name="Other project")
        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", "team_ids": f"[{other_team.pk}]"},
            HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        passed_params = mock_get_usage_data.call_args[0][1]
        self.assertEqual(passed_params["team_ids"], f"[{other_team.pk}]")
        self.assertNotIn("teams_map", passed_params)

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    def test_get_usage_allows_project_scoped_billing_read_oauth_token_for_org_billing(self, mock_get_usage_data):
        mock_get_usage_data.return_value = self.MOCK_USAGE_DATA
        other_team = Team.objects.create(organization=self.organization, name="Other project")
        headers = self._oauth_token_headers(["billing:read"], scoped_teams=[self.team.pk])

        response = self.client.get(
            "/api/billing/usage/",
            {"start_date": "2025-01-01", "team_ids": f"[{other_team.pk}]"},
            HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(mock_get_usage_data.call_args[0][1]["team_ids"], f"[{other_team.pk}]")

    @parameterized.expand(
        [
            ("list", "/api/billing/", "ee.billing.billing_manager.BillingManager.get_billing"),
            ("usage", "/api/billing/usage/", "ee.billing.billing_manager.BillingManager.get_usage_data"),
        ]
    )
    def test_a_billing_read_without_a_current_project_is_denied_rather_than_unauthenticated(
        self, _name: str, path: str, billing_call: str
    ):
        headers = self._oauth_token_headers(["billing:read"])
        self.user.current_team = None
        self.user.save()

        with patch(billing_call) as mock_billing_call:
            response = self.client.get(
                path, {"start_date": "2025-01-01"}, HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"]
            )

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(response.json()["code"], "permission_denied")
        self.assertIn("your account has none", response.json()["detail"])
        mock_billing_call.assert_not_called()

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    def test_get_usage_rejects_other_org_team_ids_for_project_scoped_billing_read(self, mock_get_usage_data):
        other_org = self.create_organization_with_features([])
        other_team = self.create_team_with_organization(other_org)
        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", "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_spend_data")
    def test_get_spend_rejects_other_org_team_ids_for_project_scoped_billing_read(self, mock_get_spend_data):
        other_org = self.create_organization_with_features([])
        other_team = self.create_team_with_organization(other_org)
        headers = self._personal_api_key_headers(["billing:read"], scoped_teams=[self.team.pk])

        response = self.client.get(
            "/api/billing/spend/",
            {"start_date": "2025-01-01", "team_ids": f"[{other_team.pk}]"},
            HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],
        )

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        mock_get_spend_data.assert_not_called()

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    def test_get_usage_reads_a_project_the_organization_has_since_deleted(self, mock_get_usage_data):
        mock_get_usage_data.return_value = self.MOCK_USAGE_DATA
        deleted_team = Team.objects.create(organization=self.organization, name="Retired project")
        deleted_team_id = deleted_team.pk
        deleted_team.delete()
        headers = self._personal_api_key_headers(["billing:read"])

        response = self.client.get(
            "/api/billing/usage/",
            {"start_date": "2025-01-01", "team_ids": f"[{deleted_team_id}]"},
            HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(mock_get_usage_data.call_args[0][1]["team_ids"], f"[{deleted_team_id}]")

    def test_get_usage_rejects_personal_api_key_without_billing_read_scope(self):
        headers = self._personal_api_key_headers(["project:read"])
        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)

    def test_get_usage_rejects_billing_read_personal_api_key_for_member(self):
        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/usage/",
            {"start_date": "2025-01-01"},
            HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],
        )

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

    @parameterized.expand([("usage", "get_usage_data"), ("spend", "get_spend_data")])
    @patch("ee.billing.grants.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])
        # No teams_map: names are put into the response on the way out.
        self.assertNotIn("teams_map", passed_params)

    @parameterized.expand([("personal",), ("oauth",)])
    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.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]
        # The token is scoped to one project, so the other one must not reach billing at all -
        # not in the filter, and not in a name map either, which is why none is sent.
        self.assertEqual(json.loads(passed_params["team_ids"]), [self.team.pk])
        self.assertNotIn(str(other_team.pk), json.dumps(passed_params))

    @parameterized.expand([("personal",), ("oauth",)])
    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.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)
        self.assertEqual(response.json()["detail"], BILLING_PROJECT_ACCESS_DENIED_MESSAGE)
        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([])
        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")
    @patch("ee.billing.grants.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.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])

        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.billing.grants.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.billing.grants.posthog_feature_flag_enabled", return_value=True)
    def test_owner_only_billing_rejects_admin_usage_access(self, _mock_feature_enabled, mock_get_usage_data):
        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_403_FORBIDDEN)
        mock_get_usage_data.assert_not_called()

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=False)
    def test_admin_usage_access_allowed_when_owner_only_billing_is_off(self, mock_feature_enabled, mock_get_usage_data):
        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()
        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.billing.grants.posthog_feature_flag_enabled", return_value=None)
    def test_owner_only_billing_rejects_admin_usage_access_when_flag_is_unknown(
        self, _mock_feature_enabled, mock_get_usage_data
    ):
        response = self.client.get("/api/billing/usage/", {"start_date": "2025-01-01"})

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        mock_get_usage_data.assert_not_called()

    @patch("ee.billing.grants.capture_exception")
    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.posthog_feature_flag_enabled", side_effect=Exception("flag lookup failed"))
    def test_owner_only_billing_rejects_admin_usage_access_when_flag_check_raises(
        self, _mock_feature_enabled, mock_get_usage_data, mock_capture_exception
    ):
        response = self.client.get("/api/billing/usage/", {"start_date": "2025-01-01"})

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        mock_get_usage_data.assert_not_called()
        mock_capture_exception.assert_called_once()

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.posthog_feature_flag_enabled")
    def test_owner_only_billing_rejects_admin_usage_access_without_distinct_id(
        self, mock_feature_enabled, mock_get_usage_data
    ):
        self.user.distinct_id = ""
        self.user.save()

        response = self.client.get("/api/billing/usage/", {"start_date": "2025-01-01"})

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        mock_get_usage_data.assert_not_called()
        mock_feature_enabled.assert_not_called()

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=True)
    def test_owner_only_billing_allows_owner_usage_access(self, _mock_feature_enabled, mock_get_usage_data):
        self.organization_membership.level = OrganizationMembership.Level.OWNER
        self.organization_membership.save()
        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()

    @patch("ee.billing.billing_manager.BillingManager.update_billing")
    @patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=True)
    def test_owner_only_billing_rejects_admin_limit_update(self, _mock_feature_enabled, mock_update_billing):
        response = self.client.patch(
            "/api/billing//",
            data={"custom_limits_usd": {"events": 10}},
            content_type="application/json",
        )

        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        mock_update_billing.assert_not_called()

    def test_mutating_action_rejects_wildcard_personal_api_key(self):
        headers = self._personal_api_key_headers(["*"])
        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)
        self.assertIn("personal API key", response.json()["detail"])

    def test_get_usage_permission_denied_for_member(self):
        self.organization_membership.level = OrganizationMembership.Level.MEMBER
        self.organization_membership.save()
        response = self.client.get("/api/billing/usage/")
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(response.json()["detail"], HasBillingUsageSpendReadAccess.message)

    def test_get_spend_permission_denied_for_member(self):
        self.organization_membership.level = OrganizationMembership.Level.MEMBER
        self.organization_membership.save()
        response = self.client.get("/api/billing/spend/")
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        self.assertEqual(response.json()["detail"], HasBillingUsageSpendReadAccess.message)

    @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.billing.grants.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.billing.grants.capture_exception")
    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.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.billing.grants.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):
        mock_get_teams_map.return_value = {}
        mock_get_usage_data.return_value = self.MOCK_USAGE_DATA

        response = self.client.get(f"/api/billing/usage/?start_date=2025-01-01")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json(), self.MOCK_USAGE_DATA)
        mock_get_usage_data.assert_called_once()
        call_args = mock_get_usage_data.call_args[0]
        passed_params = call_args[1]
        self.assertNotIn("teams_map", passed_params)
        mock_get_teams_map.assert_called_once()

    @patch("ee.billing.billing_manager.BillingManager.get_spend_data")
    @patch("ee.api.billing.BillingViewset._get_teams_map")
    def test_get_spend_empty_teams_map_graceful_handling(self, mock_get_teams_map, mock_get_spend_data):
        mock_get_teams_map.return_value = {}
        mock_get_spend_data.return_value = self.MOCK_SPEND_DATA

        response = self.client.get(f"/api/billing/spend/?start_date=2025-01-01")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json(), self.MOCK_SPEND_DATA)
        mock_get_spend_data.assert_called_once()
        call_args = mock_get_spend_data.call_args[0]
        passed_params = call_args[1]
        self.assertNotIn("teams_map", passed_params)
        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.billing.grants.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])
        # No teams_map: names are put into the response on the way out.
        self.assertNotIn("teams_map", passed_params)

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.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])
        # No teams_map: names are put into the response on the way out.
        self.assertNotIn("teams_map", passed_params)

    @parameterized.expand([("usage",), ("spend",)])
    @patch("ee.billing.billing_manager.BillingManager.get_spend_data")
    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.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)
        self.assertEqual(response.json()["detail"], BILLING_PROJECT_ACCESS_DENIED_MESSAGE)
        # 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.billing.grants.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.billing.grants.posthog_feature_flag_enabled")
    def test_member_chart_response_options_are_scoped(self, mock_flag_eval: MagicMock, mock_get_usage_data: MagicMock):
        """Billing still lists every project's id on the chart response for older callers; a
        member gets only theirs there too."""
        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, 999999]}
        response = self.client.get("/api/billing/usage/", {"start_date": "2026-08-01", "end_date": "2026-08-02"})
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json()["team_id_options"], [self.team.pk])

    @patch("ee.billing.billing_manager.BillingManager.get_usage_team_options")
    @patch("ee.billing.billing_manager.BillingManager.get_usage_csv")
    def test_a_billing_read_token_reaches_the_export_and_the_options(self, mock_get_usage_csv, mock_get_team_options):
        """The read actions are on the viewset's scope allowlist, so a personal API key with
        billing:read is not turned away before the view runs."""
        upstream = MagicMock()
        upstream.iter_content.return_value = iter([b"Product,Project,Project ID,Total\n"])
        upstream.headers = {"Content-Type": "text/csv"}
        mock_get_usage_csv.return_value = upstream
        mock_get_team_options.return_value = {"team_id_options": [self.team.pk]}
        headers = self._personal_api_key_headers(["billing:read"])

        export = self.client.get(
            "/api/billing/usage/export/?start_date=2026-08-01&end_date=2026-08-02",
            HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"],
        )
        options = self.client.get("/api/billing/usage/team_options/", HTTP_AUTHORIZATION=headers["HTTP_AUTHORIZATION"])

        self.assertEqual(export.status_code, status.HTTP_200_OK)
        self.assertEqual(options.status_code, status.HTTP_200_OK)
        self.assertEqual(options.json(), {"team_id_options": [self.team.pk]})

    @parameterized.expand([("usage",), ("spend",)])
    def test_a_paged_response_keeps_next_and_total_count(self, endpoint: str):
        with patch(f"ee.billing.billing_manager.BillingManager.get_{endpoint}_data") as mock_fetch:
            mock_fetch.return_value = {"results": [], "next": "abc", "total_count": 48000}
            response = self.client.get(f"/api/billing/{endpoint}/?start_date=2026-08-01&page_size=100")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json()["next"], "abc")
        self.assertEqual(response.json()["total_count"], 48000)

    @patch("ee.billing.billing_manager.BillingManager.get_usage_csv")
    @patch("ee.billing.grants.posthog_feature_flag_enabled")
    def test_an_export_carries_only_the_projects_the_member_may_export(
        self, mock_flag_eval: MagicMock, mock_get_usage_csv: MagicMock
    ):
        """Export access is set per project. A member who may export one visible project but not
        another gets a file of the first alone, whatever project they are working in."""
        self._setup_member_with_private_team()
        mock_flag_eval.side_effect = self._member_access_flags
        restricted = Team.objects.create(organization=self.organization, name="Export denied")
        AccessControl.objects.create(
            team=restricted,
            resource="export",
            resource_id=None,
            access_level="none",
            organization_member=None,
            role=None,
        )
        upstream = MagicMock()
        upstream.iter_content.return_value = iter([b"Product,Project,Project ID,Total\n"])
        upstream.headers = {"Content-Type": "text/csv"}
        mock_get_usage_csv.return_value = upstream

        response = self.client.get("/api/billing/usage/export/?start_date=2026-08-01&end_date=2026-08-02")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        passed = json.loads(mock_get_usage_csv.call_args.args[1]["team_ids"])
        self.assertEqual(passed, [self.team.pk])

    @patch("ee.billing.billing_manager.BillingManager.get_usage_csv")
    @patch("ee.billing.grants.posthog_feature_flag_enabled")
    def test_an_export_is_refused_when_the_member_may_export_none_of_the_projects(
        self, mock_flag_eval: MagicMock, mock_get_usage_csv: MagicMock
    ):
        self._setup_member_with_private_team()
        mock_flag_eval.side_effect = self._member_access_flags
        AccessControl.objects.create(
            team=self.team,
            resource="export",
            resource_id=None,
            access_level="none",
            organization_member=None,
            role=None,
        )

        for path in ("/api/billing/usage/export/", "/api/billing/spend/export/"):
            response = self.client.get(f"{path}?start_date=2026-08-01&end_date=2026-08-02")
            self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, path)
        mock_get_usage_csv.assert_not_called()

    @patch("ee.billing.billing_manager.BillingManager.get_usage_team_options")
    @patch("ee.billing.grants.posthog_feature_flag_enabled")
    def test_member_team_options_are_scoped(self, mock_flag_eval: MagicMock, mock_get_team_options: MagicMock):
        """The project filter's options load on their own, scoped like the charts: a member sees
        only their projects, not a private one and not a deleted one."""
        private_team = self._setup_member_with_private_team()
        mock_flag_eval.side_effect = self._member_access_flags
        deleted_team_id = 999999
        mock_get_team_options.return_value = {"team_id_options": [self.team.pk, private_team.pk, deleted_team_id]}
        response = self.client.get("/api/billing/usage/team_options/")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json(), {"team_id_options": [self.team.pk]})

    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.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
    ):
        self._setup_member_with_private_team()
        mock_flag_eval.side_effect = self._member_access_flags
        mock_get_usage_data.return_value = {"results": []}

        # 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])
        # No teams_map: names are put into the response on the way out.
        self.assertNotIn("teams_map", passed_params)

    @parameterized.expand([("not-json",), ('["a"]',)])
    @patch("ee.billing.billing_manager.BillingManager.get_usage_data")
    @patch("ee.billing.grants.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_a_refusal_billing_gives_no_guidance_for_is_a_400_in_the_pages_words(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"], "billing_query_rejected")
        self.assertEqual(data["detail"], BillingQueryRejected.default_detail)
        self.assertNotIn("start_date is invalid", response.content.decode())


def _billing_rate_limited_response() -> Response:
    response = Response()
    response.status_code = status.HTTP_429_TOO_MANY_REQUESTS
    response.headers["Retry-After"] = "30"
    response._content = json.dumps({"detail": "Request was throttled. Expected available in 30 seconds."}).encode()
    response.raw = MagicMock()
    return response


@patch(
    "ee.billing.billing_manager.http_session.get", side_effect=lambda *args, **kwargs: _billing_rate_limited_response()
)
class TestBillingRateLimitedAPI(APILicensedTest):
    def setUp(self):
        super().setUp()
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()

    def _assert_rate_limited(self, response: Any) -> None:
        self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
        self.assertEqual(response.json()["code"], "billing_rate_limited")
        self.assertEqual(response.headers["Retry-After"], "30")

    def test_billing_list_returns_429(self, _mock_get):
        self._assert_rate_limited(self.client.get("/api/billing/"))

    def test_billing_usage_returns_429(self, _mock_get):
        self._assert_rate_limited(self.client.get("/api/billing/usage/?start_date=2025-01-01"))

    def test_billing_invoices_returns_429(self, _mock_get):
        self._assert_rate_limited(self.client.get("/api/billing/get_invoices"))

    def test_billing_429_is_not_captured(self, _mock_get):
        with patch("posthog.exceptions.capture_exception", return_value=None) as mock_capture_exception:
            response = self.client.get("/api/billing/")

        self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
        mock_capture_exception.assert_not_called()


class TestBillingPeriodAPI(APILicensedTest):
    def test_member_can_read_synced_organization_period(self):
        self.organization_membership.level = OrganizationMembership.Level.MEMBER
        self.organization_membership.save()
        self.organization.usage = {
            "period": ["2026-07-09T00:00:00Z", "2026-08-09T00:00:00Z"],
        }
        self.organization.save()

        response = self.client.get("/api/billing/period/")

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(
            response.json(),
            {
                "current_period_start": "2026-07-09T00:00:00Z",
                "current_period_end": "2026-08-09T00:00:00Z",
            },
        )

    def test_gateway_scoped_personal_api_key_can_read_team_period(self):
        self.organization.usage = {
            "period": ["2026-07-09T00:00:00Z", "2026-08-09T00:00:00Z"],
        }
        self.organization.save()
        self.client.logout()
        raw_key = generate_random_token_personal()
        PersonalAPIKey.objects.create(
            label="billing-period-test",
            user=self.user,
            secure_value=hash_key_value(raw_key),
            scopes=["llm_gateway:read"],
            scoped_teams=[self.team.pk],
        )

        response = self.client.get(
            f"/api/billing/period/?team_id={self.team.pk}",
            headers={"authorization": f"Bearer {raw_key}"},
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.json()["current_period_end"], "2026-08-09T00:00:00Z")


class TestBillingPermissionDeniedForMembers(APILicensedTest):
    """Verify that billing-modifying actions reject member-level users with 403."""

    def setUp(self):
        super().setUp()
        self.organization_membership.level = OrganizationMembership.Level.MEMBER
        self.organization_membership.save()

    @parameterized.expand(
        [
            ("activate", "post", "/api/billing/activate", {"products": "all_products:"}, BILLING_ACCESS_DENIED_MESSAGE),
            ("deactivate", "post", "/api/billing/deactivate", {"products": "product_1"}, BILLING_ACCESS_DENIED_MESSAGE),
            ("patch", "patch", "/api/billing//", {"custom_limits_usd": {}}, BILLING_ACCESS_DENIED_MESSAGE),
            (
                "subscription_switch_plan",
                "post",
                "/api/billing/subscription/switch-plan",
                {"plan": "test"},
                BILLING_ACCESS_DENIED_MESSAGE,
            ),
            ("portal", "get", "/api/billing/portal", None, BILLING_ACCESS_DENIED_MESSAGE),
            (
                "activate_trial",
                "post",
                "/api/billing/trials/activate",
                {"product": "test"},
                BILLING_ACCESS_DENIED_MESSAGE,
            ),
            ("cancel_trial", "post", "/api/billing/trials/cancel", {"product": "test"}, BILLING_ACCESS_DENIED_MESSAGE),
            (
                "purchase_credits",
                "post",
                "/api/billing/credits/purchase",
                {"amount": 100},
                BILLING_ACCESS_DENIED_MESSAGE,
            ),
            ("claim_coupon", "post", "/api/billing/coupons/claim", {"code": "TEST"}, BILLING_ACCESS_DENIED_MESSAGE),
            ("startup_apply", "post", "/api/billing/startups/apply", "USE_ORG_ID", None),
        ]
    )
    def test_permission_denied(self, _name, method, url, data, expected_detail):
        if data == "USE_ORG_ID":
            data = {"organization_id": str(self.organization.id)}
        if _name == "activate":
            data = {**data, "organization_id": str(self.organization.id)}
        client_method = getattr(self.client, method)
        if data is not None:
            kwargs = {"data": data}
            if method == "patch":
                kwargs["content_type"] = "application/json"
            response = client_method(url, **kwargs)
        else:
            response = client_method(url)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        if expected_detail:
            self.assertEqual(response.json()["detail"], expected_detail)

    @patch("ee.billing.billing_manager.http_session.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 = 200
        mock_request.return_value.json.return_value = create_billing_response(
            customer=create_billing_customer(),
        )

        response = self.client.get("/api/billing")
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_get_invoices_still_accessible(self):
        response = self.client.get("/api/billing/get_invoices")
        self.assertIn(
            response.status_code, [status.HTTP_200_OK, status.HTTP_301_MOVED_PERMANENTLY, status.HTTP_302_FOUND]
        )

    def test_credits_overview_still_accessible(self):
        response = self.client.get("/api/billing/credits/overview")
        self.assertIn(
            response.status_code, [status.HTTP_200_OK, status.HTTP_301_MOVED_PERMANENTLY, status.HTTP_302_FOUND]
        )

    def test_coupons_overview_still_accessible(self):
        response = self.client.get("/api/billing/coupons/overview")
        self.assertIn(
            response.status_code, [status.HTTP_200_OK, status.HTTP_301_MOVED_PERMANENTLY, status.HTTP_302_FOUND]
        )


class TestResolveTeamLabels(SimpleTestCase):
    """Project names are put into labels on the way out, not sent in with the request.

    Billing keys usage by project id. An id-to-name map on every request would be about 16KB
    of query string for an organization with several hundred projects, built from data PostHog
    already holds. Resolving from the response sends none of it and leaves the response shape
    identical, which the MCP tools rely on too.
    """

    def test_names_replace_ids_in_a_product_and_project_breakdown(self):
        results = [
            {"label": "134::Events", "breakdown_type": "multiple", "breakdown_value": ["event_count_in_period", "134"]}
        ]

        _resolve_team_labels(results, {134: "Payments API"})

        self.assertEqual(results[0]["label"], "Payments API::Events")

    def test_names_replace_ids_in_a_project_only_breakdown(self):
        results = [{"label": "134", "breakdown_type": "team", "breakdown_value": "134"}]

        _resolve_team_labels(results, {134: "Payments API"})

        self.assertEqual(results[0]["label"], "Payments API")

    def test_the_folded_series_keeps_the_label_billing_gave_it(self):
        results = [
            {
                "label": "All other projects (380)::Events",
                "breakdown_type": "multiple",
                "breakdown_value": ["event_count_in_period", "__other__"],
            }
        ]

        _resolve_team_labels(results, {134: "Payments API"})

        self.assertEqual(results[0]["label"], "All other projects (380)::Events")

    def test_a_project_with_no_name_keeps_its_id(self):
        """A deleted project's id has no name, so the label is left as billing produced it."""
        results = [
            {"label": "999::Events", "breakdown_type": "multiple", "breakdown_value": ["event_count_in_period", "999"]}
        ]

        _resolve_team_labels(results, {134: "Payments API"})

        self.assertEqual(results[0]["label"], "999::Events")

    def test_a_product_only_breakdown_is_untouched(self):
        results = [{"label": "Events", "breakdown_type": "type", "breakdown_value": "event_count_in_period"}]

        _resolve_team_labels(results, {134: "Payments API"})

        self.assertEqual(results[0]["label"], "Events")

    def test_the_product_half_of_a_label_is_left_to_billing(self):
        """Only the project part is replaced; separators inside the product name survive."""
        results = [
            {
                "label": "134::Logs 30-day retention (MB)",
                "breakdown_type": "multiple",
                "breakdown_value": ["logs_retention_30d_mb_in_period", "134"],
            }
        ]

        _resolve_team_labels(results, {134: "Payments API"})

        self.assertEqual(results[0]["label"], "Payments API::Logs 30-day retention (MB)")

    def test_a_malformed_response_does_not_raise(self):
        results = [
            {"label": None},
            "not a dict",
            {"breakdown_type": "multiple", "breakdown_value": ["x"], "label": "a::b"},
        ]

        _resolve_team_labels(results, {134: "Payments API"})
        _resolve_team_labels(None, {134: "Payments API"})


class TestExportGzip(APILicensedTest):
    """Django's gzip middleware compresses an asynchronous body one chunk at a time, each as its
    own gzip member, and browsers stop reading at the end of the first member. The proxy
    compresses the file itself as one stream."""

    def setUp(self):
        super().setUp()
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()

    def test_one_gzip_stream_that_every_chunk_advances(self):
        chunks = [b"Product,Project\n", b"Events,1\n" * 300, b"Events,2\n" * 300]
        out = list(_gzip_stream(iter(chunks)))

        assert gzip.decompress(b"".join(out)) == b"".join(chunks)
        # A sync flush per chunk: the first chunk is on its way before the second is read.
        assert len(out) == len(chunks) + 1 and all(out[:-1])
        # One member, not one per chunk: a second gzip header nowhere after the first.
        assert b"".join(out).count(b"\x1f\x8b\x08") == 1

    @patch("ee.billing.billing_manager.BillingManager.get_usage_csv")
    def test_the_export_leaves_the_proxy_as_one_gzip_stream_with_names_in_place(self, mock_get_usage_csv):
        upstream = MagicMock()
        upstream.headers = {"Content-Type": "text/csv", "Content-Disposition": 'attachment; filename="usage.csv"'}
        upstream.iter_content.return_value = iter(
            [b"Product,Project,Project ID,Total\n", f"Events,{self.team.pk},{self.team.pk},10\n".encode()]
        )
        mock_get_usage_csv.return_value = upstream

        response = self.client.get(
            "/api/billing/usage/export/?start_date=2025-01-01&breakdowns=%5B%22type%22%2C%22team%22%5D",
            HTTP_ACCEPT_ENCODING="gzip, deflate",
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response["Content-Encoding"], "gzip")
        self.assertEqual(response["Content-Disposition"], 'attachment; filename="usage.csv"')
        body = b"".join(response)
        self.assertEqual(body.count(b"\x1f\x8b\x08"), 1, "one gzip member for the whole file")
        self.assertEqual(
            gzip.decompress(body).decode(),
            f"Product,Project,Project ID,Total\nEvents,{self.team.name},{self.team.pk},10\n",
        )
        upstream.close.assert_called_once()


class TestExportStreaming(SimpleTestCase):
    """Django 5 under ASGI consumes a synchronous streaming body in full before it sends a byte,
    so a large export would arrive all at once at the end. The proxy hands Django an
    asynchronous iterator, so the first chunk goes out before the last is read from billing."""

    def test_the_first_chunk_is_sent_before_the_last_is_read(self):
        pulled: list[int] = []

        def chunks():
            for i in range(3):
                pulled.append(i)
                yield f"row {i}\n".encode()

        upstream = MagicMock()
        stream = _stream_chunks(upstream, chunks())

        async def first():
            async for chunk in stream:
                return chunk
            return None

        assert async_to_sync(first)() == b"row 0\n"
        assert pulled == [0], "the rest of the file must not have been read yet"

        async_to_sync(stream.aclose)()
        upstream.close.assert_called_once()

    def test_the_whole_file_arrives_in_order(self):
        upstream = MagicMock()

        async def everything():
            return [chunk async for chunk in _stream_chunks(upstream, iter([b"a", b"b", b"c"]))]

        assert async_to_sync(everything)() == [b"a", b"b", b"c"]
        upstream.close.assert_called_once()


class TestRewriteCsvLabels(SimpleTestCase):
    """Project names go into an exported CSV as it streams past, in place of ids.

    Billing has no names, so its Project column carries the id, and the proxy substitutes the
    name.
    """

    HEADER = b"Product,Project,Project ID,Total\n"

    @staticmethod
    def _run(body: bytes, teams_map: dict, chunk_size: int = 8192) -> str:
        chunks = (body[i : i + chunk_size] for i in range(0, len(body), chunk_size))
        return b"".join(_rewrite_csv_labels(chunks, teams_map)).decode()

    def test_a_name_a_spreadsheet_would_run_as_a_formula_gets_a_leading_quote(self):
        body = self.HEADER + b"Events,134,134,10\n"
        out = self._run(body, {134: '=HYPERLINK("http://x")'})
        self.assertEqual(out.splitlines()[1], 'Events,"\'=HYPERLINK(""http://x"")",134,10')

    def test_puts_names_in_place_of_ids_and_keeps_the_id_column(self):
        """Project names are not unique inside an organization, so the Project ID column is what
        tells two same-named projects apart. Substituting the name must not shift or change it."""
        body = self.HEADER + b"Events,134,134,10\n"

        self.assertEqual(
            self._run(body, {134: "Payments API"}),
            "Product,Project,Project ID,Total\nEvents,Payments API,134,10\n",
        )

    def test_handles_a_project_only_row(self):
        body = self.HEADER + b",134,134,10\n"

        self.assertEqual(
            self._run(body, {134: "Payments API"}), "Product,Project,Project ID,Total\n,Payments API,134,10\n"
        )

    def test_leaves_the_header_and_unknown_ids_alone(self):
        body = self.HEADER + b"Events,999,999,10\n"

        self.assertEqual(self._run(body, {134: "Payments API"}), body.decode())

    def test_leaves_the_folded_row_alone(self):
        body = self.HEADER + b"Events,All other projects (380),,10\n"

        self.assertEqual(self._run(body, {134: "Payments API"}), body.decode())

    def test_leaves_a_row_with_no_project_alone(self):
        body = self.HEADER + b"Events,,,10\n"

        self.assertEqual(self._run(body, {134: "Payments API"}), body.decode())

    def test_quotes_a_name_containing_a_comma(self):
        """Otherwise the substituted name would silently split the row into two columns."""
        body = self.HEADER + b"Events,134,134,10\n"

        self.assertEqual(
            self._run(body, {134: "Payments, EU"}), 'Product,Project,Project ID,Total\nEvents,"Payments, EU",134,10\n'
        )

    def test_survives_a_row_split_across_chunks(self):
        """The transfer chunks by bytes, so a row rarely arrives whole."""
        body = self.HEADER + b"Events,134,134,10\nEvents,135,135,20\n"

        self.assertEqual(
            self._run(body, {134: "Payments API", 135: "Ingest"}, chunk_size=7),
            "Product,Project,Project ID,Total\nEvents,Payments API,134,10\nEvents,Ingest,135,20\n",
        )

    def test_handles_a_file_with_no_trailing_newline(self):
        body = self.HEADER + b"Events,134,134,10"

        self.assertEqual(
            self._run(body, {134: "Payments API"}), "Product,Project,Project ID,Total\nEvents,Payments API,134,10"
        )

    def test_preserves_a_quoted_field_that_already_contains_a_comma(self):
        body = self.HEADER + b'"Logs, ingested",134,134,10\n'

        self.assertEqual(
            self._run(body, {134: "Payments API"}),
            'Product,Project,Project ID,Total\n"Logs, ingested",Payments API,134,10\n',
        )


class TestExportLimits(APILicensedTest):
    """An export holds a response from billing open for as long as the browser reads it, so the
    proxy bounds how many one person has open at once, and how often they start one."""

    def setUp(self):
        super().setUp()
        self.organization_membership.level = OrganizationMembership.Level.ADMIN
        self.organization_membership.save()
        cache.clear()

    def _export(self, rows: list[bytes]) -> Any:
        upstream = MagicMock()
        upstream.headers = {"Content-Type": "text/csv"}
        upstream.iter_content.return_value = iter(rows)
        with patch("ee.billing.billing_manager.BillingManager.get_usage_csv", return_value=upstream):
            return self.client.get("/api/billing/usage/export/?start_date=2025-01-01&breakdowns=%5B%22type%22%5D")

    @patch.object(_EXPORT_STREAMS, "max_concurrency", 1)
    def test_exports_open_at_once_are_capped_per_person_and_a_finished_one_frees_its_slot(self):
        first = self._export([b"Product\n", b"Events\n"])
        self.assertEqual(first.status_code, status.HTTP_200_OK)

        refused = self._export([b"Product\n"])
        self.assertEqual(refused.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
        self.assertIn("exports downloading", refused.json()["detail"])

        self.assertEqual(b"".join(first), b"Product\nEvents\n")
        self.assertEqual(self._export([b"Product\n"]).status_code, status.HTTP_200_OK)

    @patch.object(_EXPORT_STREAMS, "max_concurrency", 1)
    def test_each_project_secret_key_has_its_own_export_slots(self):
        first, second = (
            ProjectSecretAPIKey.objects.create(team=self.team, label=label, secure_value=f"sha256${label}")
            for label in ("first", "second")
        )
        held = _take_export_stream_slot(ProjectSecretAPIKeyUser(first))
        try:
            _release_export_stream_slot(_take_export_stream_slot(ProjectSecretAPIKeyUser(second)))
        finally:
            _release_export_stream_slot(held)

    @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
    @patch.object(BillingExportThrottle, "rate", "1/minute")
    def test_export_starts_are_rate_limited_per_person(self, _rate_limit_enabled):
        self.assertEqual(self._export([b"Product\n"]).status_code, status.HTTP_200_OK)
        self.assertEqual(self._export([b"Product\n"]).status_code, status.HTTP_429_TOO_MANY_REQUESTS)