Skip to content

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

feat(customer-analytics): Create Account model with typed properties and group attachment (#58154)

Arthur Moreira de Deus5e1462a23bde
diff --git a/.idea/posthog.iml b/.idea/posthog.iml
index 956babb7affb..02f603a43650 100644
--- a/.idea/posthog.iml
+++ b/.idea/posthog.iml
@@ -1,21 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
-<module type="PYTHON_MODULE" version="4">
- <component name="FacetManager">
- <facet type="django" name="Django">
- <configuration>
- <option name="rootFolder" value="$MODULE_DIR$" />
- <option name="settingsModule" value="posthog/settings" />
- <option name="manageScript" value="manage.py" />
- <option name="environment" value="&lt;map/&gt;" />
- <option name="doNotUseTestRunner" value="true" />
- <option name="trackFilePattern" value="migrations" />
- </configuration>
- </facet>
- </component>
+<module external.system.id="pyproject.toml" type="PYTHON_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/.flox/cache/venv/lib/python3.11/site-packages/loginas/tests" />
<sourceFolder url="file://$MODULE_DIR$/.flox/cache/venv/lib/python3.11/site-packages/loginas/tests" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/.flox/cache/venv" />
<excludeFolder url="file://$MODULE_DIR$/.venv" />
@@ -50,6 +39,41 @@
<excludeFolder url="file://$MODULE_DIR$/staticfiles/services" />
<excludeFolder url="file://$MODULE_DIR$/staticfiles/transformations" />
<excludeFolder url="file://$MODULE_DIR$/.claude/worktrees" />
+ <excludeFolder url="file://$MODULE_DIR$/frontend/.venv" />
+ <excludeFolder url="file://$MODULE_DIR$/.claude/worktrees" />
+ <excludeFolder url="file://$MODULE_DIR$/.dagster_home/.logs_queue" />
+ <excludeFolder url="file://$MODULE_DIR$/.dagster_home/.telemetry" />
+ <excludeFolder url="file://$MODULE_DIR$/.dagster_home/history" />
+ <excludeFolder url="file://$MODULE_DIR$/.dagster_home/logs" />
+ <excludeFolder url="file://$MODULE_DIR$/.dagster_home/schedules" />
+ <excludeFolder url="file://$MODULE_DIR$/.dagster_home/storage" />
+ <excludeFolder url="file://$MODULE_DIR$/.flox/cache" />
+ <excludeFolder url="file://$MODULE_DIR$/.flox/cache/venv" />
+ <excludeFolder url="file://$MODULE_DIR$/.flox/log" />
+ <excludeFolder url="file://$MODULE_DIR$/.flox/run" />
+ <excludeFolder url="file://$MODULE_DIR$/.parcel-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/.turbo" />
+ <excludeFolder url="file://$MODULE_DIR$/.typegen" />
+ <excludeFolder url="file://$MODULE_DIR$/.venv" />
+ <excludeFolder url="file://$MODULE_DIR$/common/hogvm/typescript/.turbo" />
+ <excludeFolder url="file://$MODULE_DIR$/data" />
+ <excludeFolder url="file://$MODULE_DIR$/frontend/.venv" />
+ <excludeFolder url="file://$MODULE_DIR$/frontend/src/assets" />
+ <excludeFolder url="file://$MODULE_DIR$/node_modules" />
+ <excludeFolder url="file://$MODULE_DIR$/playwright/playwright-report" />
+ <excludeFolder url="file://$MODULE_DIR$/playwright/test-results" />
+ <excludeFolder url="file://$MODULE_DIR$/rust/target" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/admin" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/assets" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/coming-soon-destinations" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/django_admin_inline_paginator" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/django_extensions" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/email" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/hedgehog" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/icons" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/rest_framework" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/services" />
+ <excludeFolder url="file://$MODULE_DIR$/staticfiles/transformations" />
<excludePattern pattern="*node_modules*" />
</content>
<orderEntry type="inheritedJdk" />
@@ -70,4 +94,4 @@
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="py.test" />
</component>
-</module>
+</module>
\ No newline at end of file
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 5eb9adffb195..d37543e55e18 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -55,6 +55,7 @@ rules:
regex: |
(?x)(
AccessControl
+ |Account
|Action
|AgentArtifact
|Alert
@@ -276,6 +277,7 @@ rules:
regex: |
(?x)(
AccessControl
+ |Account
|Action
|AgentArtifact
|Alert
diff --git a/posthog/models/scoping/root_mixin.py b/posthog/models/scoping/root_mixin.py
index bca8d38d9226..866f89929881 100644
--- a/posthog/models/scoping/root_mixin.py
+++ b/posthog/models/scoping/root_mixin.py
@@ -49,7 +49,7 @@ class TeamScopedRootMixin(RootTeamMixin):
# infer that the parent's narrower manager is intentionally being
# widened, so the assignment looks incompatible. The override is the
# whole point of this mixin.
- objects = TeamScopedManager() # type: ignore[assignment]
+ objects = TeamScopedManager() # type: ignore[assignment, misc]
class Meta:
abstract = True
diff --git a/products/customer_analytics/backend/migrations/0005_account.py b/products/customer_analytics/backend/migrations/0005_account.py
new file mode 100644
index 000000000000..e821a094cfc8
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0005_account.py
@@ -0,0 +1,67 @@
+# Generated by Django 5.2.13 on 2026-05-07 20:37
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0004_teamcustomeranalyticsconfig_account_group_type_index"),
+ ("posthog", "1151_cimd_followup_hardening"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="Account",
+ 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,
+ ),
+ ),
+ (
+ "external_id",
+ models.CharField(blank=True, max_length=400, null=True),
+ ),
+ ("name", models.CharField(max_length=400)),
+ (
+ "_properties",
+ models.JSONField(db_column="properties", default=dict),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="account",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("external_id__isnull", False)),
+ fields=("team", "external_id"),
+ name="unique_account_external_id_per_team",
+ ),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index 41f397638c65..a0db376f0946 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0004_teamcustomeranalyticsconfig_account_group_type_index
+0005_account
diff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.py
index 9578f8fba1d6..69170b49a50a 100644
--- a/products/customer_analytics/backend/models/__init__.py
+++ b/products/customer_analytics/backend/models/__init__.py
@@ -1,8 +1,10 @@
+from .account import Account
from .customer_journey import CustomerJourney
from .customer_profile_config import CustomerProfileConfig
from .team_customer_analytics_config import TeamCustomerAnalyticsConfig
__all__ = [
+ "Account",
"CustomerJourney",
"CustomerProfileConfig",
"TeamCustomerAnalyticsConfig",
diff --git a/products/customer_analytics/backend/models/account.py b/products/customer_analytics/backend/models/account.py
new file mode 100644
index 000000000000..d758cff42e24
--- /dev/null
+++ b/products/customer_analytics/backend/models/account.py
@@ -0,0 +1,90 @@
+from typing import Any
+
+from django.apps import apps
+from django.core.exceptions import ValidationError
+from django.db import models
+from django.db.models import JSONField, Q
+from django.db.models.signals import pre_save
+from django.dispatch import receiver
+
+from pydantic import BaseModel, ConfigDict
+
+from posthog.models.scoping.manager import TeamScopedManager
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+
+
+class AccountAssignment(BaseModel):
+ id: int
+ email: str
+
+
+class AccountProperties(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ csm: AccountAssignment | None = None
+ account_executive: AccountAssignment | None = None
+ account_owner: AccountAssignment | None = None
+
+
+class AccountManager(TeamScopedManager["Account"]):
+ def create(
+ self,
+ *,
+ properties: "dict | AccountProperties | None" = None,
+ **kwargs: Any,
+ ) -> "Account":
+ if properties is not None:
+ validated = (
+ properties
+ if isinstance(properties, AccountProperties)
+ else AccountProperties.model_validate(properties)
+ )
+ kwargs["_properties"] = validated.model_dump(mode="json")
+ return super().create(**kwargs)
+
+
+class Account(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
+
+ external_id = models.CharField(max_length=400, null=True, blank=True)
+ name = models.CharField(max_length=400)
+ _properties = JSONField(default=dict, db_column="properties")
+
+ objects = AccountManager() # type: ignore[assignment, misc]
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["team", "external_id"],
+ name="unique_account_external_id_per_team",
+ condition=Q(external_id__isnull=False),
+ ),
+ ]
+
+ @property
+ def properties(self) -> AccountProperties:
+ return AccountProperties.model_validate(self._properties or {})
+
+ @properties.setter
+ def properties(self, value: "dict | AccountProperties") -> None:
+ validated = value if isinstance(value, AccountProperties) else AccountProperties.model_validate(value)
+ self._properties = validated.model_dump(mode="json")
+
+
+@receiver(pre_save, sender="customer_analytics.TeamCustomerAnalyticsConfig")
+def _enforce_account_group_type_index_drift_policy(sender, instance, **kwargs) -> None:
+ if instance.pk is None:
+ return
+
+ update_fields = kwargs.get("update_fields")
+ if update_fields and "account_group_type_index" not in update_fields:
+ return
+
+ previous = sender.objects.filter(pk=instance.pk).values_list("account_group_type_index", flat=True).first()
+ if previous == instance.account_group_type_index:
+ return
+
+ AccountModel = apps.get_model("customer_analytics", "Account")
+ if AccountModel.objects.unscoped().filter(team_id=instance.team_id).exists():
+ raise ValidationError("Cannot change account_group_type_index once accounts exist for this team")
diff --git a/products/customer_analytics/backend/models/account_test.py b/products/customer_analytics/backend/models/account_test.py
new file mode 100644
index 000000000000..6a1a4615904c
--- /dev/null
+++ b/products/customer_analytics/backend/models/account_test.py
@@ -0,0 +1,114 @@
+from contextlib import AbstractContextManager
+
+import pytest
+from posthog.test.base import BaseTest
+
+from django.core.exceptions import ValidationError as DjangoValidationError
+from django.db import IntegrityError, transaction
+
+from pydantic import ValidationError as PydanticValidationError
+
+from posthog.models import Team, User
+from posthog.models.scoping import team_scope
+
+from products.customer_analytics.backend.models import Account, TeamCustomerAnalyticsConfig
+from products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties
+
+
+class _AccountTeamScopedTestMixin:
+ """Wraps setUp/tearDown with team_scope so test-body queries to Account find a scope."""
+
+ _team_scope_cm: AbstractContextManager[None] | None = None
+
+ def setUp(self) -> None:
+ super().setUp() # type: ignore[misc]
+ cm = team_scope(self.team.id) # type: ignore[attr-defined]
+ cm.__enter__()
+ self._team_scope_cm = cm
+
+ def tearDown(self) -> None:
+ if self._team_scope_cm is not None:
+ try:
+ self._team_scope_cm.__exit__(None, None, None)
+ finally:
+ self._team_scope_cm = None
+ super().tearDown() # type: ignore[misc]
+
+
+class AccountPropertiesValidationTest(_AccountTeamScopedTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.user = User.objects.create_user(
+ email="[email protected]", password=None, first_name="APV", is_email_verified=True
+ )
+
+ def test_rejects_unknown_keys(self):
+ with pytest.raises(PydanticValidationError):
+ AccountProperties.model_validate({"unknown_field": "x"})
+
+ def test_typed_property_round_trip_through_setter(self):
+ account = Account.objects.create(team=self.team, name="Round-trip")
+ account.properties = AccountProperties(
+ csm=AccountAssignment(id=self.user.id, email=self.user.email),
+ )
+ account.save()
+ account.refresh_from_db()
+
+ props = account.properties
+ assert isinstance(props, AccountProperties)
+ assert props.csm == AccountAssignment(id=self.user.id, email=self.user.email)
+ assert props.account_executive is None
+ assert props.account_owner is None
+
+ def test_setter_validates_dict_input(self):
+ account = Account.objects.create(team=self.team, name="Bad input")
+
+ with pytest.raises(PydanticValidationError):
+ account.properties = {"unknown_field": "x"}
+
+
+class AccountExternalIdUniquenessTest(_AccountTeamScopedTestMixin, BaseTest):
+ def test_duplicate_external_id_within_team_rejected(self):
+ Account.objects.create(team=self.team, name="First", external_id="acme")
+
+ with pytest.raises(IntegrityError):
+ with transaction.atomic():
+ Account.objects.create(team=self.team, name="Second", external_id="acme")
+
+ def test_same_external_id_allowed_across_teams(self):
+ other_team = Team.objects.create(organization=self.organization)
+ with team_scope(other_team.id):
+ Account.objects.create(team=other_team, name="Other team", external_id="acme")
+
+ account = Account.objects.create(team=self.team, name="Same key, different team", external_id="acme")
+
+ assert account.external_id == "acme"
+
+ def test_multiple_null_external_ids_allowed_within_team(self):
+ first = Account.objects.create(team=self.team, name="No group A")
+ second = Account.objects.create(team=self.team, name="No group B")
+
+ assert first.external_id is None
+ assert second.external_id is None
+
+
+class TeamCustomerAnalyticsConfigDriftPolicyTest(_AccountTeamScopedTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.config = TeamCustomerAnalyticsConfig.objects.get(team=self.team)
+ self.config.account_group_type_index = 0
+ self.config.save()
+
+ def test_drift_blocked_when_accounts_exist(self):
+ Account.objects.create(team=self.team, name="Existing")
+
+ self.config.account_group_type_index = 1
+ with pytest.raises(DjangoValidationError):
+ self.config.save()
+
+ def test_drift_allowed_when_no_accounts_exist(self):
+ self.config.account_group_type_index = 1
+ self.config.save()
+
+ self.config.refresh_from_db()
+ assert self.config.account_group_type_index == 1