:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(billing): lock self-serve billing for partner-paid organizations (#109479)
Matt Brooker69f21c852974
diff --git a/ee/api/billing.py b/ee/api/billing.pyindex 7612b9f5573a..c24c3fd6e9e2 100644--- a/ee/api/billing.py+++ b/ee/api/billing.py@@ -27,6 +27,7 @@ from posthog.event_usage import groupsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Organization, OrganizationIntegration, Team, Userfrom posthog.models.organization import OrganizationMembership+from posthog.models.organization_provisioning import get_billing_lock_partnerfrom posthog.permissions import get_authenticator_scoped_team_ids, get_authenticator_scopesfrom posthog.rate_limit import PersonalApiKeyOrUserRateThrottlefrom posthog.user_permissions import UserPermissions@@ -34,7 +35,7 @@ from posthog.utils import get_trusted_client_ip, relative_date_parsefrom products.access_control.backend.facade.user_access_control import UserAccessControl, visible_teams_for_user-from ee.billing.billing_manager import BillingManager, http_session+from ee.billing.billing_manager import BillingManager, http_session, raise_if_billing_managed_by_partnerfrom ee.billing.billing_types import USAGE_TYPE_VALUESfrom ee.billing.exports import ( # noqa: F401_EXPORT_STREAMS,@@ -266,11 +267,36 @@ class HasBillingUsageSpendReadAccess(permissions.BasePermission):return user_has_billing_usage_spend_read_access(request.user, org)+class BillingNotManagedByPartner(permissions.BasePermission):+ def has_permission(self, request: Request, view: Any) -> bool:+ organization = view._get_org()+ if organization is not None:+ raise_if_billing_managed_by_partner(organization)+ return True+++def billing_managed_by_partner(organization: Organization | None) -> dict[str, str] | None:+ partner = get_billing_lock_partner(organization) if organization else None+ return {"partner_name": partner.name} if partner else None++class BillingSerializer(serializers.Serializer):plan = serializers.CharField(max_length=100)billing_limit = serializers.IntegerField()+class BillingManagedByPartnerSerializer(serializers.Serializer):+ partner_name = serializers.CharField(+ allow_blank=True, help_text="Name of the partner that pays for this organization. Can be empty."+ )+++BILLING_MANAGED_BY_PARTNER_HELP_TEXT = (+ "Set when a provisioning partner pays for this organization and the organization has no Stripe customer of "+ "its own. Self-serve subscription and payment changes are refused while it is set. Null otherwise."+)++@extend_schema_serializer(many=False)class BillingOverviewResponseSerializer(serializers.Serializer):customer_id = serializers.CharField(required=False, allow_null=True)@@ -310,6 +336,9 @@ class BillingOverviewResponseSerializer(serializers.Serializer):account_owner = serializers.JSONField(required=False, allow_null=True)customer_trust_scores = serializers.JSONField(required=False)never_drop_data = serializers.BooleanField(required=False)+ billing_managed_by_partner = BillingManagedByPartnerSerializer(+ allow_null=True, help_text=BILLING_MANAGED_BY_PARTNER_HELP_TEXT+ )class LicenseKeySerializer(serializers.Serializer):@@ -542,6 +571,8 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if account_url:response["external_billing_provider_invoices_url"] = f"{account_url}/invoices"+ response["billing_managed_by_partner"] = billing_managed_by_partner(org)+return Response(response)@extend_schema(@@ -630,7 +661,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@action(methods=["POST"],detail=False,- permission_classes=[permissions.IsAuthenticated, HasBillingAccess],+ permission_classes=[permissions.IsAuthenticated, HasBillingAccess, BillingNotManagedByPartner],)def activate(self, request: Request, *args: Any, **kwargs: Any) -> Response:organization = self._get_org_required()@@ -679,7 +710,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):methods=["POST"],detail=False,url_path="subscription/switch-plan",- permission_classes=[permissions.IsAuthenticated, HasBillingAccess],+ permission_classes=[permissions.IsAuthenticated, HasBillingAccess, BillingNotManagedByPartner],)def subscription_switch_plan(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:organization = self._get_org_required()@@ -690,7 +721,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@action(methods=["GET"],detail=False,- permission_classes=[permissions.IsAuthenticated, HasBillingAccess],+ permission_classes=[permissions.IsAuthenticated, HasBillingAccess, BillingNotManagedByPartner],)def portal(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:license = get_cached_instance_license()@@ -764,7 +795,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):methods=["POST"],detail=False,url_path="credits/purchase",- permission_classes=[permissions.IsAuthenticated, HasBillingAccess],+ permission_classes=[permissions.IsAuthenticated, HasBillingAccess, BillingNotManagedByPartner],)def purchase_credits(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:license = get_cached_instance_license()@@ -784,7 +815,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):methods=["POST"],detail=False,url_path="trials/activate",- permission_classes=[permissions.IsAuthenticated, HasBillingAccess],+ permission_classes=[permissions.IsAuthenticated, HasBillingAccess, BillingNotManagedByPartner],)def activate_trial(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:organization = self._get_org_required()@@ -804,7 +835,12 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):res = billing_manager.cancel_trial(organization, request.data)return Response(res, status=status.HTTP_200_OK)- @action(methods=["POST"], detail=False, url_path="activate/authorize")+ @action(+ methods=["POST"],+ detail=False,+ url_path="activate/authorize",+ permission_classes=[permissions.IsAuthenticated, BillingNotManagedByPartner],+ )def authorize(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:license = get_cached_instance_license()if not license:diff --git a/ee/api/organization_billing.py b/ee/api/organization_billing.pyindex 88783d277f01..bdbbe5b436ae 100644--- a/ee/api/organization_billing.py+++ b/ee/api/organization_billing.py@@ -36,11 +36,14 @@ from posthog.rate_limit import BillingReadBurstRateThrottle, BillingReadSustainefrom posthog.utils import get_trusted_client_ipfrom ee.api.billing import (+ BILLING_MANAGED_BY_PARTNER_HELP_TEXT,USAGE_BREAKDOWNS_MESSAGE,BillingExportThrottle,+ BillingManagedByPartnerSerializer,BillingQueryTimeout,BillingTimeSeriesPointSerializer,BillingUsageRequestSerializer,+ billing_managed_by_partner,)from ee.billing.billing_manager import BillingManagerfrom ee.billing.exports import (@@ -167,6 +170,9 @@ class BillingSubscriptionSerializer(serializers.Serializer):billing_portal_url = serializers.URLField()invoices_url = serializers.URLField(required=False)license = LicenseSerializer()+ billing_managed_by_partner = BillingManagedByPartnerSerializer(+ allow_null=True, help_text=BILLING_MANAGED_BY_PARTNER_HELP_TEXT+ )class ProductFeatureSerializer(serializers.Serializer):@@ -790,6 +796,7 @@ class OrganizationBillingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet"startup_program_label_previous": data.get("startup_program_label_previous"),"billing_portal_url": f"{settings.SITE_URL}/api/billing/portal","license": {"plan": license.plan if license else None},+ "billing_managed_by_partner": billing_managed_by_partner(organization),}vercel_integration = OrganizationIntegration.objects.filter(organization=organization, kind=OrganizationIntegration.OrganizationIntegrationKind.VERCELdiff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.pyindex 10174ae78f45..33b272d49d13 100644--- a/ee/api/test/test_billing.py+++ b/ee/api/test/test_billing.py@@ -1,5 +1,6 @@import gzipimport json+from collections.abc import Sequencefrom datetime import datetime, timedeltafrom typing import Any, cast, get_argsfrom uuid import uuid4@@ -26,6 +27,7 @@ from posthog.cloud_utils import TEST_clear_instance_license_cache, get_cached_infrom posthog.constants import AvailableFeaturefrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import Organization, OrganizationMembership+from posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Teamfrom posthog.models.user import User@@ -39,6 +41,7 @@ from ee.api.billing import (BILLING_PROJECT_ACCESS_DENIED_MESSAGE,BillingDateRangeTooLong,BillingExportThrottle,+ BillingNotManagedByPartner,BillingQueryRejected,BillingQueryTooLarge,BillingUsageRequestSerializer,@@ -50,6 +53,7 @@ from ee.api.billing import (_stream_chunks,)from ee.api.test.base import APILicensedTest+from ee.billing.billing_manager import BillingManagerfrom ee.billing.billing_types import USAGE_TYPE_OPTIONS, BillingPeriod, CustomerInfo, CustomerProduct, UsageTypefrom ee.billing.grants import (BILLING_LIMIT_TODAYS_USAGE_FLAG,@@ -301,6 +305,7 @@ class TestUnlicensedBillingAPI(APIBaseTest):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):@@ -482,6 +487,7 @@ class TestBillingAPI(APILicensedTest):},"usage_summary": create_usage_summary(),"free_trial_until": None,+ "billing_managed_by_partner": None,}@patch("ee.billing.billing_manager.http_session.get")@@ -609,6 +615,7 @@ class TestBillingAPI(APILicensedTest):"discount_amount_usd": None,"deactivated": False,"stripe_portal_url": "http://localhost:8010/api/billing/portal",+ "billing_managed_by_partner": None,}@patch("ee.billing.billing_manager.http_session.get")@@ -1192,6 +1199,155 @@ class TestCouponClaimBillingAPI(APILicensedTest):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:+ allowed = getattr(self.client, method)(url)+ application.update_provisioning(pays_for_customers=True)+ refused = getattr(self.client, method)(url)+ self.organization.customer_id = "cus_example"+ self.organization.save(update_fields=["customer_id"])+ self_billed = getattr(self.client, method)(url)++ 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+++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: dict[str, Sequence[object]] = {+ action.__name__: getattr(action, "kwargs", {}).get("permission_classes", [])+ 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] = BillingViewset.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 TestBillingUsageRequestSerializer(TestCase):def test_valid_dates(self):serializer = BillingUsageRequestSerializer(data={"start_date": "2025-01-01", "end_date": "2025-01-31"})diff --git a/ee/api/test/test_organization_billing.py b/ee/api/test/test_organization_billing.pyindex 15c3e511649d..4a650890a77a 100644--- a/ee/api/test/test_organization_billing.py+++ b/ee/api/test/test_organization_billing.py@@ -14,6 +14,7 @@ from rest_framework import statusfrom posthog.models import OrganizationMembership, PersonalAPIKey, Teamfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rate_limit import BillingReadBurstRateThrottle@@ -182,6 +183,40 @@ class TestOrganizationBillingAPI(OrganizationBillingTestMixin, APILicensedTest):called_url = mock_get.call_args.args[0]self.assertTrue(called_url.endswith("/api/v2/billing/subscription/"), called_url)+ @parameterized.expand(+ [+ ("partner_billed", None, {"partner_name": "Example Partner"}),+ ("partner_billed_org_with_own_stripe_customer", "cus_example", None),+ ]+ )+ @patch("ee.billing.billing_manager.http_session.get")+ def test_subscription_names_the_partner_that_locks_billing(+ self, _name: str, customer_id: str | None, expected: dict[str, str] | None, mock_get: MagicMock+ ) -> None:+ mock_get.return_value = _response(SUBSCRIPTION)+ application = OAuthApplication.objects.create(+ name="Example Partner",+ client_id="example-partner",+ 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=True)+ OrganizationProvisioning.objects.create(+ organization=self.organization,+ partner=OrganizationProvisioning.Partner.PROVISIONING_API,+ application=application,+ )+ self.organization.customer_id = customer_id+ self.organization.save(update_fields=["customer_id"])++ response = self.client.get(self._url("subscription/"))++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(response.json()["billing_managed_by_partner"], expected)+@patch("ee.billing.billing_manager.http_session.get")def test_the_call_to_billing_carries_a_minted_token_with_the_grants(self, mock_get):mock_get.return_value = _response(SUBSCRIPTION)diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.pyindex 88405e9062a4..ac26c0a70653 100644--- a/ee/billing/billing_manager.py+++ b/ee/billing/billing_manager.py@@ -25,7 +25,9 @@ from posthog.dataclasses import frozenfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Organization+from posthog.models.oauth import OAuthApplicationfrom posthog.models.organization import OrganizationMembership, OrganizationUsageInfo+from posthog.models.organization_provisioning import get_billing_lock_partnerfrom posthog.models.team.event_retention import (organization_events_retention_months,reconcile_organization_events_retention,@@ -97,6 +99,21 @@ class BillingServiceOpenInvoicesError(Exception):super().__init__(message)+class BillingManagedByPartnerError(PermissionDenied):+ def __init__(self, partner: OAuthApplication) -> None:+ partner_name = partner.name.strip() or "your partner"+ super().__init__(+ f"Billing for this organization is managed by {partner_name}. "+ f"Contact {partner_name} to change your plan or payment details."+ )+++def raise_if_billing_managed_by_partner(organization: Organization) -> None:+ partner = get_billing_lock_partner(organization)+ if partner is not None:+ raise BillingManagedByPartnerError(partner)++def _has_quota_limiting_markers(usage: dict | None) -> bool:if not usage:return False@@ -1028,7 +1045,10 @@ class BillingManager:Raises:ValueError: If billing_provider is specified but the organization doesn't have the integration+ BillingManagedByPartnerError: If a partner pays for the organization and it has no Stripe customer"""+ raise_if_billing_managed_by_partner(organization)+# Validate that organization has the integration if billing_provider is specifiedif billing_provider:from posthog.models import OrganizationIntegration@@ -1053,6 +1073,18 @@ class BillingManager:return res.json()+ def authorize_with_shared_payment_token(self, organization: Organization, shared_payment_token: str) -> None:+ raise_if_billing_managed_by_partner(organization)++ res = http_session.post(+ f"{BILLING_SERVICE_URL}/api/activate/authorize",+ headers=self.get_auth_headers(organization),+ json={"shared_payment_token": shared_payment_token},+ timeout=30,+ )++ handle_billing_service_error(res, valid_codes=(200, 201))+def authorize_status(self, organization: Organization, data: dict[str, Any]):res = http_session.post(f"{BILLING_SERVICE_URL}/api/activate/authorize/status",diff --git a/ee/partners/stripe/api/provisioning/billing.py b/ee/partners/stripe/api/provisioning/billing.pyindex 3004eaf1a83b..2b65c02b3157 100644--- a/ee/partners/stripe/api/provisioning/billing.py+++ b/ee/partners/stripe/api/provisioning/billing.py@@ -12,20 +12,23 @@ from typing import Anyimport requestsimport structlog+from posthog.cloud_utils import get_cached_instance_licensefrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.team.team import Teamfrom posthog.models.user import User+from ee.billing.billing_manager import (+ BillingManagedByPartnerError,+ BillingManager,+ BillingServiceResponseError,+ build_billing_token,+)from ee.settings import BILLING_SERVICE_URLlogger = structlog.get_logger(__name__)def _build_billing_token(team: Team, user: User) -> str | None:- from posthog.cloud_utils import get_cached_instance_license-- from ee.billing.billing_manager import build_billing_token-license = get_cached_instance_license()if not license:return None@@ -60,32 +63,30 @@ def _activate_billing_with_spt(team: Team, user: User, spt_token: str) -> bool:Returns True if activation succeeded, False otherwise."""- try:- billing_token = _build_billing_token(team, user)- if not billing_token:- capture_exception(Exception("No license found for SPT billing activation"))- return False+ log_context = {"team_id": team.id, "org_id": str(team.organization_id)}+ license = get_cached_instance_license()+ if not license:+ capture_exception(Exception("No license found for SPT billing activation"))+ return False- res = requests.post(- f"{BILLING_SERVICE_URL}/api/activate/authorize",- headers={"Authorization": f"Bearer {billing_token}"},- json={"shared_payment_token": spt_token},- timeout=30,+ try:+ BillingManager(license, user).authorize_with_shared_payment_token(team.organization, spt_token)+ except BillingManagedByPartnerError:+ logger.info("stripe_provisioning.spt_billing_refused_partner_managed", **log_context)+ return False+ except BillingServiceResponseError as error:+ capture_exception(+ Exception(f"Billing SPT activation failed: {error.status_code}"),+ {**log_context, "status": error.status_code},)-- if res.status_code not in (200, 201):- capture_exception(- Exception(f"Billing SPT activation failed: {res.status_code}"),- {"team_id": team.id, "org_id": str(team.organization_id), "status": res.status_code},- )- return False-- logger.info("stripe_provisioning.spt_billing_activated", team_id=team.id, org_id=str(team.organization_id))- return True+ return Falseexcept Exception:- capture_exception(additional_properties={"team_id": team.id, "org_id": str(team.organization_id)})+ capture_exception(additional_properties=log_context)return False+ logger.info("stripe_provisioning.spt_billing_activated", **log_context)+ return True+def extract_spt(payment_credentials: Any) -> str | None:if isinstance(payment_credentials, dict) and payment_credentials.get("type") == "stripe_payment_token":diff --git a/ee/partners/stripe/api/provisioning/test/test_resources.py b/ee/partners/stripe/api/provisioning/test/test_resources.pyindex dbf81bfeed54..a09ec9523722 100644--- a/ee/partners/stripe/api/provisioning/test/test_resources.py+++ b/ee/partners/stripe/api/provisioning/test/test_resources.py@@ -4,17 +4,20 @@ from unittest.mock import patchfrom django.utils import timezone+import requestsfrom parameterized import parameterizedfrom posthog.constants import AvailableFeaturefrom posthog.models.oauth import OAuthAccessTokenfrom posthog.models.organization import OrganizationMembership+from posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team_provisioning_config import TeamProvisioningConfigfrom posthog.models.utils import generate_random_oauth_access_tokenfrom products.access_control.backend.models.access_control import AccessControl+from ee.models.license import Licensefrom ee.partners.stripe.api.provisioning.test.base import BASE_PATH, StripeProvisioningTestBaseRESOURCES_URL = f"{BASE_PATH}/provisioning/resources"@@ -166,6 +169,47 @@ class TestResources(StripeProvisioningTestBase):"error": {"code": "requires_payment_credentials", "message": "Billing activation failed"},}+ @parameterized.expand(+ [+ ("partner_billed", None, 400, []),+ ("partner_billed_org_with_own_stripe_customer", "cus_example", 200, [{"shared_payment_token": "spt_1"}]),+ ]+ )+ def test_spt_activates_billing_unless_billing_is_locked_to_the_partner(+ self, _name: str, customer_id: str | None, expected_status: int, expected_billing_payloads: list[dict[str, str]]+ ) -> None:+ self.stripe_app.update_provisioning(pays_for_customers=True)+ OrganizationProvisioning.objects.create(+ organization=self.organization,+ partner=OrganizationProvisioning.Partner.STRIPE_PROJECTS,+ application=self.stripe_app,+ )+ self.organization.customer_id = customer_id+ self.organization.save(update_fields=["customer_id"])+ token = self._get_bearer_token()+ billing_response = requests.Response()+ billing_response.status_code = 201++ with (+ patch(+ "ee.partners.stripe.api.provisioning.billing.get_cached_instance_license",+ return_value=License(key="12345::67890"),+ ),+ patch("ee.partners.stripe.api.provisioning.billing._team_has_active_billing", return_value=False),+ patch("ee.billing.billing_manager.http_session.post", return_value=billing_response) as billing_post,+ ):+ res = self._post_signed_with_bearer(+ RESOURCES_URL,+ data={+ "service_id": "pay_as_you_go",+ "payment_credentials": {"type": "stripe_payment_token", "stripe_payment_token": "spt_1"},+ },+ token=token,+ )++ assert res.status_code == expected_status, res.json()+ assert [call.kwargs["json"] for call in billing_post.call_args_list] == expected_billing_payloads+def test_detail_returns_resource(self):token = self._get_bearer_token()res = self._get_signed_with_bearer(f"{RESOURCES_URL}/{self.team.id}", token=token)diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 35bed2d437f8..c08a565c1cbb 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -13398,6 +13398,10 @@ snapshots:hash: v1.k794b7964.3aeba40d04a6226aeae25c8200dfc1bb74f34ba545f1294dab4293a63d7896c9.ANAwCdWwZqiMOI2A2gxChSERhIOiXhGfgnkygj1g1foscenes-other-billing--billing--light:hash: v1.k794b7964.5f8b924682d9559deaa6475ff343555090fde4c698b2fe38974b65a6e5e0057b.YuyS1jntLfGAqEfElxa_JW7bd6t9zzUrTkhZ2pJYfPg+ scenes-other-billing--billing-managed-by-partner--dark:+ hash: v1.k794b7964.9c4901f2fd036dde6005571c91a0614fbe86ed75692bef8c6b9eb46eaf500b93.-H-jk4ghSU02mUj-657ibApn_DE-SQibqIShQqlwtLo+ scenes-other-billing--billing-managed-by-partner--light:+ hash: v1.k794b7964.60287e6a945be4ebce959c34bc7806927268d678b473ec000d6ef104db3aa6c4.7yOxBzp7X6CqAfJStAvdccTo7MYJz9u9VOydRpU-iBIscenes-other-billing--billing-on-startup-plan--dark:hash: v1.k794b7964.327140e7888b473bf72795b84b3524a8effa471cdf5da775e81e9b060ae5ae5b.DyCRhAUTLZNQm4YUA_GDmPQ-FXb0z7XI0x0p8me4E8sscenes-other-billing--billing-on-startup-plan--light:diff --git a/frontend/src/lib/components/BillingUpgradeCTA.tsx b/frontend/src/lib/components/BillingUpgradeCTA.tsxindex 581657e459cd..dd59e2d3edcf 100644--- a/frontend/src/lib/components/BillingUpgradeCTA.tsx+++ b/frontend/src/lib/components/BillingUpgradeCTA.tsx@@ -1,12 +1,18 @@-import { useActions } from 'kea'+import { useActions, useValues } from 'kea'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { LemonButton, LemonButtonProps } from 'lib/lemon-ui/LemonButton'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'+import { billingLogic } from 'scenes/billing/billingLogic'-export function BillingUpgradeCTA({ children, ...props }: LemonButtonProps): JSX.Element {+export function BillingUpgradeCTA({ children, disabledReason, ...props }: LemonButtonProps): JSX.Element {const { reportBillingCTAShown } = useActions(eventUsageLogic)+ const { billingManagedByPartnerDisabledReason } = useValues(billingLogic)useOnMountEffect(reportBillingCTAShown)- return <LemonButton {...props}>{children}</LemonButton>+ return (+ <LemonButton {...props} disabledReason={billingManagedByPartnerDisabledReason || disabledReason}>+ {children}+ </LemonButton>+ )}diff --git a/frontend/src/lib/components/PayGateMini/PayGateButton.tsx b/frontend/src/lib/components/PayGateMini/PayGateButton.tsxindex 5db3b49b683a..d55e7b3139d7 100644--- a/frontend/src/lib/components/PayGateMini/PayGateButton.tsx+++ b/frontend/src/lib/components/PayGateMini/PayGateButton.tsx@@ -13,7 +13,7 @@ import type { payGateMiniLogicType } from './payGateMiniLogic'type UsePayGateButtonReturn = Pick<payGateMiniLogicType['values'],- 'ctaLabel' | 'gateVariant' | 'productWithFeature'+ 'ctaLabel' | 'ctaDisabledReason' | 'gateVariant' | 'productWithFeature'> & {clickHandlerProps: Pick<LemonButtonProps, 'onClick' | 'to'>}@@ -23,7 +23,7 @@ function usePayGateButton({currentUsage,onClick,}: PayGateMiniLogicProps & Pick<LemonButtonProps, 'onClick'>): UsePayGateButtonReturn {- const { productWithFeature, ctaLink, ctaLabel, gateVariant, isPaymentEntryFlow } = useValues(+ const { productWithFeature, ctaLink, ctaLabel, ctaDisabledReason, gateVariant, isPaymentEntryFlow } = useValues(payGateMiniLogic({ feature, currentUsage }))const { startPaymentEntryFlow } = useActions(paymentEntryLogic)@@ -45,6 +45,7 @@ function usePayGateButton({return {clickHandlerProps,ctaLabel,+ ctaDisabledReason,gateVariant,productWithFeature,}@@ -52,10 +53,20 @@ function usePayGateButton({type PayGateButtonProps = PayGateMiniLogicProps & Partial<LemonButtonProps>export const PayGateButton = ({ feature, currentUsage, ...buttonProps }: PayGateButtonProps): JSX.Element | null => {- const { clickHandlerProps, ctaLabel } = usePayGateButton({ feature, currentUsage, onClick: buttonProps.onClick })+ const { clickHandlerProps, ctaLabel, ctaDisabledReason } = usePayGateButton({+ feature,+ currentUsage,+ onClick: buttonProps.onClick,+ })return (- <LemonButton type="primary" center {...buttonProps} {...clickHandlerProps}>+ <LemonButton+ type="primary"+ center+ {...buttonProps}+ {...clickHandlerProps}+ disabledReason={ctaDisabledReason || buttonProps.disabledReason}+ >{ctaLabel}</LemonButton>)@@ -69,7 +80,7 @@ export const PayGateIcon = ({disableAutoHide,...buttonProps}: PayGateIconProps): JSX.Element | null => {- const { clickHandlerProps, ctaLabel, gateVariant, productWithFeature } = usePayGateButton({+ const { clickHandlerProps, ctaLabel, ctaDisabledReason, gateVariant, productWithFeature } = usePayGateButton({feature,currentUsage,onClick: (ev) => {@@ -99,6 +110,7 @@ export const PayGateIcon = ({tooltip={ctaLabel}{...buttonProps}{...clickHandlerProps}+ disabledReason={ctaDisabledReason || buttonProps.disabledReason}/>)}diff --git a/frontend/src/lib/components/PayGateMini/payGateMiniLogic.test.ts b/frontend/src/lib/components/PayGateMini/payGateMiniLogic.test.tsnew file mode 100644index 000000000000..fbf92273c79e--- /dev/null+++ b/frontend/src/lib/components/PayGateMini/payGateMiniLogic.test.ts@@ -0,0 +1,52 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { expectLogic } from 'kea-test-utils'++import { billingLogic } from 'scenes/billing/billingLogic'+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'++import { billingJson } from '~/mocks/fixtures/_billing'+import preflightJson from '~/mocks/fixtures/_preflight.json'+import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { AvailableFeature, BillingType } from '~/types'++import { payGateMiniLogic } from './payGateMiniLogic'++describe('payGateMiniLogic', () => {+ it.each([+ {+ name: 'disables the payment entry button',+ subscriptionLevel: 'free' as const,+ expected: {+ isPaymentEntryFlow: true,+ ctaDisabledReason: 'Billing for this organization is managed by Example Partner.',+ },+ },+ {+ name: 'keeps the link to the billing page enabled',+ subscriptionLevel: 'paid' as const,+ expected: { isPaymentEntryFlow: false, ctaDisabledReason: null },+ },+ ])('$name when a partner manages billing', async ({ subscriptionLevel, expected }) => {+ const billing: BillingType = {+ ...billingJson,+ customer_id: '',+ subscription_level: subscriptionLevel,+ billing_managed_by_partner: { partner_name: 'Example Partner' },+ }+ useMocks({+ get: {+ '/_preflight': [200, { ...preflightJson, cloud: true }],+ '/api/billing': [200, billing],+ },+ })+ initKeaTests()+ await expectLogic(preflightLogic).toFinishAllListeners()+ billingLogic.mount()+ await expectLogic(billingLogic, () => billingLogic.actions.loadBilling()).toFinishAllListeners()+ const logic = payGateMiniLogic({ feature: AvailableFeature.SUBSCRIPTIONS })+ logic.mount()++ expect(logic.values).toMatchObject({ gateVariant: 'add-card', ...expected })+ })+})diff --git a/frontend/src/lib/components/PayGateMini/payGateMiniLogic.tsx b/frontend/src/lib/components/PayGateMini/payGateMiniLogic.tsxindex c90a25fc8049..4476cf68deb2 100644--- a/frontend/src/lib/components/PayGateMini/payGateMiniLogic.tsx+++ b/frontend/src/lib/components/PayGateMini/payGateMiniLogic.tsx@@ -19,12 +19,14 @@ export type GateVariantType = 'add-card' | 'contact-sales' | 'move-to-cloud' | nexport interface payGateMiniLogicValues {billing: BillingType | null // billingLogicbillingLoading: boolean // billingLogic+ billingManagedByPartnerDisabledReason: string | null // billingLogicisCloudOrDev: boolean | undefined // preflightLogicavailableFeature: (feature: AvailableFeature) => BillingFeatureType | null | undefined // userLogichasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogicuser: UserType | null // userLogicaddonTrialModalOpen: booleanbypassPaywall: boolean+ ctaDisabledReason: string | nullctaLabel: 'Contact sales' | 'Move to PostHog Cloud' | 'Upgrade now' | 'View plans'ctaLink: string | undefinedfeatureAvailableOnOrg: BillingFeatureType | null | undefined@@ -99,6 +101,10 @@ export interface payGateMiniLogicMeta {isAddonProduct: boolean | undefined,billing: BillingType | null) => boolean+ ctaDisabledReason: (+ isPaymentEntryFlow: boolean,+ billingManagedByPartnerDisabledReason: string | null+ ) => string | null}}@@ -116,7 +122,7 @@ export const payGateMiniLogic = kea<payGateMiniLogicType>([connect(() => ({values: [billingLogic,- ['billing', 'billingLoading'],+ ['billing', 'billingLoading', 'billingManagedByPartnerDisabledReason'],userLogic,['user', 'hasAvailableFeature', 'availableFeature'],preflightLogic,@@ -297,5 +303,10 @@ export const payGateMiniLogic = kea<payGateMiniLogicType>([return gateVariant === 'add-card' && !isAddonProduct && billing?.subscription_level === 'free'},],+ ctaDisabledReason: [+ (s) => [s.isPaymentEntryFlow, s.billingManagedByPartnerDisabledReason],+ (isPaymentEntryFlow: boolean, billingManagedByPartnerDisabledReason: string | null): string | null =>+ isPaymentEntryFlow ? billingManagedByPartnerDisabledReason : null,+ ],})),])diff --git a/frontend/src/scenes/billing/Billing.stories.tsx b/frontend/src/scenes/billing/Billing.stories.tsxindex 06de03c03665..96eefe9469fd 100644--- a/frontend/src/scenes/billing/Billing.stories.tsx+++ b/frontend/src/scenes/billing/Billing.stories.tsx@@ -2,6 +2,7 @@ import { Meta, StoryObj } from '@storybook/react'import { mswDecorator, useStorybookMocks } from '~/mocks/browser'import { billingJson } from '~/mocks/fixtures/_billing'+import { billingUnsubscribedJson } from '~/mocks/fixtures/_billing_unsubscribed'import billingJsonWith100PercentDiscount from '~/mocks/fixtures/_billing_with_100_percent_discount.json'import billingJsonWithCredits from '~/mocks/fixtures/_billing_with_credits.json'import billingJsonWithDiscount from '~/mocks/fixtures/_billing_with_discount.json'@@ -67,6 +68,22 @@ export const _Billing: Story = {},}+export const BillingManagedByPartner: Story = {+ render: () => {+ useStorybookMocks({+ get: {+ '/api/billing/': {+ ...billingUnsubscribedJson,+ customer_id: '',+ billing_managed_by_partner: { partner_name: 'Example Partner' },+ },+ },+ })++ return <Billing />+ },+}+export const BillingOnStartupPlan: Story = {render: () => {useStorybookMocks({diff --git a/frontend/src/scenes/billing/Billing.tsx b/frontend/src/scenes/billing/Billing.tsxindex 1ea1940e2d4c..5d883a76dc6e 100644--- a/frontend/src/scenes/billing/Billing.tsx+++ b/frontend/src/scenes/billing/Billing.tsx@@ -58,6 +58,7 @@ export function Billing(): JSX.Element {minimumBillingAccessLevel,canOnlyViewUsageAndSpend,hasSupportAddonPlan,+ billingManagedByPartnerNotice,} = useValues(billingLogic)const { reportBillingShown } = useActions(billingLogic)const { preflight, isCloudOrDev } = useValues(preflightLogic)@@ -161,6 +162,12 @@ export function Billing(): JSX.Element {</LemonBanner>)}+ {billingManagedByPartnerNotice && (+ <LemonBanner type="info" className="max-w-300 mb-2">+ {billingManagedByPartnerNotice}+ </LemonBanner>+ )}+{billing?.trial ? (<LemonBanner type="info" hideIcon className="max-w-300 mb-2"><div className="flex items-center gap-4">diff --git a/frontend/src/scenes/billing/BillingProduct.tsx b/frontend/src/scenes/billing/BillingProduct.tsxindex 98b806c5b0dd..5952e1e4406d 100644--- a/frontend/src/scenes/billing/BillingProduct.tsx+++ b/frontend/src/scenes/billing/BillingProduct.tsx@@ -61,7 +61,7 @@ export const getTierDescription = (export const BillingProduct = ({ product }: { product: BillingProductV2Type }): JSX.Element | null => {const productRef = useRef<HTMLDivElement | null>(null)- const { billing, isUnlicensedDebug } = useValues(billingLogic)+ const { billing, isUnlicensedDebug, isBillingManagedByPartner } = useValues(billingLogic)const {hasCustomLimitSet,showTierBreakdown,@@ -548,7 +548,7 @@ export const BillingProduct = ({ product }: { product: BillingProductV2Type }):<div className="pb-8">{/* Add-ons title */}<h4 className="my-4">{addonSectionLabel}</h4>- {billing?.subscription_level == 'free' && (+ {billing?.subscription_level == 'free' && !isBillingManagedByPartner && (<LemonBanner type="warning" className="text-sm mb-4" hideIcon><div className="flex justify-between items-center"><div>diff --git a/frontend/src/scenes/billing/BillingProductAddonActions.tsx b/frontend/src/scenes/billing/BillingProductAddonActions.tsxindex 1d9456c919b3..304b3f45c788 100644--- a/frontend/src/scenes/billing/BillingProductAddonActions.tsx+++ b/frontend/src/scenes/billing/BillingProductAddonActions.tsx@@ -60,7 +60,8 @@ export const BillingProductAddonActions = ({purchaseDisabledReason,onPurchaseClick,}: BillingProductAddonActionsProps): JSX.Element => {- const { billing, billingError, currentPlatformAddon, switchPlanLoading } = useValues(billingLogic)+ const { billing, billingError, currentPlatformAddon, switchPlanLoading, billingManagedByPartnerDisabledReason } =+ useValues(billingLogic)const { preflight } = useValues(preflightLogic)const {currentAndUpgradePlans,@@ -173,6 +174,7 @@ export const BillingProductAddonActions = ({size={buttonSize || 'small'}disableClientSideRoutingdisabledReason={+ billingManagedByPartnerDisabledReason ||(billingError && billingError.message) ||(billing?.subscription_level === 'free' && 'Upgrade to add add-ons') ||purchaseDisabledReason@@ -250,7 +252,10 @@ export const BillingProductAddonActions = ({overlay={<LemonButtonfullWidth- disabledReason={switchPlanLoading ? 'Switching plans...' : undefined}+ disabledReason={+ billingManagedByPartnerDisabledReason ||+ (switchPlanLoading ? 'Switching plans...' : undefined)+ }onClick={() => {reportBillingAddonPlanSwitchStarted(currentPlatformAddon.type, addon.type, 'downgrade')showConfirmDowngradeModal()@@ -287,7 +292,9 @@ export const BillingProductAddonActions = ({<LemonButtontype="primary"- disabledReason={switchPlanLoading ? 'Switching plans...' : undefined}+ disabledReason={+ billingManagedByPartnerDisabledReason || (switchPlanLoading ? 'Switching plans...' : undefined)+ }onClick={() => {reportBillingAddonPlanSwitchStarted(currentPlatformAddon.type, addon.type, 'upgrade')showConfirmUpgradeModal()@@ -325,7 +332,7 @@ export const BillingProductAddonActions = ({type="secondary"size="xsmall"loading={trialLoading || billingProductLoading === addon.type}- disabledReason={purchaseDisabledReason}+ disabledReason={billingManagedByPartnerDisabledReason || purchaseDisabledReason}tooltip="Local dev only — starts the self-serve trial. Never shown in production."onClick={() => {onPurchaseClick?.()diff --git a/frontend/src/scenes/billing/StripePortalButton.tsx b/frontend/src/scenes/billing/StripePortalButton.tsxindex cea99e630e12..bdd733117f7b 100644--- a/frontend/src/scenes/billing/StripePortalButton.tsx+++ b/frontend/src/scenes/billing/StripePortalButton.tsx@@ -5,9 +5,9 @@ import { LemonButton } from '@posthog/lemon-ui'import { billingLogic } from './billingLogic'export const StripePortalButton = (): JSX.Element | null => {- const { billing, isExternallyBilled } = useValues(billingLogic)+ const { billing, isExternallyBilled, isBillingManagedByPartner } = useValues(billingLogic)- if (!billing || (!isExternallyBilled && !billing.customer_id)) {+ if (!billing || isBillingManagedByPartner || (!isExternallyBilled && !billing.customer_id)) {return null}diff --git a/frontend/src/scenes/billing/billing-utils.ts b/frontend/src/scenes/billing/billing-utils.tsindex 2b2551db9559..6a18b549e9d4 100644--- a/frontend/src/scenes/billing/billing-utils.ts+++ b/frontend/src/scenes/billing/billing-utils.ts@@ -8,7 +8,7 @@ import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { dateStringToDayJs } from 'lib/utils/dateFilters'import { compactNumber } from 'lib/utils/numbers'import { membershipLevelToName } from 'lib/utils/permissioning'-import { wordPluralize } from 'lib/utils/strings'+import { capitalizeFirstLetter, wordPluralize } from 'lib/utils/strings'import { Params } from 'scenes/sceneTypes'import { BillingPeriod, BillingProductV2AddonType, BillingProductV2Type, BillingTierType, BillingType } from '~/types'@@ -698,7 +698,8 @@ export function getUsageLimitConsequence(productName: string): string {export function buildUsageLimitReachedMessage(products: Array<{ type?: string | null; name: string; subscribed: boolean | null }>,hasBillingAccess: boolean = true,- minimumBillingAccessLevel: OrganizationMembershipLevel = OrganizationMembershipLevel.Admin+ minimumBillingAccessLevel: OrganizationMembershipLevel = OrganizationMembershipLevel.Admin,+ billingManagedByPartnerNotice: string | null = null): {title: stringmessage: string@@ -715,6 +716,14 @@ export function buildUsageLimitReachedMessage(const productListText = formatProductNames(productNames)const consequenceText = consequences.join(' and ')+ const title = products.length === 1 ? 'Usage limit reached' : 'Usage limits reached'++ if (billingManagedByPartnerNotice && !allSubscribed) {+ return {+ title,+ message: `You have reached the usage limit for ${productListText}. ${capitalizeFirstLetter(consequenceText)}. ${billingManagedByPartnerNotice}`,+ }+ }let actionText: stringif (hasBillingAccess) {@@ -727,7 +736,7 @@ export function buildUsageLimitReachedMessage(}return {- title: products.length === 1 ? 'Usage limit reached' : 'Usage limits reached',+ title,message: `You have reached the usage limit for ${productListText}. Please ${actionText} or ${consequenceText}.`,}}diff --git a/frontend/src/scenes/billing/billingLogic.test.ts b/frontend/src/scenes/billing/billingLogic.test.tsindex 88cb85bcd33d..cd045275f1d2 100644--- a/frontend/src/scenes/billing/billingLogic.test.ts+++ b/frontend/src/scenes/billing/billingLogic.test.ts@@ -182,8 +182,21 @@ describe('billingLogic', () => {})- it('treats exactly 100% usage as a reached limit alert', async () => {- billingState = billingWithProducts([productWithUsage(1)])+ it.each([+ {+ name: 'self-serve billing',+ billing: {},+ expectedMessage:+ 'You have reached the usage limit for Product analytics. Please upgrade your plan or data loss may occur.',+ },+ {+ name: 'partner-managed billing',+ billing: { customer_id: '', billing_managed_by_partner: { partner_name: 'Example Partner' } },+ expectedMessage:+ 'You have reached the usage limit for Product analytics. Data loss may occur. Billing for this organization is managed by Example Partner. Contact them to change your plan or payment details.',+ },+ ])('treats exactly 100% usage as a reached limit alert with $name', async ({ billing, expectedMessage }) => {+ billingState = { ...billingWithProducts([productWithUsage(1, { subscribed: false })]), ...billing }billingLogic.mount()await expectLogic(preflightLogic).toFinishAllListeners()@@ -194,7 +207,7 @@ describe('billingLogic', () => {expect(billingLogic.values.billingAlert).toMatchObject({status: 'error',title: 'Usage limit reached',- message: expect.stringContaining('You have reached the usage limit for Product analytics.'),+ message: expectedMessage,productKey: ProductKey.PRODUCT_ANALYTICS,})expect(billingLogic.values.isProductAtOrOverUsageLimit(ProductKey.PRODUCT_ANALYTICS)).toBe(true)@@ -212,6 +225,38 @@ describe('billingLogic', () => {expect(billingLogic.values.isProductAtOrOverUsageLimit(ProductKey.PRODUCT_ANALYTICS)).toBe(false)})+ it.each([+ { name: 'eligible for credits', eligible: true, partnerName: 'Example Partner', shownName: 'Example Partner' },+ {+ name: 'not eligible for credits',+ eligible: false,+ partnerName: 'Example Partner',+ shownName: 'Example Partner',+ },+ { name: 'blank partner name', eligible: false, partnerName: '', shownName: 'your partner' },+ ])(+ 'hides the upgrade and credits heroes when a partner manages billing ($name)',+ async ({ eligible, partnerName, shownName }) => {+ billingState = {+ ...billingJson,+ customer_id: '',+ billing_managed_by_partner: { partner_name: partnerName },+ }+ useMocks({ get: { '/api/billing/credits/overview': [200, { ...creditOverviewResponse, eligible }] } })+ billingLogic.mount()++ await expectLogic(billingLogic, () => {+ billingLogic.actions.loadBilling()+ }).toFinishAllListeners()++ expect(billingLogic.values).toMatchObject({+ showCreditCTAHero: false,+ showBillingHero: false,+ billingManagedByPartnerNotice: `Billing for this organization is managed by ${shownName}. Contact them to change your plan or payment details.`,+ })+ }+ )+it('clears a stale usage limit alert when refreshed billing data no longer qualifies', async () => {billingState = billingWithProducts([productWithUsage(1)])billingLogic.mount()diff --git a/frontend/src/scenes/billing/billingLogic.tsx b/frontend/src/scenes/billing/billingLogic.tsxindex 6d8647f75a95..c5116a7afafb 100644--- a/frontend/src/scenes/billing/billingLogic.tsx+++ b/frontend/src/scenes/billing/billingLogic.tsx@@ -219,6 +219,8 @@ export interface billingLogicValues {billingEntryUrl: string | nullbillingError: BillingError | nullbillingLoading: boolean+ billingManagedByPartnerDisabledReason: string | null+ billingManagedByPartnerNotice: string | nullbillingPeriodUTC: BillingPeriodbillingPlan: BillingPlan | nullcanAccessBilling: boolean@@ -268,6 +270,7 @@ export interface billingLogicValues {isActivateLicenseSubmitting: booleanisActivateLicenseValid: booleanisAnnualPlanCustomer: boolean+ isBillingManagedByPartner: booleanisCreditCTAHeroDismissed: booleanisCreditFormSubmitting: booleanisCreditFormValid: boolean@@ -647,20 +650,27 @@ export interface billingLogicMeta {isProductAtOrOverUsageLimit: (billing: BillingType | null) => (productKey: ProductKey) => booleanbillingPeriodUTC: (billing: BillingType | null) => BillingPeriodshowBillingSummary: (billing: BillingType | null, isOnboarding: boolean) => boolean- showCreditCTAHero: (creditOverview: {- cc_last_four: null- collection_method: null- credit_brackets: never[]- eligible: false- email: null- estimated_monthly_credit_amount_usd: null- invoice_url: null- status: string- }) => boolean+ isBillingManagedByPartner: (billing: BillingType | null) => boolean+ billingManagedByPartnerDisabledReason: (billing: BillingType | null) => string | null+ billingManagedByPartnerNotice: (billingManagedByPartnerDisabledReason: string | null) => string | null+ showCreditCTAHero: (+ creditOverview: {+ cc_last_four: null+ collection_method: null+ credit_brackets: never[]+ eligible: false+ email: null+ estimated_monthly_credit_amount_usd: null+ invoice_url: null+ status: string+ },+ isBillingManagedByPartner: boolean+ ) => booleanshowBillingHero: (billing: BillingType | null,billingPlan: BillingPlan | null,- showCreditCTAHero: boolean+ showCreditCTAHero: boolean,+ isBillingManagedByPartner: boolean) => booleanisManagedAccount: (billing: BillingType | null) => booleanisExternallyBilled: (billing: BillingType | null) => boolean@@ -1229,29 +1239,58 @@ export const billingLogic = kea<billingLogicType>([return !isOnboarding && !!billing?.billing_period},],+ isBillingManagedByPartner: [+ (s) => [s.billing],+ (billing: BillingType | null): boolean => !!billing?.billing_managed_by_partner,+ ],+ billingManagedByPartnerDisabledReason: [+ (s) => [s.billing],+ (billing: BillingType | null): string | null => {+ const partner = billing?.billing_managed_by_partner+ if (!partner) {+ return null+ }+ return `Billing for this organization is managed by ${partner.partner_name.trim() || 'your partner'}.`+ },+ ],+ billingManagedByPartnerNotice: [+ (s) => [s.billingManagedByPartnerDisabledReason],+ (billingManagedByPartnerDisabledReason: string | null): string | null =>+ billingManagedByPartnerDisabledReason+ ? `${billingManagedByPartnerDisabledReason} Contact them to change your plan or payment details.`+ : null,+ ],showCreditCTAHero: [- (s) => [s.creditOverview],- (creditOverview: {- cc_last_four: null- collection_method: null- credit_brackets: never[]- eligible: false- email: null- estimated_monthly_credit_amount_usd: null- invoice_url: null- status: string- }): boolean => {+ (s) => [s.creditOverview, s.isBillingManagedByPartner],+ (+ creditOverview: {+ cc_last_four: null+ collection_method: null+ credit_brackets: never[]+ eligible: false+ email: null+ estimated_monthly_credit_amount_usd: null+ invoice_url: null+ status: string+ },+ isBillingManagedByPartner: boolean+ ): boolean => {const isEligible = creditOverview.eligible- return isEligible && creditOverview.status !== 'paid'+ return !isBillingManagedByPartner && isEligible && creditOverview.status !== 'paid'},],showBillingHero: [- (s) => [s.billing, s.billingPlan, s.showCreditCTAHero],- (billing: BillingType | null, billingPlan: BillingPlan | null, showCreditCTAHero: boolean): boolean => {+ (s) => [s.billing, s.billingPlan, s.showCreditCTAHero, s.isBillingManagedByPartner],+ (+ billing: BillingType | null,+ billingPlan: BillingPlan | null,+ showCreditCTAHero: boolean,+ isBillingManagedByPartner: boolean+ ): boolean => {const platformAndSupportProduct = billing?.products?.find((product) => product.type === ProductKey.PLATFORM_AND_SUPPORT)- return !!billingPlan && !!platformAndSupportProduct && !showCreditCTAHero+ return !!billingPlan && !!platformAndSupportProduct && !showCreditCTAHero && !isBillingManagedByPartner},],isManagedAccount: [@@ -1578,7 +1617,8 @@ export const billingLogic = kea<billingLogicType>([const { title, message } = buildUsageLimitReachedMessage(productsAtOrOverLimit,values.canAccessBilling,- values.minimumBillingAccessLevel+ values.minimumBillingAccessLevel,+ values.billingManagedByPartnerNotice)actions.setBillingAlert({diff --git a/frontend/src/scenes/billing/paymentEntryLogic.test.ts b/frontend/src/scenes/billing/paymentEntryLogic.test.tsindex d3d2f3023ebf..2489be592956 100644--- a/frontend/src/scenes/billing/paymentEntryLogic.test.ts+++ b/frontend/src/scenes/billing/paymentEntryLogic.test.ts@@ -119,4 +119,22 @@ describe('paymentEntryLogic', () => {expect(toastErrorSpy).not.toHaveBeenCalled()})})++ describe('startPaymentEntryFlow — billing managed by a partner', () => {+ it('neither activates nor opens the payment modal', async () => {+ await seedBilling({+ subscription_level: 'free',+ billing_managed_by_partner: { partner_name: 'Example Partner' },+ })+ const activate = jest.fn(() => [200, { success: true }] as [number, Record<string, unknown>])+ useMocks({ post: { '/api/billing/activate': activate } })+ logic = paymentEntryLogic()+ logic.mount()++ await expectLogic(logic, () => logic.actions.startPaymentEntryFlow(null, '/foo')).toFinishAllListeners()++ expect(activate).not.toHaveBeenCalled()+ expect(logic.values.paymentEntryModalOpen).toBe(false)+ })+ })})diff --git a/frontend/src/scenes/billing/paymentEntryLogic.ts b/frontend/src/scenes/billing/paymentEntryLogic.tsindex c9111a7f3e60..f25eb565c106 100644--- a/frontend/src/scenes/billing/paymentEntryLogic.ts+++ b/frontend/src/scenes/billing/paymentEntryLogic.ts@@ -145,7 +145,12 @@ export const paymentEntryLogic = kea<paymentEntryLogicType>([}),listeners(({ actions, values }) => ({startPaymentEntryFlow: async ({ product, redirectPath }) => {- const { billing } = billingLogic.values+ const { billing, billingManagedByPartnerNotice } = billingLogic.values++ if (billingManagedByPartnerNotice) {+ lemonToast.info(billingManagedByPartnerNotice)+ return+ }if (billing?.customer_id) {// Returning customer — call POST API to activate subscriptiondiff --git a/frontend/src/scenes/startups/StartupProgram.tsx b/frontend/src/scenes/startups/StartupProgram.tsxindex 5578195c77bd..986bb013f7b1 100644--- a/frontend/src/scenes/startups/StartupProgram.tsx+++ b/frontend/src/scenes/startups/StartupProgram.tsx@@ -25,6 +25,9 @@ import {ItemTitle,Spinner,Text,+ Tooltip,+ TooltipContent,+ TooltipTrigger,} from '@posthog/quill'import { pngHoggie } from 'lib/brand/hoggies'@@ -75,18 +78,19 @@ function BillingUpgradeButton({}: {platformAndSupportProduct: BillingProductV2Type}): JSX.Element {- const { billing } = useValues(billingLogic)+ const { billing, billingManagedByPartnerDisabledReason } = useValues(billingLogic)const { startPaymentEntryFlow } = useActions(paymentEntryLogic)const { billingProductLoading } = useValues(billingProductLogic({ product: platformAndSupportProduct }))const { reportBillingCTAShown } = useActions(eventUsageLogic)useOnMountEffect(reportBillingCTAShown)- return (+ const button = (<Buttonvariant="primary"size="lg"data-attr="startup-program-upgrade-cta"loading={!!billingProductLoading}+ disabled={!!billingManagedByPartnerDisabledReason}onClick={() =>startPaymentEntryFlow(platformAndSupportProduct, window.location.pathname + window.location.search)}@@ -94,6 +98,17 @@ function BillingUpgradeButton({{billing?.customer_id ? 'Subscribe' : 'Add billing details'}</Button>)++ if (billingManagedByPartnerDisabledReason) {+ return (+ <Tooltip>+ <TooltipTrigger render={button} />+ <TooltipContent>{billingManagedByPartnerDisabledReason}</TooltipContent>+ </Tooltip>+ )+ }++ return button}export const scene: SceneExport<StartupProgramLogicProps> = {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 21bcf2f91e10..089fd1401054 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -2490,6 +2490,7 @@ export interface BillingType {email?: stringname?: string}+ billing_managed_by_partner?: { partner_name: string } | null}export interface ClaimedCouponInfo {diff --git a/posthog/models/oauth_provisioning.py b/posthog/models/oauth_provisioning.pyindex c49c456c62b0..c7319ed28765 100644--- a/posthog/models/oauth_provisioning.py+++ b/posthog/models/oauth_provisioning.py@@ -82,6 +82,10 @@ class ProvisioningConfig(BaseModel):# Grandfathered: only the legacy Stripe app still mints a Personal API Key.issues_personal_api_key: bool = False+ # Staff-only. Billing refuses to move an organization to partner billing once the organization+ # has its own Stripe customer, so the partner's organizations must not start self-serve billing.+ pays_for_customers: bool = False+# Per-endpoint hourly overrides, keyed by rate-limit endpoint name. An absent key# means the tier-derived budget applies; UNLIMITED_OVERRIDE disables the limit.# Every value stored here is admin-authored: the self-serve tiers are derived atdiff --git a/posthog/models/organization_provisioning.py b/posthog/models/organization_provisioning.pyindex 476636e85e89..88f7efedd8f3 100644--- a/posthog/models/organization_provisioning.py+++ b/posthog/models/organization_provisioning.py@@ -1,6 +1,13 @@+from typing import TYPE_CHECKING+from django.db import modelsfrom django.db.models import Q+from posthog.models.oauth import OAuthApplication++if TYPE_CHECKING:+ from posthog.models.organization import Organization+class OrganizationProvisioning(models.Model):class Partner(models.TextChoices):@@ -36,3 +43,14 @@ class OrganizationProvisioning(models.Model):name="org_provisioning_application_matches_partner",)]+++def get_billing_lock_partner(organization: "Organization") -> OAuthApplication | None:+ # customer_id is the organization's own Stripe customer, synced from billing. An organization+ # that already has one keeps paying for itself, and keeps self-serve billing to manage it.+ if organization.customer_id:+ return None+ return OAuthApplication.objects.filter(+ provisioned_organizations__organization=organization,+ _provisioning_config__pays_for_customers=True,+ ).first()diff --git a/products/billing/frontend/generated/api.schemas.ts b/products/billing/frontend/generated/api.schemas.tsindex 0ab108c48651..8405c01d11a9 100644--- a/products/billing/frontend/generated/api.schemas.ts+++ b/products/billing/frontend/generated/api.schemas.ts@@ -9,6 +9,11 @@*/export type BillingOverviewResponseApiProductsItem = { [key: string]: unknown }+export interface BillingManagedByPartnerApi {+ /** Name of the partner that pays for this organization. Can be empty. */+ partner_name: string+}+export interface BillingOverviewResponseApi {/** @nullable */customer_id?: string | null@@ -57,6 +62,8 @@ export interface BillingOverviewResponseApi {account_owner?: unknowncustomer_trust_scores?: unknownnever_drop_data?: boolean+ /** Set when a provisioning partner pays for this organization and the organization has no Stripe customer of its own. Self-serve subscription and payment changes are refused while it is set. Null otherwise. */+ billing_managed_by_partner: BillingManagedByPartnerApi | null}export interface BillingApi {@@ -1143,6 +1150,8 @@ export interface BillingSubscriptionApi {billing_portal_url: stringinvoices_url?: stringlicense: LicenseApi+ /** Set when a provisioning partner pays for this organization and the organization has no Stripe customer of its own. Self-serve subscription and payment changes are refused while it is set. Null otherwise. */+ billing_managed_by_partner: BillingManagedByPartnerApi | null}export interface UsageKeySummaryApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3a7cdd1cb068..d53e3b628457 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17237,6 +17237,11 @@ export namespace Schemas {results: ProductLimit[];}+ export interface BillingManagedByPartner {+ /** Name of the partner that pays for this organization. Can be empty. */+ partner_name: string;+ }+export type BillingOverviewResponseProductsItem = {[key: string]: unknown};export interface BillingOverviewResponse {@@ -17287,6 +17292,8 @@ export namespace Schemas {account_owner?: unknown;customer_trust_scores?: unknown;never_drop_data?: boolean;+ /** Set when a provisioning partner pays for this organization and the organization has no Stripe customer of its own. Self-serve subscription and payment changes are refused while it is set. Null otherwise. */+ billing_managed_by_partner: BillingManagedByPartner | null;}export interface BillingPeriodResponse {@@ -17519,6 +17526,8 @@ export namespace Schemas {billing_portal_url: string;invoices_url?: string;license: License;+ /** Set when a provisioning partner pays for this organization and the organization has no Stripe customer of its own. Self-serve subscription and payment changes are refused while it is set. Null otherwise. */+ billing_managed_by_partner: BillingManagedByPartner | null;}export interface BillingTeamOptionsResponse {