Skip to content

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

fix(billing): bind payment flows to the selected organization (#112506)

Roy Cohen5ee244d4cf97
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index edab1eb29815..fcbfb84e26fe 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -301,6 +301,14 @@ This also applies to the organization usage/spend time-series endpoints and CSV
The billing overview, usage, and spend tools do not need a rollout flag.
API scopes and billing access checks still apply.
+The underlying root billing API also supports an optional `organization_id` UUID on overview reads.
+Use it when refreshing billing after a payment so another tab changing the user's current project cannot change the target.
+The `billing-overview-get` tool does not expose it.
+Subscription activation, payment authorization, and authorization status requests require an explicit `organization_id` in the body.
+They reject missing or invalid IDs rather than falling back to the current project, and require billing access in the requested organization.
+These payment actions remain unavailable to personal API keys and OAuth tokens.
+The browser keeps the organization through Stripe redirects; payment links from older clients must be restarted from billing.
+
System tables are defined in [`posthog/hogql/database/schema/system.py`](https://github.com/PostHog/posthog/blob/master/posthog/hogql/database/schema/system.py) as `PostgresTable` instances.
Each table must include a `team_id` column for data isolation.
diff --git a/ee/api/billing.py b/ee/api/billing.py
index d1aabb45b28c..dd1bfadcc837 100644
--- a/ee/api/billing.py
+++ b/ee/api/billing.py
@@ -2,7 +2,8 @@ import re
import json
from collections.abc import Callable, Sequence
from datetime import timedelta
-from typing import Any, NoReturn, Optional, cast
+from typing import Any, Literal, NoReturn, Optional, cast
+from uuid import UUID
from zoneinfo import ZoneInfo
from django.conf import settings
@@ -19,7 +20,10 @@ from rest_framework import permissions, serializers, status, viewsets
from rest_framework.exceptions import APIException, NotFound, PermissionDenied, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
+from rest_framework_extensions.settings import extensions_api_settings
+from posthog.api.fields import OptionalBooleanField
+from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.streaming import streaming_response
from posthog.api.utils import action
@@ -541,11 +545,63 @@ class BillingPeriodResponseSerializer(serializers.Serializer):
)
+class BillingPaymentOrganizationSerializer(serializers.Serializer):
+ organization_id = serializers.UUIDField(help_text="Organization selected when this payment flow started.")
+
+ def validate_organization_id(self, value: UUID) -> UUID:
+ if not isinstance(self.initial_data.get("organization_id"), str):
+ raise serializers.ValidationError("A UUID string is required.")
+ return value
+
+
+class BillingOverviewRequestSerializer(serializers.Serializer):
+ organization_id = serializers.UUIDField(required=False, help_text="Explicit organization to refresh after payment.")
+ include_forecasting = OptionalBooleanField(required=False, help_text="Whether to include usage forecasting.")
+
+
+class BillingActivationRequestSerializer(BillingPaymentOrganizationSerializer):
+ products = serializers.CharField(required=False, help_text="Product and plan keys to activate.")
+ intent_product = serializers.CharField(required=False, help_text="Product that prompted the subscription upgrade.")
+ custom_limits_usd = serializers.CharField(
+ required=False, allow_blank=True, help_text="JSON-encoded custom product limits to apply on activation."
+ )
+
+
+class BillingActivationResponseSerializer(serializers.Serializer):
+ success = serializers.BooleanField(required=False, help_text="Whether the subscription was activated.")
+ must_setup_payment = serializers.BooleanField(required=False, help_text="Whether payment details are required.")
+ products = serializers.ListField(
+ child=serializers.CharField(), required=False, help_text="Products activated by this request."
+ )
+ error = serializers.CharField(required=False, allow_null=True, help_text="Reason activation failed.")
+
+
+class BillingAuthorizationResponseSerializer(serializers.Serializer):
+ clientSecret = serializers.CharField(required=False, help_text="Stripe client secret for the authorization intent.")
+ success = serializers.BooleanField(
+ required=False, help_text="Whether authorization completed without a payment form."
+ )
+
+
+class BillingAuthorizationStatusRequestSerializer(BillingPaymentOrganizationSerializer):
+ payment_intent_id = serializers.CharField(
+ required=False, allow_null=True, help_text="Stripe payment intent created for this organization."
+ )
+
+
+class BillingAuthorizationStatusResponseSerializer(serializers.Serializer):
+ status = serializers.CharField(required=False, help_text="Authorization status: loading, success, or failed.")
+ error = serializers.CharField(required=False, allow_null=True, help_text="Reason authorization failed.")
+ success = serializers.BooleanField(
+ required=False, help_text="Whether authorization completed without a payment form."
+ )
+
+
@extend_schema(tags=["billing"])
class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
serializer_class = BillingSerializer
pagination_class = None
- param_derived_from_user_current_team = "team_id"
+ param_derived_from_user_current_team: Literal["team_id", "project_id"] | None = "team_id"
scope_object = "billing"
scope_object_read_actions = ["list", "usage", "spend", "usage_export", "spend_export", "usage_team_options"]
@@ -554,13 +610,32 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# Billing opts in so generated clients and MCP scaffolding include these read actions.
force_include_in_api_docs = True
+ payment_actions = {"activate", "authorize", "authorize_status"}
+
+ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:
+ scoped_billing_read = self.action == "list" and "organization_id" in request.query_params
+ if self.action in self.payment_actions or scoped_billing_read:
+ serializer = BillingPaymentOrganizationSerializer(
+ data=request.query_params if scoped_billing_read else request.data
+ )
+ serializer.is_valid(raise_exception=True)
+ # Configure normal organization scope before shared permissions resolve any cached
+ # routing properties. The user's current project can change in another browser tab.
+ self.param_derived_from_user_current_team = None
+ parent_prefix = extensions_api_settings.DEFAULT_PARENT_LOOKUP_KWARG_NAME_PREFIX
+ self.kwargs[f"{parent_prefix}organization_id"] = str(serializer.validated_data["organization_id"])
+ super().initial(request, *args, **kwargs)
+
def get_billing_manager(self) -> BillingManager:
license = get_cached_instance_license()
user = self.request.user if isinstance(self.request.user, User) and self.request.user.distinct_id else None
return BillingManager(license, user, ip_address=get_trusted_client_ip(self.request))
- @extend_schema(responses={200: OpenApiResponse(response=BillingOverviewResponseSerializer)})
- def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ @validated_request(
+ query_serializer=BillingOverviewRequestSerializer,
+ responses={200: OpenApiResponse(response=BillingOverviewResponseSerializer)},
+ )
+ def list(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
license = get_cached_instance_license()
if license and not license.is_v2_license:
raise NotFound("Billing is not supported for this license type")
@@ -577,8 +652,9 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
billing_manager = self.get_billing_manager()
query = {}
- if "include_forecasting" in request.query_params:
- query["include_forecasting"] = request.query_params.get("include_forecasting")
+ include_forecasting = request.validated_query_data.get("include_forecasting")
+ if include_forecasting is not None:
+ query["include_forecasting"] = str(include_forecasting).lower()
response = billing_manager.get_billing(org, query)
vercel_integration = OrganizationIntegration.objects.filter(
@@ -678,6 +754,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return self.list(request, *args, **kwargs)
+ @extend_schema(request=BillingActivationRequestSerializer, responses={200: BillingActivationResponseSerializer})
@action(
methods=["POST"],
detail=False,
@@ -686,7 +763,10 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
def activate(self, request: Request, *args: Any, **kwargs: Any) -> Response:
organization = self._get_org_required()
billing_manager = self.get_billing_manager()
- res = billing_manager.activate_subscription(organization, request.data)
+ 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)
return Response(res, status=status.HTTP_200_OK)
class DeactivateSerializer(serializers.Serializer):
@@ -855,11 +935,14 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
res = billing_manager.cancel_trial(organization, request.data)
return Response(res, status=status.HTTP_200_OK)
+ @extend_schema(
+ request=BillingPaymentOrganizationSerializer, responses={200: BillingAuthorizationResponseSerializer}
+ )
@action(
methods=["POST"],
detail=False,
url_path="activate/authorize",
- permission_classes=[permissions.IsAuthenticated, BillingNotManagedByPartner],
+ permission_classes=[permissions.IsAuthenticated, HasBillingAccess, BillingNotManagedByPartner],
)
def authorize(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:
license = get_cached_instance_license()
@@ -874,7 +957,16 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
res = billing_manager.authorize(organization)
return Response(res, status=status.HTTP_200_OK)
- @action(methods=["POST"], detail=False, url_path="activate/authorize/status")
+ @extend_schema(
+ request=BillingAuthorizationStatusRequestSerializer,
+ responses={200: BillingAuthorizationStatusResponseSerializer},
+ )
+ @action(
+ methods=["POST"],
+ detail=False,
+ url_path="activate/authorize/status",
+ permission_classes=[permissions.IsAuthenticated, HasBillingAccess],
+ )
def authorize_status(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:
license = get_cached_instance_license()
if not license:
@@ -885,7 +977,10 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
organization = self._get_org_required()
billing_manager = self.get_billing_manager()
- res = billing_manager.authorize_status(organization, request.data)
+ serializer = BillingAuthorizationStatusRequestSerializer(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.authorize_status(organization, data)
return Response(res, status=status.HTTP_200_OK)
@action(
@@ -1332,6 +1427,10 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return None
try:
+ if self.action in self.payment_actions or (
+ self.action == "list" and "organization_id" in self.request.query_params
+ ):
+ return self.organization
return self.team.organization
except Exception:
return None
diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.py
index 9d78af867698..dd1bc98b1a48 100644
--- a/ee/api/test/test_billing.py
+++ b/ee/api/test/test_billing.py
@@ -48,6 +48,7 @@ from ee.api.billing import (
BillingQueryTooLarge,
BillingUsageRequestSerializer,
BillingViewset,
+ HasBillingAccess,
HasBillingUsageSpendReadAccess,
_gzip_stream,
_resolve_team_labels,
@@ -899,9 +900,20 @@ class TestBillingAPI(APILicensedTest):
"surveys": 0,
}
+ @parameterized.expand(
+ [
+ (None, {}),
+ ("true", {"include_forecasting": "true"}),
+ ("false", {"include_forecasting": "false"}),
+ ("1", {"include_forecasting": "true"}),
+ ("0", {"include_forecasting": "false"}),
+ ]
+ )
@patch("ee.billing.billing_manager.http_session.get")
- def test_billing_with_supported_params(self, mock_get):
- """Test that the include_forecasting param is passed through to the billing service."""
+ def test_billing_with_supported_params(
+ self, include_forecasting: str | None, expected_params: dict[str, str], mock_get: MagicMock
+ ) -> None:
+ """Normalize explicit forecasting values and preserve the downstream default when omitted."""
def mock_implementation(url: str, headers: Any = None, params: Any = None) -> MagicMock:
mock = MagicMock()
@@ -918,7 +930,8 @@ class TestBillingAPI(APILicensedTest):
mock_get.side_effect = mock_implementation
- response = self.client.get("/api/billing/?include_forecasting=true")
+ params = {} if include_forecasting is None else {"include_forecasting": include_forecasting}
+ response = self.client.get("/api/billing/", params)
assert response.status_code == 200
# Verify the billing service was called with the correct query param
@@ -928,7 +941,14 @@ class TestBillingAPI(APILicensedTest):
if "api/billing" in call[0][0] and "api/billing/portal" not in call[0][0]
]
assert len(billing_calls) == 1
- assert billing_calls[0].kwargs["params"] == {"include_forecasting": "true"}
+ assert billing_calls[0].kwargs["params"] == expected_params
+
+ @patch("ee.billing.billing_manager.BillingManager.get_billing")
+ def test_billing_rejects_malformed_forecasting_param(self, mock_get_billing: MagicMock) -> None:
+ response = self.client.get("/api/billing/", {"include_forecasting": "invalid"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ mock_get_billing.assert_not_called()
@patch("ee.billing.billing_manager.BillingManager.get_billing")
@patch("ee.billing.billing_manager.BillingManager.update_billing")
@@ -1016,7 +1036,7 @@ class TestActivateBillingAPI(APILicensedTest):
mock_activate_subscription.return_value = {"success": True, "products": ["product_analytics"]}
url = "/api/billing/activate"
- data = {"products": "all_products:"}
+ data = {"organization_id": str(self.organization.id), "products": "all_products:"}
response = self.client.post(url, data, content_type="application/json")
@@ -1029,6 +1049,190 @@ 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", "activate_subscription"),
+ ("activate/authorize", "authorize"),
+ ("activate/authorize/status", "authorize_status"),
+ ]
+ )
+ @patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=False)
+ def test_payment_targets_explicit_organization_after_current_team_changes(
+ self, action: str, manager_method: str, _flag: MagicMock
+ ) -> None:
+ other_org = Organization.objects.create(name="Another organization")
+ other_team = Team.objects.create(organization=other_org, name="Another project")
+ OrganizationMembership.objects.create(
+ organization=other_org, user=self.user, level=OrganizationMembership.Level.ADMIN
+ )
+ self.user.current_organization = other_org
+ self.user.current_team = other_team
+ self.user.save()
+ with patch.object(BillingManager, manager_method, return_value={"success": True}) as manager:
+ response = self.client.post(
+ f"/api/billing/{action}",
+ {
+ "organization_id": str(self.organization.id),
+ "products": "all_products:",
+ "payment_intent_id": "pi_test",
+ },
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert manager.call_args.args[0] == self.organization
+
+ @parameterized.expand(
+ [
+ (action, manager_method, level, owner_only, expected)
+ for action, manager_method in [
+ ("activate", "activate_subscription"),
+ ("activate/authorize", "authorize"),
+ ("activate/authorize/status", "authorize_status"),
+ ]
+ for level, owner_only, expected in [
+ (OrganizationMembership.Level.MEMBER, False, 403),
+ (OrganizationMembership.Level.ADMIN, False, 200),
+ (OrganizationMembership.Level.ADMIN, True, 403),
+ (OrganizationMembership.Level.ADMIN, None, 403),
+ (OrganizationMembership.Level.OWNER, True, 200),
+ ]
+ ]
+ )
+ def test_payment_respects_requested_organization_billing_access(
+ self, action: str, manager_method: str, level: int, owner_only: bool | None, expected: int
+ ) -> None:
+ self.organization_membership.level = level
+ self.organization_membership.save()
+ with (
+ patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=owner_only),
+ patch.object(BillingManager, manager_method, return_value={"success": True}) as manager,
+ ):
+ response = self.client.post(
+ f"/api/billing/{action}",
+ {"organization_id": str(self.organization.id)},
+ content_type="application/json",
+ )
+ assert response.status_code == expected
+ assert manager.call_count == (1 if expected == 200 else 0)
+
+ @parameterized.expand(
+ [
+ (action, value)
+ for action in ["activate", "activate/authorize", "activate/authorize/status"]
+ for value in [None, "", "@current", "invalid", 123]
+ ]
+ )
+ def test_payment_requires_concrete_organization_id(self, action: str, value: Any) -> None:
+ with patch("ee.api.billing.BillingManager") as manager:
+ data = {} if value is None else {"organization_id": value}
+ response = self.client.post(f"/api/billing/{action}", data, content_type="application/json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ manager.assert_not_called()
+
+ @parameterized.expand(["activate", "activate/authorize", "activate/authorize/status"])
+ def test_payment_denies_foreign_organization(self, action: str) -> None:
+ organization = Organization.objects.create(name="Foreign organization")
+ with patch("ee.api.billing.BillingManager") as manager:
+ response = self.client.post(
+ f"/api/billing/{action}", {"organization_id": str(organization.id)}, content_type="application/json"
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ manager.assert_not_called()
+
+ @parameterized.expand(["activate", "activate/authorize", "activate/authorize/status"])
+ def test_payment_denies_member_of_target_when_admin_of_current_organization(self, action: str) -> None:
+ organization = Organization.objects.create(name="Member organization")
+ OrganizationMembership.objects.create(
+ organization=organization, user=self.user, level=OrganizationMembership.Level.MEMBER
+ )
+ with patch("ee.api.billing.BillingManager") as manager:
+ response = self.client.post(
+ f"/api/billing/{action}", {"organization_id": str(organization.id)}, content_type="application/json"
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ manager.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("activate", "activate_subscription"),
+ ("activate/authorize", "authorize"),
+ ("activate/authorize/status", "authorize_status"),
+ ]
+ )
+ @patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=False)
+ def test_payment_preserves_token_access_restrictions(
+ self, action: str, manager_method: str, _flag: MagicMock
+ ) -> None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Payment test",
+ user=self.user,
+ secure_value=hash_key_value(token),
+ scopes=["*"],
+ scoped_organizations=[str(self.organization.id)],
+ )
+ self.client.logout()
+ with patch.object(BillingManager, manager_method, return_value={"success": True}) as manager:
+ response = self.client.post(
+ f"/api/billing/{action}",
+ {"organization_id": str(self.organization.id)},
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json()["detail"] == "This action does not support personal API key access"
+ manager.assert_not_called()
+
+ @patch("ee.billing.billing_manager.BillingManager.get_billing")
+ def test_payment_refresh_reads_original_organization_after_current_team_changes(self, manager: MagicMock) -> None:
+ organization = Organization.objects.create(name="Another organization")
+ team = Team.objects.create(organization=organization, name="Another project")
+ OrganizationMembership.objects.create(
+ organization=organization, user=self.user, level=OrganizationMembership.Level.ADMIN
+ )
+ self.user.current_team = team
+ self.user.current_organization = organization
+ self.user.save()
+ manager.return_value = {"products": [], "available_product_features": []}
+ response = self.client.get("/api/billing", {"organization_id": str(self.organization.id)})
+ assert response.status_code == status.HTTP_200_OK
+ manager.assert_called_once_with(self.organization, {})
+
+ @parameterized.expand(["", "@current", "invalid"])
+ def test_explicit_billing_refresh_rejects_invalid_organization(self, organization_id: str) -> None:
+ with patch("ee.api.billing.BillingManager") as manager:
+ response = self.client.get("/api/billing", {"organization_id": organization_id})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ manager.assert_not_called()
+
+ @patch("ee.billing.grants.posthog_feature_flag_enabled", return_value=False)
+ def test_explicit_billing_refresh_enforces_token_organization_scope(self, _flag: MagicMock) -> None:
+ organization = Organization.objects.create(name="Other permitted organization")
+ OrganizationMembership.objects.create(
+ organization=organization, user=self.user, level=OrganizationMembership.Level.ADMIN
+ )
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="Scoped billing",
+ user=self.user,
+ secure_value=hash_key_value(token),
+ scopes=["billing:read"],
+ scoped_organizations=[str(self.organization.id)],
+ )
+ self.client.logout()
+ with patch.object(
+ BillingManager, "get_billing", return_value={"products": [], "available_product_features": []}
+ ) as manager:
+ allowed = self.client.get(
+ "/api/billing", {"organization_id": str(self.organization.id)}, HTTP_AUTHORIZATION=f"Bearer {token}"
+ )
+ refused = self.client.get(
+ "/api/billing", {"organization_id": str(organization.id)}, HTTP_AUTHORIZATION=f"Bearer {token}"
+ )
+ assert allowed.status_code == status.HTTP_200_OK
+ assert refused.status_code == status.HTTP_403_FORBIDDEN
+ manager.assert_called_once_with(self.organization, {})
+
@patch("ee.billing.billing_manager.BillingManager.deactivate_products")
@patch("ee.billing.billing_manager.BillingManager.get_billing")
def test_deactivate_success(self, mock_get_billing, mock_deactivate_products):
@@ -1268,12 +1472,17 @@ class TestPartnerManagedBillingAPI(APILicensedTest):
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)
+ data = (
+ {"organization_id": str(self.organization.id)}
+ if _name.startswith("activate") or _name == "authorize"
+ else {}
+ )
+ allowed = getattr(self.client, method)(url, data)
application.update_provisioning(pays_for_customers=True)
- refused = getattr(self.client, method)(url)
+ refused = getattr(self.client, method)(url, data)
self.organization.customer_id = "cus_example"
self.organization.save(update_fields=["customer_id"])
- self_billed = getattr(self.client, method)(url)
+ self_billed = getattr(self.client, method)(url, data)
assert (allowed.status_code, refused.status_code, self_billed.status_code) == (
allowed_status,
@@ -1314,6 +1523,18 @@ class TestPartnerManagedBillingAPI(APILicensedTest):
assert response.json()["billing_managed_by_partner"] == expected
+def _billing_action_permission_classes() -> dict[str, Sequence[object]]:
+ viewset_default = BillingViewset.permission_classes
+ declared_permissions: dict[str, Sequence[object]] = {
+ action.__name__: getattr(action, "kwargs", {}).get("permission_classes", viewset_default)
+ for action in BillingViewset.get_extra_actions()
+ }
+ for standard_action in ("list", "create", "retrieve", "update", "partial_update", "destroy"):
+ if hasattr(BillingViewset, standard_action):
+ declared_permissions[standard_action] = viewset_default
+ return declared_permissions
+
+
class TestPartnerBillingLockCoverage(SimpleTestCase):
READ_ONLY_ACTIONS = {
"list",
@@ -1338,19 +1559,27 @@ class TestPartnerBillingLockCoverage(SimpleTestCase):
}
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
-
+ declared_permissions = _billing_action_permission_classes()
unlocked = {name for name, classes in declared_permissions.items() if BillingNotManagedByPartner not in classes}
assert unlocked == self.READ_ONLY_ACTIONS | self.UNLOCKED_WRITE_ACTIONS
+class TestBillingAccessCoverage(SimpleTestCase):
+ MEMBER_READ_ACTIONS = {"list", "period", "get_invoices", "credits_overview", "coupons_overview"}
+ USAGE_SPEND_READ_ACTIONS = {"usage", "usage_team_options", "spend", "usage_export", "spend_export"}
+ CHECKS_ACCESS_IN_METHOD_ACTIONS = {"apply_startup_program"}
+
+ def test_every_billing_action_requires_billing_access_or_is_explicitly_exempt(self) -> None:
+ without_access = {
+ name for name, classes in _billing_action_permission_classes().items() if HasBillingAccess not in classes
+ }
+ exempt = self.MEMBER_READ_ACTIONS | self.USAGE_SPEND_READ_ACTIONS | self.CHECKS_ACCESS_IN_METHOD_ACTIONS
+
+ assert without_access <= exempt, f"Add HasBillingAccess to {sorted(without_access - exempt)} or list as exempt"
+ assert exempt <= without_access, f"Remove {sorted(exempt - without_access)} from the exempt sets"
+
+
class TestBillingUsageRequestSerializer(SimpleTestCase):
def test_valid_dates(self):
serializer = BillingUsageRequestSerializer(data={"start_date": "2025-01-01", "end_date": "2025-01-31"})
@@ -2656,6 +2885,8 @@ class TestBillingPermissionDeniedForMembers(APILicensedTest):
def test_permission_denied(self, _name, method, url, data, expected_detail):
if data == "USE_ORG_ID":
data = {"organization_id": str(self.organization.id)}
+ if _name == "activate":
+ data = {**data, "organization_id": str(self.organization.id)}
client_method = getattr(self.client, method)
if data is not None:
kwargs = {"data": data}
diff --git a/frontend/src/scenes/billing/AuthorizationStatus.test.tsx b/frontend/src/scenes/billing/AuthorizationStatus.test.tsx
new file mode 100644
index 000000000000..8f6e205ab971
--- /dev/null
+++ b/frontend/src/scenes/billing/AuthorizationStatus.test.tsx
@@ -0,0 +1,32 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { initKeaTests } from '~/test/init'
+
+import { AuthorizationStatus } from './AuthorizationStatus'
+
+describe('AuthorizationStatus', () => {
+ beforeEach(() => {
+ initKeaTests()
+ window.history.replaceState({}, '', '/billing/authorization_status?payment_intent=pi_old')
+ })
+
+ afterEach(() => {
+ cleanup()
+ window.history.replaceState({}, '', '/')
+ })
+
+ it('shows a way back to billing for an old callback without an organization', async () => {
+ render(
+ <Provider>
+ <AuthorizationStatus />
+ </Provider>
+ )
+ expect(
+ await screen.findByText('This payment link is missing its organization. Return to billing and start again.')
+ ).toBeInTheDocument()
+ expect(screen.getByText('Return to billing').closest('a')).toHaveAttribute('href', '/organization/billing')
+ })
+})
diff --git a/frontend/src/scenes/billing/AuthorizationStatus.tsx b/frontend/src/scenes/billing/AuthorizationStatus.tsx
index 1c38e922321b..b0fd10040758 100644
--- a/frontend/src/scenes/billing/AuthorizationStatus.tsx
+++ b/frontend/src/scenes/billing/AuthorizationStatus.tsx
@@ -1,16 +1,32 @@
-import { useActions } from 'kea'
+import { useActions, useValues } from 'kea'
-import { SpinnerOverlay } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { urls } from 'scenes/urls'
+import { PaymentCompletion } from './PaymentCompletion'
import { paymentEntryLogic } from './paymentEntryLogic'
// note(@zach): this page is only used when a payment method is entered into the payment entry modal
// that requires the user to be redirect to another url, this is where they get redirected back to
export const AuthorizationStatus = (): JSX.Element => {
const { pollAuthorizationStatus } = useActions(paymentEntryLogic)
+ const { apiError, stripeError, completedPaymentOrganization } = useValues(paymentEntryLogic)
useOnMountEffect(pollAuthorizationStatus)
+ if (completedPaymentOrganization) {
+ return <PaymentCompletion />
+ }
+ if (apiError || stripeError) {
+ return (
+ <LemonBanner type="error">
+ <p>{apiError || stripeError}</p>
+ <LemonButton to={urls.organizationBilling()} type="primary">
+ Return to billing
+ </LemonButton>
+ </LemonBanner>
+ )
+ }
return <SpinnerOverlay sceneLevel />
}
diff --git a/frontend/src/scenes/billing/PaymentCompletion.tsx b/frontend/src/scenes/billing/PaymentCompletion.tsx
new file mode 100644
index 000000000000..19d993759970
--- /dev/null
+++ b/frontend/src/scenes/billing/PaymentCompletion.tsx
@@ -0,0 +1,21 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { paymentEntryLogic } from './paymentEntryLogic'
+
+export const PaymentCompletion = (): JSX.Element | null => {
+ const { completedPaymentOrganization } = useValues(paymentEntryLogic)
+ const { viewCompletedPaymentOrganization } = useActions(paymentEntryLogic)
+ if (!completedPaymentOrganization) {
+ return null
+ }
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonBanner type="success">Payment setup completed for {completedPaymentOrganization.name}</LemonBanner>
+ <LemonButton type="primary" onClick={viewCompletedPaymentOrganization}>
+ View {completedPaymentOrganization.name}’s billing
+ </LemonButton>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/billing/PaymentEntryModal.test.tsx b/frontend/src/scenes/billing/PaymentEntryModal.test.tsx
index 952d14853ebd..018bdd029938 100644
--- a/frontend/src/scenes/billing/PaymentEntryModal.test.tsx
+++ b/frontend/src/scenes/billing/PaymentEntryModal.test.tsx
@@ -1,32 +1,70 @@
/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */
import '@testing-library/jest-dom'
-import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Provider } from 'kea'
import { supportLogic } from 'lib/components/Support/supportLogic'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { paymentEntryLogic } from 'scenes/billing/paymentEntryLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { PaymentEntryModal } from './PaymentEntryModal'
+import { paymentEntryLogic } from './paymentEntryLogic'
+import { PaymentEntryModal, PaymentForm } from './PaymentEntryModal'
+
+const mockConfirmPayment = jest.fn((_: { confirmParams: { return_url: string } }) => new Promise(() => {}))
+
+jest.mock('@stripe/react-stripe-js', () => ({
+ PaymentElement: () => null,
+ useStripe: () => ({ confirmPayment: mockConfirmPayment }),
+ useElements: () => ({}),
+}))
const BLOCKED_MESSAGE = "You've been blocked from subscribing. Please contact support."
+describe('PaymentForm', () => {
+ beforeEach(() => {
+ initKeaTests()
+ paymentEntryLogic.mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ paymentEntryLogic.unmount()
+ })
+
+ it('returns from Stripe to the paying organization', async () => {
+ const organizationId = organizationLogic.values.currentOrganization!.id
+ paymentEntryLogic.actions.beginPaymentFlow(organizationId, '/project/1/replay')
+ render(
+ <Provider>
+ <PaymentForm />
+ </Provider>
+ )
+ fireEvent.click(screen.getByText('Submit'))
+ await waitFor(() => expect(mockConfirmPayment).toHaveBeenCalledTimes(1))
+ const returnUrl = new URL(mockConfirmPayment.mock.calls[0][0].confirmParams.return_url)
+ expect(returnUrl.pathname).toBe('/billing/authorization_status')
+ expect(returnUrl.searchParams.get('organization_id')).toBe(organizationId)
+ expect(returnUrl.searchParams.get('postRedirectPath')).toBe('/project/1/replay')
+ })
+})
+
describe('PaymentEntryModal', () => {
beforeEach(() => {
useMocks({
post: {
- 'api/billing/activate/authorize': () => [403, { detail: BLOCKED_MESSAGE }],
+ '/api/billing/activate/authorize': () => [403, { detail: BLOCKED_MESSAGE }],
},
})
initKeaTests()
paymentEntryLogic.mount()
supportLogic.mount()
+ paymentEntryLogic.actions.beginPaymentFlow(organizationLogic.values.currentOrganization!.id)
})
afterEach(cleanup)
diff --git a/frontend/src/scenes/billing/PaymentEntryModal.tsx b/frontend/src/scenes/billing/PaymentEntryModal.tsx
index 1dfe310466ec..a3f83dd3a7ad 100644
--- a/frontend/src/scenes/billing/PaymentEntryModal.tsx
+++ b/frontend/src/scenes/billing/PaymentEntryModal.tsx
@@ -7,8 +7,8 @@ import { LemonBanner, LemonButton, LemonModal } from '@posthog/lemon-ui'
import { SupportFormFields, supportLogic } from 'lib/components/Support/supportLogic'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { urls } from 'scenes/urls'
+import { PaymentCompletion } from './PaymentCompletion'
import { paymentEntryLogic } from './paymentEntryLogic'
const stripeJs = async (): Promise<typeof import('@stripe/stripe-js')> => await import('@stripe/stripe-js')
@@ -30,16 +30,15 @@ const supportRequestForError = (error: string): Partial<SupportFormFields> => ({
})
export const PaymentForm = (): JSX.Element => {
- const { stripeError, isLoading, redirectPath } = useValues(paymentEntryLogic)
- const { setStripeError, clearErrors, hidePaymentEntryModal, pollAuthorizationStatus, setLoading } =
- useActions(paymentEntryLogic)
+ const { stripeError, isLoading } = useValues(paymentEntryLogic)
+ const { setStripeError, clearErrors, hidePaymentEntryModal, confirmPayment } = useActions(paymentEntryLogic)
const { openSupportForm } = useActions(supportLogic)
const showContactSupport = useFeatureFlag('PAYMENT_ENTRY_CONTACT_SUPPORT')
const stripe = useStripe()
const elements = useElements()
- const handleSubmit = async (event: React.MouseEvent<HTMLElement>): Promise<void> => {
+ const handleSubmit = (event: React.MouseEvent<HTMLElement>): void => {
clearErrors()
event.preventDefault()
// Stripe.js never became usable: no publishable key, a blocked script, or a load failure.
@@ -54,23 +53,7 @@ export const PaymentForm = (): JSX.Element => {
})
return
}
- setLoading(true)
-
- const returnUrl = `${window.location.origin}${urls.billingAuthorizationStatus()}`
- const queryParams = redirectPath ? `?postRedirectPath=${encodeURIComponent(redirectPath)}` : ''
- const result = await stripe.confirmPayment({
- elements,
- confirmParams: { return_url: `${returnUrl}${queryParams}` },
- redirect: 'if_required',
- })
-
- if (result.error) {
- setLoading(false)
- setStripeError(result.error.message)
- posthog.captureException(new Error('payment entry stripe error', { cause: result.error }))
- } else {
- pollAuthorizationStatus(result.paymentIntent.id)
- }
+ confirmPayment(stripe, elements)
}
return (
@@ -97,7 +80,7 @@ export const PaymentForm = (): JSX.Element => {
<LemonButton disabled={isLoading} type="secondary" onClick={hidePaymentEntryModal}>
Cancel
</LemonButton>
- <LemonButton loading={isLoading} type="primary" onClick={(event) => void handleSubmit(event)}>
+ <LemonButton loading={isLoading} type="primary" onClick={handleSubmit}>
Submit
</LemonButton>
</div>
@@ -106,7 +89,8 @@ export const PaymentForm = (): JSX.Element => {
}
export const PaymentEntryModal = (): JSX.Element => {
- const { clientSecret, paymentEntryModalOpen, apiError } = useValues(paymentEntryLogic)
+ const { clientSecret, paymentEntryModalOpen, apiError, paymentFlow, completedPaymentOrganization } =
+ useValues(paymentEntryLogic)
const { hidePaymentEntryModal, initiateAuthorization, setStripeError } = useActions(paymentEntryLogic)
const { openSupportForm } = useActions(supportLogic)
const showContactSupport = useFeatureFlag('PAYMENT_ENTRY_CONTACT_SUPPORT')
@@ -114,7 +98,7 @@ export const PaymentEntryModal = (): JSX.Element => {
useEffect(() => {
// Only load Stripe.js when the modal is opened
- if (paymentEntryModalOpen && !stripePromise) {
+ if (paymentEntryModalOpen && !completedPaymentOrganization && !stripePromise) {
const loadStripeJs = async (): Promise<void> => {
const { loadStripe } = await stripeJs()
const publicKey = window.STRIPE_PUBLIC_KEY!
@@ -130,24 +114,26 @@ export const PaymentEntryModal = (): JSX.Element => {
setStripeError(STRIPE_UNAVAILABLE_MESSAGE)
})
}
- }, [paymentEntryModalOpen, stripePromise, setStripeError])
+ }, [paymentEntryModalOpen, completedPaymentOrganization, stripePromise, setStripeError])
useEffect(() => {
- if (paymentEntryModalOpen) {
+ if (paymentEntryModalOpen && !completedPaymentOrganization) {
initiateAuthorization()
}
- }, [paymentEntryModalOpen, initiateAuthorization])
+ }, [paymentEntryModalOpen, paymentFlow, completedPaymentOrganization, initiateAuthorization])
return (
<LemonModal
onClose={hidePaymentEntryModal}
width="max(44vw)"
isOpen={paymentEntryModalOpen}
- title="Add your payment details to subscribe"
+ title={completedPaymentOrganization ? 'Payment setup completed' : 'Add your payment details to subscribe'}
description=""
>
<div>
- {clientSecret ? (
+ {completedPaymentOrganization ? (
+ <PaymentCompletion />
+ ) : clientSecret ? (
<Elements stripe={stripePromise} options={{ clientSecret }}>
<PaymentForm />
</Elements>
diff --git a/frontend/src/scenes/billing/billingLogic.test.ts b/frontend/src/scenes/billing/billingLogic.test.ts
index 9dfc639cf667..b49e33df1b35 100644
--- a/frontend/src/scenes/billing/billingLogic.test.ts
+++ b/frontend/src/scenes/billing/billingLogic.test.ts
@@ -11,6 +11,7 @@ import { BillingAPIErrorCodes, billingLogic } from 'scenes/billing/billingLogic'
import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
import { billingJson } from '~/mocks/fixtures/_billing'
import preflightJson from '~/mocks/fixtures/_preflight.json'
@@ -110,6 +111,45 @@ describe('billingLogic', () => {
expect(billingLogic.values.billing).toEqual(loaded)
})
+ it('keeps ambient credit and profile refreshes for an unscoped successful billing load', async () => {
+ billingState = { ...billingState, has_active_subscription: true }
+ billingLogic.mount()
+ await expectLogic(billingLogic, () => billingLogic.actions.loadBilling()).toFinishAllListeners()
+ const organization = organizationLogic.values.currentOrganization!
+ const user = userLogic.values.user!
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ await expectLogic(billingLogic).toFinishAllListeners()
+ const ambientCredits = jest.fn(() => [200, creditOverviewResponse])
+ const ambientUser = jest.fn(() => [200, user])
+ const ambientOrganization = jest.fn(() => [200, organization])
+ useMocks({
+ get: {
+ '/api/billing/credits/overview': ambientCredits,
+ '/api/users/@me': ambientUser,
+ '/api/organizations/@current': ambientOrganization,
+ },
+ })
+ router.actions.push('/organization/billing', { success: 'true' })
+
+ jest.useFakeTimers()
+ try {
+ const expectation = expectLogic(billingLogic, () => {
+ billingLogic.actions.loadBilling()
+ }).toFinishAllListeners()
+ await jest.advanceTimersByTimeAsync(2000)
+ await expectation
+ await expectLogic(userLogic).toFinishAllListeners()
+ await expectLogic(organizationLogic).toFinishAllListeners()
+
+ expect(ambientCredits).toHaveBeenCalled()
+ expect(ambientUser).toHaveBeenCalled()
+ expect(ambientOrganization).toHaveBeenCalled()
+ expect(router.values.searchParams).toEqual({})
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
it('reports a failed limit update as a failure, so the limit editor keeps the value', async () => {
useMocks({ patch: { '/api/billing': () => [500, { detail: 'A server error occurred.' }] } })
billingLogic.mount()
diff --git a/frontend/src/scenes/billing/billingLogic.tsx b/frontend/src/scenes/billing/billingLogic.tsx
index 3907902326ac..9f91f1df75e0 100644
--- a/frontend/src/scenes/billing/billingLogic.tsx
+++ b/frontend/src/scenes/billing/billingLogic.tsx
@@ -110,7 +110,7 @@ export type SwitchPlanPayload = {
}
// Billing can answer with an empty body (a proxy error page, an upstream failure), so this takes null.
-const parseBillingResponse = (data: Partial<BillingType> | null): BillingType | null => {
+export const parseBillingResponse = (data: Partial<BillingType> | null): BillingType | null => {
if (!data) {
return null
}
@@ -1537,9 +1537,14 @@ export const billingLogic = kea<billingLogicType>([
switchFlatrateSubscriptionPlan: async (payload) => {
actions.setSwitchPlanLoading(payload.to_product_key)
},
- loadBillingSuccess: async (_, breakpoint) => {
+ loadBillingSuccess: async ({ payload }, breakpoint) => {
actions.registerInstrumentationProps()
actions.determineBillingAlert()
+ // Scoped payment refreshes update their organization's entitlements separately.
+ // The endpoints below read the server's selected organization.
+ if (payload) {
+ return
+ }
actions.loadCreditOverview()
// If the activation is successful, we reload the user/organization to get the updated available features
diff --git a/frontend/src/scenes/billing/billingProductLogic.test.ts b/frontend/src/scenes/billing/billingProductLogic.test.ts
index 45a9d2f89708..89372835e14f 100644
--- a/frontend/src/scenes/billing/billingProductLogic.test.ts
+++ b/frontend/src/scenes/billing/billingProductLogic.test.ts
@@ -1,4 +1,6 @@
/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */
+import { waitFor } from '@testing-library/react'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -9,6 +11,8 @@ import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { billingLogic } from 'scenes/billing/billingLogic'
import { billingProductLogic } from 'scenes/billing/billingProductLogic'
+import { paymentEntryLogic } from 'scenes/billing/paymentEntryLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { billingJson } from '~/mocks/fixtures/_billing'
import { defaultPlatformAddons } from '~/mocks/fixtures/_billing_platform_addons'
@@ -379,7 +383,15 @@ describe('billingProductLogic — confirm purchase modal', () => {
// Respond with an error so activation stops before any real-charge side effects, while still
// proving the request fired with the right add-on + plan.
const activate = jest.fn(() => [200, { success: false, error: 'stop before charge' }] as [number, unknown])
- useMocks({ post: { '/api/billing/activate': activate } })
+ let body: unknown
+ useMocks({
+ post: {
+ '/api/billing/activate': async ({ request }) => {
+ body = await request.json()
+ return activate()
+ },
+ },
+ })
logic = billingProductLogic({ product: scaleAddon })
logic.mount()
@@ -393,6 +405,93 @@ describe('billingProductLogic — confirm purchase modal', () => {
.toFinishAllListeners()
expect(activate).toHaveBeenCalled()
+ expect(body).toEqual({
+ organization_id: organizationLogic.values.currentOrganization!.id,
+ products: `${scaleAddon.type}:${scaleAddon.plans[0].plan_key}`,
+ })
+ })
+
+ it('refreshes the paid organization and keeps the page params after an add-on purchase', async () => {
+ const organization = organizationLogic.values.currentOrganization!
+ const billingBefore = billingLogic.values.billing
+ const billingReads: (string | null)[] = []
+ useMocks({
+ get: {
+ '/api/billing': ({ request }) => {
+ billingReads.push(new URL(request.url).searchParams.get('organization_id'))
+ return [200, { customer_id: 'cus_test', subscription_level: 'paid', has_active_subscription: true }]
+ },
+ },
+ post: { '/api/billing/activate': () => [200, { success: true }] },
+ })
+ router.actions.push('/project/1/replay', { foo: 'bar' })
+ logic = billingProductLogic({ product: scaleAddon })
+ logic.mount()
+ const push = jest.spyOn(router.actions, 'push')
+ try {
+ await expectLogic(logic, () => logic.actions.handleProductUpgrade('scale:scale', '')).toFinishAllListeners()
+ expect(billingReads).toEqual([organization.id])
+ expect(billingLogic.values.billing).not.toBe(billingBefore)
+ expect(billingLogic.values.billing?.has_active_subscription).toBe(true)
+ expect(push).toHaveBeenCalledWith('/project/1/replay', {
+ foo: 'bar',
+ upgraded: 'true',
+ products: 'scale:scale',
+ })
+ expect(toastErrorSpy).not.toHaveBeenCalled()
+ } finally {
+ push.mockRestore()
+ }
+ })
+
+ it('keeps the add-on loading until its activation settles', async () => {
+ let resolveActivation!: (response: [number, unknown]) => void
+ const activate = jest.fn(
+ () =>
+ new Promise<[number, unknown]>((resolve) => {
+ resolveActivation = resolve
+ })
+ )
+ useMocks({ post: { '/api/billing/activate': activate } })
+ logic = billingProductLogic({ product: scaleAddon })
+ logic.mount()
+ logic.actions.initiateProductUpgrade(scaleAddon, scaleAddon.plans[0], '')
+ await waitFor(() => expect(activate).toHaveBeenCalledTimes(1))
+ expect(logic.values.billingProductLoading).toBe(scaleAddon.type)
+ resolveActivation([200, { success: false, error: 'Stopped before charging' }])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.billingProductLoading).toBe(null)
+ })
+
+ it('keeps another selected organization after the original product activation succeeds', async () => {
+ const original = organizationLogic.values.currentOrganization!
+ const selected = { ...original, id: '00000000-0000-4000-8000-000000000002', name: 'Selected organization' }
+ let resolveActivation!: (response: [number, { success: boolean }]) => void
+ const response = new Promise<[number, { success: boolean }]>((resolve) => {
+ resolveActivation = resolve
+ })
+ const activate = jest.fn(() => response)
+ useMocks({ post: { '/api/billing/activate': activate } })
+ logic = billingProductLogic({ product: scaleAddon })
+ logic.mount()
+ const push = jest.spyOn(router.actions, 'push')
+ try {
+ logic.actions.handleProductUpgrade('scale:scale', '/project/1/replay')
+ await waitFor(() => expect(activate).toHaveBeenCalledTimes(1))
+ organizationLogic.actions.loadCurrentOrganizationSuccess(selected)
+ resolveActivation([200, { success: true }])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(organizationLogic.values.currentOrganization?.id).toBe(selected.id)
+ expect(push).not.toHaveBeenCalled()
+ expect(paymentEntryLogic.values.completedPaymentOrganization).toEqual({
+ id: original.id,
+ name: original.name,
+ })
+ expect(toastErrorSpy).not.toHaveBeenCalled()
+ } finally {
+ push.mockRestore()
+ }
})
it('auto-closes the modal once activation finishes', async () => {
diff --git a/frontend/src/scenes/billing/billingProductLogic.ts b/frontend/src/scenes/billing/billingProductLogic.ts
index c28f41e3eaaf..2dac8ba0964d 100644
--- a/frontend/src/scenes/billing/billingProductLogic.ts
+++ b/frontend/src/scenes/billing/billingProductLogic.ts
@@ -1,7 +1,6 @@
import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
-import { router } from 'kea-router'
import posthog from 'posthog-js'
import React from 'react'
@@ -11,8 +10,6 @@ import api from 'lib/api'
import type { FeatureFlagKey } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { organizationLogic } from 'scenes/organizationLogic'
-import { userLogic } from 'scenes/userLogic'
import {
BillingPlan,
@@ -239,6 +236,13 @@ export interface billingProductLogicActions {
[key: string]: number | null
}
} // billingLogic
+ upgradeProducts: (
+ products: string,
+ redirectPath: string | null
+ ) => {
+ products: string
+ redirectPath: string | null
+ } // paymentEntryLogic
activateTrial: () => {
value: true
}
@@ -588,6 +592,8 @@ export const billingProductLogic = kea<billingProductLogicType>([
['featureFlags'],
],
actions: [
+ paymentEntryLogic,
+ ['upgradeProducts'],
billingLogic,
[
'updateBillingLimits',
@@ -1298,32 +1304,7 @@ export const billingProductLogic = kea<billingProductLogicType>([
},
handleProductUpgrade: async ({ products, redirectPath }) => {
try {
- const body: Record<string, string> = { products }
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingActivateCreate() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
- const response = await api.create('api/billing/activate', body)
-
- if (response.success) {
- await billingLogic.asyncActions.loadBilling()
- if (redirectPath) {
- window.location.pathname = redirectPath
- } else {
- router.actions.push(router.values.location.pathname, {
- ...router.values.searchParams,
- upgraded: 'true',
- products,
- })
- organizationLogic.actions.loadCurrentOrganization()
- userLogic.actions.loadUser()
- }
- } else if (response.must_setup_payment) {
- paymentEntryLogic.actions.setRedirectPath(redirectPath || null)
- paymentEntryLogic.actions.showPaymentEntryModal()
- } else {
- lemonToast.error(response.error || 'Failed to activate subscription')
- }
- } catch (error) {
- posthog.captureException(new Error('payment entry api error - product upgrade error', { cause: error }))
- lemonToast.error('Failed to activate subscription. Please try again.')
+ 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.ts
index 2489be592956..5f7a0e9d65c3 100644
--- a/frontend/src/scenes/billing/paymentEntryLogic.test.ts
+++ b/frontend/src/scenes/billing/paymentEntryLogic.test.ts
@@ -1,6 +1,9 @@
+import type { Stripe, StripeElements } from '@stripe/stripe-js'
+import { waitFor } from '@testing-library/react'
/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
// Imported from the source module rather than the `@posthog/lemon-ui` barrel so that the
// spy below replaces `.error` on the same `lemonToast` singleton that `paymentEntryLogic`
@@ -9,10 +12,14 @@ import { expectLogic } from 'kea-test-utils'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { billingLogic } from 'scenes/billing/billingLogic'
import { paymentEntryLogic } from 'scenes/billing/paymentEntryLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
+import { userLogic } from 'scenes/userLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { BillingType } from '~/types'
+import { AvailableFeature, BillingType } from '~/types'
+
+const OTHER_ORGANIZATION_ID = '00000000-0000-4000-8000-000000000002'
const seedBilling = async (billing: Partial<BillingType> | null): Promise<void> => {
useMocks({ get: { '/api/billing': () => [200, billing ?? {}] } })
@@ -20,18 +27,74 @@ const seedBilling = async (billing: Partial<BillingType> | null): Promise<void>
await expectLogic(billingLogic, () => billingLogic.actions.loadBilling()).toFinishAllListeners()
}
+const stubLocation = (): { href: string } => {
+ const location = { ...window.location, href: window.location.href }
+ jest.spyOn(window, 'location', 'get').mockReturnValue(location)
+ return location
+}
+
+const deferred = <T>(): { promise: Promise<T>; resolve: (value: T) => void; reject: (error: unknown) => void } => {
+ let resolve!: (value: T) => void
+ let reject!: (error: unknown) => void
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+ return { promise, resolve, reject }
+}
+
+const fakeStripe = (confirmPayment: () => Promise<unknown>): Stripe => ({ confirmPayment }) as unknown as Stripe
+const fakeElements = {} as StripeElements
+
+const setDocumentHidden = (hidden: boolean): void => {
+ Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden })
+ document.dispatchEvent(new Event('visibilitychange'))
+}
+
+// Holds the 2 second status retries so a test can fire them; clearing one drops it like a real timer.
+const holdStatusRetries = (): { fire: () => Promise<void> } => {
+ const retries = new Map<number, () => void>()
+ let nextId = 1_000_000
+ const { setTimeout: realSetTimeout, clearTimeout: realClearTimeout } = global
+ jest.spyOn(global, 'setTimeout').mockImplementation(((callback: () => void, delay?: number, ...args: unknown[]) => {
+ if (delay !== 2000) {
+ return realSetTimeout(callback, delay, ...args)
+ }
+ retries.set(++nextId, callback)
+ return nextId
+ }) as typeof setTimeout)
+ jest.spyOn(global, 'clearTimeout').mockImplementation(((id: number) => {
+ if (!retries.delete(id)) {
+ realClearTimeout(id)
+ }
+ }) as typeof clearTimeout)
+ return {
+ fire: async () => {
+ const callbacks = [...retries.values()]
+ retries.clear()
+ callbacks.forEach((callback) => callback())
+ await new Promise((resolve) => realSetTimeout(resolve, 0))
+ },
+ }
+}
+
describe('paymentEntryLogic', () => {
let logic: ReturnType<typeof paymentEntryLogic.build>
let toastErrorSpy: jest.SpyInstance
+ let toastInfoSpy: jest.SpyInstance
beforeEach(() => {
initKeaTests()
toastErrorSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => ({ id: 'x' }) as any)
+ toastInfoSpy = jest.spyOn(lemonToast, 'info').mockImplementation(() => ({ id: 'x' }) as any)
})
afterEach(() => {
logic?.unmount()
- toastErrorSpy.mockRestore()
+ jest.restoreAllMocks()
+ jest.useRealTimers()
+ delete (document as { hidden?: boolean }).hidden
+ window.history.replaceState({}, '', '/')
})
describe('startPaymentEntryFlow — returning customer (customer_id present)', () => {
@@ -55,6 +118,24 @@ describe('paymentEntryLogic', () => {
expect(logic.values.apiError).toBe(null)
})
+ it('includes the displayed organization in subscription activation', async () => {
+ let body: unknown
+ useMocks({
+ post: {
+ '/api/billing/activate': async ({ request }) => {
+ body = await request.json()
+ return [200, { must_setup_payment: true }]
+ },
+ },
+ })
+ logic = paymentEntryLogic()
+ logic.mount()
+ const organizationId = organizationLogic.values.currentOrganization!.id
+ await expectLogic(logic, () => logic.actions.startPaymentEntryFlow()).toFinishAllListeners()
+ expect(body).toEqual({ organization_id: organizationId, products: 'all_products:' })
+ expect(logic.values.paymentOrganizationId).toBe(organizationId)
+ })
+
it('falls back to a generic toast when activate responds without an error string', async () => {
setupActivate([200, { success: false }])
@@ -63,6 +144,19 @@ describe('paymentEntryLogic', () => {
expect(toastErrorSpy).toHaveBeenCalledWith('Failed to activate subscription')
})
+ it('lets the next start activate again after an activation error', async () => {
+ const activate = jest.fn(() => [200, { success: false, error: 'test failure' }])
+ useMocks({ post: { '/api/billing/activate': activate } })
+ logic = paymentEntryLogic()
+ logic.mount()
+
+ await expectLogic(logic, () => logic.actions.startPaymentEntryFlow()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.startPaymentEntryFlow()).toFinishAllListeners()
+
+ expect(activate).toHaveBeenCalledTimes(2)
+ expect(toastInfoSpy).not.toHaveBeenCalled()
+ })
+
it('surfaces a toast when activate throws', async () => {
// 500 body is unused — api.create rejects on non-2xx before reading JSON.
setupActivate([500])
@@ -104,6 +198,30 @@ describe('paymentEntryLogic', () => {
})
describe('startPaymentEntryFlow — new customer (no customer_id)', () => {
+ it('authorizes the initiating organization after the current organization changes', async () => {
+ await seedBilling({ subscription_level: 'free' })
+ const originalOrganization = organizationLogic.values.currentOrganization!
+ const bodies: unknown[] = []
+ useMocks({
+ post: {
+ '/api/billing/activate/authorize': async ({ request }) => {
+ bodies.push(await request.json().catch(() => null))
+ return [200, { clientSecret: 'secret_original' }]
+ },
+ },
+ })
+ logic = paymentEntryLogic()
+ logic.mount()
+ await expectLogic(logic, () => logic.actions.startPaymentEntryFlow()).toFinishAllListeners()
+ organizationLogic.actions.loadCurrentOrganizationSuccess({
+ ...originalOrganization,
+ id: '00000000-0000-4000-8000-000000000002',
+ })
+ await expectLogic(logic, () => logic.actions.initiateAuthorization()).toFinishAllListeners()
+ expect(bodies).toEqual([{ organization_id: originalOrganization.id }])
+ expect(logic.values.clientSecret).toBe('secret_original')
+ })
+
it('opens the payment entry modal without calling activate', async () => {
await seedBilling({ subscription_level: 'free' })
const activate = jest.fn(() => [200, { success: true }] as [number, Record<string, unknown>])
@@ -137,4 +255,844 @@ describe('paymentEntryLogic', () => {
expect(logic.values.paymentEntryModalOpen).toBe(false)
})
})
+
+ describe('activation completion after an organization switch', () => {
+ it('keeps B selected and shows A in the completion modal after activation succeeds', async () => {
+ await seedBilling({ customer_id: 'cus_original', subscription_level: 'free' })
+ const original = organizationLogic.values.currentOrganization!
+ const selected = { ...original, id: '00000000-0000-4000-8000-000000000002', name: 'Selected organization' }
+ const activation = deferred<[number, unknown]>()
+ const activate = jest.fn(() => activation.promise)
+ useMocks({ post: { '/api/billing/activate': activate } })
+ logic = paymentEntryLogic()
+ logic.mount()
+ const push = jest.spyOn(router.actions, 'push')
+ logic.actions.startPaymentEntryFlow(null, '/project/1/replay')
+ await waitFor(() => expect(activate).toHaveBeenCalledTimes(1))
+ organizationLogic.actions.loadCurrentOrganizationSuccess(selected)
+ activation.resolve([200, { success: true }])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(organizationLogic.values.currentOrganization?.id).toBe(selected.id)
+ expect(push).not.toHaveBeenCalled()
+ expect(logic.values.completedPaymentOrganization).toEqual({ id: original.id, name: original.name })
+ expect(logic.values.paymentEntryModalOpen).toBe(true)
+ // The cached user still names A, so userLogic.updateCurrentOrganization would skip the switch.
+ expect(userLogic.values.user?.organization?.id).toBe(original.id)
+ const switches: unknown[] = []
+ useMocks({
+ patch: {
+ '/api/users/@me': async ({ request }) => {
+ switches.push(await request.json())
+ return [200, userLogic.values.user]
+ },
+ },
+ })
+ const location = stubLocation()
+ await expectLogic(logic, () => logic.actions.viewCompletedPaymentOrganization()).toFinishAllListeners()
+ expect(switches).toEqual([{ set_current_organization: original.id }])
+ expect(location.href).toBe('/organization/billing')
+ })
+
+ it('stays on the page when switching to the paid organization fails', async () => {
+ useMocks({ patch: { '/api/users/@me': () => [500, { detail: 'A server error occurred.' }] } })
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.setCompletedPaymentOrganization({ id: OTHER_ORGANIZATION_ID, name: 'Original organization' })
+ const location = stubLocation()
+ const href = location.href
+ await expectLogic(logic, () => logic.actions.viewCompletedPaymentOrganization()).toFinishAllListeners()
+ expect(toastErrorSpy).toHaveBeenCalledWith('Could not switch organization. Try again.')
+ expect(location.href).toBe(href)
+ })
+ })
+
+ describe('callback completion while another organization is already selected', () => {
+ it.each([true, false])('preserves B when the explicit A name lookup succeeds: %s', async (lookupSucceeds) => {
+ await seedBilling({ subscription_level: 'free' })
+ const original = {
+ ...organizationLogic.values.currentOrganization!,
+ id: '00000000-0000-4000-8000-000000000001',
+ name: 'Original organization',
+ }
+ const selected = { ...original, id: '00000000-0000-4000-8000-000000000002', name: 'Selected organization' }
+ organizationLogic.actions.loadCurrentOrganizationSuccess(selected)
+ const retrieveOriginal = jest.fn(() =>
+ lookupSucceeds ? [200, original] : [403, { detail: 'You do not have access to this organization.' }]
+ )
+ useMocks({
+ get: { [`/api/organizations/${original.id}`]: retrieveOriginal },
+ post: { '/api/billing/activate/authorize/status': () => [200, { status: 'success' }] },
+ })
+ window.history.replaceState(
+ {},
+ '',
+ `/billing/authorization_status?organization_id=${original.id}&payment_intent=pi_original`
+ )
+ logic = paymentEntryLogic()
+ logic.mount()
+ const push = jest.spyOn(router.actions, 'push')
+ await expectLogic(logic, () => logic.actions.pollAuthorizationStatus()).toFinishAllListeners()
+ expect(retrieveOriginal).toHaveBeenCalledTimes(1)
+ expect(logic.values.completedPaymentOrganization).toEqual({
+ id: original.id,
+ name: lookupSucceeds ? original.name : 'the original organization',
+ })
+ expect(logic.values.apiError).toBe(null)
+ expect(logic.values.authorizationStatus).toBe('success')
+ expect(organizationLogic.values.currentOrganization?.id).toBe(selected.id)
+ expect(push).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('payment flow organization binding', () => {
+ it('applies the paid organization to the latest user state', async () => {
+ await seedBilling({ subscription_level: 'free' })
+ const organization = organizationLogic.values.currentOrganization!
+ const user = userLogic.values.user!
+ const response = deferred<[number, unknown]>()
+ let requested = false
+ useMocks({
+ get: {
+ [`/api/organizations/${organization.id}`]: () => {
+ requested = true
+ return response.promise
+ },
+ },
+ })
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.beginPaymentFlow(organization.id)
+ logic.actions.completePaymentFlow(null, { success: true })
+ await waitFor(() => expect(requested).toBe(true))
+ userLogic.actions.loadUserSuccess({ ...user, first_name: 'Updated name' })
+ response.resolve([200, { ...organization, customer_id: 'cus_refreshed' }])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(userLogic.values.user?.first_name).toBe('Updated name')
+ expect(userLogic.values.user?.organization?.customer_id).toBe('cus_refreshed')
+ expect(organizationLogic.values.currentOrganization?.customer_id).toBe('cus_refreshed')
+ })
+
+ it('applies nothing when another organization is selected while the paid organization loads', async () => {
+ await seedBilling({ subscription_level: 'free' })
+ const original = organizationLogic.values.currentOrganization!
+ const user = userLogic.values.user!
+ const billingBefore = billingLogic.values.billing
+ const organizationResponse = deferred<[number, unknown]>()
+ let requested = false
+ useMocks({
+ get: {
+ '/api/billing': () => [200, { subscription_level: 'paid', customer_id: 'cus_paid' }],
+ [`/api/organizations/${original.id}`]: () => {
+ requested = true
+ return organizationResponse.promise
+ },
+ },
+ })
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.beginPaymentFlow(original.id)
+ logic.actions.completePaymentFlow(null, { success: true })
+ await waitFor(() => expect(requested).toBe(true))
+ const selected = { ...original, id: OTHER_ORGANIZATION_ID }
+ organizationLogic.actions.loadCurrentOrganizationSuccess(selected)
+ userLogic.actions.loadUserSuccess({ ...user, first_name: 'Updated name', organization: selected })
+ organizationResponse.resolve([200, { ...original, customer_id: 'cus_refreshed' }])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(billingLogic.values.billing).toBe(billingBefore)
+ expect(organizationLogic.values.currentOrganization).toEqual(selected)
+ expect(userLogic.values.user).toMatchObject({ first_name: 'Updated name', organization: selected })
+ expect(logic.values.completedPaymentOrganization).toEqual({ id: original.id, name: original.name })
+ })
+
+ it('leaves billing alone when another organization is selected while the paid billing loads', async () => {
+ await seedBilling({ subscription_level: 'free' })
+ const original = organizationLogic.values.currentOrganization!
+ const billingBefore = billingLogic.values.billing
+ const billingResponse = deferred<[number, unknown]>()
+ let requested = false
+ useMocks({
+ get: {
+ '/api/billing': () => {
+ requested = true
+ return billingResponse.promise
+ },
+ },
+ })
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.beginPaymentFlow(original.id)
+ logic.actions.completePaymentFlow(null, { success: true })
+ await waitFor(() => expect(requested).toBe(true))
+ organizationLogic.actions.loadCurrentOrganizationSuccess({ ...original, id: OTHER_ORGANIZATION_ID })
+ billingResponse.resolve([200, { subscription_level: 'paid', customer_id: 'cus_paid' }])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(billingLogic.values.billing).toBe(billingBefore)
+ expect(logic.values.completedPaymentOrganization).toEqual({ id: original.id, name: original.name })
+ })
+
+ it('applies the features the billing read saves after an add-on purchase', async () => {
+ await seedBilling({ customer_id: 'cus_paid', subscription_level: 'paid' })
+ const organization = organizationLogic.values.currentOrganization!
+ const features = [
+ { key: AvailableFeature.GROUP_ANALYTICS, name: 'Group analytics', limit: null, note: null },
+ ]
+ const billingResponse = deferred<[number, unknown]>()
+ let billingRequested = false
+ let billingSaved = false
+ let organizationRequested = false
+ useMocks({
+ get: {
+ '/api/billing': () => {
+ billingRequested = true
+ return billingResponse.promise
+ },
+ [`/api/organizations/${organization.id}`]: () => {
+ organizationRequested = true
+ return [
+ 200,
+ {
+ ...organization,
+ available_product_features: billingSaved
+ ? features
+ : organization.available_product_features,
+ },
+ ]
+ },
+ },
+ post: { '/api/billing/activate': () => [200, { success: true }] },
+ })
+ logic = paymentEntryLogic()
+ logic.mount()
+ expect(userLogic.values.hasAvailableFeature(AvailableFeature.GROUP_ANALYTICS)).toBe(false)
+ logic.actions.upgradeProducts('scale:scale', null)
+ await waitFor(() => expect(billingRequested).toBe(true))
+ expect(organizationRequested).toBe(false)
+ billingSaved = true
+ billingResponse.resolve([200, { customer_id: 'cus_paid', subscription_level: 'paid' }])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(userLogic.values.hasAvailableFeature(AvailableFeature.GROUP_ANALYTICS)).toBe(true)
+ })
+
+ it.each([
+ ['/organization/billing', { upgraded: 'true' }],
+ ['/onboarding/product_analytics', { success: 'true' }],
+ ])('keeps the paid organization when a payment completes on %s', async (pathname, params) => {
+ await seedBilling({ customer_id: 'cus_paid', subscription_level: 'paid' })
+ const organization = organizationLogic.values.currentOrganization!
+ const other = { ...organization, id: OTHER_ORGANIZATION_ID, name: 'Other organization' }
+ const billingReads: (string | null)[] = []
+ const ambientCredits = jest.fn(() => [200, { eligible: true, email: '[email protected]' }])
+ const ambientUser = jest.fn(() => [200, { ...userLogic.values.user, organization: other }])
+ const ambientOrganization = jest.fn(() => [200, other])
+ useMocks({
+ get: {
+ '/api/billing': ({ request }) => {
+ billingReads.push(new URL(request.url).searchParams.get('organization_id'))
+ return [
+ 200,
+ { customer_id: 'cus_paid', subscription_level: 'paid', has_active_subscription: true },
+ ]
+ },
+ [`/api/organizations/${organization.id}`]: () => [200, organization],
+ '/api/billing/credits/overview': ambientCredits,
+ '/api/users/@me': ambientUser,
+ '/api/organizations/@current': ambientOrganization,
+ },
+ post: { '/api/billing/activate': () => [200, { success: true }] },
+ })
+ router.actions.push(pathname, params)
+ logic = paymentEntryLogic()
+ logic.mount()
+ jest.useFakeTimers()
+ const upgrade = logic.asyncActions.upgradeProducts('scale:scale', null)
+ await jest.advanceTimersByTimeAsync(2000)
+ await upgrade
+ await expectLogic(billingLogic).toFinishAllListeners()
+ await expectLogic(userLogic).toFinishAllListeners()
+ await expectLogic(organizationLogic).toFinishAllListeners()
+ jest.useRealTimers()
+ expect(billingReads).toEqual([organization.id])
+ expect(ambientCredits).not.toHaveBeenCalled()
+ expect(ambientUser).not.toHaveBeenCalled()
+ expect(ambientOrganization).not.toHaveBeenCalled()
+ expect(billingLogic.values.billing?.has_active_subscription).toBe(true)
+ expect(organizationLogic.values.currentOrganization?.id).toBe(organization.id)
+ expect(userLogic.values.user?.organization?.id).toBe(organization.id)
+ })
+
+ it('restores the organization and redirect from the Stripe callback', async () => {
+ const organizationId = '00000000-0000-4000-8000-000000000002'
+ const redirectPath = '/project/2/replay?foo=bar'
+ window.history.replaceState(
+ {},
+ '',
+ `/?organization_id=${organizationId}&postRedirectPath=${encodeURIComponent(redirectPath)}`
+ )
+ logic = paymentEntryLogic()
+ logic.mount()
+ expect(logic.values.paymentOrganizationId).toBe(organizationId)
+ const returnUrl = new URL(logic.values.stripeReturnUrl!)
+ expect(returnUrl.pathname).toBe('/billing/authorization_status')
+ expect(returnUrl.searchParams.get('organization_id')).toBe(organizationId)
+ expect(returnUrl.searchParams.get('postRedirectPath')).toBe(redirectPath)
+ })
+
+ it.each(['', '?organization_id=invalid', '?organization_id=@current'])(
+ 'rejects old or invalid callbacks %s without polling',
+ async (query) => {
+ const statusRequest = jest.fn(() => [200, { status: 'success' }])
+ useMocks({ post: { '/api/billing/activate/authorize/status': statusRequest } })
+ window.history.replaceState({}, '', `/${query}`)
+ logic = paymentEntryLogic()
+ logic.mount()
+ await expectLogic(logic, () => logic.actions.pollAuthorizationStatus('pi_test')).toFinishAllListeners()
+ expect(statusRequest).not.toHaveBeenCalled()
+ expect(logic.values.apiError).toContain('Return to billing and start again')
+ }
+ )
+
+ it('clears the previous secret when a new flow starts', () => {
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.beginPaymentFlow('00000000-0000-4000-8000-000000000001')
+ logic.actions.setClientSecret('secret_previous')
+ logic.actions.beginPaymentFlow('00000000-0000-4000-8000-000000000002')
+ expect(logic.values.clientSecret).toBe(null)
+ })
+
+ it('keeps the captured redirect through retries while the original organization stays selected', async () => {
+ await seedBilling({ subscription_level: 'free' })
+ const originalOrganization = organizationLogic.values.currentOrganization!
+ const bodies: unknown[] = []
+ useMocks({
+ post: {
+ '/api/billing/activate/authorize/status': async ({ request }) => {
+ bodies.push(await request.json())
+ return [200, { status: bodies.length === 1 ? 'loading' : 'success' }]
+ },
+ },
+ })
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.beginPaymentFlow(originalOrganization.id, '/project/1/replay?foo=bar')
+ const pushSpy = jest.spyOn(router.actions, 'push')
+ const retries = holdStatusRetries()
+ await expectLogic(logic, () => logic.actions.pollAuthorizationStatus('pi_original')).toFinishAllListeners()
+ logic.actions.setRedirectPath(null)
+ await retries.fire()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(pushSpy).toHaveBeenCalledWith('/project/1/replay', { foo: 'bar', success: true })
+ expect(bodies).toEqual(
+ Array(2).fill({ organization_id: originalOrganization.id, payment_intent_id: 'pi_original' })
+ )
+ })
+ })
+
+ describe('closing the modal after the card is submitted', () => {
+ let pushSpy: jest.SpyInstance
+ const features = [{ key: 'session_recording', name: 'Session recording', limit: null, note: null }]
+
+ let billingReads: (string | null)[] = []
+ const mockPaidOrganization = (statuses: string[]): jest.Mock => {
+ const organization = organizationLogic.values.currentOrganization!
+ const statusRequest = jest.fn(() => [200, { status: statuses.shift() ?? 'success' }])
+ billingReads = []
+ useMocks({
+ get: {
+ '/api/billing': ({ request }) => {
+ billingReads.push(new URL(request.url).searchParams.get('organization_id'))
+ return [200, { subscription_level: 'paid', customer_id: 'cus_paid' }]
+ },
+ [`/api/organizations/${organization.id}`]: () => [
+ 200,
+ { ...organization, available_product_features: features },
+ ],
+ },
+ post: { '/api/billing/activate/authorize/status': statusRequest },
+ })
+ return statusRequest
+ }
+
+ const expectPaidOrganizationApplied = (): void => {
+ expect(billingReads).toEqual([organizationLogic.values.currentOrganization!.id])
+ expect(billingLogic.values.billing?.customer_id).toBe('cus_paid')
+ expect(organizationLogic.values.currentOrganization?.available_product_features).toEqual(features)
+ expect(userLogic.values.user?.organization?.available_product_features).toEqual(features)
+ expect(pushSpy).toHaveBeenCalledWith('/project/1/replay', { success: true })
+ }
+
+ const submitCard = (): void =>
+ logic.actions.confirmPayment(
+ fakeStripe(async () => ({ paymentIntent: { id: 'pi_submitted' } })),
+ fakeElements
+ )
+
+ const startAgainAndExpectRefusal = (): void => {
+ const flow = logic.values.paymentFlow
+ logic.actions.startPaymentEntryFlow(null, '/project/1/replay')
+ expect(toastInfoSpy).toHaveBeenCalledWith("We're still confirming your last payment.")
+ expect(logic.values.paymentEntryModalOpen).toBe(false)
+ expect(logic.values.paymentFlow).toBe(flow)
+ }
+
+ beforeEach(async () => {
+ await seedBilling({ subscription_level: 'free' })
+ pushSpy = jest.spyOn(router.actions, 'push')
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.beginPaymentFlow(organizationLogic.values.currentOrganization!.id, '/project/1/replay')
+ logic.actions.showPaymentEntryModal()
+ })
+
+ it('still polls and refreshes when the modal closes while the confirmation is pending', async () => {
+ const statusRequest = mockPaidOrganization(['success'])
+ const confirmation = deferred<unknown>()
+ logic.actions.confirmPayment(
+ fakeStripe(() => confirmation.promise),
+ fakeElements
+ )
+ logic.actions.hidePaymentEntryModal()
+ confirmation.resolve({ paymentIntent: { id: 'pi_submitted' } })
+ await waitFor(() => expect(statusRequest).toHaveBeenCalledTimes(1))
+ await expectLogic(logic).toFinishAllListeners()
+ expectPaidOrganizationApplied()
+ })
+
+ it('still refreshes when the modal closes while the status is loading', async () => {
+ const statusRequest = mockPaidOrganization(['loading', 'success'])
+ const retries = holdStatusRetries()
+ logic.actions.confirmPayment(
+ fakeStripe(async () => ({ paymentIntent: { id: 'pi_submitted' } })),
+ fakeElements
+ )
+ await expectLogic(logic).toFinishAllListeners()
+ expect(statusRequest).toHaveBeenCalledTimes(1)
+ logic.actions.hidePaymentEntryModal()
+ await retries.fire()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(statusRequest).toHaveBeenCalledTimes(2)
+ expectPaidOrganizationApplied()
+ })
+
+ it('ends the flow when the modal closes after the card is declined', async () => {
+ logic.actions.setClientSecret('secret_submitted')
+ logic.actions.confirmPayment(
+ fakeStripe(async () => ({ error: { message: 'Your card was declined.' } })),
+ fakeElements
+ )
+ await expectLogic(logic).toFinishAllListeners()
+ // The card form stays so the decline shows and another card can be tried.
+ expect(logic.values).toMatchObject({
+ stripeError: 'Your card was declined.',
+ isLoading: false,
+ clientSecret: 'secret_submitted',
+ })
+ logic.actions.hidePaymentEntryModal()
+ expect(logic.values.paymentFlow).toBe(null)
+ })
+
+ it('closes the modal and clears the card form after the payment completes', async () => {
+ mockPaidOrganization(['success'])
+ logic.actions.setClientSecret('secret_submitted')
+ submitCard()
+ await expectLogic(logic).toFinishAllListeners()
+ expectPaidOrganizationApplied()
+ expect(logic.values).toMatchObject({ paymentEntryModalOpen: false, isLoading: false, clientSecret: null })
+ })
+
+ it('refuses a second start while the status is loading and still completes the first payment', async () => {
+ const statusRequest = mockPaidOrganization(['loading', 'success'])
+ const retries = holdStatusRetries()
+ submitCard()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.hidePaymentEntryModal()
+ startAgainAndExpectRefusal()
+ await retries.fire()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(statusRequest).toHaveBeenCalledTimes(2)
+ expectPaidOrganizationApplied()
+ expect(pushSpy).toHaveBeenCalledTimes(1)
+ })
+
+ it('refuses a second start while the confirmation is pending and still completes the first payment', async () => {
+ const statusRequest = mockPaidOrganization(['success'])
+ const confirmation = deferred<unknown>()
+ logic.actions.confirmPayment(
+ fakeStripe(() => confirmation.promise),
+ fakeElements
+ )
+ logic.actions.hidePaymentEntryModal()
+ startAgainAndExpectRefusal()
+ confirmation.resolve({ paymentIntent: { id: 'pi_submitted' } })
+ await waitFor(() => expect(statusRequest).toHaveBeenCalledTimes(1))
+ await expectLogic(logic).toFinishAllListeners()
+ expectPaidOrganizationApplied()
+ expect(pushSpy).toHaveBeenCalledTimes(1)
+ })
+
+ it('lets the next start begin after a failed payment is closed', async () => {
+ mockPaidOrganization(['failed'])
+ submitCard()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.hidePaymentEntryModal()
+ logic.actions.startPaymentEntryFlow(null, '/project/1/replay')
+ expect(toastInfoSpy).not.toHaveBeenCalled()
+ expect(logic.values.paymentEntryModalOpen).toBe(true)
+ })
+
+ it('lets an add-on purchase start after the payment completes', async () => {
+ mockPaidOrganization(['success'])
+ const activate = jest.fn(() => [200, { success: false, error: 'Stopped before charging' }])
+ useMocks({ post: { '/api/billing/activate': activate } })
+ submitCard()
+ await expectLogic(logic).toFinishAllListeners()
+ expectPaidOrganizationApplied()
+ await expectLogic(logic, () => logic.actions.upgradeProducts('scale:scale', null)).toFinishAllListeners()
+ expect(toastInfoSpy).not.toHaveBeenCalled()
+ expect(activate).toHaveBeenCalledTimes(1)
+ })
+
+ it('lets the next start begin after a payment for another organization completes', async () => {
+ const organization = organizationLogic.values.currentOrganization!
+ mockPaidOrganization(['success'])
+ submitCard()
+ organizationLogic.actions.loadCurrentOrganizationSuccess({ ...organization, id: OTHER_ORGANIZATION_ID })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.completedPaymentOrganization?.id).toBe(organization.id)
+ logic.actions.hidePaymentEntryModal()
+ logic.actions.startPaymentEntryFlow(null, '/project/1/replay')
+ expect(toastInfoSpy).not.toHaveBeenCalled()
+ expect(logic.values.paymentEntryModalOpen).toBe(true)
+ })
+
+ it('refuses an add-on purchase while the status is loading and still completes the first payment', async () => {
+ const statusRequest = mockPaidOrganization(['loading', 'success'])
+ const activate = jest.fn(() => [200, { success: true }])
+ useMocks({ post: { '/api/billing/activate': activate } })
+ const retries = holdStatusRetries()
+ submitCard()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.hidePaymentEntryModal()
+ const flow = logic.values.paymentFlow
+ await expectLogic(logic, () => logic.actions.upgradeProducts('scale:scale', null)).toFinishAllListeners()
+ expect(toastInfoSpy).toHaveBeenCalledWith("We're still confirming your last payment.")
+ expect(activate).not.toHaveBeenCalled()
+ expect(logic.values.paymentFlow).toBe(flow)
+ await retries.fire()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(statusRequest).toHaveBeenCalledTimes(2)
+ expectPaidOrganizationApplied()
+ expect(pushSpy).toHaveBeenCalledTimes(1)
+ })
+
+ it('completes once when two status checks for the same payment both succeed', async () => {
+ const organization = organizationLogic.values.currentOrganization!
+ const status = deferred<[number, unknown]>()
+ let statusChecks = 0
+ useMocks({
+ get: { [`/api/organizations/${organization.id}`]: () => [200, organization] },
+ post: {
+ '/api/billing/activate/authorize/status': () => {
+ statusChecks++
+ return status.promise
+ },
+ },
+ })
+ logic.actions.confirmPayment(
+ fakeStripe(async () => ({ paymentIntent: { id: 'pi_submitted' } })),
+ fakeElements
+ )
+ await waitFor(() => expect(statusChecks).toBe(1))
+ logic.actions.pollAuthorizationStatus('pi_submitted')
+ await waitFor(() => expect(statusChecks).toBe(2))
+ status.resolve([200, { status: 'success' }])
+ await expectLogic(logic).toFinishAllListeners()
+ expect(pushSpy).toHaveBeenCalledTimes(1)
+ })
+
+ it.each([
+ ['success', [200, { status: 'success' }]],
+ ['failed', [200, { status: 'failed', error: 'Your card was declined.' }]],
+ ['error', [500, { detail: 'Server error' }]],
+ ])('does not poll again when the tab becomes visible after a %s outcome', async (_, finalResponse) => {
+ const responses: unknown[] = [[200, { status: 'loading' }], finalResponse]
+ const statusRequest = jest.fn(() => responses.shift() ?? [200, { status: 'loading' }])
+ useMocks({ post: { '/api/billing/activate/authorize/status': statusRequest } })
+ const retries = holdStatusRetries()
+ await expectLogic(logic, () => logic.actions.pollAuthorizationStatus('pi_submitted')).toFinishAllListeners()
+ await retries.fire()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(statusRequest).toHaveBeenCalledTimes(2)
+ setDocumentHidden(true)
+ setDocumentHidden(false)
+ await retries.fire()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(statusRequest).toHaveBeenCalledTimes(2)
+ })
+ })
+
+ describe('authorization status failures', () => {
+ let captureSpy: jest.SpyInstance
+
+ beforeEach(() => {
+ captureSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)
+ logic = paymentEntryLogic()
+ logic.mount()
+ logic.actions.beginPaymentFlow('00000000-0000-4000-8000-000000000001', '/project/1/replay')
+ logic.actions.setClientSecret('secret_test')
+ })
+
+ const submitCard = (): void =>
+ logic.actions.confirmPayment(
+ fakeStripe(async () => ({ paymentIntent: { id: 'pi_test' } })),
+ fakeElements
+ )
+
+ const expectFlowEnded = (): void => {
+ expect(logic.values).toMatchObject({
+ isLoading: false,
+ clientSecret: null,
+ redirectPath: null,
+ paymentSubmitted: false,
+ })
+ }
+
+ const capturedError = (): { message: string; cause: string } => {
+ expect(captureSpy).toHaveBeenCalledTimes(1)
+ const [error] = captureSpy.mock.calls[0]
+ return { message: error.message, cause: error.cause.message }
+ }
+
+ it('reports a failed authorization', async () => {
+ useMocks({
+ post: {
+ '/api/billing/activate/authorize/status': () => [
+ 200,
+ { status: 'failed', error: 'Your card was declined.' },
+ ],
+ },
+ })
+ await expectLogic(logic, () => submitCard()).toFinishAllListeners()
+ expect(logic.values.apiError).toBe('Your card was declined.')
+ expect(capturedError()).toEqual({
+ message: 'payment entry api error - authorization status failed',
+ cause: 'Your card was declined.',
+ })
+ expectFlowEnded()
+ })
+
+ it('reports a status check that times out', async () => {
+ const statusRequest = jest.fn(() => [200, { status: 'loading' }])
+ useMocks({ post: { '/api/billing/activate/authorize/status': statusRequest } })
+ const retries = holdStatusRetries()
+ await expectLogic(logic, () => submitCard()).toFinishAllListeners()
+ while (statusRequest.mock.calls.length < 30) {
+ await retries.fire()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+ expect(statusRequest).toHaveBeenCalledTimes(30)
+ expect(logic.values.apiError).toBe('Payment status check timed out')
+ expect(capturedError()).toEqual({
+ message: 'payment entry api error - authorization status timed out',
+ cause: 'Payment failed. Please try again.',
+ })
+ expectFlowEnded()
+ })
+
+ it('reports a status check that errors', async () => {
+ useMocks({ post: { '/api/billing/activate/authorize/status': () => [500, { detail: 'Server error' }] } })
+ await expectLogic(logic, () => submitCard()).toFinishAllListeners()
+ expect(logic.values.apiError).toBe('Failed to complete. Please refresh the page and try again.')
+ expect(capturedError().message).toBe('payment entry api error')
+ expectFlowEnded()
+ })
+ })
+
+ describe('a payment step that settles after it was superseded', () => {
+ type Outcome = 'resolves' | 'rejects'
+ interface PendingStep {
+ start: () => void
+ requested: () => boolean
+ settle: (outcome: Outcome) => void
+ }
+
+ const pendingRequest = (method: 'get' | 'post', url: string, body: unknown): Omit<PendingStep, 'start'> => {
+ const response = deferred<[number, unknown]>()
+ let requested = false
+ const handlers = {
+ [url]: () => {
+ requested = true
+ return response.promise
+ },
+ }
+ useMocks(method === 'get' ? { get: handlers } : { post: handlers })
+ return {
+ requested: () => requested,
+ settle: (outcome) =>
+ response.resolve(outcome === 'resolves' ? [200, body] : [500, { detail: 'Server error' }]),
+ }
+ }
+
+ const steps: Record<string, (organizationId: string) => PendingStep> = {
+ 'subscription activation': () => ({
+ ...pendingRequest('post', '/api/billing/activate', { success: true }),
+ start: () => logic.actions.startPaymentEntryFlow(),
+ }),
+ 'add-on activation': () => ({
+ ...pendingRequest('post', '/api/billing/activate', { success: true }),
+ start: () => logic.actions.upgradeProducts('scale:scale', null),
+ }),
+ 'card authorization': (organizationId) => ({
+ ...pendingRequest('post', '/api/billing/activate/authorize', { clientSecret: 'secret_stale' }),
+ start: () => {
+ logic.actions.beginPaymentFlow(organizationId)
+ logic.actions.initiateAuthorization()
+ },
+ }),
+ 'card confirmation': (organizationId) => {
+ const confirmation = deferred<unknown>()
+ let requested = false
+ const stripe = fakeStripe(() => {
+ requested = true
+ return confirmation.promise
+ })
+ return {
+ start: () => {
+ logic.actions.beginPaymentFlow(organizationId)
+ logic.actions.confirmPayment(stripe, fakeElements)
+ },
+ requested: () => requested,
+ settle: (outcome) =>
+ outcome === 'resolves'
+ ? confirmation.resolve({ paymentIntent: { id: 'pi_stale' } })
+ : confirmation.reject(new Error('Network error')),
+ }
+ },
+ 'status check': (organizationId) => ({
+ ...pendingRequest('post', '/api/billing/activate/authorize/status', { status: 'success' }),
+ start: () => {
+ logic.actions.beginPaymentFlow(organizationId)
+ logic.actions.pollAuthorizationStatus('pi_stale')
+ },
+ }),
+ 'billing read': (organizationId) => ({
+ ...pendingRequest('get', '/api/billing', { subscription_level: 'paid', customer_id: 'cus_stale' }),
+ start: () => {
+ logic.actions.beginPaymentFlow(organizationId)
+ logic.actions.completePaymentFlow(null, { success: true })
+ },
+ }),
+ 'organization read': (organizationId) => ({
+ ...pendingRequest('get', `/api/organizations/${organizationId}`, {
+ ...organizationLogic.values.currentOrganization,
+ name: 'Stale name',
+ }),
+ start: () => {
+ logic.actions.beginPaymentFlow(organizationId)
+ logic.actions.completePaymentFlow(null, { success: true })
+ },
+ }),
+ }
+
+ let captureSpy: jest.SpyInstance
+ let pushSpy: jest.SpyInstance
+
+ beforeEach(async () => {
+ await seedBilling({ customer_id: 'cus_test', subscription_level: 'free' })
+ captureSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)
+ pushSpy = jest.spyOn(router.actions, 'push')
+ logic = paymentEntryLogic()
+ logic.mount()
+ })
+
+ const snapshot = (): Record<string, unknown> => ({
+ payment: Object.fromEntries(
+ Object.keys(paymentEntryLogic.selectors).map((key) => [key, (logic.values as any)[key]])
+ ),
+ billing: billingLogic.values.billing,
+ organization: organizationLogic.values.currentOrganization,
+ user: userLogic.values.user,
+ })
+
+ const sideEffects = (): Record<string, unknown[]> => ({
+ toasts: toastErrorSpy.mock.calls,
+ captures: captureSpy.mock.calls,
+ navigations: pushSpy.mock.calls,
+ })
+
+ const settleLate = async (
+ step: PendingStep,
+ outcome: Outcome,
+ supersede: () => void
+ ): Promise<{ before: unknown; after: unknown; sideEffects: Record<string, unknown[]> }> => {
+ step.start()
+ await waitFor(() => expect(step.requested()).toBe(true))
+ supersede()
+ const before = snapshot()
+ step.settle(outcome)
+ await expectLogic(logic).toFinishAllListeners()
+ return { before, after: snapshot(), sideEffects: sideEffects() }
+ }
+ const NO_SIDE_EFFECTS = { toasts: [], captures: [], navigations: [] }
+
+ const cases = Object.keys(steps).flatMap((name) =>
+ (['resolves', 'rejects'] as const).map((outcome) => [name, outcome] as const)
+ )
+
+ it.each(cases)('%s that %s after a new flow starts changes nothing', async (name, outcome) => {
+ const step = steps[name](organizationLogic.values.currentOrganization!.id)
+ const { before, after, sideEffects } = await settleLate(step, outcome, () =>
+ logic.actions.beginPaymentFlow(OTHER_ORGANIZATION_ID)
+ )
+ expect(after).toEqual(before)
+ expect(sideEffects).toEqual(NO_SIDE_EFFECTS)
+ })
+
+ it('status check retry that fires after a new flow starts changes nothing', async () => {
+ const statuses = ['loading', 'success']
+ const statusRequest = jest.fn(() => [200, { status: statuses.shift() }])
+ useMocks({ post: { '/api/billing/activate/authorize/status': statusRequest } })
+ const retries = holdStatusRetries()
+ logic.actions.beginPaymentFlow(organizationLogic.values.currentOrganization!.id)
+ await expectLogic(logic, () => logic.actions.pollAuthorizationStatus('pi_stale')).toFinishAllListeners()
+ logic.actions.beginPaymentFlow(OTHER_ORGANIZATION_ID)
+ const before = snapshot()
+ await retries.fire()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(snapshot()).toEqual(before)
+ expect(statusRequest).toHaveBeenCalledTimes(1)
+ expect(sideEffects()).toEqual(NO_SIDE_EFFECTS)
+ })
+
+ it.each(['resolves', 'rejects'] as const)(
+ 'card authorization that %s after the modal is cancelled changes nothing',
+ async (outcome) => {
+ const step = steps['card authorization'](organizationLogic.values.currentOrganization!.id)
+ const { before, after, sideEffects } = await settleLate(step, outcome, () =>
+ logic.actions.hidePaymentEntryModal()
+ )
+ expect(after).toEqual(before)
+ expect(sideEffects).toEqual(NO_SIDE_EFFECTS)
+ expect(logic.values.paymentFlow).toBe(null)
+ }
+ )
+
+ it.each(['resolves', 'rejects'] as const)(
+ 'card authorization that %s after the logic unmounts reports nothing',
+ async (outcome) => {
+ const step = steps['card authorization'](organizationLogic.values.currentOrganization!.id)
+ step.start()
+ await waitFor(() => expect(step.requested()).toBe(true))
+ logic.unmount()
+ try {
+ step.settle(outcome)
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(toastErrorSpy).not.toHaveBeenCalled()
+ expect(captureSpy).not.toHaveBeenCalled()
+ } finally {
+ logic.mount()
+ }
+ }
+ )
+ })
})
diff --git a/frontend/src/scenes/billing/paymentEntryLogic.ts b/frontend/src/scenes/billing/paymentEntryLogic.ts
index 494c767d2f44..d744b8f13fec 100644
--- a/frontend/src/scenes/billing/paymentEntryLogic.ts
+++ b/frontend/src/scenes/billing/paymentEntryLogic.ts
@@ -1,38 +1,81 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
+import type { Stripe, StripeElements } from '@stripe/stripe-js'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { router } from 'kea-router'
import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { organizationLogic } from 'scenes/organizationLogic'
+import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
-import { BillingProductV2Type } from '~/types'
+import { usersPartialUpdate } from '~/generated/core/api'
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
+import { BillingProductV2Type, BillingType, OrganizationType } from '~/types'
-import { billingLogic } from './billingLogic'
+import {
+ billingActivateAuthorizeCreate,
+ billingActivateAuthorizeStatusCreate,
+ billingActivateCreate,
+ getBillingListUrl,
+} from 'products/billing/frontend/generated/api'
+import type { BillingActivationRequestApi } from 'products/billing/frontend/generated/api.schemas'
+import { retrieve as retrieveOrganization } from 'products/platform_features/frontend/generated/api'
+
+import { billingLogic, parseBillingResponse } from './billingLogic'
import { billingProductLogic } from './billingProductLogic'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface paymentEntryLogicValues {
- apiError: null
+ apiError: string | null
authorizationStatus: string | null
- clientSecret: null
+ clientSecret: string | null
+ completedPaymentOrganization: {
+ id: string
+ name: string
+ } | null
isLoading: boolean
paymentEntryModalOpen: boolean
+ paymentFlow: PaymentFlow | null
+ paymentOrganizationId: string | null
+ paymentSubmitted: boolean
redirectPath: string | null
- stripeError: null
+ stripeError: string | null
+ stripeReturnUrl: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface paymentEntryLogicActions {
- loadCurrentOrganization: () => any // organizationLogic
- loadUser: (resetOnFailure?: boolean | undefined) => {
- resetOnFailure: boolean | undefined
- } // userLogic
+ beginPaymentFlow: (
+ organizationId: string,
+ redirectPath?: string | null
+ ) => {
+ flow: PaymentFlow
+ redirectPath: string | null
+ }
+ cancelPaymentFlow: () => {
+ value: true
+ }
clearErrors: () => {
value: true
}
+ completePaymentFlow: (
+ redirectPath: string | null,
+ searchParams: CompletionParams
+ ) => {
+ redirectPath: string | null
+ searchParams: CompletionParams
+ }
+ confirmPayment: (
+ stripe: Stripe,
+ elements: StripeElements
+ ) => {
+ elements: StripeElements
+ stripe: Stripe
+ }
hidePaymentEntryModal: () => {
value: true
}
@@ -42,23 +85,32 @@ export interface paymentEntryLogicActions {
pollAuthorizationStatus: (paymentIntentId?: string) => {
paymentIntentId: string | undefined
}
- setApiError: (error: any) => {
- error: any
+ setApiError: (error: string | null) => {
+ error: string | null
}
setAuthorizationStatus: (status: string | null) => {
status: string | null
}
- setClientSecret: (clientSecret: any) => {
- clientSecret: any
+ setClientSecret: (clientSecret: string | null) => {
+ clientSecret: string | null
+ }
+ setCompletedPaymentOrganization: (organization: { id: string; name: string }) => {
+ organization: {
+ id: string
+ name: string
+ }
}
- setLoading: (loading: any) => {
- loading: any
+ setLoading: (loading: boolean) => {
+ loading: boolean
}
setRedirectPath: (redirectPath: string | null) => {
redirectPath: string | null
}
- setStripeError: (error: any) => {
- error: any
+ setStripeError: (error: string | null) => {
+ error: string | null
+ }
+ settlePaymentFlow: () => {
+ value: true
}
showPaymentEntryModal: () => {
value: true
@@ -70,245 +122,490 @@ export interface paymentEntryLogicActions {
product: BillingProductV2Type | null | undefined
redirectPath: string | null | undefined
}
+ upgradeProducts: (
+ products: string,
+ redirectPath: string | null
+ ) => {
+ products: string
+ redirectPath: string | null
+ }
+ viewCompletedPaymentOrganization: () => {
+ value: true
+ }
}
-export type paymentEntryLogicType = MakeLogicType<paymentEntryLogicValues, paymentEntryLogicActions>
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface paymentEntryLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ paymentOrganizationId: (paymentFlow: PaymentFlow | null) => string | null
+ stripeReturnUrl: (paymentOrganizationId: string | null, redirectPath: string | null) => string | null
+ }
+}
+
+export type paymentEntryLogicType = MakeLogicType<
+ paymentEntryLogicValues,
+ paymentEntryLogicActions,
+ Record<string, any>,
+ paymentEntryLogicMeta
+>
+
+const PAYMENT_ORGANIZATION_ERROR = 'This payment link is missing its organization. Return to billing and start again.'
+
+interface PaymentFlow {
+ organizationId: string
+ organizationName: string | null
+}
+
+type CompletionParams = Record<string, string | boolean>
+
+const fetchBilling = async (organizationId: string): Promise<BillingType | null> => {
+ const skipForecasting = featureFlagLogic.values.featureFlags[FEATURE_FLAGS.BILLING_SKIP_FORECASTING]
+ // nosemgrep: prefer-codegen-api -- The generated overview response still has generic product/period fields; retain the existing parser's BillingType contract while using the generated URL and query schema.
+ const response = await api.get<BillingType>(
+ getBillingListUrl({
+ organization_id: organizationId,
+ ...(skipForecasting ? { include_forecasting: false } : {}),
+ })
+ )
+ return parseBillingResponse(response)
+}
+
+const navigateAfterPayment = (redirectPath: string | null, searchParams: CompletionParams): void => {
+ const onCallbackPage = router.values.location.pathname === urls.billingAuthorizationStatus()
+ if (!redirectPath && !onCallbackPage) {
+ router.actions.push(router.values.location.pathname, { ...router.values.searchParams, ...searchParams })
+ return
+ }
+ const url = new URL(redirectPath || urls.organizationBilling(), window.location.origin)
+ router.actions.push(url.pathname, { ...Object.fromEntries(url.searchParams.entries()), ...searchParams })
+}
export const paymentEntryLogic = kea<paymentEntryLogicType>([
path(['scenes', 'billing', 'PaymentEntryLogic']),
connect({
logic: [billingLogic],
- actions: [userLogic, ['loadUser'], organizationLogic, ['loadCurrentOrganization']],
}),
actions({
- setClientSecret: (clientSecret) => ({ clientSecret }),
- setLoading: (loading) => ({ loading }),
- setStripeError: (error) => ({ error }),
- setApiError: (error) => ({ error }),
+ setClientSecret: (clientSecret: string | null) => ({ clientSecret }),
+ setLoading: (loading: boolean) => ({ loading }),
+ setStripeError: (error: string | null) => ({ error }),
+ setApiError: (error: string | null) => ({ error }),
clearErrors: true,
+ beginPaymentFlow: (organizationId: string, redirectPath: string | null = null) => {
+ const selected = organizationLogic.values.currentOrganization
+ const flow: PaymentFlow = {
+ organizationId,
+ organizationName: selected?.id === organizationId ? selected.name : null,
+ }
+ return { flow, redirectPath }
+ },
+ cancelPaymentFlow: true,
+ settlePaymentFlow: true,
+ completePaymentFlow: (redirectPath: string | null, searchParams: CompletionParams) => ({
+ redirectPath,
+ searchParams,
+ }),
+ setCompletedPaymentOrganization: (organization: { id: string; name: string }) => ({ organization }),
+ viewCompletedPaymentOrganization: true,
initiateAuthorization: true,
+ confirmPayment: (stripe: Stripe, elements: StripeElements) => ({ stripe, elements }),
pollAuthorizationStatus: (paymentIntentId?: string) => ({ paymentIntentId }),
setAuthorizationStatus: (status: string | null) => ({ status }),
startPaymentEntryFlow: (product?: BillingProductV2Type | null, redirectPath?: string | null) => ({
product,
redirectPath,
}),
+ upgradeProducts: (products: string, redirectPath: string | null) => ({ products, redirectPath }),
showPaymentEntryModal: true,
hidePaymentEntryModal: true,
setRedirectPath: (redirectPath: string | null) => ({ redirectPath }),
}),
reducers({
+ paymentFlow: [
+ null as PaymentFlow | null,
+ { beginPaymentFlow: (_, { flow }) => flow, cancelPaymentFlow: () => null },
+ ],
+ paymentSubmitted: [
+ false,
+ {
+ confirmPayment: () => true,
+ setStripeError: () => false,
+ beginPaymentFlow: () => false,
+ settlePaymentFlow: () => false,
+ },
+ ],
+ completedPaymentOrganization: [
+ null as { id: string; name: string } | null,
+ {
+ setCompletedPaymentOrganization: (_, { organization }) => organization,
+ beginPaymentFlow: () => null,
+ hidePaymentEntryModal: () => null,
+ },
+ ],
clientSecret: [
- null,
+ null as string | null,
{
setClientSecret: (_, { clientSecret }) => clientSecret,
+ beginPaymentFlow: () => null,
+ hidePaymentEntryModal: () => null,
+ settlePaymentFlow: () => null,
},
],
isLoading: [
false,
{
setLoading: (_, { loading }) => loading,
+ beginPaymentFlow: () => false,
+ hidePaymentEntryModal: () => false,
+ settlePaymentFlow: () => false,
},
],
stripeError: [
- null,
- {
- setStripeError: (_, { error }) => error,
- clearErrors: () => null,
- },
+ null as string | null,
+ { setStripeError: (_, { error }) => error, clearErrors: () => null, beginPaymentFlow: () => null },
],
apiError: [
- null,
- {
- setApiError: (_, { error }) => error,
- clearErrors: () => null,
- },
+ null as string | null,
+ { setApiError: (_, { error }) => error, clearErrors: () => null, beginPaymentFlow: () => null },
],
authorizationStatus: [
null as string | null,
- {
- setAuthorizationStatus: (_, { status }) => status,
- },
- ],
- paymentEntryModalOpen: [
- false,
- {
- showPaymentEntryModal: () => true,
- hidePaymentEntryModal: () => false,
- },
+ { setAuthorizationStatus: (_, { status }) => status, beginPaymentFlow: () => null },
],
+ paymentEntryModalOpen: [false, { showPaymentEntryModal: () => true, hidePaymentEntryModal: () => false }],
redirectPath: [
null as string | null,
{
setRedirectPath: (_, { redirectPath }) => redirectPath,
+ beginPaymentFlow: (_, { redirectPath }) => redirectPath,
+ settlePaymentFlow: () => null,
},
],
}),
- listeners(({ actions, values }) => ({
- startPaymentEntryFlow: async ({ product, redirectPath }) => {
- const { billing, billingManagedByPartnerNotice } = billingLogic.values
-
- if (billingManagedByPartnerNotice) {
- lemonToast.info(billingManagedByPartnerNotice)
+ selectors({
+ paymentOrganizationId: [
+ (s) => [s.paymentFlow],
+ (flow: PaymentFlow | null): string | null => flow?.organizationId ?? null,
+ ],
+ stripeReturnUrl: [
+ (s) => [s.paymentOrganizationId, s.redirectPath],
+ (organizationId: string | null, redirectPath: string | null): string | null => {
+ if (!organizationId) {
+ return null
+ }
+ const url = new URL(urls.billingAuthorizationStatus(), window.location.origin)
+ url.searchParams.set('organization_id', organizationId)
+ if (redirectPath) {
+ url.searchParams.set('postRedirectPath', redirectPath)
+ }
+ return url.toString()
+ },
+ ],
+ }),
+ listeners(({ actions, asyncActions, values, cache }) => {
+ // Handlers run only while the flow that started the step is still the live one.
+ const runPaymentStep = async <T>(
+ request: () => Promise<T>,
+ onSuccess: (result: T) => void | Promise<void>,
+ onError?: (error: unknown) => void
+ ): Promise<void> => {
+ const flow = values.paymentFlow
+ const isCurrent = (): boolean => !!flow && !cache.disposables.isDisposed && values.paymentFlow === flow
+ let result: T
+ try {
+ result = await request()
+ } catch (error) {
+ if (isCurrent()) {
+ onError?.(error)
+ }
return
}
+ if (isCurrent()) {
+ await onSuccess(result)
+ }
+ }
- if (billing?.customer_id) {
- // Returning customer — call POST API to activate subscription
- actions.setLoading(true)
- if (product) {
- const theBillingProductLogic = billingProductLogic({ product })
- theBillingProductLogic.actions.setBillingProductLoading(product.type)
- }
-
- try {
- const body: Record<string, string> = { products: 'all_products:' }
- if (product?.type) {
- body.intent_product = product.type
- }
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingActivateCreate() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
- const response = await api.create('api/billing/activate', body)
-
+ const activateProducts = async (
+ organizationId: string,
+ body: Omit<BillingActivationRequestApi, 'organization_id'>,
+ redirectPath: string | null,
+ searchParams: CompletionParams,
+ errorMessage: string
+ ): Promise<void> => {
+ await runPaymentStep(
+ () => billingActivateCreate({ organization_id: organizationId, ...body }),
+ async (response) => {
if (response.success) {
- await billingLogic.asyncActions.loadBilling()
- if (redirectPath) {
- const url = new URL(redirectPath, window.location.origin)
- const searchParams = Object.fromEntries(url.searchParams.entries())
- router.actions.push(url.pathname, { ...searchParams, upgraded: 'true' })
- } else {
- router.actions.push(router.values.location.pathname, {
- ...router.values.searchParams,
- upgraded: 'true',
- })
- }
- actions.loadCurrentOrganization()
- actions.loadUser()
- } else if (response.must_setup_payment) {
- // Card invalid or missing — show modal (same as new customer flow)
- actions.setRedirectPath(redirectPath || null)
+ await asyncActions.completePaymentFlow(redirectPath, searchParams)
+ return
+ }
+ actions.setLoading(false)
+ if (response.must_setup_payment) {
actions.showPaymentEntryModal()
} else {
lemonToast.error(response.error || 'Failed to activate subscription')
}
- } catch (error) {
- posthog.captureException(
- new Error('payment entry api error - activate subscription error', { cause: error })
- )
- lemonToast.error('Failed to activate subscription. Please try again.')
- } finally {
+ },
+ (error) => {
actions.setLoading(false)
- if (product) {
- const { setBillingProductLoading } = billingProductLogic({ product }).actions
- setBillingProductLoading(null)
- }
+ posthog.captureException(new Error(errorMessage, { cause: error }))
+ lemonToast.error('Failed to activate subscription. Please try again.')
}
- return
- }
+ )
+ }
- // New customer — show the payment modal
- actions.setRedirectPath(redirectPath || null)
- actions.showPaymentEntryModal()
- },
- initiateAuthorization: async () => {
- actions.setLoading(true)
- actions.clearErrors()
- try {
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingActivateAuthorizeCreate() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
- const response = await api.create('api/billing/activate/authorize')
- actions.setClientSecret(response.clientSecret)
- actions.setLoading(false)
- } catch (error) {
- posthog.captureException(
- new Error('payment entry api error - initiate authorization error', { cause: error })
- )
- actions.setApiError('Failed to initialize payment')
- actions.setLoading(false)
+ // Replacing a submitted flow would drop its result, so a new flow waits until it settles.
+ const startFlow = (redirectPath: string | null): string | null => {
+ if (values.paymentSubmitted) {
+ lemonToast.info("We're still confirming your last payment.")
+ return null
}
- },
-
- pollAuthorizationStatus: ({ paymentIntentId }) => {
- const pollInterval = 2000 // Poll every 2 seconds
- const maxAttempts = 30 // Max 1 minute of polling (30 * 2 seconds)
-
- let attempts = 0
- const poll = async (): Promise<void> => {
- try {
- const urlParams = new URLSearchParams(window.location.search)
- const searchPaymentIntentId = urlParams.get('payment_intent')
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. billingActivateAuthorizeStatusCreate() from 'products/billing/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.
- const response = await api.create('api/billing/activate/authorize/status', {
- payment_intent_id: paymentIntentId || searchPaymentIntentId,
- })
- const status = response.status
- const errorMessage = response.error || 'Payment failed. Please try again.'
-
- actions.setAuthorizationStatus(status)
+ const organizationId = organizationLogic.values.currentOrganization?.id
+ if (!organizationId) {
+ lemonToast.error('Reload the page before updating payment details.')
+ return null
+ }
+ actions.beginPaymentFlow(organizationId, redirectPath)
+ return organizationId
+ }
- if (status === 'success') {
- // Load before doing anything to reload in entitlements on the organization
- await billingLogic.asyncActions.loadBilling()
- if (values.redirectPath) {
- const url = new URL(values.redirectPath, window.location.origin)
- const searchParams = Object.fromEntries(url.searchParams.entries())
- router.actions.push(url.pathname, { ...searchParams, success: true })
- } else {
- router.actions.push(router.values.location.pathname, {
- ...router.values.searchParams,
- success: true,
+ return {
+ beginPaymentFlow: () => {
+ cache.disposables.dispose('authorizationPoll')
+ },
+ completePaymentFlow: async ({ redirectPath, searchParams }) => {
+ const flow = values.paymentFlow
+ if (!flow || cache.completedPaymentFlow === flow) {
+ return
+ }
+ cache.completedPaymentFlow = flow
+ const { organizationId } = flow
+ await runPaymentStep(
+ async (): Promise<[BillingType | null, OrganizationType | null]> => {
+ // The billing read saves the organization's new features, so read the organization after it.
+ const billing = await fetchBilling(organizationId).catch(() => null)
+ // Generated organization teams/features are readonly arrays; the stores use OrganizationType.
+ const fetchedOrganization = await retrieveOrganization(organizationId)
+ .then((organization) => organization as unknown as OrganizationType)
+ .catch(() => null)
+ return [billing, fetchedOrganization]
+ },
+ ([billing, fetchedOrganization]) => {
+ actions.settlePaymentFlow()
+ const organization = fetchedOrganization?.id === organizationId ? fetchedOrganization : null
+ if (organizationLogic.values.currentOrganization?.id !== organizationId) {
+ actions.setCompletedPaymentOrganization({
+ id: organizationId,
+ name: flow.organizationName || organization?.name || 'the original organization',
})
+ actions.clearErrors()
+ if (router.values.location.pathname !== urls.billingAuthorizationStatus()) {
+ actions.showPaymentEntryModal()
+ }
+ return
+ }
+ if (billing) {
+ billingLogic.actions.loadBillingSuccess(billing, organizationId)
+ }
+ if (organization) {
+ organizationLogic.actions.loadCurrentOrganizationSuccess(organization)
+ const user = userLogic.values.user
+ if (user) {
+ userLogic.actions.loadUserSuccess({ ...user, organization })
+ }
}
- actions.loadCurrentOrganization()
- actions.loadUser()
+ navigateAfterPayment(redirectPath, searchParams)
actions.hidePaymentEntryModal()
- return
- } else if (status === 'failed') {
- actions.setApiError(errorMessage)
- posthog.captureException(
- new Error('payment entry api error - authorization status failed', {
- cause: new Error(errorMessage),
- })
- )
- return
}
-
- attempts++
- if (attempts < maxAttempts) {
- setTimeout(() => void poll(), pollInterval)
- } else {
- actions.setApiError('Payment status check timed out')
+ )
+ },
+ viewCompletedPaymentOrganization: async () => {
+ const organization = values.completedPaymentOrganization
+ if (!organization) {
+ return
+ }
+ // Not userLogic.updateCurrentOrganization: it skips the switch while the cached user names this
+ // organization, and that cache can lag a switch made in another tab.
+ try {
+ await usersPartialUpdate('@me', { set_current_organization: organization.id })
+ } catch {
+ lemonToast.error('Could not switch organization. Try again.')
+ return
+ }
+ sidePanelStateLogic.findMounted()?.actions.closeSidePanel()
+ window.location.href = urls.organizationBilling()
+ },
+ startPaymentEntryFlow: async ({ product, redirectPath }) => {
+ const { billing, billingManagedByPartnerNotice } = billingLogic.values
+ if (billingManagedByPartnerNotice) {
+ lemonToast.info(billingManagedByPartnerNotice)
+ return
+ }
+ const organizationId = startFlow(redirectPath || null)
+ if (!organizationId) {
+ return
+ }
+ if (!billing?.customer_id) {
+ actions.showPaymentEntryModal()
+ return
+ }
+ actions.setLoading(true)
+ if (product) {
+ billingProductLogic({ product }).actions.setBillingProductLoading(product.type)
+ }
+ try {
+ await activateProducts(
+ organizationId,
+ { products: 'all_products:', ...(product?.type ? { intent_product: product.type } : {}) },
+ redirectPath || null,
+ { upgraded: 'true' },
+ 'payment entry api error - activate subscription error'
+ )
+ } finally {
+ if (product) {
+ billingProductLogic({ product }).actions.setBillingProductLoading(null)
+ }
+ }
+ },
+ upgradeProducts: async ({ products, redirectPath }) => {
+ const organizationId = startFlow(redirectPath)
+ if (!organizationId) {
+ return
+ }
+ await activateProducts(
+ organizationId,
+ { products },
+ redirectPath,
+ { upgraded: 'true', products },
+ 'payment entry api error - product upgrade error'
+ )
+ },
+ initiateAuthorization: async () => {
+ if (values.completedPaymentOrganization) {
+ return
+ }
+ const organizationId = values.paymentOrganizationId
+ if (!organizationId) {
+ actions.setApiError(PAYMENT_ORGANIZATION_ERROR)
+ return
+ }
+ actions.setClientSecret(null)
+ actions.setLoading(true)
+ actions.clearErrors()
+ await runPaymentStep(
+ () => billingActivateAuthorizeCreate({ organization_id: organizationId }),
+ (response) => {
+ actions.setClientSecret(response.clientSecret || null)
+ actions.setLoading(false)
+ },
+ (error) => {
posthog.captureException(
- new Error('payment entry api error - authorization status timed out', {
- cause: new Error(errorMessage),
- })
+ new Error('payment entry api error - initiate authorization error', { cause: error })
)
+ actions.setApiError('Failed to initialize payment')
+ actions.setLoading(false)
}
- } catch (error) {
- actions.setStripeError('Failed to complete. Please refresh the page and try again.')
- posthog.captureException(new Error('payment entry api error', { cause: error }))
- } finally {
+ )
+ },
+ confirmPayment: async ({ stripe, elements }) => {
+ const returnUrl = values.stripeReturnUrl
+ if (!returnUrl) {
+ actions.setStripeError('Return to billing and start the payment flow again.')
+ return
+ }
+ actions.setLoading(true)
+ const failConfirmation = (error: unknown, message: string): void => {
actions.setLoading(false)
- actions.setClientSecret(null)
- actions.setRedirectPath(null)
+ actions.setStripeError(message)
+ posthog.captureException(new Error('payment entry stripe error', { cause: error }))
}
- }
-
- // Fire and forget polling, it'll handle cancelation and stopping itself when it reaches max attempts
- poll()
- },
-
- hidePaymentEntryModal: () => {
- // Clear client secret when modal is closed to ensure a fresh one is used next time
- actions.setClientSecret(null)
- actions.clearErrors()
- },
- })),
+ await runPaymentStep(
+ () =>
+ stripe.confirmPayment({
+ elements,
+ confirmParams: { return_url: returnUrl },
+ redirect: 'if_required',
+ }),
+ (result) => {
+ if (result.error) {
+ failConfirmation(result.error, result.error.message || 'Payment failed. Please try again.')
+ } else {
+ actions.pollAuthorizationStatus(result.paymentIntent.id)
+ }
+ },
+ (error) => failConfirmation(error, 'Payment failed. Please try again.')
+ )
+ },
+ pollAuthorizationStatus: async ({ paymentIntentId }) => {
+ const organizationId = values.paymentOrganizationId
+ const redirectPath = values.redirectPath
+ const intentId = paymentIntentId || new URLSearchParams(window.location.search).get('payment_intent')
+ if (!organizationId) {
+ actions.setApiError(PAYMENT_ORGANIZATION_ERROR)
+ return
+ }
+ actions.setLoading(true)
+ let attempts = 0
+ const poll = async (): Promise<void> => {
+ // Only a pending retry stays registered, so a tab becoming visible cannot restart a finished poll.
+ cache.disposables.dispose('authorizationPoll')
+ await runPaymentStep(
+ () =>
+ billingActivateAuthorizeStatusCreate({
+ organization_id: organizationId,
+ payment_intent_id: intentId,
+ }),
+ async (response) => {
+ const status = response.status || (response.success ? 'success' : 'failed')
+ const errorMessage = response.error || 'Payment failed. Please try again.'
+ actions.setAuthorizationStatus(status)
+ if (status === 'success') {
+ await asyncActions.completePaymentFlow(redirectPath, { success: true })
+ } else if (status === 'failed') {
+ actions.setApiError(errorMessage)
+ posthog.captureException(
+ new Error('payment entry api error - authorization status failed', {
+ cause: new Error(errorMessage),
+ })
+ )
+ actions.settlePaymentFlow()
+ } else if (++attempts < 30) {
+ cache.disposables.add(() => {
+ const timer = setTimeout(() => void poll(), 2000)
+ return () => clearTimeout(timer)
+ }, 'authorizationPoll')
+ } else {
+ actions.setApiError('Payment status check timed out')
+ posthog.captureException(
+ new Error('payment entry api error - authorization status timed out', {
+ cause: new Error(errorMessage),
+ })
+ )
+ actions.settlePaymentFlow()
+ }
+ },
+ (error) => {
+ actions.setApiError('Failed to complete. Please refresh the page and try again.')
+ posthog.captureException(new Error('payment entry api error', { cause: error }))
+ actions.settlePaymentFlow()
+ }
+ )
+ }
+ await poll()
+ },
+ hidePaymentEntryModal: () => {
+ if (!values.paymentSubmitted) {
+ actions.cancelPaymentFlow()
+ }
+ actions.clearErrors()
+ },
+ }
+ }),
afterMount(({ actions }) => {
- // In case the user gets redirected back to the app after completing payment on Stripe's hosted page,
- // we need to set up the proper `redirectPath` so that polling sends us to the right place after successful payment
- const urlParams = new URLSearchParams(window.location.search)
- const postRedirectPath = urlParams.get('postRedirectPath')
- if (postRedirectPath) {
- actions.setRedirectPath(postRedirectPath)
+ const params = new URLSearchParams(window.location.search)
+ const organizationId = params.get('organization_id')
+ if (organizationId && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(organizationId)) {
+ actions.beginPaymentFlow(organizationId, params.get('postRedirectPath'))
}
}),
])
diff --git a/products/billing/frontend/generated/api.schemas.ts b/products/billing/frontend/generated/api.schemas.ts
index f1a5ce49eb65..46fa6a440c43 100644
--- a/products/billing/frontend/generated/api.schemas.ts
+++ b/products/billing/frontend/generated/api.schemas.ts
@@ -66,6 +66,65 @@ export interface BillingOverviewResponseApi {
billing_managed_by_partner: BillingManagedByPartnerApi | null
}
+export interface BillingActivationRequestApi {
+ /** Organization selected when this payment flow started. */
+ organization_id: string
+ /** Product and plan keys to activate. */
+ products?: string
+ /** Product that prompted the subscription upgrade. */
+ intent_product?: string
+ /** JSON-encoded custom product limits to apply on activation. */
+ custom_limits_usd?: string
+}
+
+export interface BillingActivationResponseApi {
+ /** Whether the subscription was activated. */
+ success?: boolean
+ /** Whether payment details are required. */
+ must_setup_payment?: boolean
+ /** Products activated by this request. */
+ products?: string[]
+ /**
+ * Reason activation failed.
+ * @nullable
+ */
+ error?: string | null
+}
+
+export interface BillingPaymentOrganizationApi {
+ /** Organization selected when this payment flow started. */
+ organization_id: string
+}
+
+export interface BillingAuthorizationResponseApi {
+ /** Stripe client secret for the authorization intent. */
+ clientSecret?: string
+ /** Whether authorization completed without a payment form. */
+ success?: boolean
+}
+
+export interface BillingAuthorizationStatusRequestApi {
+ /** Organization selected when this payment flow started. */
+ organization_id: string
+ /**
+ * Stripe payment intent created for this organization.
+ * @nullable
+ */
+ payment_intent_id?: string | null
+}
+
+export interface BillingAuthorizationStatusResponseApi {
+ /** Authorization status: loading, success, or failed. */
+ status?: string
+ /**
+ * Reason authorization failed.
+ * @nullable
+ */
+ error?: string | null
+ /** Whether authorization completed without a payment form. */
+ success?: boolean
+}
+
export interface BillingApi {
/** @maxLength 100 */
plan: string
@@ -1265,6 +1324,18 @@ export interface ProjectUsageSummaryApi {
results: ProjectUsageItemApi[]
}
+export type BillingListParams = {
+ /**
+ * Whether to include usage forecasting.
+ * @nullable
+ */
+ include_forecasting?: boolean | null
+ /**
+ * Explicit organization to refresh after payment.
+ */
+ organization_id?: string
+}
+
export type BillingSpendRetrieveParams = {
/**
* The `next` cursor from the previous page. Opaque. Ignored without page_size.
diff --git a/products/billing/frontend/generated/api.ts b/products/billing/frontend/generated/api.ts
index b2aa0aa3a10b..b5f57ecfb707 100644
--- a/products/billing/frontend/generated/api.ts
+++ b/products/billing/frontend/generated/api.ts
@@ -9,6 +9,8 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ BillingActivationRequestApi,
+ BillingActivationResponseApi,
BillingAlertCheckNowResponseApi,
BillingAlertConfigurationApi,
BillingAlertDeleteDestinationApi,
@@ -17,12 +19,17 @@ import type {
BillingAlertsEventsListParams,
BillingAlertsListParams,
BillingApi,
+ BillingAuthorizationResponseApi,
+ BillingAuthorizationStatusRequestApi,
+ BillingAuthorizationStatusResponseApi,
BillingFeaturesApi,
BillingForecastApi,
BillingInvoicesApi,
BillingInvoicesListParams,
BillingLimitsApi,
+ BillingListParams,
BillingOverviewResponseApi,
+ BillingPaymentOrganizationApi,
BillingPeriodResponseApi,
BillingProductApi,
BillingProductsApi,
@@ -73,12 +80,25 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
-export const getBillingListUrl = () => {
- return `/api/billing/`
+export const getBillingListUrl = (params?: BillingListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0 ? `/api/billing/?${stringifiedParams}` : `/api/billing/`
}
-export const billingList = async (options?: RequestInit): Promise<BillingOverviewResponseApi> => {
- return apiMutator<BillingOverviewResponseApi>(getBillingListUrl(), {
+export const billingList = async (
+ params?: BillingListParams,
+ options?: RequestInit
+): Promise<BillingOverviewResponseApi> => {
+ return apiMutator<BillingOverviewResponseApi>(getBillingListUrl(params), {
...options,
method: 'GET',
})
@@ -88,12 +108,15 @@ export const getBillingActivateCreateUrl = () => {
return `/api/billing/activate/`
}
-export const billingActivateCreate = async (billingApi: BillingApi, options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getBillingActivateCreateUrl(), {
+export const billingActivateCreate = async (
+ billingActivationRequestApi: BillingActivationRequestApi,
+ options?: RequestInit
+): Promise<BillingActivationResponseApi> => {
+ return apiMutator<BillingActivationResponseApi>(getBillingActivateCreateUrl(), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(billingApi),
+ body: JSON.stringify(billingActivationRequestApi),
})
}
@@ -101,12 +124,15 @@ export const getBillingActivateAuthorizeCreateUrl = () => {
return `/api/billing/activate/authorize/`
}
-export const billingActivateAuthorizeCreate = async (billingApi: BillingApi, options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getBillingActivateAuthorizeCreateUrl(), {
+export const billingActivateAuthorizeCreate = async (
+ billingPaymentOrganizationApi: BillingPaymentOrganizationApi,
+ options?: RequestInit
+): Promise<BillingAuthorizationResponseApi> => {
+ return apiMutator<BillingAuthorizationResponseApi>(getBillingActivateAuthorizeCreateUrl(), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(billingApi),
+ body: JSON.stringify(billingPaymentOrganizationApi),
})
}
@@ -115,14 +141,14 @@ export const getBillingActivateAuthorizeStatusCreateUrl = () => {
}
export const billingActivateAuthorizeStatusCreate = async (
- billingApi: BillingApi,
+ billingAuthorizationStatusRequestApi: BillingAuthorizationStatusRequestApi,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getBillingActivateAuthorizeStatusCreateUrl(), {
+): Promise<BillingAuthorizationStatusResponseApi> => {
+ return apiMutator<BillingAuthorizationStatusResponseApi>(getBillingActivateAuthorizeStatusCreateUrl(), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(billingApi),
+ body: JSON.stringify(billingAuthorizationStatusRequestApi),
})
}
diff --git a/products/billing/frontend/generated/api.zod.ts b/products/billing/frontend/generated/api.zod.ts
index 85311eaf1db8..c3a391316169 100644
--- a/products/billing/frontend/generated/api.zod.ts
+++ b/products/billing/frontend/generated/api.zod.ts
@@ -9,25 +9,20 @@
*/
import * as zod from 'zod'
-export const billingActivateCreateBodyPlanMax = 100
-
export const BillingActivateCreateBody = /* @__PURE__ */ zod.object({
- plan: zod.string().max(billingActivateCreateBodyPlanMax),
- billing_limit: zod.number(),
+ organization_id: zod.uuid().describe('Organization selected when this payment flow started.'),
+ products: zod.string().optional().describe('Product and plan keys to activate.'),
+ intent_product: zod.string().optional().describe('Product that prompted the subscription upgrade.'),
+ custom_limits_usd: zod.string().optional().describe('JSON-encoded custom product limits to apply on activation.'),
})
-export const billingActivateAuthorizeCreateBodyPlanMax = 100
-
export const BillingActivateAuthorizeCreateBody = /* @__PURE__ */ zod.object({
- plan: zod.string().max(billingActivateAuthorizeCreateBodyPlanMax),
- billing_limit: zod.number(),
+ organization_id: zod.uuid().describe('Organization selected when this payment flow started.'),
})
-export const billingActivateAuthorizeStatusCreateBodyPlanMax = 100
-
export const BillingActivateAuthorizeStatusCreateBody = /* @__PURE__ */ zod.object({
- plan: zod.string().max(billingActivateAuthorizeStatusCreateBodyPlanMax),
- billing_limit: zod.number(),
+ organization_id: zod.uuid().describe('Organization selected when this payment flow started.'),
+ payment_intent_id: zod.string().nullish().describe('Stripe payment intent created for this organization.'),
})
export const billingCouponsClaimCreateBodyPlanMax = 100
diff --git a/products/billing/mcp/tools.yaml b/products/billing/mcp/tools.yaml
index 6c59fd79e722..a173cb91cbfb 100644
--- a/products/billing/mcp/tools.yaml
+++ b/products/billing/mcp/tools.yaml
@@ -79,6 +79,8 @@ tools:
exclude_params:
- limit
- offset
+ - organization_id
+ - include_forecasting
url_prefix: /organization/billing/overview
response:
exclude:
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 823d5f0d4940..27f38ca4c95e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17531,6 +17531,31 @@ export namespace Schemas {
billing_limit: number;
}
+ export interface BillingActivationRequest {
+ /** Organization selected when this payment flow started. */
+ organization_id: string;
+ /** Product and plan keys to activate. */
+ products?: string;
+ /** Product that prompted the subscription upgrade. */
+ intent_product?: string;
+ /** JSON-encoded custom product limits to apply on activation. */
+ custom_limits_usd?: string;
+ }
+
+ export interface BillingActivationResponse {
+ /** Whether the subscription was activated. */
+ success?: boolean;
+ /** Whether payment details are required. */
+ must_setup_payment?: boolean;
+ /** Products activated by this request. */
+ products?: string[];
+ /**
+ * Reason activation failed.
+ * @nullable
+ */
+ error?: string | null;
+ }
+
/**
* * `product` - Product
* * `addon` - Addon
@@ -18055,6 +18080,35 @@ export namespace Schemas {
hog_function_ids: string[];
}
+ export interface BillingAuthorizationResponse {
+ /** Stripe client secret for the authorization intent. */
+ clientSecret?: string;
+ /** Whether authorization completed without a payment form. */
+ success?: boolean;
+ }
+
+ export interface BillingAuthorizationStatusRequest {
+ /** Organization selected when this payment flow started. */
+ organization_id: string;
+ /**
+ * Stripe payment intent created for this organization.
+ * @nullable
+ */
+ payment_intent_id?: string | null;
+ }
+
+ export interface BillingAuthorizationStatusResponse {
+ /** Authorization status: loading, success, or failed. */
+ status?: string;
+ /**
+ * Reason authorization failed.
+ * @nullable
+ */
+ error?: string | null;
+ /** Whether authorization completed without a payment form. */
+ success?: boolean;
+ }
+
export interface BillingFeatures {
available_product_features: ProductFeature[];
}
@@ -18248,6 +18302,11 @@ export namespace Schemas {
billing_managed_by_partner: BillingManagedByPartner | null;
}
+ export interface BillingPaymentOrganization {
+ /** Organization selected when this payment flow started. */
+ organization_id: string;
+ }
+
export interface BillingPeriodResponse {
/**
* Start of the organization's current billing period, or null when billing has not synced a period.
@@ -117443,6 +117502,18 @@ export namespace Schemas {
compare: _SpanTreeNode[] | null;
}
+ export type BillingListParams = {
+ /**
+ * Whether to include usage forecasting.
+ * @nullable
+ */
+ include_forecasting?: boolean | null;
+ /**
+ * Explicit organization to refresh after payment.
+ */
+ organization_id?: string;
+ };
+
export type BillingSpendRetrieveParams = {
/**
* The `next` cursor from the previous page. Opaque. Ignored without page_size.
diff --git a/services/mcp/src/generated/billing/api.ts b/services/mcp/src/generated/billing/api.ts
index 799d1e84ce38..3b3a6a428f7f 100644
--- a/services/mcp/src/generated/billing/api.ts
+++ b/services/mcp/src/generated/billing/api.ts
@@ -8,6 +8,11 @@
*/
import * as zod from 'zod'
+export const BillingListQueryParams = () => zod.object({
+ include_forecasting: zod.boolean().nullish().describe('Whether to include usage forecasting.'),
+ organization_id: zod.string().optional().describe('Explicit organization to refresh after payment.'),
+})
+
/**
* Endpoint to fetch spend data (proxy to billing service).
*/