: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
refactor(customer-analytics): Thin external account API behind facade (#64979)
Arthur Moreira de Deus24079ab9c796
diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.pyindex 08267592c84b..4db34f9f429d 100644--- a/products/customer_analytics/backend/constants.py+++ b/products/customer_analytics/backend/constants.py@@ -3,6 +3,10 @@ DEFAULT_ACTIVITY_EVENT = {"kind": "EventsNode", "event": "$pageview", "name": "$# Mirrors frontend `FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP`.CUSTOMER_ANALYTICS_CSP_FLAG = "customer-analytics-csp"+# Account assignment roles, each assignable to a user. Shared by the external account API's+# request validation and the facade write path so the set is defined once.+ACCOUNT_ASSIGNMENT_ROLE_FIELDS = ("csm", "account_executive", "account_owner")+# Mirrors frontend `BILLING_INSIGHT_SHORT_IDS` in accountBillingLogic.ts. These saved insights read# warehouse-synced billing data to report an account's PostHog consumption (events ingested, rows# synced, recordings, etc.) and spend (MRR, per-product cost). PostHog-internal: they only resolvediff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex dc2d77fd71cf..c591aa61d39c 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -18,11 +18,17 @@ Do NOT:from typing import TYPE_CHECKINGfrom django.core.exceptions import ValidationError+from django.db import transactionfrom django.db.models import Q+from posthog.api.tagged_item import set_tags_on_object+from posthog.exceptions_capture import capture_exception+from posthog.models import OrganizationMembership, Tag+from posthog.models.tag import tagifyfrom posthog.models.tagged_item import TaggedItemfrom products.customer_analytics.backend.account_urls import build_account_deeplink as build_account_deeplink+from products.customer_analytics.backend.constants import ACCOUNT_ASSIGNMENT_ROLE_FIELDSfrom products.customer_analytics.backend.logic.usage_spike_notifications import (notify_managers_of_usage_spike as notify_managers_of_usage_spike,)@@ -196,3 +202,135 @@ def get_account(properties=_to_account_properties(account.properties),created_at=account.created_at,)+++# --- External (CDP worker) account API ---+#+# The data access, transactional write, org-membership resolution, tag+# application, and exception capture for the Bearer-authed external account+# endpoint. The view keeps only HTTP concerns (auth, throttles, the flag gate,+# request validation) and maps the results below to responses.+++def _to_external_account(account: Account) -> contracts.ExternalAccount:+ """Map an account to the verbatim external wire shape.++ ``properties`` is the exact ``model_dump(mode="json")`` of the validated+ pydantic properties and ``tags`` the sorted tag names — byte-identical to+ what the CDP worker consumed before this moved behind the facade.+ """+ return contracts.ExternalAccount(+ id=str(account.id),+ external_id=account.external_id,+ name=account.name,+ properties=account.properties.model_dump(mode="json"),+ tags=sorted(account.tagged_items.values_list("tag__name", flat=True)),+ )+++def _get_external_account_by_external_id(team_id: int, external_id: str) -> Account | None:+ try:+ return Account.objects.for_team(team_id).select_related("team").get(external_id=external_id)+ except Account.DoesNotExist:+ return None+++def get_external_account(team_id: int, external_id: str) -> contracts.ExternalAccount | None:+ """Fetch the team's account by external id for the external API, or None."""+ account = _get_external_account_by_external_id(team_id, external_id)+ if account is None:+ return None+ return _to_external_account(account)+++def _apply_external_tags(account: Account, tags: list[str], mode: str) -> None:+ normalized = list({tagify(t) for t in tags})+ if mode == "remove":+ account.tagged_items.filter(tag__name__in=normalized).delete()+ elif mode == "set":+ set_tags_on_object(normalized, account)+ else:+ for tag_name in normalized:+ tag, _ = Tag.objects.get_or_create(name=tag_name, team_id=account.team_id)+ account.tagged_items.get_or_create(tag_id=tag.id)+++def _apply_external_role_assignments(+ account: Account, role_assignments: dict[str, int | None]+) -> contracts.ExternalAccountUpdateResult | None:+ """Apply provided role assignments to the account's properties.++ ``role_assignments`` holds only the roles present in the request (None+ clears a role). Each non-None user id is resolved against an+ ``OrganizationMembership`` in the account's org so the stored ``{id, email}``+ is always trusted. Returns an error result (membership missing / invalid+ properties) or None on success.+ """+ properties = dict(account._properties or {})+ changed = False++ for field in ACCOUNT_ASSIGNMENT_ROLE_FIELDS:+ if field not in role_assignments:+ continue+ user_id = role_assignments[field]+ if user_id is None:+ properties[field] = None+ else:+ membership = (+ OrganizationMembership.objects.select_related("user")+ .filter(organization_id=account.team.organization_id, user_id=user_id)+ .first()+ )+ if membership is None:+ return contracts.ExternalAccountUpdateResult(+ error=contracts.ExternalAccountUpdateError.USER_NOT_IN_ORGANIZATION,+ error_field=field,+ )+ properties[field] = {"id": membership.user.id, "email": membership.user.email}+ changed = True++ if not changed:+ return None++ try:+ account.properties = _ModelAccountProperties.model_validate(properties)+ except Exception as e:+ capture_exception(e, {"account_id": str(account.id)})+ return contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.INVALID_PROPERTIES)++ account.save(update_fields=["_properties", "updated_at"])+ return None+++def update_external_account(+ team_id: int,+ external_id: str,+ *,+ role_assignments: dict[str, int | None],+ tags: list[str] | None,+ tags_mode: str,+) -> contracts.ExternalAccountUpdateResult:+ """Apply role assignments and tags to an account, transactionally, for the external API.++ Role assignments and tags are all-or-nothing — a tag failure must not leave the+ role-contact changes committed. Returns a result the view maps to the exact HTTP+ status/body: not found, a per-role org-membership failure, invalid properties, a+ generic write failure, or success carrying the re-serialized account.+ """+ account = _get_external_account_by_external_id(team_id, external_id)+ if account is None:+ return contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.NOT_FOUND)++ try:+ with transaction.atomic():+ error_result = _apply_external_role_assignments(account, role_assignments)+ if error_result is not None:+ return error_result+ if tags is not None:+ _apply_external_tags(account, tags, tags_mode)+ except Exception as e:+ capture_exception(e, {"account_id": str(account.id)})+ return contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.UPDATE_FAILED)++ account.refresh_from_db()+ return contracts.ExternalAccountUpdateResult(account=_to_external_account(account))diff --git a/products/customer_analytics/backend/facade/constants.py b/products/customer_analytics/backend/facade/constants.pyindex a04011964d3d..b1b2e7891797 100644--- a/products/customer_analytics/backend/facade/constants.py+++ b/products/customer_analytics/backend/facade/constants.py@@ -6,6 +6,7 @@ stays as the source of truth."""from products.customer_analytics.backend.constants import (+ ACCOUNT_ASSIGNMENT_ROLE_FIELDS,BILLING_SPEND_INSIGHT_SHORT_IDS,BILLING_USAGE_INSIGHT_SHORT_IDS,CUSTOMER_ANALYTICS_CSP_FLAG,@@ -13,6 +14,7 @@ from products.customer_analytics.backend.constants import ()__all__ = [+ "ACCOUNT_ASSIGNMENT_ROLE_FIELDS","BILLING_SPEND_INSIGHT_SHORT_IDS","BILLING_USAGE_INSIGHT_SHORT_IDS","CUSTOMER_ANALYTICS_CSP_FLAG",diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex e98e5db40e4d..16bb7057f001 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -12,6 +12,7 @@ instead of producing a malformed payload deeper in a caller.from dataclasses import fieldfrom datetime import datetime+from enum import Enumfrom uuid import UUIDfrom pydantic.dataclasses import dataclass@@ -93,3 +94,46 @@ class AccountContextData:properties: AccountPropertiestags: list[str] = field(default_factory=list)notes: list[AccountNote] = field(default_factory=list)+++@dataclass(frozen=True)+class ExternalAccount:+ """The account shape the external (CDP worker) API serializes verbatim.++ ``properties`` is carried as a plain dict set to exactly+ ``account.properties.model_dump(mode="json")`` so the JSON the CDP worker+ consumes stays byte-identical to the pre-facade response — a validated+ pydantic pass-through, not a re-typed projection. ``id`` is the stringified+ UUID, matching the wire shape.+ """++ id: str+ external_id: str | None+ name: str+ properties: dict+ tags: list[str] = field(default_factory=list)+++class ExternalAccountUpdateError(Enum):+ """Failure modes of the external account write, each mapping to a distinct+ HTTP response in the view."""++ NOT_FOUND = "not_found"+ USER_NOT_IN_ORGANIZATION = "user_not_in_organization"+ INVALID_PROPERTIES = "invalid_properties"+ UPDATE_FAILED = "update_failed"+++@dataclass(frozen=True)+class ExternalAccountUpdateResult:+ """Outcome of the external account write, modeled so the view can map each+ case to its exact HTTP status and error string without holding write logic.++ Exactly one of ``account`` / ``error`` is set. ``error_field`` carries the+ role field name for a ``USER_NOT_IN_ORGANIZATION`` failure (so the view can+ keep the ``"{field}: ..."`` message shape); it is None otherwise.+ """++ account: ExternalAccount | None = None+ error: ExternalAccountUpdateError | None = None+ error_field: str | None = Nonediff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.pyindex 51b45c66bd46..17d799dd982c 100644--- a/products/customer_analytics/backend/presentation/views/external.py+++ b/products/customer_analytics/backend/presentation/views/external.py@@ -3,12 +3,16 @@ External API endpoints for the Customer analytics product.These endpoints are used by the CDP worker for workflow actions. Authenticatedvia the team secret API token passed as a Bearer token in the Authorization header.++The view holds only HTTP concerns — Bearer auth, throttles, the feature-flag gate,+request validation, and mapping facade results to responses. Data access, the+transactional write, org-membership resolution, tag application, and exception+capture live behind ``facade.api``."""import hashlibfrom typing import Any-from django.db import transactionfrom django.db.models import Qimport structlog@@ -20,16 +24,16 @@ from rest_framework.response import Responsefrom rest_framework.throttling import SimpleRateThrottlefrom rest_framework.views import APIView-from posthog.api.tagged_item import set_tags_on_object-from posthog.exceptions_capture import capture_exception-from posthog.models import OrganizationMembership, Tag, Team-from posthog.models.tag import tagify--from products.customer_analytics.backend.constants import CUSTOMER_ANALYTICS_CSP_FLAG-from products.customer_analytics.backend.models import Account-from products.customer_analytics.backend.models.account import AccountProperties+from posthog.models import Team-ASSIGNMENT_ROLE_FIELDS = ("csm", "account_executive", "account_owner")+from products.customer_analytics.backend.facade import (+ api as facade,+ contracts,+)+from products.customer_analytics.backend.facade.constants import (+ ACCOUNT_ASSIGNMENT_ROLE_FIELDS,+ CUSTOMER_ANALYTICS_CSP_FLAG,+)logger = structlog.get_logger(__name__)@@ -92,28 +96,42 @@ def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Respreturn team, None-def _serialize_account(account: Account) -> dict[str, Any]:+def _external_account_body(account: contracts.ExternalAccount) -> dict[str, Any]:return {- "id": str(account.id),+ "id": account.id,"external_id": account.external_id,"name": account.name,- "properties": account.properties.model_dump(mode="json"),- "tags": sorted(account.tagged_items.values_list("tag__name", flat=True)),+ "properties": account.properties,+ "tags": account.tags,}-def _get_account_by_external_id(team: Team, external_id: str) -> Account | None:- try:- return Account.objects.for_team(team.id).get(external_id=external_id)- except Account.DoesNotExist:- return None+_UPDATE_ERROR_RESPONSES = {+ contracts.ExternalAccountUpdateError.NOT_FOUND: ("Account not found", status.HTTP_404_NOT_FOUND),+ contracts.ExternalAccountUpdateError.INVALID_PROPERTIES: (+ "Invalid account properties",+ status.HTTP_400_BAD_REQUEST,+ ),+ contracts.ExternalAccountUpdateError.UPDATE_FAILED: ("Failed to update account", status.HTTP_400_BAD_REQUEST),+}+++def _update_error_response(result: contracts.ExternalAccountUpdateResult) -> Response:+ if result.error == contracts.ExternalAccountUpdateError.USER_NOT_IN_ORGANIZATION:+ return Response(+ {"error": f"{result.error_field}: user is not a member of this organization"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ assert result.error is not None+ message, code = _UPDATE_ERROR_RESPONSES[result.error]+ return Response({"error": message}, status=code)class ExternalAccountUpdateSerializer(serializers.Serializer):external_id = serializers.CharField(max_length=400)# Each role accepts a `posthog_assignee` value `{type, id}`, `null` to clear, or is# omitted to leave unchanged. Roles (RBAC) are rejected — accounts assign users only.- # `validate` normalizes a provided assignment down to the user id; the view resolves+ # `validate` normalizes a provided assignment down to the user id; the facade resolves# the email against an org membership so the stored `{id, email}` is always trusted.csm = serializers.JSONField(required=False, allow_null=True)account_executive = serializers.JSONField(required=False, allow_null=True)@@ -122,7 +140,7 @@ class ExternalAccountUpdateSerializer(serializers.Serializer):tags_mode = serializers.ChoiceField(choices=["add", "set", "remove"], required=False, default="add")def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:- for field in ASSIGNMENT_ROLE_FIELDS:+ for field in ACCOUNT_ASSIGNMENT_ROLE_FIELDS:if field in attrs and attrs[field] is not None:attrs[field] = self._normalize_assignee(field, attrs[field])return attrs@@ -141,18 +159,6 @@ class ExternalAccountUpdateSerializer(serializers.Serializer):raise serializers.ValidationError({field: "Assignee id must be a user id"})-def _apply_tags(account: Account, tags: list[str], mode: str) -> None:- normalized = list({tagify(t) for t in tags})- if mode == "remove":- account.tagged_items.filter(tag__name__in=normalized).delete()- elif mode == "set":- set_tags_on_object(normalized, account)- else:- for tag_name in normalized:- tag, _ = Tag.objects.get_or_create(name=tag_name, team_id=account.team_id)- account.tagged_items.get_or_create(tag_id=tag.id)--class ExternalAccountView(APIView):"""GET /api/customer_analytics/external/account?external_id=<external_id> — Fetch account data@@ -176,11 +182,11 @@ class ExternalAccountView(APIView):if not external_id:return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)- account = _get_account_by_external_id(team, external_id)+ account = facade.get_external_account(team.id, external_id)if account is None:return Response({"error": "Account not found"}, status=status.HTTP_404_NOT_FOUND)- return Response(_serialize_account(account))+ return Response(_external_account_body(account))def patch(self, request: Request) -> Response:team, error = _authenticate_team(request)@@ -198,58 +204,15 @@ class ExternalAccountView(APIView):if not external_id:return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)- account = _get_account_by_external_id(team, external_id)- if account is None:- return Response({"error": "Account not found"}, status=status.HTTP_404_NOT_FOUND)-- # Role assignments and tags must be all-or-nothing — a tag failure must not leave the- # role-contact changes committed. Validation errors return before any write happens.- try:- with transaction.atomic():- error = self._apply_role_assignments(team, account, data)- if error:- return error- if "tags" in data:- _apply_tags(account, data["tags"], data.get("tags_mode", "add"))- except Exception as e:- capture_exception(e, {"account_id": str(account.id)})- return Response({"error": "Failed to update account"}, status=status.HTTP_400_BAD_REQUEST)-- account.refresh_from_db()- return Response(_serialize_account(account))-- def _apply_role_assignments(self, team: Team, account: Account, data: dict[str, Any]) -> Response | None:- properties = dict(account._properties or {})- changed = False-- for field in ASSIGNMENT_ROLE_FIELDS:- if field not in data:- continue- user_id = data[field]- if user_id is None:- properties[field] = None- else:- membership = (- OrganizationMembership.objects.select_related("user")- .filter(organization_id=team.organization_id, user_id=user_id)- .first()- )- if membership is None:- return Response(- {"error": f"{field}: user is not a member of this organization"},- status=status.HTTP_400_BAD_REQUEST,- )- properties[field] = {"id": membership.user.id, "email": membership.user.email}- changed = True-- if not changed:- return None-- try:- account.properties = AccountProperties.model_validate(properties)- except Exception as e:- capture_exception(e, {"account_id": str(account.id)})- return Response({"error": "Invalid account properties"}, status=status.HTTP_400_BAD_REQUEST)+ role_assignments = {field: data[field] for field in ACCOUNT_ASSIGNMENT_ROLE_FIELDS if field in data}+ result = facade.update_external_account(+ team.id,+ external_id,+ role_assignments=role_assignments,+ tags=data["tags"] if "tags" in data else None,+ tags_mode=data.get("tags_mode", "add"),+ )+ if result.account is None:+ return _update_error_response(result)- account.save(update_fields=["_properties", "updated_at"])- return None+ return Response(_external_account_body(result.account))diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.pyindex 64bc7bedf296..a6a1539fe956 100644--- a/products/customer_analytics/backend/test/test_external.py+++ b/products/customer_analytics/backend/test/test_external.py@@ -197,7 +197,7 @@ class TestExternalAccountAPI(APIBaseTest):def test_patch_rolls_back_role_assignment_when_tags_fail(self):with patch(- "products.customer_analytics.backend.presentation.views.external._apply_tags",+ "products.customer_analytics.backend.facade.api._apply_external_tags",side_effect=Exception("boom"),):response = self._patch(diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.pyindex 150fd6213a6c..49628f716dd9 100644--- a/products/customer_analytics/backend/test/test_facade.py+++ b/products/customer_analytics/backend/test/test_facade.py@@ -1,6 +1,7 @@from posthog.test.base import BaseTest-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patch+from posthog.models import Organization, Userfrom posthog.models.tag import Tagfrom posthog.models.tagged_item import TaggedItemfrom posthog.rbac.user_access_control import UserAccessControl@@ -112,3 +113,161 @@ class TestCustomerAnalyticsFacade(BaseTest):assert count == 2assert {r.name for r in rows} == {"First", "Second"}++ # -- External account API (CDP worker) --------------------------------++ def test_get_external_account_returns_verbatim_shape(self):+ account = create_account(+ team_id=self.team.id,+ name="Acme Corp",+ external_id="acme-1",+ _properties=AccountProperties(+ csm=AccountAssignment(id=self.user.id, email=self.user.email),+ ).model_dump(mode="json"),+ )+ tag = Tag.objects.create(name="enterprise", team_id=self.team.id)+ TaggedItem.objects.create(tag=tag, account=account)++ result = facade.get_external_account(self.team.id, "acme-1")++ assert isinstance(result, contracts.ExternalAccount)+ assert result.id == str(account.id)+ assert result.external_id == "acme-1"+ assert result.name == "Acme Corp"+ assert result.tags == ["enterprise"]+ assert result.properties == account.properties.model_dump(mode="json")+ assert result.properties["csm"] == {"id": self.user.id, "email": self.user.email}++ def test_get_external_account_missing_and_other_team(self):+ create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")+ other_team = Organization.objects.bootstrap(None, name="Other")[2]++ assert facade.get_external_account(self.team.id, "nope") is None+ assert facade.get_external_account(other_team.id, "acme-1") is None++ def test_update_external_account_not_found_returns_not_found(self):+ result = facade.update_external_account(+ self.team.id, "missing", role_assignments={}, tags=None, tags_mode="add"+ )+ assert result.account is None+ assert result.error == contracts.ExternalAccountUpdateError.NOT_FOUND++ def test_update_external_account_assigns_role_and_resolves_email(self):+ account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")++ result = facade.update_external_account(+ self.team.id, "acme-1", role_assignments={"csm": self.user.id}, tags=None, tags_mode="add"+ )++ assert result.error is None+ assert result.account is not None+ assert result.account.properties["csm"] == {"id": self.user.id, "email": self.user.email}+ account.refresh_from_db()+ assert account.properties.csm == AccountAssignment(id=self.user.id, email=self.user.email)++ def test_update_external_account_clears_role_with_none(self):+ account = create_account(+ team_id=self.team.id,+ name="Acme Corp",+ external_id="acme-1",+ _properties=AccountProperties(+ csm=AccountAssignment(id=self.user.id, email=self.user.email),+ ).model_dump(mode="json"),+ )++ result = facade.update_external_account(+ self.team.id, "acme-1", role_assignments={"csm": None}, tags=None, tags_mode="add"+ )++ assert result.account is not None+ assert result.account.properties["csm"] is None+ account.refresh_from_db()+ assert account.properties.csm is None++ def test_update_external_account_preserves_unmentioned_properties(self):+ account = create_account(+ team_id=self.team.id,+ name="Acme Corp",+ external_id="acme-1",+ _properties=AccountProperties(stripe_customer_id="cus_123").model_dump(mode="json"),+ )++ facade.update_external_account(+ self.team.id, "acme-1", role_assignments={"csm": self.user.id}, tags=None, tags_mode="add"+ )++ account.refresh_from_db()+ assert account.properties.stripe_customer_id == "cus_123"+ assert account.properties.csm == AccountAssignment(id=self.user.id, email=self.user.email)++ def test_update_external_account_rejects_non_member(self):+ account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")+ outsider = User.objects.create_and_join(Organization.objects.create(name="Outsiders"), "[email protected]", None)++ result = facade.update_external_account(+ self.team.id, "acme-1", role_assignments={"csm": outsider.id}, tags=None, tags_mode="add"+ )++ assert result.account is None+ assert result.error == contracts.ExternalAccountUpdateError.USER_NOT_IN_ORGANIZATION+ assert result.error_field == "csm"+ account.refresh_from_db()+ assert account.properties.csm is None++ def test_update_external_account_invalid_properties(self):+ create_account(+ team_id=self.team.id,+ name="Acme Corp",+ external_id="acme-1",+ _properties={"not_a_real_property": "x"},+ )++ result = facade.update_external_account(+ self.team.id, "acme-1", role_assignments={"csm": self.user.id}, tags=None, tags_mode="add"+ )++ assert result.account is None+ assert result.error == contracts.ExternalAccountUpdateError.INVALID_PROPERTIES++ def test_update_external_account_tag_modes(self):+ create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")++ added = facade.update_external_account(+ self.team.id, "acme-1", role_assignments={}, tags=["enterprise"], tags_mode="add"+ )+ assert added.account is not None and added.account.tags == ["enterprise"]++ added_more = facade.update_external_account(+ self.team.id, "acme-1", role_assignments={}, tags=["priority"], tags_mode="add"+ )+ assert added_more.account is not None and added_more.account.tags == ["enterprise", "priority"]++ replaced = facade.update_external_account(+ self.team.id, "acme-1", role_assignments={}, tags=["only"], tags_mode="set"+ )+ assert replaced.account is not None and replaced.account.tags == ["only"]++ removed = facade.update_external_account(+ self.team.id, "acme-1", role_assignments={}, tags=["only"], tags_mode="remove"+ )+ assert removed.account is not None and removed.account.tags == []++ def test_update_external_account_rolls_back_role_when_tags_fail(self):+ account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")++ with patch(+ "products.customer_analytics.backend.facade.api._apply_external_tags",+ side_effect=Exception("boom"),+ ):+ result = facade.update_external_account(+ self.team.id,+ "acme-1",+ role_assignments={"csm": self.user.id},+ tags=["enterprise"],+ tags_mode="add",+ )++ assert result.account is None+ assert result.error == contracts.ExternalAccountUpdateError.UPDATE_FAILED+ account.refresh_from_db()+ assert account.properties.csm is Nonediff --git a/pyproject.toml b/pyproject.tomlindex de42a64ae7c0..a9d06aed003d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -572,9 +572,6 @@ ignore_imports = [# TODO: customer_analytics presentation wave — these views still reach internals directly.# Thin each view to parse -> facade -> serialize and delete its entry. backend:contract-check# stays off until this list is empty.- "products.customer_analytics.backend.presentation.views.external -> products.customer_analytics.backend.constants",- "products.customer_analytics.backend.presentation.views.external -> products.customer_analytics.backend.models",- "products.customer_analytics.backend.presentation.views.external -> products.customer_analytics.backend.models.account","products.customer_analytics.backend.presentation.views.organization_members -> products.customer_analytics.backend.constants","products.customer_analytics.backend.presentation.views.serializers -> products.customer_analytics.backend.models","products.customer_analytics.backend.presentation.views.utils -> products.customer_analytics.backend.models",