: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
fix(billing): stop self-serve plan changes for Vercel-billed orgs (#115507)
Matt Brookera1d83915a98a
diff --git a/docs/published/handbook/engineering/vercel-integration.md b/docs/published/handbook/engineering/vercel-integration.mdindex 45e9ed3cbf20..647e7896d624 100644--- a/docs/published/handbook/engineering/vercel-integration.md+++ b/docs/published/handbook/engineering/vercel-integration.md@@ -170,6 +170,25 @@ graph LR| **SSO** | Via Vercel (`/login/vercel`) | PostHog login || **Uninstall** | Resets to `billing_provider=posthog` | N/A |+The billing page also treats Vercel customers differently:++- A banner says billing for the organization is managed by Vercel. The "View invoices in Vercel" button links to the Vercel invoices page when `external_billing_provider_invoices_url` is set.+- The "Downgrade to free plan" card is hidden.+- With an active subscription, add-ons, platform plan switches, and billing limits work as usual.+- Without an active subscription, the page locks self-serve billing the same way it does for a paying partner, through `selfServeBillingDisabledReason` in `billingLogic`:+ - The upgrade hero and the add-on upgrade banner are hidden.+ - `BillingUpgradeCTA`, pay gate, and startup program upgrade buttons are disabled.+ - `startPaymentEntryFlow` and `handleProductUpgrade` show a toast and stop before they call `api/billing/activate`.+ - The banner, the toast, and the usage limit alert tell the customer to contact support to change their plan.++The billing service refuses these requests for Vercel customers with a 400 and the code `billing_managed_by_provider`:++- `POST /api/activate` when the customer has no subscription+- card authorization at `POST /api/activate/authorize`+- `GET /api/billing/portal`++PostHog's `api/billing/activate` and `api/billing/activate/authorize` pass the refusal on as a 400 with billing's message and the same code. `api/billing/portal` redirects to the Vercel invoices page instead, and returns that 400 only when the organization's Vercel integration has no account URL.+### The `billing_provider` fieldOn the Customer model (`billing/models/customer.py`):diff --git a/ee/api/billing.py b/ee/api/billing.pyindex dd1bfadcc837..fd4f4d23091f 100644--- a/ee/api/billing.py+++ b/ee/api/billing.py@@ -1,6 +1,7 @@import reimport json-from collections.abc import Callable, Sequence+from collections.abc import Callable, Iterator, Sequence+from contextlib import contextmanagerfrom datetime import timedeltafrom typing import Any, Literal, NoReturn, Optional, castfrom uuid import UUID@@ -40,7 +41,12 @@ 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, raise_if_billing_managed_by_partner+from ee.billing.billing_manager import (+ BillingManager,+ BillingServiceResponseError,+ http_session,+ raise_if_billing_managed_by_partner,+)from ee.billing.billing_types import USAGE_TYPE_VALUESfrom ee.billing.exports import ( # noqa: F401_EXPORT_STREAMS,@@ -118,6 +124,29 @@ class BillingServiceError(APIException):default_detail = "Billing could not answer this request. Try again in a moment."+class BillingManagedByProviderError(APIException):+ status_code = status.HTTP_400_BAD_REQUEST+ default_code = "billing_managed_by_provider"+ default_detail = "Billing for this organization is managed outside PostHog. Contact support to change your plan."+ default_type = "invalid_request"+++@contextmanager+def translate_managed_by_provider_refusal() -> Iterator[None]:+ try:+ yield+ except BillingServiceResponseError as error:+ body = error.body+ if (+ error.status_code != status.HTTP_400_BAD_REQUEST+ or not isinstance(body, dict)+ or body.get("code") != BillingManagedByProviderError.default_code+ ):+ raise+ message = body.get("error")+ raise BillingManagedByProviderError(message if isinstance(message, str) and message else None) from error++class BillingExportThrottle(PersonalApiKeyOrUserRateThrottle):"""How often one person may start an export. Each one has billing build a whole file."""@@ -285,6 +314,19 @@ def billing_managed_by_partner(organization: Organization | None) -> dict[str, sreturn {"partner_name": partner.name} if partner else None+def vercel_invoices_url(organization: Organization | None) -> str | None:+ if organization is None:+ return None+ vercel_integration = OrganizationIntegration.objects.filter(+ organization=organization,+ kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,+ ).first()+ if not vercel_integration or not vercel_integration.integration_id:+ return None+ account_url = vercel_integration.config.get("account", {}).get("url", "")+ return f"{account_url}/invoices" if account_url else None++class BillingSerializer(serializers.Serializer):plan = serializers.CharField(max_length=100)billing_limit = serializers.IntegerField()@@ -657,15 +699,9 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):query["include_forecasting"] = str(include_forecasting).lower()response = billing_manager.get_billing(org, query)- vercel_integration = OrganizationIntegration.objects.filter(- organization=org,- kind=OrganizationIntegration.OrganizationIntegrationKind.VERCEL,- ).first()-- if vercel_integration and vercel_integration.integration_id:- account_url = vercel_integration.config.get("account", {}).get("url", "")- if account_url:- response["external_billing_provider_invoices_url"] = f"{account_url}/invoices"+ invoices_url = vercel_invoices_url(org)+ if invoices_url:+ response["external_billing_provider_invoices_url"] = invoices_urlresponse["billing_managed_by_partner"] = billing_managed_by_partner(org)@@ -766,7 +802,8 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer = BillingActivationRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)data = {key: value for key, value in serializer.validated_data.items() if key != "organization_id"}- res = billing_manager.activate_subscription(organization, data)+ with translate_managed_by_provider_refusal():+ res = billing_manager.activate_subscription(organization, data)return Response(res, status=status.HTTP_200_OK)class DeactivateSerializer(serializers.Serializer):@@ -834,7 +871,14 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):organization = self._get_org_required()billing_manager = self.get_billing_manager()- res = billing_manager._get_stripe_portal_url(organization)+ try:+ with translate_managed_by_provider_refusal():+ res = billing_manager._get_stripe_portal_url(organization)+ except BillingManagedByProviderError:+ invoices_url = vercel_invoices_url(organization)+ if invoices_url is None:+ raise+ return redirect(invoices_url)return redirect(res)@action(methods=["GET"], detail=False)@@ -954,7 +998,8 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):organization = self._get_org_required()billing_manager = self.get_billing_manager()- res = billing_manager.authorize(organization)+ with translate_managed_by_provider_refusal():+ res = billing_manager.authorize(organization)return Response(res, status=status.HTTP_200_OK)@extend_schema(diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.pyindex dd1bc98b1a48..88b8fcc312ff 100644--- a/ee/api/test/test_billing.py+++ b/ee/api/test/test_billing.py@@ -28,6 +28,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_integration import OrganizationIntegrationfrom posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.project_secret_api_key import ProjectSecretAPIKey@@ -56,7 +57,7 @@ from ee.api.billing import (_stream_chunks,)from ee.api.test.base import APILicensedTest-from ee.billing.billing_manager import BillingManager+from ee.billing.billing_manager import BillingManager, BillingServiceResponseErrorfrom ee.billing.billing_types import USAGE_TYPE_OPTIONS, BillingPeriod, CustomerInfo, CustomerProduct, UsageTypefrom ee.billing.exports import _release_export_stream_slot, _take_export_stream_slotfrom ee.billing.grants import (@@ -68,6 +69,17 @@ from ee.billing.quota_limiting import QuotaResourcefrom ee.billing.test.test_billing_manager import create_default_products_responsefrom 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] = {@@ -1024,6 +1036,28 @@ class TestPortalBillingAPI(APILicensedTest):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):@@ -1049,6 +1083,30 @@ class TestActivateBillingAPI(APILicensedTest):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"),diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d9c2c2fc4d20..e1846e4756da 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -15154,6 +15154,14 @@ snapshots:hash: v1.k794b7964.9c4901f2fd036dde6005571c91a0614fbe86ed75692bef8c6b9eb46eaf500b93.-H-jk4ghSU02mUj-657ibApn_DE-SQibqIShQqlwtLoscenes-other-billing--billing-managed-by-partner--light:hash: v1.k794b7964.60287e6a945be4ebce959c34bc7806927268d678b473ec000d6ef104db3aa6c4.7yOxBzp7X6CqAfJStAvdccTo7MYJz9u9VOydRpU-iBI+ scenes-other-billing--billing-managed-by-vercel--dark:+ hash: v1.k794b7964.68344f009e863c11016ba1b8cd67115fd209f5dbfa8bcc9a7fd54dd04aae6464.FObRaJvaoO0UmEeme0s-vHv0e1glMIdCp8Nghm7Cer4+ scenes-other-billing--billing-managed-by-vercel--light:+ hash: v1.k794b7964.ea6cc3637b1a906cf63ea8df90981e93afc0e80ff08e267535c753186847690c.Hab7Ab-RJyG4pYXNFugGpnHUVBQPquA3PYJAtmb9Pbw+ scenes-other-billing--billing-managed-by-vercel-without-subscription--dark:+ hash: v1.k794b7964.9ac1320cbb5caa3a32874333b4ea79ec0e57f9976c053a475259fe6ad9cf4e77.EO-Vq9V9IX1OYOT54xoSmSJHRpQ2SoG2FgbaBFeFbtU+ scenes-other-billing--billing-managed-by-vercel-without-subscription--light:+ hash: v1.k794b7964.47f96c85dbfc75283077063514f7d22f15db67e03c155d791c2e734484e09020.yMoXHXlQWwXF2UP3pCtl6WU4CBwSRriWG98N2R9UUmYscenes-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 dd59e2d3edcf..6fd44691fd73 100644--- a/frontend/src/lib/components/BillingUpgradeCTA.tsx+++ b/frontend/src/lib/components/BillingUpgradeCTA.tsx@@ -7,11 +7,11 @@ import { billingLogic } from 'scenes/billing/billingLogic'export function BillingUpgradeCTA({ children, disabledReason, ...props }: LemonButtonProps): JSX.Element {const { reportBillingCTAShown } = useActions(eventUsageLogic)- const { billingManagedByPartnerDisabledReason } = useValues(billingLogic)+ const { selfServeBillingDisabledReason } = useValues(billingLogic)useOnMountEffect(reportBillingCTAShown)return (- <LemonButton {...props} disabledReason={billingManagedByPartnerDisabledReason || disabledReason}>+ <LemonButton {...props} disabledReason={selfServeBillingDisabledReason || disabledReason}>{children}</LemonButton>)diff --git a/frontend/src/lib/components/PayGateMini/payGateMiniLogic.test.ts b/frontend/src/lib/components/PayGateMini/payGateMiniLogic.test.tsindex fbf92273c79e..38e5774ea0f8 100644--- a/frontend/src/lib/components/PayGateMini/payGateMiniLogic.test.ts+++ b/frontend/src/lib/components/PayGateMini/payGateMiniLogic.test.ts@@ -8,36 +8,55 @@ 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 { AvailableFeature, BillingProvider, BillingType } from '~/types'import { payGateMiniLogic } from './payGateMiniLogic'describe('payGateMiniLogic', () => {- it.each([+ it.each<{+ name: string+ billing: Partial<BillingType>+ expected: { isPaymentEntryFlow: boolean; ctaDisabledReason: string | null }+ }>([{- name: 'disables the payment entry button',- subscriptionLevel: 'free' as const,+ name: 'disables the payment entry button when a partner manages billing',+ billing: {+ customer_id: '',+ subscription_level: 'free',+ billing_managed_by_partner: { partner_name: 'Example Partner' },+ },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,+ name: 'keeps the link to the billing page enabled when a partner manages billing',+ billing: {+ customer_id: '',+ subscription_level: 'paid',+ billing_managed_by_partner: { partner_name: 'Example Partner' },+ },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' },- }+ {+ name: 'disables the payment entry button when Vercel manages billing without an active subscription',+ billing: {+ subscription_level: 'free',+ has_active_subscription: false,+ billing_provider: BillingProvider.Vercel,+ },+ expected: {+ isPaymentEntryFlow: true,+ ctaDisabledReason:+ 'Billing for this organization is managed by Vercel. Contact support to change your plan.',+ },+ },+ ])('$name', async ({ billing, expected }) => {useMocks({get: {'/_preflight': [200, { ...preflightJson, cloud: true }],- '/api/billing': [200, billing],+ '/api/billing': [200, { ...billingJson, ...billing }],},})initKeaTests()diff --git a/frontend/src/lib/components/PayGateMini/payGateMiniLogic.tsx b/frontend/src/lib/components/PayGateMini/payGateMiniLogic.tsxindex 4476cf68deb2..561e87bb295e 100644--- a/frontend/src/lib/components/PayGateMini/payGateMiniLogic.tsx+++ b/frontend/src/lib/components/PayGateMini/payGateMiniLogic.tsx@@ -19,7 +19,7 @@ export type GateVariantType = 'add-card' | 'contact-sales' | 'move-to-cloud' | nexport interface payGateMiniLogicValues {billing: BillingType | null // billingLogicbillingLoading: boolean // billingLogic- billingManagedByPartnerDisabledReason: string | null // billingLogic+ selfServeBillingDisabledReason: string | null // billingLogicisCloudOrDev: boolean | undefined // preflightLogicavailableFeature: (feature: AvailableFeature) => BillingFeatureType | null | undefined // userLogichasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic@@ -101,10 +101,7 @@ export interface payGateMiniLogicMeta {isAddonProduct: boolean | undefined,billing: BillingType | null) => boolean- ctaDisabledReason: (- isPaymentEntryFlow: boolean,- billingManagedByPartnerDisabledReason: string | null- ) => string | null+ ctaDisabledReason: (isPaymentEntryFlow: boolean, selfServeBillingDisabledReason: string | null) => string | null}}@@ -122,7 +119,7 @@ export const payGateMiniLogic = kea<payGateMiniLogicType>([connect(() => ({values: [billingLogic,- ['billing', 'billingLoading', 'billingManagedByPartnerDisabledReason'],+ ['billing', 'billingLoading', 'selfServeBillingDisabledReason'],userLogic,['user', 'hasAvailableFeature', 'availableFeature'],preflightLogic,@@ -304,9 +301,9 @@ export const payGateMiniLogic = kea<payGateMiniLogicType>([},],ctaDisabledReason: [- (s) => [s.isPaymentEntryFlow, s.billingManagedByPartnerDisabledReason],- (isPaymentEntryFlow: boolean, billingManagedByPartnerDisabledReason: string | null): string | null =>- isPaymentEntryFlow ? billingManagedByPartnerDisabledReason : null,+ (s) => [s.isPaymentEntryFlow, s.selfServeBillingDisabledReason],+ (isPaymentEntryFlow: boolean, selfServeBillingDisabledReason: string | null): string | null =>+ isPaymentEntryFlow ? selfServeBillingDisabledReason : null,],})),])diff --git a/frontend/src/scenes/billing/Billing.stories.tsx b/frontend/src/scenes/billing/Billing.stories.tsxindex 96eefe9469fd..b821f7806804 100644--- a/frontend/src/scenes/billing/Billing.stories.tsx+++ b/frontend/src/scenes/billing/Billing.stories.tsx@@ -7,7 +7,7 @@ import billingJsonWith100PercentDiscount from '~/mocks/fixtures/_billing_with_10import billingJsonWithCredits from '~/mocks/fixtures/_billing_with_credits.json'import billingJsonWithDiscount from '~/mocks/fixtures/_billing_with_discount.json'import preflightJson from '~/mocks/fixtures/_preflight.json'-import { BillingType, StartupProgramLabel } from '~/types'+import { BillingProvider, BillingType, StartupProgramLabel } from '~/types'import { Billing } from './Billing'import { PurchaseCreditsModal } from './PurchaseCreditsModal'@@ -24,6 +24,8 @@ const billingJsonWithoutIconKeys: BillingType = {})),}+const VERCEL_INVOICES_URL = 'https://vercel.com/example-team/~/integrations/posthog/icfg_example/invoices'+const meta: Meta = {title: 'Scenes-Other/Billing',parameters: {@@ -84,6 +86,38 @@ export const BillingManagedByPartner: Story = {},}+export const BillingManagedByVercel: Story = {+ render: () => {+ useStorybookMocks({+ get: {+ '/api/billing/': {+ ...billingJson,+ billing_provider: BillingProvider.Vercel,+ external_billing_provider_invoices_url: VERCEL_INVOICES_URL,+ },+ },+ })++ return <Billing />+ },+}++export const BillingManagedByVercelWithoutSubscription: Story = {+ render: () => {+ useStorybookMocks({+ get: {+ '/api/billing/': {+ ...billingUnsubscribedJson,+ billing_provider: BillingProvider.Vercel,+ external_billing_provider_invoices_url: VERCEL_INVOICES_URL,+ },+ },+ })++ return <Billing />+ },+}+export const BillingOnStartupPlan: Story = {render: () => {useStorybookMocks({diff --git a/frontend/src/scenes/billing/Billing.tsx b/frontend/src/scenes/billing/Billing.tsxindex 45602b087c67..4894f1ecc56e 100644--- a/frontend/src/scenes/billing/Billing.tsx+++ b/frontend/src/scenes/billing/Billing.tsx@@ -60,6 +60,8 @@ export function Billing(): JSX.Element {canOnlyViewUsageAndSpend,hasSupportAddonPlan,billingManagedByPartnerNotice,+ billingManagedByVercelNotice,+ isBillingManagedByVercel,} = useValues(billingLogic)const { reportBillingShown } = useActions(billingLogic)const { preflight, isCloudOrDev } = useValues(preflightLogic)@@ -169,6 +171,12 @@ export function Billing(): JSX.Element {</LemonBanner>)}+ {billingManagedByVercelNotice && (+ <LemonBanner type="info" className="max-w-300 mb-2">+ {billingManagedByVercelNotice}+ </LemonBanner>+ )}+{billing?.trial ? (<LemonBanner type="info" hideIcon className="max-w-300 mb-2"><div className="flex items-center gap-4">@@ -271,7 +279,7 @@ export function Billing(): JSX.Element {))}<div>- {billing?.subscription_level == 'paid' && !!platformAndSupportProduct ? (+ {billing?.subscription_level == 'paid' && !!platformAndSupportProduct && !isBillingManagedByVercel ? (<><LemonDivider /><UnsubscribeCard product={platformAndSupportProduct} />diff --git a/frontend/src/scenes/billing/BillingProduct.tsx b/frontend/src/scenes/billing/BillingProduct.tsxindex 326da0d81d2a..c10b3d84fc68 100644--- a/frontend/src/scenes/billing/BillingProduct.tsx+++ b/frontend/src/scenes/billing/BillingProduct.tsx@@ -62,7 +62,7 @@ export const getTierDescription = (export const BillingProduct = ({ product }: { product: BillingProductV2Type }): JSX.Element | null => {const productRef = useRef<HTMLDivElement | null>(null)- const { billing, isUnlicensedDebug, isBillingManagedByPartner } = useValues(billingLogic)+ const { billing, isUnlicensedDebug, selfServeBillingDisabledReason } = useValues(billingLogic)const {hasCustomLimitSet,showTierBreakdown,@@ -549,7 +549,7 @@ export const BillingProduct = ({ product }: { product: BillingProductV2Type }):<div className="pb-8">{/* Add-ons title */}<h4 className="my-4">{addonSectionLabel}</h4>- {billing?.subscription_level == 'free' && !isBillingManagedByPartner && (+ {billing?.subscription_level == 'free' && !selfServeBillingDisabledReason && (<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 304b3f45c788..94c45f88c784 100644--- a/frontend/src/scenes/billing/BillingProductAddonActions.tsx+++ b/frontend/src/scenes/billing/BillingProductAddonActions.tsx@@ -60,7 +60,7 @@ export const BillingProductAddonActions = ({purchaseDisabledReason,onPurchaseClick,}: BillingProductAddonActionsProps): JSX.Element => {- const { billing, billingError, currentPlatformAddon, switchPlanLoading, billingManagedByPartnerDisabledReason } =+ const { billing, billingError, currentPlatformAddon, switchPlanLoading, selfServeBillingDisabledReason } =useValues(billingLogic)const { preflight } = useValues(preflightLogic)const {@@ -174,7 +174,7 @@ export const BillingProductAddonActions = ({size={buttonSize || 'small'}disableClientSideRoutingdisabledReason={- billingManagedByPartnerDisabledReason ||+ selfServeBillingDisabledReason ||(billingError && billingError.message) ||(billing?.subscription_level === 'free' && 'Upgrade to add add-ons') ||purchaseDisabledReason@@ -253,8 +253,7 @@ export const BillingProductAddonActions = ({<LemonButtonfullWidthdisabledReason={- billingManagedByPartnerDisabledReason ||- (switchPlanLoading ? 'Switching plans...' : undefined)+ selfServeBillingDisabledReason || (switchPlanLoading ? 'Switching plans...' : undefined)}onClick={() => {reportBillingAddonPlanSwitchStarted(currentPlatformAddon.type, addon.type, 'downgrade')@@ -293,7 +292,7 @@ export const BillingProductAddonActions = ({<LemonButtontype="primary"disabledReason={- billingManagedByPartnerDisabledReason || (switchPlanLoading ? 'Switching plans...' : undefined)+ selfServeBillingDisabledReason || (switchPlanLoading ? 'Switching plans...' : undefined)}onClick={() => {reportBillingAddonPlanSwitchStarted(currentPlatformAddon.type, addon.type, 'upgrade')@@ -332,7 +331,7 @@ export const BillingProductAddonActions = ({type="secondary"size="xsmall"loading={trialLoading || billingProductLoading === addon.type}- disabledReason={billingManagedByPartnerDisabledReason || purchaseDisabledReason}+ disabledReason={selfServeBillingDisabledReason || purchaseDisabledReason}tooltip="Local dev only — starts the self-serve trial. Never shown in production."onClick={() => {onPurchaseClick?.()diff --git a/frontend/src/scenes/billing/billing-utils.ts b/frontend/src/scenes/billing/billing-utils.tsindex a4d45fb53102..f840f8655016 100644--- a/frontend/src/scenes/billing/billing-utils.ts+++ b/frontend/src/scenes/billing/billing-utils.ts@@ -724,7 +724,7 @@ export function buildUsageLimitReachedMessage(products: Array<{ type?: string | null; name: string; subscribed: boolean | null }>,hasBillingAccess: boolean = true,minimumBillingAccessLevel: OrganizationMembershipLevel = OrganizationMembershipLevel.Admin,- billingManagedByPartnerNotice: string | null = null+ selfServeBillingNotice: string | null = null): {title: stringmessage: string@@ -743,10 +743,10 @@ export function buildUsageLimitReachedMessage(const consequenceText = consequences.join(' and ')const title = products.length === 1 ? 'Usage limit reached' : 'Usage limits reached'- if (billingManagedByPartnerNotice && !allSubscribed) {+ if (selfServeBillingNotice && !allSubscribed) {return {title,- message: `You have reached the usage limit for ${productListText}. ${capitalizeFirstLetter(consequenceText)}. ${billingManagedByPartnerNotice}`,+ message: `You have reached the usage limit for ${productListText}. ${capitalizeFirstLetter(consequenceText)}. ${selfServeBillingNotice}`,}}diff --git a/frontend/src/scenes/billing/billingLogic.test.ts b/frontend/src/scenes/billing/billingLogic.test.tsindex b49e33df1b35..42811bfa5231 100644--- a/frontend/src/scenes/billing/billingLogic.test.ts+++ b/frontend/src/scenes/billing/billingLogic.test.ts@@ -34,6 +34,10 @@ const creditOverviewResponse = {const EXTERNAL_INVOICES_URL = 'https://vercel.com/example-team/~/integrations/posthog/icfg_example/invoices'const HOSTED_INVOICE_URL = 'https://invoice.stripe.com/i/acct_example/test_example'const UNSUBSCRIBE_ERROR_DETAIL = 'Pay your open invoices first.'+const VERCEL_NOTICE =+ 'Billing for this organization is managed by Vercel, including the payment method and invoices. To cap your spend, set a billing limit on each product on this page.'+const VERCEL_DISABLED_REASON =+ 'Billing for this organization is managed by Vercel. Contact support to change your plan.'const productWithUsage = (percentageUsage: number,@@ -235,6 +239,11 @@ describe('billingLogic', () => {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.',},+ {+ name: 'Vercel-managed billing without an active subscription',+ billing: { billing_provider: BillingProvider.Vercel, has_active_subscription: false },+ expectedMessage: `You have reached the usage limit for Product analytics. Data loss may occur. ${VERCEL_DISABLED_REASON}`,+ },])('treats exactly 100% usage as a reached limit alert with $name', async ({ billing, expectedMessage }) => {billingState = { ...billingWithProducts([productWithUsage(1, { subscribed: false })]), ...billing }billingLogic.mount()@@ -297,6 +306,70 @@ describe('billingLogic', () => {})+ it.each<{+ name: string+ answer: [number, Partial<BillingType> | null]+ expected: {+ isBillingManagedByVercel: boolean+ billingManagedByVercelNotice: string | null+ billingManagedByVercelDisabledReason: string | null+ showBillingHero: boolean+ }+ }>([+ {+ name: 'Vercel with an active subscription',+ answer: [200, { ...billingJson, billing_provider: BillingProvider.Vercel, has_active_subscription: true }],+ expected: {+ isBillingManagedByVercel: true,+ billingManagedByVercelNotice: VERCEL_NOTICE,+ billingManagedByVercelDisabledReason: null,+ showBillingHero: true,+ },+ },+ {+ name: 'Vercel with no active subscription',+ answer: [200, { ...billingJson, billing_provider: BillingProvider.Vercel, has_active_subscription: false }],+ expected: {+ isBillingManagedByVercel: true,+ billingManagedByVercelNotice: VERCEL_DISABLED_REASON,+ billingManagedByVercelDisabledReason: VERCEL_DISABLED_REASON,+ showBillingHero: false,+ },+ },+ {+ name: 'PostHog with no active subscription',+ answer: [+ 200,+ { ...billingJson, billing_provider: BillingProvider.PostHog, has_active_subscription: false },+ ],+ expected: {+ isBillingManagedByVercel: false,+ billingManagedByVercelNotice: null,+ billingManagedByVercelDisabledReason: null,+ showBillingHero: true,+ },+ },+ {+ name: 'no billing loaded',+ answer: [200, null],+ expected: {+ isBillingManagedByVercel: false,+ billingManagedByVercelNotice: null,+ billingManagedByVercelDisabledReason: null,+ showBillingHero: false,+ },+ },+ ])('sets the Vercel billing selectors for $name', async ({ answer, expected }) => {+ billingAnswer = answer+ billingLogic.mount()++ await expectLogic(billingLogic, () => {+ billingLogic.actions.loadBilling()+ }).toFinishAllListeners()++ expect(billingLogic.values).toMatchObject(expected)+ })+// A companion has no billing limit, so its usage percentage must not raise a limit banner.it.each([['reached', 1.5],diff --git a/frontend/src/scenes/billing/billingLogic.tsx b/frontend/src/scenes/billing/billingLogic.tsxindex 9f91f1df75e0..a995ce1dfaa9 100644--- a/frontend/src/scenes/billing/billingLogic.tsx+++ b/frontend/src/scenes/billing/billingLogic.tsx@@ -223,6 +223,8 @@ export interface billingLogicValues {billingLoading: booleanbillingManagedByPartnerDisabledReason: string | nullbillingManagedByPartnerNotice: string | null+ billingManagedByVercelDisabledReason: string | null+ billingManagedByVercelNotice: string | nullbillingPeriodUTC: BillingPeriodbillingPlan: BillingPlan | nullcanAccessBilling: boolean@@ -273,6 +275,7 @@ export interface billingLogicValues {isActivateLicenseValid: booleanisAnnualPlanCustomer: booleanisBillingManagedByPartner: boolean+ isBillingManagedByVercel: booleanisCreditCTAHeroDismissed: booleanisCreditFormSubmitting: booleanisCreditFormValid: boolean@@ -293,6 +296,8 @@ export interface billingLogicValues {redirectPath: stringregisteredCustomLimitKeys: string[]scrollToProductKey: ProductKey | null+ selfServeBillingDisabledReason: string | null+ selfServeBillingNotice: string | nullshowActivateLicenseErrors: booleanshowBillingHero: booleanshowBillingSummary: boolean@@ -662,6 +667,23 @@ export interface billingLogicMeta {isBillingManagedByPartner: (billing: BillingType | null) => booleanbillingManagedByPartnerDisabledReason: (billing: BillingType | null) => string | nullbillingManagedByPartnerNotice: (billingManagedByPartnerDisabledReason: string | null) => string | null+ isBillingManagedByVercel: (billing: BillingType | null) => boolean+ billingManagedByVercelDisabledReason: (+ billing: BillingType | null,+ isBillingManagedByVercel: boolean+ ) => string | null+ billingManagedByVercelNotice: (+ isBillingManagedByVercel: boolean,+ billingManagedByVercelDisabledReason: string | null+ ) => string | null+ selfServeBillingDisabledReason: (+ billingManagedByPartnerDisabledReason: string | null,+ billingManagedByVercelDisabledReason: string | null+ ) => string | null+ selfServeBillingNotice: (+ billingManagedByPartnerNotice: string | null,+ billingManagedByVercelDisabledReason: string | null+ ) => string | nullshowCreditCTAHero: (creditOverview: {cc_last_four: null@@ -679,7 +701,7 @@ export interface billingLogicMeta {billing: BillingType | null,billingPlan: BillingPlan | null,showCreditCTAHero: boolean,- isBillingManagedByPartner: boolean+ selfServeBillingDisabledReason: string | null) => booleanisManagedAccount: (billing: BillingType | null) => booleanisExternallyBilled: (billing: BillingType | null) => boolean@@ -1284,6 +1306,43 @@ export const billingLogic = kea<billingLogicType>([? `${billingManagedByPartnerDisabledReason} Contact them to change your plan or payment details.`: null,],+ isBillingManagedByVercel: [+ (s) => [s.billing],+ (billing: BillingType | null): boolean => billing?.billing_provider === BillingProvider.Vercel,+ ],+ billingManagedByVercelDisabledReason: [+ (s) => [s.billing, s.isBillingManagedByVercel],+ (billing: BillingType | null, isBillingManagedByVercel: boolean): string | null =>+ isBillingManagedByVercel && !billing?.has_active_subscription+ ? 'Billing for this organization is managed by Vercel. Contact support to change your plan.'+ : null,+ ],+ billingManagedByVercelNotice: [+ (s) => [s.isBillingManagedByVercel, s.billingManagedByVercelDisabledReason],+ (isBillingManagedByVercel: boolean, billingManagedByVercelDisabledReason: string | null): string | null => {+ if (!isBillingManagedByVercel) {+ return null+ }+ return (+ billingManagedByVercelDisabledReason ??+ 'Billing for this organization is managed by Vercel, including the payment method and invoices. To cap your spend, set a billing limit on each product on this page.'+ )+ },+ ],+ selfServeBillingDisabledReason: [+ (s) => [s.billingManagedByPartnerDisabledReason, s.billingManagedByVercelDisabledReason],+ (+ billingManagedByPartnerDisabledReason: string | null,+ billingManagedByVercelDisabledReason: string | null+ ): string | null => billingManagedByPartnerDisabledReason ?? billingManagedByVercelDisabledReason,+ ],+ selfServeBillingNotice: [+ (s) => [s.billingManagedByPartnerNotice, s.billingManagedByVercelDisabledReason],+ (+ billingManagedByPartnerNotice: string | null,+ billingManagedByVercelDisabledReason: string | null+ ): string | null => billingManagedByPartnerNotice ?? billingManagedByVercelDisabledReason,+ ],showCreditCTAHero: [(s) => [s.creditOverview, s.isBillingManagedByPartner],(@@ -1304,17 +1363,22 @@ export const billingLogic = kea<billingLogicType>([},],showBillingHero: [- (s) => [s.billing, s.billingPlan, s.showCreditCTAHero, s.isBillingManagedByPartner],+ (s) => [s.billing, s.billingPlan, s.showCreditCTAHero, s.selfServeBillingDisabledReason],(billing: BillingType | null,billingPlan: BillingPlan | null,showCreditCTAHero: boolean,- isBillingManagedByPartner: boolean+ selfServeBillingDisabledReason: string | null): boolean => {const platformAndSupportProduct = billing?.products?.find((product) => product.type === ProductKey.PLATFORM_AND_SUPPORT)- return !!billingPlan && !!platformAndSupportProduct && !showCreditCTAHero && !isBillingManagedByPartner+ return (+ !!billingPlan &&+ !!platformAndSupportProduct &&+ !showCreditCTAHero &&+ !selfServeBillingDisabledReason+ )},],isManagedAccount: [@@ -1648,7 +1712,7 @@ export const billingLogic = kea<billingLogicType>([productsAtOrOverLimit,values.canAccessBilling,values.minimumBillingAccessLevel,- values.billingManagedByPartnerNotice+ values.selfServeBillingNotice)actions.setBillingAlert({diff --git a/frontend/src/scenes/billing/billingProductLogic.ts b/frontend/src/scenes/billing/billingProductLogic.tsindex 2dac8ba0964d..06c2d4c4ab40 100644--- a/frontend/src/scenes/billing/billingProductLogic.ts+++ b/frontend/src/scenes/billing/billingProductLogic.ts@@ -102,6 +102,7 @@ export interface billingProductLogicValues {isUnlicensedDebug: boolean // billingLogicplatformAddons: BillingProductV2AddonType[] // billingLogicscrollToProductKey: ProductKey | null // billingLogic+ selfServeBillingNotice: string | null // billingLogictimeRemainingInSeconds: number // billingLogictimeTotalInSeconds: number // billingLogicunsubscribeError: UnsubscribeError | null // billingLogic@@ -587,6 +588,7 @@ export const billingProductLogic = kea<billingProductLogicType>(['timeRemainingInSeconds','timeTotalInSeconds','unusedPlatformAddonAmount',+ 'selfServeBillingNotice',],featureFlagLogic,['featureFlags'],@@ -1304,6 +1306,10 @@ export const billingProductLogic = kea<billingProductLogicType>([},handleProductUpgrade: async ({ products, redirectPath }) => {try {+ if (values.selfServeBillingNotice) {+ lemonToast.info(values.selfServeBillingNotice)+ return+ }await paymentEntryLogic.asyncActions.upgradeProducts(products, redirectPath || null)} finally {actions.setBillingProductLoading(null)diff --git a/frontend/src/scenes/billing/paymentEntryLogic.test.ts b/frontend/src/scenes/billing/paymentEntryLogic.test.tsindex 5f7a0e9d65c3..a5a3d1081666 100644--- a/frontend/src/scenes/billing/paymentEntryLogic.test.ts+++ b/frontend/src/scenes/billing/paymentEntryLogic.test.ts@@ -17,7 +17,7 @@ import { userLogic } from 'scenes/userLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { AvailableFeature, BillingType } from '~/types'+import { AvailableFeature, BillingProvider, BillingType } from '~/types'const OTHER_ORGANIZATION_ID = '00000000-0000-4000-8000-000000000002'@@ -238,12 +238,26 @@ describe('paymentEntryLogic', () => {})})- 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' },- })+ describe('startPaymentEntryFlow — billing locked outside PostHog', () => {+ it.each<{ name: string; billing: Partial<BillingType> }>([+ {+ name: 'a partner manages billing',+ billing: {+ subscription_level: 'free',+ billing_managed_by_partner: { partner_name: 'Example Partner' },+ },+ },+ {+ name: 'Vercel bills an organization with no active subscription',+ billing: {+ customer_id: 'cus_test',+ subscription_level: 'free',+ has_active_subscription: false,+ billing_provider: BillingProvider.Vercel,+ },+ },+ ])('neither activates nor opens the payment modal when $name', async ({ billing }) => {+ await seedBilling(billing)const activate = jest.fn(() => [200, { success: true }] as [number, Record<string, unknown>])useMocks({ post: { '/api/billing/activate': activate } })logic = paymentEntryLogic()diff --git a/frontend/src/scenes/billing/paymentEntryLogic.ts b/frontend/src/scenes/billing/paymentEntryLogic.tsindex d744b8f13fec..d236a53c34c9 100644--- a/frontend/src/scenes/billing/paymentEntryLogic.ts+++ b/frontend/src/scenes/billing/paymentEntryLogic.ts@@ -436,9 +436,9 @@ export const paymentEntryLogic = kea<paymentEntryLogicType>([window.location.href = urls.organizationBilling()},startPaymentEntryFlow: async ({ product, redirectPath }) => {- const { billing, billingManagedByPartnerNotice } = billingLogic.values- if (billingManagedByPartnerNotice) {- lemonToast.info(billingManagedByPartnerNotice)+ const { billing, selfServeBillingNotice } = billingLogic.values+ if (selfServeBillingNotice) {+ lemonToast.info(selfServeBillingNotice)return}const organizationId = startFlow(redirectPath || null)diff --git a/frontend/src/scenes/startups/StartupProgram.tsx b/frontend/src/scenes/startups/StartupProgram.tsxindex 986bb013f7b1..709aa67c5f3c 100644--- a/frontend/src/scenes/startups/StartupProgram.tsx+++ b/frontend/src/scenes/startups/StartupProgram.tsx@@ -78,7 +78,7 @@ function BillingUpgradeButton({}: {platformAndSupportProduct: BillingProductV2Type}): JSX.Element {- const { billing, billingManagedByPartnerDisabledReason } = useValues(billingLogic)+ const { billing, selfServeBillingDisabledReason } = useValues(billingLogic)const { startPaymentEntryFlow } = useActions(paymentEntryLogic)const { billingProductLoading } = useValues(billingProductLogic({ product: platformAndSupportProduct }))const { reportBillingCTAShown } = useActions(eventUsageLogic)@@ -90,7 +90,7 @@ function BillingUpgradeButton({size="lg"data-attr="startup-program-upgrade-cta"loading={!!billingProductLoading}- disabled={!!billingManagedByPartnerDisabledReason}+ disabled={!!selfServeBillingDisabledReason}onClick={() =>startPaymentEntryFlow(platformAndSupportProduct, window.location.pathname + window.location.search)}@@ -99,11 +99,11 @@ function BillingUpgradeButton({</Button>)- if (billingManagedByPartnerDisabledReason) {+ if (selfServeBillingDisabledReason) {return (<Tooltip><TooltipTrigger render={button} />- <TooltipContent>{billingManagedByPartnerDisabledReason}</TooltipContent>+ <TooltipContent>{selfServeBillingDisabledReason}</TooltipContent></Tooltip>)}