: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): add account relationship models and JSON forward-sync (#68388)
Arthur Moreira de Deusa19c3eca2a2a
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex f0c995f003b4..308bc1ac7eef 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -56,6 +56,8 @@ rules:(?x)(AccessControl|Account+ |AccountRelationship+ |AccountRelationshipDefinition|Action|AgentApplication|AgentArtifact@@ -332,6 +334,8 @@ rules:(?x)(AccessControl|Account+ |AccountRelationship+ |AccountRelationshipDefinition|Action|AgentApplication|AgentArtifactdiff --git a/products/customer_analytics/backend/COMPROMISES.md b/products/customer_analytics/backend/COMPROMISES.mdindex 0cbd0db2efa2..612d76fb49bb 100644--- a/products/customer_analytics/backend/COMPROMISES.md+++ b/products/customer_analytics/backend/COMPROMISES.md@@ -34,3 +34,41 @@ Shortcuts taken to ship the first version. Revisit when they bite.succeeds and the enqueue is dropped (logged to error tracking) — the next materialization recovers.- **v2 materialization only.** v1 `run_workflow.py` is frozen and does not dispatch the sync; v1teams get it after migrating to v2.++## Account relationships — transitional JSON forward-sync++The relationship tables (`AccountRelationshipDefinition` + `AccountRelationship`) exist, but the+legacy JSON role keys (`csm`, `account_executive`, `account_owner`) in `Account._properties` are+still the **source of truth** for account roles. Every JSON role write forward-syncs into the+table via `logic/relationships.sync_from_account_properties` (called from `create_account_for_view`,+`update_account_for_view`, `_apply_external_role_assignments`, and the Max upsert tool), so the+table shadows the JSON and accrues assignment history. Rules while the sync is alive:++- **Nothing may write the relationship table directly** — the next JSON write reconciles direct+ table writes away. That's why the facade deliberately exposes no assign/end functions yet.+- The three seeded definitions are matched **by name** (`SEEDED_DEFINITIONS` maps JSON key →+ definition name). Renaming a seeded definition silently unlinks it from its JSON key.+- Definitions are not auto-created; on teams without them the sync is a silent no-op. They're+ created ad-hoc (or by the future definitions UI).++Cutover checklist — when done, the sync and this section are deleted:++- [ ] Relationship read path in HogQL/query runner replaces the JSON `ExpressionField`s (PR 2)+- [ ] Writers route through `logic/relationships.assign`/`end` instead of JSON keys, facade grows+ assign/end functions (PR 3)+- [ ] Ad-hoc backfill run per environment (create seeded definitions, sync existing accounts)+- [ ] JSON readers migrated (Max context, usage-spike notifications, external API shape, CDP+ "update account" template, Workflows result paths)+- [ ] Delete `sync_from_account_properties` + call sites; strip the three role keys from+ `AccountProperties`++## Tech debt++- **Account property writes have no single choke point.** `Account._properties` is mutated from four+ independent paths: `create_account_for_view` / `update_account_for_view` (via the manager),+ `_apply_external_role_assignments` (raw `account.save`, bypassing the manager), and the Max tool's+ `_create_account` / `_update_account`. Anything that must happen on every properties write — like the+ transitional relationship forward-sync — has to be repeated per call site, and a new writer can+ silently forget it. Funneling every properties write through `AccountManager` (and hooking+ cross-cutting behavior there) is the fix if account properties grow more derived behavior; not done+ now because the sync call sites are deleted at relationship cutover anyway.diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 44fc1c7c9e05..515d93c58944 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -36,7 +36,10 @@ from posthog.models.tagged_item import TaggedItemfrom products.customer_analytics.backend.account_urls import build_account_deeplink as build_account_deeplinkfrom products.customer_analytics.backend.constants import ACCOUNT_ASSIGNMENT_ROLE_FIELDS-from products.customer_analytics.backend.logic import custom_property_values as _custom_property_values_logic+from products.customer_analytics.backend.logic import (+ custom_property_values as _custom_property_values_logic,+ relationships as _relationships_logic,+)from products.customer_analytics.backend.logic.custom_property_definitions import (InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,apply_option_side_effects,@@ -48,6 +51,8 @@ from products.customer_analytics.backend.logic.usage_spike_notifications import)from products.customer_analytics.backend.models import (Account,+ AccountRelationship,+ AccountRelationshipDefinition,CustomerJourney,CustomerProfileConfig,CustomPropertyDefinition,@@ -331,6 +336,7 @@ def _apply_external_role_assignments(return contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.INVALID_PROPERTIES)account.save(update_fields=["_properties", "updated_at"])+ _relationships_logic.sync_from_account_properties(account)return None@@ -1284,6 +1290,8 @@ def create_account_for_view(properties=input.properties,)_set_tags(input.tags, account)+ if any(field in (account._properties or {}) for field in ACCOUNT_ASSIGNMENT_ROLE_FIELDS):+ _relationships_logic.sync_from_account_properties(account, created_by=user)except PydanticValidationError as exc:raise AccountPropertiesValidationError(_format_pydantic_errors(exc))except IntegrityError:@@ -1328,6 +1336,8 @@ def update_account_for_view(with transaction.atomic():account = Account.objects.update_account(account, **update_kwargs)_set_tags(input.tags, account)+ if input.properties_provided:+ _relationships_logic.sync_from_account_properties(account, created_by=user)except PydanticValidationError as exc:raise AccountPropertiesValidationError(_format_pydantic_errors(exc))except IntegrityError:@@ -1668,3 +1678,84 @@ def list_active_custom_property_values(team_id: int, account_id: str | UUID) ->"""The account's current (non-deleted) custom property values as contracts, newest first."""rows = _custom_property_values_logic.list_active_custom_property_values(team_id=team_id, account_id=account_id)return [_to_custom_property_value(row) for row in rows]+++# --- Account relationships ---+++class AccountRelationshipDefinitionConflictError(Exception):+ """Raised when a relationship definition violates the per-team unique name constraint."""+++def _to_account_relationship_definition(+ definition: AccountRelationshipDefinition,+) -> contracts.AccountRelationshipDefinition:+ return contracts.AccountRelationshipDefinition(+ id=definition.id,+ name=definition.name,+ description=definition.description,+ is_single_holder=definition.is_single_holder,+ )+++def _to_account_relationship(relationship: AccountRelationship) -> contracts.AccountRelationship:+ user = relationship.user+ return contracts.AccountRelationship(+ id=relationship.id,+ definition=_to_account_relationship_definition(relationship.definition),+ user=contracts.AccountAssignment(id=user.id, email=user.email) if user is not None else None,+ started_at=relationship.started_at,+ ended_at=relationship.ended_at,+ )+++def list_account_relationship_definitions(team_id: int) -> list[contracts.AccountRelationshipDefinition]:+ return [+ _to_account_relationship_definition(definition)+ for definition in AccountRelationshipDefinition.objects.for_team(team_id).order_by("name")+ ]+++def create_account_relationship_definition(+ *,+ team_id: int,+ name: str,+ description: str | None = None,+ is_single_holder: bool = True,+ created_by: "User",+) -> contracts.AccountRelationshipDefinition:+ try:+ definition = AccountRelationshipDefinition.objects.for_team(team_id).create(+ team_id=team_id,+ name=name,+ description=description,+ is_single_holder=is_single_holder,+ created_by=created_by,+ )+ except IntegrityError:+ raise AccountRelationshipDefinitionConflictError(+ "A relationship definition with this name already exists for this team."+ )+ return _to_account_relationship_definition(definition)+++def delete_account_relationship_definition(*, team_id: int, definition_id: str | UUID) -> bool:+ """Hard-deletes the definition and (by cascade) its assignment history. Returns False when+ no definition matches the id for this team (→ 404)."""+ deleted, _ = AccountRelationshipDefinition.objects.for_team(team_id).filter(id=definition_id).delete()+ return deleted > 0+++def list_account_relationships(+ *, team_id: int, account_id: str | UUID, include_history: bool = False+) -> list[contracts.AccountRelationship]:+ """The account's active relationships, or its full assignment timeline with ``include_history``."""+ queryset = (+ AccountRelationship.objects.for_team(team_id)+ .filter(account_id=account_id)+ .select_related("definition", "user")+ .order_by("definition__name", "-started_at")+ )+ if not include_history:+ queryset = queryset.filter(ended_at__isnull=True)+ return [_to_account_relationship(relationship) for relationship in queryset]diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 6c07ad7f830d..fd143978715c 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -30,6 +30,27 @@ class AccountAssignment:email: str+@dataclass(frozen=True)+class AccountRelationshipDefinition:+ """A team-defined account relationship type (CSM, Onboarding manager, ...)."""++ id: UUID+ name: str+ description: str | None+ is_single_holder: bool+++@dataclass(frozen=True)+class AccountRelationship:+ """One assignment of a user to an account relationship, with its effective range."""++ id: UUID+ definition: AccountRelationshipDefinition+ user: AccountAssignment | None+ started_at: datetime+ ended_at: datetime | None++@dataclass(frozen=True)class AccountProperties:"""Typed account properties — assignment roles and external-system identifiers.diff --git a/products/customer_analytics/backend/logic/relationships.py b/products/customer_analytics/backend/logic/relationships.pynew file mode 100644index 000000000000..bc085bd95732--- /dev/null+++ b/products/customer_analytics/backend/logic/relationships.py@@ -0,0 +1,103 @@+"""+Assign/end transactions for account relationships, plus the transitional forward-sync from+the legacy JSON role keys. Called by the facade and product-internal account writers only.+"""++from django.db import transaction+from django.utils import timezone++from posthog.models.user import User++from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition++# Legacy Account properties role key -> seeded definition name. Definitions carry no stable+# machine key, so the sync and backfill map role keys to seeded definitions by name.+SEEDED_DEFINITIONS: tuple[tuple[str, str], ...] = (+ ("csm", "CSM"),+ ("account_executive", "Account executive"),+ ("account_owner", "Account owner"),+)+++class AccountRelationshipNotFound(Exception):+ pass+++def assign(+ *,+ team_id: int,+ account: Account,+ definition: AccountRelationshipDefinition,+ user: User,+ created_by: User | None,+) -> AccountRelationship:+ with transaction.atomic():+ # Serializes concurrent assigns for this definition; prevents double-insert races.+ AccountRelationshipDefinition.objects.for_team(team_id).select_for_update().get(id=definition.id)+ active = list(+ AccountRelationship.objects.for_team(team_id).filter(+ account=account, definition=definition, ended_at__isnull=True+ )+ )+ existing = next((rel for rel in active if rel.user_id == user.id), None)+ if existing is not None:+ return existing+ if definition.is_single_holder:+ for rel in active:+ rel.ended_at = timezone.now()+ rel.save(update_fields=["ended_at"])+ return AccountRelationship.objects.for_team(team_id).create(+ team_id=team_id, account=account, definition=definition, user=user, created_by=created_by+ )+++def end_active(*, team_id: int, account: Account, definition: AccountRelationshipDefinition) -> int:+ return (+ AccountRelationship.objects.for_team(team_id)+ .filter(account=account, definition=definition, ended_at__isnull=True)+ .update(ended_at=timezone.now())+ )+++def end_relationship(*, team_id: int, relationship_id: str) -> AccountRelationship:+ with transaction.atomic():+ # Serializes concurrent ends of the same row, matching assign's locking contract.+ relationship = (+ AccountRelationship.objects.for_team(team_id)+ .select_related("definition", "account")+ .select_for_update(of=("self",))+ .filter(id=relationship_id, ended_at__isnull=True)+ .first()+ )+ if relationship is None:+ raise AccountRelationshipNotFound(relationship_id)+ relationship.ended_at = timezone.now()+ relationship.save(update_fields=["ended_at"])+ return relationship+++def sync_from_account_properties(account: Account, *, created_by: User | None = None) -> None:+ """Forward-sync the legacy JSON role keys into the relationships table.++ Transitional: Account._properties is still the source of truth for roles, so every JSON+ role write calls this to keep the table shadowing it — see backend/COMPROMISES.md.+ Roles whose definition doesn't exist yet and unresolvable user ids are skipped; the JSON+ stays authoritative.+ """+ definitions_by_name = {+ definition.name: definition+ for definition in AccountRelationshipDefinition.objects.for_team(account.team_id).filter(+ name__in=[name for _, name in SEEDED_DEFINITIONS]+ )+ }+ properties = account._properties or {}+ for key, name in SEEDED_DEFINITIONS:+ definition = definitions_by_name.get(name)+ if definition is None:+ continue+ assignment = properties.get(key)+ user_id = assignment.get("id") if isinstance(assignment, dict) else None+ if user_id is None:+ end_active(team_id=account.team_id, account=account, definition=definition)+ elif (user := User.objects.filter(id=user_id).first()) is not None:+ assign(team_id=account.team_id, account=account, definition=definition, user=user, created_by=created_by)diff --git a/products/customer_analytics/backend/max_tools.py b/products/customer_analytics/backend/max_tools.pyindex 2103c098abf7..3974fa9b8289 100644--- a/products/customer_analytics/backend/max_tools.py+++ b/products/customer_analytics/backend/max_tools.py@@ -13,6 +13,8 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.rbac.user_access_control import AccessControlLevelfrom posthog.scopes import APIScopeObject+from products.customer_analytics.backend.constants import ACCOUNT_ASSIGNMENT_ROLE_FIELDS+from products.customer_analytics.backend.logic import relationships as relationships_logicfrom products.customer_analytics.backend.models import Accountfrom products.notebooks.backend.models import Notebook, ResourceNotebook@@ -256,6 +258,8 @@ class UpsertAccountTool(MaxTool):)if action.tags is not None:set_tags_on_object(action.tags, account)+ if any(field in (account._properties or {}) for field in ACCOUNT_ASSIGNMENT_ROLE_FIELDS):+ relationships_logic.sync_from_account_properties(account, created_by=self._user)return account@sync_to_async@@ -273,6 +277,8 @@ class UpsertAccountTool(MaxTool):account = Account.objects.update_account(account, **update_kwargs)if action.tags is not None:set_tags_on_object(action.tags, account)+ if action.properties is not None:+ relationships_logic.sync_from_account_properties(account, created_by=self._user)return accountdiff --git a/products/customer_analytics/backend/migrations/0013_relationships.py b/products/customer_analytics/backend/migrations/0013_relationships.pynew file mode 100644index 000000000000..3064922b6849--- /dev/null+++ b/products/customer_analytics/backend/migrations/0013_relationships.py@@ -0,0 +1,186 @@+# Generated by Django 5.2.14 on 2026-07-03 20:43++import django.utils.timezone+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+from posthog.migration_helpers import AddForeignKeyNotValid+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0012_custompropertydefinition_options_and_more"),+ ("posthog", "1247_oauthaccesstoken_token_idx"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="AccountRelationshipDefinition",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(max_length=400)),+ (+ "description",+ models.TextField(+ blank=True,+ help_text="What this relationship means, e.g. 'The customer success manager responsible for this account'.",+ null=True,+ ),+ ),+ (+ "is_single_holder",+ models.BooleanField(+ default=True,+ help_text="Whether only one user can hold this relationship per account at a time, e.g. a single CSM per account.",+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ ),+ migrations.CreateModel(+ name="AccountRelationship",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("started_at", models.DateTimeField(default=django.utils.timezone.now)),+ ("ended_at", models.DateTimeField(blank=True, null=True)),+ (+ "account",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="relationships",+ to="customer_analytics.account",+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ (+ "user",+ models.ForeignKey(+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "definition",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="relationships",+ to="customer_analytics.accountrelationshipdefinition",+ ),+ ),+ ],+ ),+ migrations.AddConstraint(+ model_name="accountrelationshipdefinition",+ constraint=models.UniqueConstraint(fields=("team", "name"), name="unique_relationship_definition_name"),+ ),+ migrations.AddIndex(+ model_name="accountrelationship",+ index=models.Index(+ condition=models.Q(("ended_at__isnull", True)),+ fields=["team", "account", "definition"],+ name="idx_active_account_rel",+ ),+ ),+ migrations.AddIndex(+ model_name="accountrelationship",+ index=models.Index(+ condition=models.Q(("ended_at__isnull", True)),+ fields=["team", "user"],+ name="idx_active_rel_by_user",+ ),+ ),+ AddForeignKeyNotValid(+ model_name="accountrelationshipdefinition",+ name="accountrelationshipdefinition_team_id_fk",+ column="team_id",+ to_table="posthog_team",+ to_column="id",+ ),+ AddForeignKeyNotValid(+ model_name="accountrelationshipdefinition",+ name="accountrelationshipdefinition_created_by_id_fk",+ column="created_by_id",+ to_table="posthog_user",+ to_column="id",+ ),+ AddForeignKeyNotValid(+ model_name="accountrelationship",+ name="accountrelationship_team_id_fk",+ column="team_id",+ to_table="posthog_team",+ to_column="id",+ ),+ AddForeignKeyNotValid(+ model_name="accountrelationship",+ name="accountrelationship_created_by_id_fk",+ column="created_by_id",+ to_table="posthog_user",+ to_column="id",+ ),+ AddForeignKeyNotValid(+ model_name="accountrelationship",+ name="accountrelationship_user_id_fk",+ column="user_id",+ to_table="posthog_user",+ to_column="id",+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/0014_relationships_validate_fks.py b/products/customer_analytics/backend/migrations/0014_relationships_validate_fks.pynew file mode 100644index 000000000000..caf2a8ad1801--- /dev/null+++ b/products/customer_analytics/backend/migrations/0014_relationships_validate_fks.py@@ -0,0 +1,19 @@+from django.db import migrations++from posthog.migration_helpers import ValidateForeignKey+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0013_relationships"),+ ]++ operations = [+ ValidateForeignKey(model_name="accountrelationshipdefinition", name="accountrelationshipdefinition_team_id_fk"),+ ValidateForeignKey(+ model_name="accountrelationshipdefinition", name="accountrelationshipdefinition_created_by_id_fk"+ ),+ ValidateForeignKey(model_name="accountrelationship", name="accountrelationship_team_id_fk"),+ ValidateForeignKey(model_name="accountrelationship", name="accountrelationship_created_by_id_fk"),+ ValidateForeignKey(model_name="accountrelationship", name="accountrelationship_user_id_fk"),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 3ed99d736ca0..47be7ee44677 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0012_custompropertydefinition_options_and_more+0014_relationships_validate_fksdiff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.pyindex e3a0e2676683..f848326742c1 100644--- a/products/customer_analytics/backend/models/__init__.py+++ b/products/customer_analytics/backend/models/__init__.py@@ -4,11 +4,14 @@ from .custom_property_source import CustomPropertySourcefrom .custom_property_value import CustomPropertyValuefrom .customer_journey import CustomerJourneyfrom .customer_profile_config import CustomerProfileConfig+from .relationship import AccountRelationship, AccountRelationshipDefinitionfrom .team_customer_analytics_config import TeamCustomerAnalyticsConfig__all__ = ["DATA_TYPE_BY_DISPLAY_TYPE","Account",+ "AccountRelationship",+ "AccountRelationshipDefinition","CustomPropertyDefinition","CustomPropertySource","CustomPropertyValue",@@ -16,5 +19,6 @@ __all__ = ["CustomerProfileConfig","DataType","DisplayType",+ "RelationshipDefinition","TeamCustomerAnalyticsConfig",]diff --git a/products/customer_analytics/backend/models/relationship.py b/products/customer_analytics/backend/models/relationship.pynew file mode 100644index 000000000000..4a9e2c571bd3--- /dev/null+++ b/products/customer_analytics/backend/models/relationship.py@@ -0,0 +1,63 @@+from django.db import models+from django.db.models import Q+from django.utils import timezone++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel+++class AccountRelationshipDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False+ )++ name = models.CharField(max_length=400)+ description = models.TextField(+ null=True,+ blank=True,+ help_text="What this relationship means, e.g. 'The customer success manager responsible for this account'.",+ )+ is_single_holder = models.BooleanField(+ default=True,+ help_text="Whether only one user can hold this relationship per account at a time, e.g. a single CSM per account.",+ )++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["team", "name"],+ name="unique_relationship_definition_name",+ ),+ ]+++class AccountRelationship(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False+ )+ definition = models.ForeignKey(+ "customer_analytics.AccountRelationshipDefinition", on_delete=models.CASCADE, related_name="relationships"+ )+ account = models.ForeignKey("customer_analytics.Account", on_delete=models.CASCADE, related_name="relationships")+ user = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, db_constraint=False, related_name="+"+ )++ started_at = models.DateTimeField(default=timezone.now)+ ended_at = models.DateTimeField(null=True, blank=True)++ class Meta:+ indexes = [+ models.Index(+ fields=["team", "account", "definition"],+ condition=Q(ended_at__isnull=True),+ name="idx_active_account_rel",+ ),+ models.Index(+ fields=["team", "user"],+ condition=Q(ended_at__isnull=True),+ name="idx_active_rel_by_user",+ ),+ ]diff --git a/products/customer_analytics/backend/test/test_relationships.py b/products/customer_analytics/backend/test/test_relationships.pynew file mode 100644index 000000000000..f28c5a5c70c2--- /dev/null+++ b/products/customer_analytics/backend/test/test_relationships.py@@ -0,0 +1,279 @@+from posthog.test.base import BaseTest++from posthog.models import Team+from posthog.rbac.user_access_control import UserAccessControl++from products.customer_analytics.backend.facade import (+ api as facade,+ contracts,+)+from products.customer_analytics.backend.logic import relationships+from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition+++class TestRelationshipLogic(BaseTest):+ def setUp(self):+ super().setUp()+ self.account = Account.objects.create_account(team=self.team, name="Acme")+ self.other_user = self._create_user("[email protected]")++ def _create_definition(self, name="CSM", is_single_holder=True) -> AccountRelationshipDefinition:+ return AccountRelationshipDefinition.objects.for_team(self.team.id).create(+ team_id=self.team.id, name=name, is_single_holder=is_single_holder+ )++ def _get_active_rows_for_account(self, **filters):+ return AccountRelationship.objects.for_team(self.team.id).filter(+ account=self.account, ended_at__isnull=True, **filters+ )++ def test_assign_creates_active_row(self):+ definition = self._create_definition()+ rel = relationships.assign(+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user+ )+ assert rel.ended_at is None+ assert rel.user == self.user++ def test_reassign_single_holder_closes_previous_and_keeps_history(self):+ definition = self._create_definition()+ first = relationships.assign(+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user+ )+ second = relationships.assign(+ team_id=self.team.id,+ account=self.account,+ definition=definition,+ user=self.other_user,+ created_by=self.user,+ )+ first.refresh_from_db()+ assert first.ended_at is not None+ assert second.ended_at is None+ assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 2++ def test_assign_same_user_is_noop(self):+ definition = self._create_definition()+ first = relationships.assign(+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user+ )+ second = relationships.assign(+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user+ )+ assert first.id == second.id++ def test_multi_holder_allows_concurrent_assignees(self):+ definition = self._create_definition(name="FDE", is_single_holder=False)+ relationships.assign(+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user+ )+ relationships.assign(+ team_id=self.team.id,+ account=self.account,+ definition=definition,+ user=self.other_user,+ created_by=self.user,+ )+ assert self._get_active_rows_for_account(definition=definition).count() == 2++ def test_end_relationship_sets_ended_at(self):+ definition = self._create_definition()+ rel = relationships.assign(+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user+ )+ ended = relationships.end_relationship(team_id=self.team.id, relationship_id=str(rel.id))+ assert ended.ended_at is not None+++class TestSyncFromAccountProperties(BaseTest):+ def setUp(self):+ super().setUp()+ AccountRelationshipDefinition.objects.for_team(self.team.id).create(team_id=self.team.id, name="CSM")+ self.account = Account.objects.create_account(+ team=self.team,+ name="Acme",+ properties={"csm": {"id": self.user.id, "email": self.user.email}, "sfdc_id": "001xx"},+ )++ def _get_active_rows_for_account(self):+ return AccountRelationship.objects.for_team(self.team.id).filter(account=self.account, ended_at__isnull=True)++ def test_sync_creates_rows_from_role_properties(self):+ relationships.sync_from_account_properties(self.account, created_by=self.user)+ rows = self._get_active_rows_for_account()+ assert rows.count() == 1+ row = rows.first()+ assert row is not None+ assert row.definition.name == "CSM"+ assert row.user_id == self.user.id++ def test_sync_is_idempotent(self):+ relationships.sync_from_account_properties(self.account)+ relationships.sync_from_account_properties(self.account)+ assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 1++ def test_sync_ends_relationship_when_key_cleared(self):+ relationships.sync_from_account_properties(self.account)+ Account.objects.update_account(self.account, properties={"sfdc_id": "001xx"})+ relationships.sync_from_account_properties(self.account)+ assert self._get_active_rows_for_account().count() == 0+ assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 1++ def test_sync_hands_off_single_holder_on_user_change(self):+ other_user = self._create_user("[email protected]")+ relationships.sync_from_account_properties(self.account)+ Account.objects.update_account(+ self.account, properties={"csm": {"id": other_user.id, "email": other_user.email}}+ )+ relationships.sync_from_account_properties(self.account)+ rows = self._get_active_rows_for_account()+ assert rows.count() == 1+ row = rows.first()+ assert row is not None+ assert row.user_id == other_user.id+ assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 2++ def test_sync_skips_unresolvable_users(self):+ Account.objects.update_account(self.account, properties={"csm": {"id": 99999999, "email": "[email protected]"}})+ relationships.sync_from_account_properties(self.account)+ assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 0++ def test_sync_skips_roles_whose_definition_is_missing(self):+ Account.objects.update_account(+ self.account,+ properties={+ "csm": {"id": self.user.id, "email": self.user.email},+ "account_executive": {"id": self.user.id, "email": self.user.email},+ },+ )+ relationships.sync_from_account_properties(self.account)+ rows = self._get_active_rows_for_account()+ assert rows.count() == 1+ row = rows.first()+ assert row is not None+ assert row.definition.name == "CSM"+++class TestRelationshipFacade(BaseTest):+ def setUp(self):+ super().setUp()+ self.account = Account.objects.create_account(team=self.team, name="Acme")++ def test_create_and_list_definitions_roundtrip(self):+ created = facade.create_account_relationship_definition(+ team_id=self.team.id, name="Onboarding manager", description="Runs onboarding", created_by=self.user+ )+ listed = facade.list_account_relationship_definitions(self.team.id)+ assert [d.id for d in listed] == [created.id]+ assert listed[0].description == "Runs onboarding"+ assert listed[0].is_single_holder is True++ def test_create_duplicate_definition_name_raises_conflict(self):+ facade.create_account_relationship_definition(team_id=self.team.id, name="CSM", created_by=self.user)+ with self.assertRaises(facade.AccountRelationshipDefinitionConflictError):+ facade.create_account_relationship_definition(team_id=self.team.id, name="CSM", created_by=self.user)++ def test_delete_definition_cascades_history(self):+ definition = facade.create_account_relationship_definition(+ team_id=self.team.id, name="CSM", created_by=self.user+ )+ model_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).get(id=definition.id)+ relationships.assign(+ team_id=self.team.id,+ account=self.account,+ definition=model_definition,+ user=self.user,+ created_by=self.user,+ )+ assert facade.delete_account_relationship_definition(team_id=self.team.id, definition_id=definition.id)+ assert AccountRelationship.objects.for_team(self.team.id).count() == 0++ def test_list_relationships_current_vs_history(self):+ definition = facade.create_account_relationship_definition(+ team_id=self.team.id, name="CSM", created_by=self.user+ )+ model_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).get(id=definition.id)+ rel = relationships.assign(+ team_id=self.team.id,+ account=self.account,+ definition=model_definition,+ user=self.user,+ created_by=self.user,+ )+ relationships.end_relationship(team_id=self.team.id, relationship_id=str(rel.id))+ assert facade.list_account_relationships(team_id=self.team.id, account_id=self.account.id) == []+ history = facade.list_account_relationships(+ team_id=self.team.id, account_id=self.account.id, include_history=True+ )+ assert len(history) == 1+ assert history[0].ended_at is not None+ assert history[0].user is not None+ assert history[0].user.email == self.user.email++ def test_team_isolation(self):+ other_team = Team.objects.create(organization=self.organization, name="other")+ definition = facade.create_account_relationship_definition(+ team_id=self.team.id, name="CSM", created_by=self.user+ )+ assert facade.list_account_relationship_definitions(other_team.id) == []+ assert facade.list_account_relationships(team_id=other_team.id, account_id=self.account.id) == []+ assert not facade.delete_account_relationship_definition(team_id=other_team.id, definition_id=definition.id)+++class TestWritePathSync(BaseTest):+ def setUp(self):+ super().setUp()+ AccountRelationshipDefinition.objects.for_team(self.team.id).create(team_id=self.team.id, name="CSM")++ def _active_rows(self, account):+ return AccountRelationship.objects.for_team(self.team.id).filter(account=account, ended_at__isnull=True)++ def _update_properties(self, account_id, properties):+ return facade.update_account_for_view(+ team_id=self.team.id,+ account_id=str(account_id),+ input=contracts.UpdateAccountInput(properties=properties, properties_provided=True),+ user_access_control=UserAccessControl(user=self.user, team=self.team),+ required_level="editor",+ organization_id=self.organization.id,+ user=self.user,+ was_impersonated=False,+ )++ def test_update_account_for_view_syncs_role_assign_and_clear(self):+ account = Account.objects.create_account(team=self.team, name="Acme")+ self._update_properties(account.id, {"csm": {"id": self.user.id, "email": self.user.email}})+ rows = self._active_rows(account)+ assert rows.count() == 1+ row = rows.first()+ assert row is not None+ assert row.user_id == self.user.id+ self._update_properties(account.id, {})+ assert self._active_rows(account).count() == 0++ def test_create_account_for_view_syncs_roles(self):+ view = facade.create_account_for_view(+ team_id=self.team.id,+ team=self.team,+ input=contracts.CreateAccountInput(+ name="Acme", properties={"csm": {"id": self.user.id, "email": self.user.email}}+ ),+ organization_id=self.organization.id,+ user=self.user,+ was_impersonated=False,+ )+ assert view.id is not None+ account = Account.objects.for_team(self.team.id).get(id=view.id)+ assert self._active_rows(account).count() == 1++ 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"+ )+ assert result.error is None+ rows = self._active_rows(account)+ assert rows.count() == 1+ row = rows.first()+ assert row is not None+ assert row.user_id == self.user.id