:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(integrations): handle open-invoice block when disconnecting Vercel (#69804)
posthog[bot]f3a2393684ac
diff --git a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.tsindex 53c4f88deb20..4f91e83a1a63 100644--- a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts+++ b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts@@ -70,8 +70,8 @@ export const organizationIntegrationsLogic = kea<organizationIntegrationsLogicTyawait api.organizationIntegrations.delete(id)lemonToast.success('Integration disconnected.')actions.loadOrganizationIntegrations()- } catch {- lemonToast.error('Failed to disconnect integration. Please try again.')+ } catch (error: any) {+ lemonToast.error(error?.detail || 'Failed to disconnect integration. Please try again.')}},},diff --git a/posthog/api/organization_integration.py b/posthog/api/organization_integration.pyindex 7cfd6da301da..44f69bcf1869 100644--- a/posthog/api/organization_integration.py+++ b/posthog/api/organization_integration.py@@ -1,9 +1,10 @@from typing import Anyimport structlog-from drf_spectacular.utils import extend_schema-from rest_framework import mixins, serializers, viewsets+from drf_spectacular.utils import OpenApiResponse, extend_schema+from rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.decorators import action+from rest_framework.exceptions import APIExceptionfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -17,6 +18,15 @@ from posthog.permissions import OrganizationAdminWritePermissionslogger = structlog.get_logger(__name__)+class OpenInvoicesError(APIException):+ status_code = status.HTTP_409_CONFLICT+ default_detail = (+ "This integration has unpaid invoices that must be resolved before disconnecting. "+ "Please contact [email protected] for help."+ )+ default_code = "open_invoices_error"++class OrganizationIntegrationSerializer(serializers.ModelSerializer):"""Serializer for organization-level integrations."""@@ -66,7 +76,13 @@ class OrganizationIntegrationViewSet(serializer_class = OrganizationIntegrationSerializerpermission_classes = [OrganizationAdminWritePermissions]- @extend_schema(operation_id="organization_integrations_destroy")+ @extend_schema(+ operation_id="organization_integrations_destroy",+ responses={+ 204: None,+ 409: OpenApiResponse(description="Deauthorization is blocked because the account has unpaid invoices."),+ },+ )def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:return super().destroy(request, *args, **kwargs)@@ -74,10 +90,22 @@ class OrganizationIntegrationViewSet(is_marketplace = instance.config.get("type") != "connectable"if is_marketplace and instance.integration_id:- try:- from ee.vercel.integration import VercelIntegration+ from ee.billing.billing_manager import BillingServiceOpenInvoicesError+ from ee.vercel.integration import VercelIntegration+ try:VercelIntegration.delete_installation(instance.integration_id)+ except BillingServiceOpenInvoicesError as e:+ # Expected business condition, not a crash: billing blocks deauthorization while+ # invoices are unpaid. Mirror the marketplace DELETE API (409) so the UI disconnect+ # can't sidestep the guard, and abort the local delete instead of capturing an error.+ logger.warning(+ "organization_integration.delete_installation_blocked_by_open_invoices",+ organization_id=str(instance.organization_id),+ integration_id=instance.integration_id,+ reason=e.message,+ )+ raise OpenInvoicesError(detail=e.message)except Exception as e:capture_exception(e,diff --git a/posthog/api/test/test_organization_integration.py b/posthog/api/test/test_organization_integration.pyindex c9266490a364..993272865e4b 100644--- a/posthog/api/test/test_organization_integration.py+++ b/posthog/api/test/test_organization_integration.py@@ -1,4 +1,5 @@from posthog.test.base import APIBaseTest+from unittest.mock import patchfrom rest_framework import status@@ -131,6 +132,42 @@ class TestOrganizationIntegrationViewSet(APIBaseTest):self.assertFalse(OrganizationIntegration.objects.filter(id=self.integration_vercel.id).exists())self.assertFalse(Integration.objects.filter(id=team_integration.id).exists())+ def test_delete_org_integration_blocked_when_billing_has_open_invoices(self):+ from ee.billing.billing_manager import BillingServiceOpenInvoicesError++ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ # Marketplace installs omit type=connectable; that is what routes through delete_installation.+ self.assertNotEqual(self.integration_vercel.config.get("type"), "connectable")++ team_integration = Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.VERCEL,+ integration_id=str(self.team.id),+ config={"type": "connectable"},+ )++ billing_message = "Cannot uninstall billing provider: 1 unpaid invoice must be resolved first."+ url = f"/api/organizations/{self.organization.id}/integrations/{self.integration_vercel.id}/"+ with (+ patch(+ "ee.vercel.integration.VercelIntegration.delete_installation",+ side_effect=BillingServiceOpenInvoicesError(billing_message),+ ) as mock_delete_installation,+ patch("posthog.api.organization_integration.capture_exception") as mock_capture,+ ):+ response = self.client.delete(url)++ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)+ self.assertEqual(response.json()["detail"], billing_message)+ mock_delete_installation.assert_called_once_with(self.integration_vercel.integration_id)+ # An expected billing condition should not be reported as a crash.+ mock_capture.assert_not_called()+ # The local integration must survive so the UI disconnect can't sidestep the billing guard.+ self.assertTrue(OrganizationIntegration.objects.filter(id=self.integration_vercel.id).exists())+ self.assertTrue(Integration.objects.filter(id=team_integration.id).exists())+def test_delete_organization_integration_unauthorized(self):self.client.logout()