:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): route external account api through relationships (#69004)
Arthur Moreira de Deus2ea06eb35bd2
diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.tsindex a7574dc5ab11..d8a4099d27fb 100644--- a/nodejs/src/cdp/async-functions/customer_analytics.ts+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts@@ -50,9 +50,6 @@ registerAsyncFunction('postHogGetAccount', {external_id: args[0]?.external_id ?? 'mock-external-id',name: 'Mock Account',properties: {- csm: { id: 1, email: '[email protected]' },- account_executive: { id: 2, email: '[email protected]' },- account_owner: { id: 3, email: '[email protected]' },stripe_customer_id: 'cus_mock',hubspot_deal_id: 'deal_mock',billing_id: 'bill_mock',@@ -61,6 +58,10 @@ registerAsyncFunction('postHogGetAccount', {slack_channel_id: 'C0MOCK',usage_dashboard_link: 'https://example.com/dashboard',},+ relationships: {+ CSM: [{ user_id: 1, email: '[email protected]' }],+ 'Account executive': [{ user_id: 2, email: '[email protected]' }],+ },},}},diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.tsindex e8738c06adb4..cd2d0ce4198c 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts@@ -16,17 +16,22 @@ if (empty(inputs.external_id)) {}let updates := {}+let relationships := {}if (not empty(inputs.csm)) {- updates.csm := inputs.csm+ relationships['CSM'] := inputs.csm}if (not empty(inputs.account_executive)) {- updates.account_executive := inputs.account_executive+ relationships['Account executive'] := inputs.account_executive}if (not empty(inputs.account_owner)) {- updates.account_owner := inputs.account_owner+ relationships['Account owner'] := inputs.account_owner+}++if (not empty(relationships)) {+ updates.relationships := relationships}if (not empty(inputs.tags)) {diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 50bc7ba6b7fd..bf7f067e4f4a 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -256,12 +256,24 @@ def _to_external_account(account: Account) -> contracts.ExternalAccount:pydantic properties and ``tags`` the sorted tag names — byte-identical towhat the CDP worker consumed before this moved behind the facade."""+ relationships: dict[str, list[dict]] = {}+ for relationship in (+ AccountRelationship.objects.for_team(account.team_id)+ .filter(account=account, ended_at__isnull=True, user__isnull=False)+ .select_related("definition", "user")+ .order_by("definition__name", "user__email")+ ):+ assert relationship.user is not None+ relationships.setdefault(relationship.definition.name, []).append(+ {"user_id": relationship.user.id, "email": relationship.user.email}+ )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)),+ relationships=relationships,)@@ -292,51 +304,51 @@ def _apply_external_tags(account: Account, tags: list[str], mode: str) -> None:account.tagged_items.get_or_create(tag_id=tag.id)-def _apply_external_role_assignments(- account: Account, role_assignments: dict[str, int | None]+def _apply_external_relationship_assignments(+ account: Account, 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.+ """Apply provided relationship assignments, keyed by definition name (None ends the+ active assignment). Each non-None user id is resolved against an+ ``OrganizationMembership`` in the account's org so assignees are always trusted.+ Everything is validated before the first write — the caller's ``atomic()`` block+ returns (commits) on an error result rather than rolling back."""- 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]+ definitions = {+ definition.name: definition+ for definition in AccountRelationshipDefinition.objects.for_team(account.team_id).filter(+ name__in=assignments.keys()+ )+ }+ resolved: list[tuple[AccountRelationshipDefinition, User | None]] = []+ for name, user_id in assignments.items():+ definition = definitions.get(name)+ if definition is None:+ return contracts.ExternalAccountUpdateResult(+ error=contracts.ExternalAccountUpdateError.RELATIONSHIP_DEFINITION_NOT_FOUND,+ error_field=name,+ )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()+ resolved.append((definition, None))+ continue+ 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=name,)- 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+ resolved.append((definition, membership.user))- 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"])- _relationships_logic.sync_from_account_properties(account)+ for definition, assignee in resolved:+ if assignee is None:+ _relationships_logic.end_active(team_id=account.team_id, account=account, definition=definition)+ else:+ _relationships_logic.assign(+ team_id=account.team_id, account=account, definition=definition, user=assignee, created_by=None+ )return None@@ -344,24 +356,32 @@ def update_external_account(team_id: int,external_id: str,*,- role_assignments: dict[str, int | None],+ relationship_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.+ """Apply relationship 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.+ Assignments and tags are all-or-nothing — a tag failure must not leave the+ relationship changes committed. Returns a result the view maps to the exact HTTP+ status/body: not found, a per-assignment failure (unknown definition, non-member+ user), 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)+ # Stored properties are re-serialized onto the success response, so reject accounts+ # whose stored JSON no longer validates before writing anything.+ try:+ _ = account.properties+ except PydanticValidationError:+ return contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.INVALID_PROPERTIES)+try:with transaction.atomic():- error_result = _apply_external_role_assignments(account, role_assignments)+ error_result = _apply_external_relationship_assignments(account, relationship_assignments)if error_result is not None:return error_resultif tags is not None:diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 23a761c7665a..7988efd8ff46 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -141,6 +141,7 @@ class ExternalAccount:name: strproperties: dicttags: list[str] = field(default_factory=list)+ relationships: dict[str, list[dict]] = field(default_factory=dict)class ExternalAccountUpdateError(Enum):@@ -149,6 +150,7 @@ class ExternalAccountUpdateError(Enum):NOT_FOUND = "not_found"USER_NOT_IN_ORGANIZATION = "user_not_in_organization"+ RELATIONSHIP_DEFINITION_NOT_FOUND = "relationship_definition_not_found"INVALID_PROPERTIES = "invalid_properties"UPDATE_FAILED = "update_failed"diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.pyindex e38ab83c26ea..3accbb04899f 100644--- a/products/customer_analytics/backend/presentation/views/external.py+++ b/products/customer_analytics/backend/presentation/views/external.py@@ -32,10 +32,7 @@ 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,-)+from products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYTICS_CSP_FLAGlogger = structlog.get_logger(__name__)@@ -105,6 +102,7 @@ def _external_account_body(account: contracts.ExternalAccount) -> dict[str, Any]"name": account.name,"properties": account.properties,"tags": account.tags,+ "relationships": account.relationships,}@@ -124,30 +122,50 @@ def _update_error_response(result: contracts.ExternalAccountUpdateResult) -> Res{"error": f"{result.error_field}: user is not a member of this organization"},status=status.HTTP_400_BAD_REQUEST,)+ if result.error == contracts.ExternalAccountUpdateError.RELATIONSHIP_DEFINITION_NOT_FOUND:+ return Response(+ {"error": f"{result.error_field}: no relationship definition with this name"},+ status=status.HTTP_400_BAD_REQUEST,+ )assert result.error is not Nonemessage, 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.+ external_id = serializers.CharField(max_length=400, help_text="External ID (group key) of the account to update.")+ # Each value accepts a `posthog_assignee` object `{type, id}`, or `null` to end the+ # active assignment. Roles (RBAC) are rejected — accounts assign users only.# `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)- account_owner = serializers.JSONField(required=False, allow_null=True)- tags = serializers.ListField(child=serializers.CharField(max_length=200), required=False, max_length=100)- 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 ACCOUNT_ASSIGNMENT_ROLE_FIELDS:- if field in attrs and attrs[field] is not None:- attrs[field] = self._normalize_assignee(field, attrs[field])- return attrs-- def _normalize_assignee(self, field: str, value: Any) -> int:+ # it against an org membership so assignees are always trusted.+ relationships = serializers.DictField(+ child=serializers.JSONField(allow_null=True),+ required=False,+ help_text=(+ "Relationship assignments keyed by definition name (e.g. 'CSM'). Each value is an "+ "assignee object `{type: 'user', id}` or null to end the active assignment. Only the "+ "named definitions are changed."+ ),+ )+ tags = serializers.ListField(+ child=serializers.CharField(max_length=200),+ required=False,+ max_length=100,+ help_text="Tag names to apply, per tags_mode.",+ )+ tags_mode = serializers.ChoiceField(+ choices=["add", "set", "remove"],+ required=False,+ default="add",+ help_text="How to apply tags: add to, replace, or remove from the existing set.",+ )++ def validate_relationships(self, value: dict[str, Any]) -> dict[str, int | None]:+ return {name: self._normalize_assignee(name, assignee) for name, assignee in value.items()}++ def _normalize_assignee(self, field: str, value: Any) -> int | None:+ if value is None:+ return Noneif not isinstance(value, dict):raise serializers.ValidationError({field: "Must be an assignee object or null"})if value.get("type") != "user":@@ -206,11 +224,10 @@ class ExternalAccountView(APIView):if not external_id:return Response({"error": "external_id is required"}, 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,+ relationship_assignments=data.get("relationships") or {},tags=data["tags"] if "tags" in data else None,tags_mode=data.get("tags_mode", "add"),)diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.pyindex 765df490b252..dd9cd8b7c424 100644--- a/products/customer_analytics/backend/test/test_external.py+++ b/products/customer_analytics/backend/test/test_external.py@@ -10,8 +10,13 @@ from rest_framework.test import APIClientfrom posthog.models import Organization, Team, Userfrom posthog.models.utils import generate_random_token_secret-from products.customer_analytics.backend.models import CustomPropertyValue, DisplayType-from products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties+from products.customer_analytics.backend.models import (+ AccountRelationship,+ AccountRelationshipDefinition,+ CustomPropertyValue,+ DisplayType,+)+from products.customer_analytics.backend.models.account import AccountPropertiesfrom products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition@@ -23,6 +28,9 @@ class TestExternalAccountAPI(APIBaseTest):# Fresh client so requests are unauthenticated unless they carry the Bearer token.self.client = APIClient()self.account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")+ self.csm_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(+ team_id=self.team.id, name="CSM"+ )self.url = "/api/customer_analytics/external/account"csp_enabled = patch("products.customer_analytics.backend.presentation.views.external.posthoganalytics.feature_enabled",@@ -40,6 +48,18 @@ class TestExternalAccountAPI(APIBaseTest):def _patch(self, payload, token=None):return self.client.patch(self.url, data=payload, format="json", **self._auth_headers(token))+ def _assign_csm(self, user):+ return AccountRelationship.objects.for_team(self.team.id).create(+ team_id=self.team.id, definition=self.csm_definition, account=self.account, user=user+ )++ def _active_csm_user_ids(self):+ return list(+ AccountRelationship.objects.for_team(self.team.id)+ .filter(account=self.account, definition=self.csm_definition, ended_at__isnull=True)+ .values_list("user_id", flat=True)+ )+# -- Authentication ---------------------------------------------------def test_get_requires_auth(self):@@ -92,20 +112,17 @@ class TestExternalAccountAPI(APIBaseTest):self.assertEqual(data["id"], str(self.account.id))self.assertEqual(data["external_id"], "acme-1")self.assertEqual(data["name"], "Acme Corp")- self.assertIn("properties", data)- self.assertIsNone(data["properties"]["csm"])+ self.assertEqual(data["relationships"], {})- def test_get_account_returns_role_properties(self):- self.account.properties = AccountProperties(- csm=AccountAssignment(id=self.user.id, email=self.user.email),- )- self.account.save(update_fields=["_properties"])+ def test_get_account_returns_active_relationships(self):+ self._assign_csm(self.user)response = self._get()self.assertEqual(response.status_code, status.HTTP_200_OK)- csm = response.json()["properties"]["csm"]- self.assertEqual(csm["id"], self.user.id)- self.assertEqual(csm["email"], self.user.email)+ self.assertEqual(+ response.json()["relationships"],+ {"CSM": [{"user_id": self.user.id, "email": self.user.email}]},+ )def test_does_not_leak_accounts_from_other_team(self):other_team = Team.objects.create(organization=self.organization, name="Other")@@ -129,48 +146,59 @@ class TestExternalAccountAPI(APIBaseTest):response = self._patch({"external_id": "does-not-exist", "tags": ["enterprise"]})self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)- def test_patch_assigns_role_and_resolves_email(self):- response = self._patch({"external_id": "acme-1", "csm": {"type": "user", "id": self.user.id}})+ def test_patch_assigns_relationship_and_returns_it(self):+ response = self._patch(+ {"external_id": "acme-1", "relationships": {"CSM": {"type": "user", "id": self.user.id}}}+ )self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ response.json()["relationships"],+ {"CSM": [{"user_id": self.user.id, "email": self.user.email}]},+ )+ self.assertEqual(self._active_csm_user_ids(), [self.user.id])- self.account.refresh_from_db()- csm = self.account.properties.csm- assert csm is not None- self.assertEqual(csm.id, self.user.id)- self.assertEqual(csm.email, self.user.email)-- def test_patch_clears_role_with_null(self):- self.account.properties = AccountProperties(csm=AccountAssignment(id=self.user.id, email=self.user.email))- self.account.save(update_fields=["_properties"])+ def test_patch_null_ends_active_assignment(self):+ self._assign_csm(self.user)- response = self._patch({"external_id": "acme-1", "csm": None})+ response = self._patch({"external_id": "acme-1", "relationships": {"CSM": None}})self.assertEqual(response.status_code, status.HTTP_200_OK)- self.account.refresh_from_db()- self.assertIsNone(self.account.properties.csm)+ self.assertEqual(response.json()["relationships"], {})+ self.assertEqual(self._active_csm_user_ids(), [])- def test_patch_preserves_unmentioned_properties(self):+ def test_patch_relationships_do_not_touch_properties(self):self.account.properties = AccountProperties(stripe_customer_id="cus_123")self.account.save(update_fields=["_properties"])- response = self._patch({"external_id": "acme-1", "csm": {"type": "user", "id": self.user.id}})+ response = self._patch(+ {"external_id": "acme-1", "relationships": {"CSM": {"type": "user", "id": self.user.id}}}+ )self.assertEqual(response.status_code, status.HTTP_200_OK)- self.account.refresh_from_db()- csm = self.account.properties.csm- assert csm is not None- self.assertEqual(self.account.properties.stripe_customer_id, "cus_123")- self.assertEqual(csm.id, self.user.id)+ self.assertEqual(response.json()["properties"]["stripe_customer_id"], "cus_123")++ @parameterized.expand(+ [+ ("role_assignee", {"type": "role", "id": "some-role-uuid"}),+ ("not_an_object", "[email protected]"),+ ("bad_id", {"type": "user", "id": {"nested": True}}),+ ]+ )+ def test_patch_rejects_invalid_assignee(self, _name, assignee):+ response = self._patch({"external_id": "acme-1", "relationships": {"CSM": assignee}})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(self._active_csm_user_ids(), [])- def test_patch_rejects_role_assignee(self):- response = self._patch({"external_id": "acme-1", "csm": {"type": "role", "id": "some-role-uuid"}})+ def test_patch_rejects_unknown_definition_name(self):+ response = self._patch({"external_id": "acme-1", "relationships": {"AE": {"type": "user", "id": self.user.id}}})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["error"], "AE: no relationship definition with this name")def test_patch_rejects_non_member_user(self):other_org = Organization.objects.create(name="Outsiders")outsider = User.objects.create_and_join(other_org, "[email protected]", None)- response = self._patch({"external_id": "acme-1", "csm": {"type": "user", "id": outsider.id}})+ response = self._patch({"external_id": "acme-1", "relationships": {"CSM": {"type": "user", "id": outsider.id}}})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.account.refresh_from_db()- self.assertIsNone(self.account.properties.csm)+ self.assertEqual(response.json()["error"], "CSM: user is not a member of this organization")+ self.assertEqual(self._active_csm_user_ids(), [])def test_patch_adds_tags_by_default(self):self._patch({"external_id": "acme-1", "tags": ["enterprise"]})@@ -198,21 +226,24 @@ class TestExternalAccountAPI(APIBaseTest):response = self._patch({"external_id": "acme-1", "tags": ["enterprise"]}, token=other_team.secret_api_token)self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)- def test_patch_rolls_back_role_assignment_when_tags_fail(self):+ def test_patch_rolls_back_relationship_assignment_when_tags_fail(self):with patch("products.customer_analytics.backend.facade.api._apply_external_tags",side_effect=Exception("boom"),):response = self._patch(- {"external_id": "acme-1", "csm": {"type": "user", "id": self.user.id}, "tags": ["enterprise"]}+ {+ "external_id": "acme-1",+ "relationships": {"CSM": {"type": "user", "id": self.user.id}},+ "tags": ["enterprise"],+ })self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.account.refresh_from_db()- self.assertIsNone(self.account.properties.csm)+ self.assertEqual(self._active_csm_user_ids(), [])def test_patch_cannot_change_external_id_or_name(self):# external_id only identifies the account; renaming/rebinding is not exposed to workflows.- response = self._patch({"external_id": "acme-1", "name": "Renamed", "new_external_id": "acme-2", "csm": None})+ response = self._patch({"external_id": "acme-1", "name": "Renamed", "new_external_id": "acme-2"})self.assertEqual(response.status_code, status.HTTP_200_OK)self.account.refresh_from_db()self.assertEqual(self.account.external_id, "acme-1")diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.pyindex e76b9936c9bb..c0e958e9d553 100644--- a/products/customer_analytics/backend/test/test_facade.py+++ b/products/customer_analytics/backend/test/test_facade.py@@ -22,6 +22,8 @@ from products.customer_analytics.backend.logic.custom_property_definitions imporfrom products.customer_analytics.backend.logic.custom_property_values import set_custom_property_valuefrom products.customer_analytics.backend.models import (Account,+ AccountRelationship,+ AccountRelationshipDefinition,CustomPropertyDefinition,CustomPropertySource,CustomPropertyValue,@@ -165,44 +167,47 @@ class TestCustomerAnalyticsFacade(BaseTest):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"+ self.team.id, "missing", relationship_assignments={}, tags=None, tags_mode="add")assert result.account is Noneassert result.error == contracts.ExternalAccountUpdateError.NOT_FOUND- def test_update_external_account_assigns_role_and_resolves_email(self):+ def _create_csm_definition(self) -> AccountRelationshipDefinition:+ return AccountRelationshipDefinition.objects.for_team(self.team.id).create(team_id=self.team.id, name="CSM")++ def _active_relationships(self, account: Account):+ return AccountRelationship.objects.for_team(self.team.id).filter(account_id=account.id, ended_at__isnull=True)++ def test_update_external_account_assigns_relationship_and_resolves_email(self):+ self._create_csm_definition()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"+ self.team.id, "acme-1", relationship_assignments={"CSM": self.user.id}, tags=None, tags_mode="add")assert result.error is Noneassert 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)+ assert result.account.relationships == {"CSM": [{"user_id": self.user.id, "email": self.user.email}]}+ assert list(self._active_relationships(account).values_list("user_id", flat=True)) == [self.user.id]- 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"),+ def test_update_external_account_ends_assignment_with_none(self):+ definition = self._create_csm_definition()+ account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")+ AccountRelationship.objects.for_team(self.team.id).create(+ team_id=self.team.id, definition=definition, account_id=account.id, user=self.user)result = facade.update_external_account(- self.team.id, "acme-1", role_assignments={"csm": None}, tags=None, tags_mode="add"+ self.team.id, "acme-1", relationship_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+ assert result.account.relationships == {}+ assert self._active_relationships(account).count() == 0- def test_update_external_account_preserves_unmentioned_properties(self):+ def test_update_external_account_does_not_touch_properties(self):+ self._create_csm_definition()account = create_account(team_id=self.team.id,name="Acme Corp",@@ -211,26 +216,26 @@ class TestCustomerAnalyticsFacade(BaseTest):)facade.update_external_account(- self.team.id, "acme-1", role_assignments={"csm": self.user.id}, tags=None, tags_mode="add"+ self.team.id, "acme-1", relationship_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)+ assert account.properties.csm is Nonedef test_update_external_account_rejects_non_member(self):+ self._create_csm_definition()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"+ self.team.id, "acme-1", relationship_assignments={"CSM": outsider.id}, tags=None, tags_mode="add")assert result.account is Noneassert result.error == contracts.ExternalAccountUpdateError.USER_NOT_IN_ORGANIZATION- assert result.error_field == "csm"- account.refresh_from_db()- assert account.properties.csm is None+ assert result.error_field == "CSM"+ assert self._active_relationships(account).count() == 0def test_update_external_account_invalid_properties(self):create_account(@@ -241,7 +246,7 @@ class TestCustomerAnalyticsFacade(BaseTest):)result = facade.update_external_account(- self.team.id, "acme-1", role_assignments={"csm": self.user.id}, tags=None, tags_mode="add"+ self.team.id, "acme-1", relationship_assignments={"csm": self.user.id}, tags=None, tags_mode="add")assert result.account is None@@ -251,26 +256,27 @@ class TestCustomerAnalyticsFacade(BaseTest):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"+ self.team.id, "acme-1", relationship_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"+ self.team.id, "acme-1", relationship_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"+ self.team.id, "acme-1", relationship_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"+ self.team.id, "acme-1", relationship_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):+ def test_update_external_account_rolls_back_relationship_when_tags_fail(self):+ self._create_csm_definition()account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")with patch(@@ -280,15 +286,14 @@ class TestCustomerAnalyticsFacade(BaseTest):result = facade.update_external_account(self.team.id,"acme-1",- role_assignments={"csm": self.user.id},+ relationship_assignments={"CSM": self.user.id},tags=["enterprise"],tags_mode="add",)assert result.account is Noneassert result.error == contracts.ExternalAccountUpdateError.UPDATE_FAILED- account.refresh_from_db()- assert account.properties.csm is None+ assert self._active_relationships(account).count() == 0class TestCustomerAnalyticsCRUDFacade(BaseTest):diff --git a/products/customer_analytics/backend/test/test_relationships.py b/products/customer_analytics/backend/test/test_relationships.pyindex 4e174650931d..4ddf2530689e 100644--- a/products/customer_analytics/backend/test/test_relationships.py+++ b/products/customer_analytics/backend/test/test_relationships.py@@ -384,7 +384,7 @@ class TestWritePathSync(BaseTest):def test_update_external_account_syncs_roles(self):account = Account.objects.create_account(team=self.team, name="Acme", 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"+ self.team.id, "acme-1", relationship_assignments={"CSM": self.user.id}, tags=None, tags_mode="add")assert result.error is Nonerows = self._active_rows(account)diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.tsindex 939ebb680432..f0924a1822ba 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts@@ -38,14 +38,9 @@ describe('customer analytics action registry', () => {expect(outputVars).toContainEqual({ key: 'account', result_path: null, label: 'Account' })expect(outputVars).toContainEqual({- key: 'account_csm_email',- result_path: 'properties.csm.email',- label: 'CSM email',- })- expect(outputVars).toContainEqual({- key: 'account_executive_id',- result_path: 'properties.account_executive.id',- label: 'Account executive ID',+ key: 'account_relationships',+ result_path: 'relationships',+ label: 'Relationships',})expect(outputVars).toContainEqual({key: 'account_slack_channel_id',@@ -55,12 +50,7 @@ describe('customer analytics action registry', () => {expect(outputVars.map((v) => v.key)).toEqual(['account',- 'account_csm_email',- 'account_csm_id',- 'account_executive_email',- 'account_executive_id',- 'account_owner_email',- 'account_owner_id',+ 'account_relationships','account_stripe_customer_id','account_hubspot_deal_id','account_billing_id',diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.tsindex d220d8b32cba..d3da1e2800a2 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts@@ -43,24 +43,7 @@ registerActionNodeCategory({getDefaultInputs: getAccountExternalIdDefaultInputs,output_variable: [{ key: 'account', result_path: null, label: 'Account' },- { key: 'account_csm_email', result_path: 'properties.csm.email', label: 'CSM email' },- { key: 'account_csm_id', result_path: 'properties.csm.id', label: 'CSM ID' },- {- key: 'account_executive_email',- result_path: 'properties.account_executive.email',- label: 'Account executive email',- },- {- key: 'account_executive_id',- result_path: 'properties.account_executive.id',- label: 'Account executive ID',- },- {- key: 'account_owner_email',- result_path: 'properties.account_owner.email',- label: 'Account owner email',- },- { key: 'account_owner_id', result_path: 'properties.account_owner.id', label: 'Account owner ID' },+ { key: 'account_relationships', result_path: 'relationships', label: 'Relationships' },{key: 'account_stripe_customer_id',result_path: 'properties.stripe_customer_id',