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.

refactor(customer-analytics): move account creation from manager to facade (#74261)

Arthur Moreira de Deus9a8c585c74ae
diff --git a/.semgrep/rules/devex/customer-analytics-no-raw-account-properties-write.yaml b/.semgrep/rules/devex/customer-analytics-no-raw-account-properties-write.yaml
deleted file mode 100644
index 0042dc3cedb5..000000000000
--- a/.semgrep/rules/devex/customer-analytics-no-raw-account-properties-write.yaml
+++ /dev/null
@@ -1,36 +0,0 @@
-rules:
- - id: customer-analytics-no-raw-account-properties-write
- message: |
- Don't write Account `_properties` directly. Every account write must go through the
- AccountManager chokepoint — `Account.objects.create_account(...)` or
- `Account.objects.update_account(...)` — which validates and coerces properties via
- `AccountProperties.from_input`.
-
- Passing `_properties=` to `.create(...)` or assigning `account._properties = ...`
- bypasses that validation and can persist malformed properties.
-
- Pass `properties=<dict>` to the manager instead. Tags and the surrounding transaction
- are the caller's responsibility (see `api/serializers.py` and `max_tools/upsert_account.py`
- for the pattern).
-
- Test setup may build fixtures directly, so this rule excludes tests. For a genuine
- non-test exception, add
- `# nosemgrep: customer-analytics-no-raw-account-properties-write` with a short reason.
- severity: ERROR
- languages: [python]
- paths:
- include:
- - '/products/customer_analytics/backend/**'
- exclude:
- - '/products/customer_analytics/backend/models/account.py'
- - '**/test_*.py'
- - '**/*_test.py'
- - '**/test/**'
- - '**/migrations/**'
- pattern-either:
- - pattern: $X.create(..., _properties=$V, ...)
- - pattern: $OBJ._properties = $V
- metadata:
- category: best-practice
- subcategory:
- - audit
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 37c89abe353e..323bfd9b9785 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -17,13 +17,14 @@ Do NOT:
from collections.abc import Iterable
from datetime import datetime
+from enum import Enum
from typing import TYPE_CHECKING, Any, Optional, cast
from uuid import UUID
from django.apps import apps
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
-from django.db.models import Exists, OuterRef, Prefetch, Q
+from django.db.models import CharField, Exists, OuterRef, Prefetch, Q
from django.utils import timezone
import structlog
@@ -736,7 +737,7 @@ def _log_activity_swallowing(
name: str,
organization_id,
team_id: int,
- user: "User",
+ user: "User | None",
was_impersonated: bool,
previous=None,
) -> None:
@@ -1985,27 +1986,70 @@ def get_account_for_view(
return _to_account_view(account)
-def create_account_for_view(
+class _Unset(Enum):
+ UNSET = "unset"
+
+
+_UNSET = _Unset.UNSET
+
+
+def _cap_to_field_length(field_name: str, value: str) -> str:
+ max_length = cast(CharField, Account._meta.get_field(field_name)).max_length
+ return value[:max_length]
+
+
+def update_account(
+ account: Account,
*,
- team_id: int,
- team,
- input: contracts.CreateAccountInput,
- organization_id,
- user: "User",
- was_impersonated: bool,
-) -> contracts.AccountView:
+ name: str | _Unset = _UNSET,
+ external_id: str | None | _Unset = _UNSET,
+ properties: "dict | _ModelAccountProperties | _Unset" = _UNSET,
+) -> Account:
+ """Field-write primitive shared by every account update path. Only the fields passed are
+ written; ``properties`` replaces the stored JSON wholesale. Product-internal — takes and
+ returns the model, so it must not be called across the product boundary."""
+ update_fields: list[str] = []
+ if not isinstance(name, _Unset):
+ account.name = _cap_to_field_length("name", name)
+ update_fields.append("name")
+ if not isinstance(external_id, _Unset):
+ account.external_id = _cap_to_field_length("external_id", external_id) if external_id is not None else None
+ update_fields.append("external_id")
+ if not isinstance(properties, _Unset):
+ account._properties = _ModelAccountProperties.from_input(properties).model_dump(mode="json", exclude_unset=True)
+ update_fields.append("_properties")
+ if update_fields:
+ account.save(update_fields=update_fields)
+ return account
+
+
+def create_account(
+ *,
+ team: Team,
+ name: str,
+ created_by: "User | None" = None,
+ external_id: str | None = None,
+ properties: "dict | _ModelAccountProperties | None" = None,
+ tags: list[str] | None = None,
+ was_impersonated: bool = False,
+) -> Account:
+ """The single account-creation write path: validates properties, sets tags, shadows role
+ assignments into the relationships table, and logs activity. Product-internal — it returns
+ the model, so it must not be called across the product boundary.
+ Raises ``AccountPropertiesValidationError`` / ``AccountConflictError``."""
try:
with transaction.atomic():
- account = Account.objects.create_account(
+ validated = _ModelAccountProperties.from_input(properties or {})
+ account = Account.objects.unscoped().create(
team=team,
- created_by=user,
- name=input.name,
- external_id=input.external_id,
- properties=input.properties,
+ created_by=created_by,
+ name=_cap_to_field_length("name", name),
+ external_id=_cap_to_field_length("external_id", external_id) if external_id is not None else None,
+ _properties=validated.model_dump(mode="json", exclude_unset=True),
)
- _set_tags(input.tags, account, actor=user)
+ _set_tags(tags, account, actor=created_by)
if any(field in (account._properties or {}) for field in ACCOUNT_ASSIGNMENT_ROLE_FIELDS):
- _relationships_logic.sync_from_account_properties(account, created_by=user)
+ _relationships_logic.sync_from_account_properties(account, created_by=created_by)
except PydanticValidationError as exc:
raise AccountPropertiesValidationError(_format_pydantic_errors(exc))
except IntegrityError:
@@ -2015,9 +2059,28 @@ def create_account_for_view(
scope="Account",
activity="created",
name=account.name,
- organization_id=organization_id,
- team_id=team_id,
- user=user,
+ organization_id=team.organization_id,
+ team_id=team.pk,
+ user=created_by,
+ was_impersonated=was_impersonated,
+ )
+ return account
+
+
+def create_account_for_view(
+ *,
+ team: Team,
+ input: contracts.CreateAccountInput,
+ user: "User",
+ was_impersonated: bool,
+) -> contracts.AccountView:
+ account = create_account(
+ team=team,
+ created_by=user,
+ name=input.name,
+ external_id=input.external_id,
+ properties=input.properties,
+ tags=input.tags,
was_impersonated=was_impersonated,
)
return _to_account_view(account)
@@ -2048,7 +2111,7 @@ def update_account_for_view(
try:
with transaction.atomic():
- account = Account.objects.update_account(account, **update_kwargs)
+ account = update_account(account, **update_kwargs)
_set_tags(input.tags, account, actor=user)
if input.properties_provided:
_relationships_logic.sync_from_account_properties(account, created_by=user)
diff --git a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py
index 4787259eb020..1b1bfc146992 100644
--- a/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py
+++ b/products/customer_analytics/backend/management/commands/seed_customer_analytics_accounts.py
@@ -28,6 +28,7 @@ from posthog.models import OrganizationMembership, Team, User
from posthog.models.scoping import team_scope
from posthog.persons_db import persons_db_connection
+from products.customer_analytics.backend.facade.api import create_account
from products.customer_analytics.backend.models.account import Account, AccountAssignment, AccountProperties
from products.customer_analytics.backend.models.team_customer_analytics_config import TeamCustomerAnalyticsConfig
from products.notebooks.backend.facade import api as notebooks
@@ -164,7 +165,7 @@ class Command(BaseCommand):
for index, (group_key, props) in enumerate(groups):
account = existing.get(group_key)
if account is None:
- account = Account.objects.create_account(
+ account = create_account(
team=team,
name=props.get("name") or group_key,
external_id=group_key,
diff --git a/products/customer_analytics/backend/max_tools.py b/products/customer_analytics/backend/max_tools.py
index 31f0a2338fd0..5b734468b8b5 100644
--- a/products/customer_analytics/backend/max_tools.py
+++ b/products/customer_analytics/backend/max_tools.py
@@ -13,7 +13,12 @@ from posthog.models import OrganizationMembership
from posthog.rbac.user_access_control import AccessControlLevel
from posthog.scopes import APIScopeObject
-from products.customer_analytics.backend.facade.api import _set_tags
+from products.customer_analytics.backend.facade.api import (
+ AccountConflictError,
+ _set_tags,
+ create_account,
+ update_account,
+)
from products.customer_analytics.backend.logic import relationships as relationships_logic
from products.customer_analytics.backend.models import Account, AccountRelationshipDefinition
from products.notebooks.backend.models import Notebook, ResourceNotebook
@@ -214,7 +219,7 @@ class UpsertAccountTool(MaxTool):
properties = action.properties.model_dump(exclude_unset=True) if action.properties is not None else {}
try:
account = await self._create_account(action, properties)
- except IntegrityError:
+ except AccountConflictError:
return f"An account with external_id '{action.external_id}' already exists for this team.", {
"error": "duplicate_external_id",
}
@@ -273,15 +278,14 @@ class UpsertAccountTool(MaxTool):
@sync_to_async
def _create_account(self, action: CreateAccountAction, properties: dict[str, Any]) -> Account:
with transaction.atomic():
- account = Account.objects.create_account(
+ account = create_account(
team=self._team,
created_by=self._user,
name=action.name,
external_id=(action.external_id or None),
properties=properties,
+ tags=action.tags,
)
- if action.tags is not None:
- _set_tags(action.tags, account, actor=self._user)
if action.relationships:
self._apply_relationship_assignments(account, action.relationships)
return account
@@ -298,7 +302,7 @@ class UpsertAccountTool(MaxTool):
properties.update(action.properties.model_dump(exclude_unset=True))
update_kwargs["properties"] = properties
with transaction.atomic():
- account = Account.objects.update_account(account, **update_kwargs)
+ account = update_account(account, **update_kwargs)
if action.tags is not None:
_set_tags(action.tags, account, actor=self._user)
if action.relationships:
diff --git a/products/customer_analytics/backend/models/account.py b/products/customer_analytics/backend/models/account.py
index be9756622ef1..d23630fbceab 100644
--- a/products/customer_analytics/backend/models/account.py
+++ b/products/customer_analytics/backend/models/account.py
@@ -1,6 +1,3 @@
-from enum import Enum
-from typing import TYPE_CHECKING, cast
-
from django.apps import apps
from django.core.exceptions import ValidationError
from django.db import models
@@ -10,13 +7,9 @@ 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
-if TYPE_CHECKING:
- from posthog.models import Team, User
-
class AccountAssignment(BaseModel):
id: int
@@ -47,61 +40,6 @@ class AccountProperties(BaseModel):
return cls.model_validate(data)
-class _Unset(Enum):
- UNSET = "unset"
-
-
-_UNSET = _Unset.UNSET
-
-
-class AccountManager(TeamScopedManager["Account"]):
- def create_account(
- self,
- *,
- team: "Team",
- name: str,
- created_by: "User | None" = None,
- external_id: str | None = None,
- properties: "dict | AccountProperties | None" = None,
- ) -> "Account":
- validated = AccountProperties.from_input(properties or {})
- return self.unscoped().create(
- team=team,
- created_by=created_by,
- name=self._cap_to_field_length("name", name),
- external_id=self._cap_to_field_length("external_id", external_id) if external_id is not None else None,
- _properties=validated.model_dump(mode="json", exclude_unset=True),
- )
-
- def update_account(
- self,
- account: "Account",
- *,
- name: str | _Unset = _UNSET,
- external_id: str | None | _Unset = _UNSET,
- properties: "dict | AccountProperties | _Unset" = _UNSET,
- ) -> "Account":
- update_fields: list[str] = []
- if name is not _UNSET:
- account.name = self._cap_to_field_length("name", name)
- update_fields.append("name")
- if external_id is not _UNSET:
- account.external_id = (
- self._cap_to_field_length("external_id", external_id) if external_id is not None else None
- )
- update_fields.append("external_id")
- if properties is not _UNSET:
- account._properties = AccountProperties.from_input(properties).model_dump(mode="json", exclude_unset=True)
- update_fields.append("_properties")
- if update_fields:
- account.save(update_fields=update_fields)
- return account
-
- def _cap_to_field_length(self, field_name: str, value: str) -> str:
- max_length = cast(models.CharField, self.model._meta.get_field(field_name)).max_length
- return value[:max_length]
-
-
class Account(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
@@ -109,8 +47,6 @@ class Account(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFiel
name = models.CharField(max_length=400)
_properties = JSONField(default=dict, db_column="properties")
- objects = AccountManager() # type: ignore[assignment, misc]
-
class Meta:
constraints = [
models.UniqueConstraint(
diff --git a/products/customer_analytics/backend/models/account_test.py b/products/customer_analytics/backend/models/account_test.py
index ea5e16623642..bd7a7c33518a 100644
--- a/products/customer_analytics/backend/models/account_test.py
+++ b/products/customer_analytics/backend/models/account_test.py
@@ -1,11 +1,8 @@
-from typing import cast
-
import pytest
from posthog.test.base import BaseTest
from django.core.exceptions import ValidationError as DjangoValidationError
-from django.db import IntegrityError, models, transaction
-from django.test import SimpleTestCase
+from django.db import IntegrityError, transaction
from parameterized import parameterized
from pydantic import ValidationError as PydanticValidationError
@@ -106,56 +103,3 @@ class TeamCustomerAnalyticsConfigDriftPolicyTest(TeamScopedTestMixin, BaseTest):
self.config.save()
self.config.refresh_from_db()
assert self.config.account_group_type_index == new_index
-
-
-class AccountManagerWriteTest(TeamScopedTestMixin, BaseTest):
- def setUp(self):
- super().setUp()
- self.user = User.objects.create_user(
- email="[email protected]", password=None, first_name="Mgr", is_email_verified=True
- )
-
- def test_update_account_replaces_properties_wholesale(self):
- account = Account.objects.create_account(
- team=self.team,
- created_by=self.user,
- name="Acme",
- properties={"csm": {"id": self.user.id, "email": self.user.email}},
- )
- Account.objects.update_account(account, properties={"stripe_customer_id": "cus_123"})
- account.refresh_from_db()
- assert account.properties.csm is None
- assert account.properties.stripe_customer_id == "cus_123"
-
- def test_update_account_leaves_properties_untouched_when_not_passed(self):
- account = Account.objects.create_account(
- team=self.team,
- created_by=self.user,
- name="Acme",
- properties={"stripe_customer_id": "cus_123"},
- )
-
- Account.objects.update_account(account, name="Renamed")
-
- account.refresh_from_db()
- assert account.name == "Renamed"
- assert account.properties.stripe_customer_id == "cus_123"
-
- def test_update_account_updates_name_and_external_id(self):
- account = Account.objects.create_account(team=self.team, created_by=self.user, name="Old")
- Account.objects.update_account(account, name="New", external_id="acme-1")
- account.refresh_from_db()
- assert account.name == "New"
- assert account.external_id == "acme-1"
-
-
-class AccountManagerCapToFieldLengthTest(SimpleTestCase):
- @parameterized.expand([("name",), ("external_id",)])
- def test_caps_value_to_field_max_length(self, field_name):
- max_length = cast(models.CharField, Account._meta.get_field(field_name)).max_length
- assert max_length is not None
- result = Account.objects._cap_to_field_length(field_name, "x" * (max_length + 50))
- assert result == "x" * max_length
-
- def test_leaves_value_within_limit_unchanged(self):
- assert Account.objects._cap_to_field_length("name", "Acme") == "Acme"
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 84e961eb7bce..ab550dcc0522 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -975,7 +975,6 @@ class AccountViewSet(
data = serializer.validated_data
try:
account = api.create_account_for_view(
- team_id=self.team_id,
team=self.team,
input=contracts.CreateAccountInput(
name=data.name,
@@ -983,7 +982,6 @@ class AccountViewSet(
properties=data.properties or {},
tags=_account_tags_input(serializer),
),
- organization_id=self.organization.id,
user=cast(User, request.user),
was_impersonated=is_impersonated(request),
)
diff --git a/products/customer_analytics/backend/test/test_announcements.py b/products/customer_analytics/backend/test/test_announcements.py
index 8fb35b282e3d..2f7be5feb20b 100644
--- a/products/customer_analytics/backend/test/test_announcements.py
+++ b/products/customer_analytics/backend/test/test_announcements.py
@@ -9,7 +9,8 @@ from rest_framework import status
from posthog.models.team import Team
from products.conversations.backend.facade.api import SupportChannel, SupportSlackNotConfigured
-from products.customer_analytics.backend.models import Account, Announcement, AnnouncementDelivery
+from products.customer_analytics.backend.models import Announcement, AnnouncementDelivery
+from products.customer_analytics.backend.test.factories import create_account as create_account_row
HELPER = "products.customer_analytics.backend.logic.announcements.list_support_bot_channels"
@@ -156,7 +157,7 @@ class TestAnnouncementAPI(APIBaseTest):
SupportChannel(id="C1", name="zzz-internal", is_member=True),
SupportChannel(id="C2", name="acme-shared", is_member=True),
]
- Account.objects.create_account(team=self.team, name="Acme", properties={"slack_channel_id": "C2"})
+ create_account_row(team_id=self.team.pk, name="Acme", _properties={"slack_channel_id": "C2"})
response = self.client.get(f"{self.base_url}channels/")
diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.py
index 2e8b4ac7eeb2..09841fb0a4ed 100644
--- a/products/customer_analytics/backend/test/test_facade.py
+++ b/products/customer_analytics/backend/test/test_facade.py
@@ -1,3 +1,4 @@
+from typing import cast
from uuid import uuid4
import pytest
@@ -5,6 +6,8 @@ from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.apps import apps
+from django.db import models
+from django.test import SimpleTestCase
from parameterized import parameterized
@@ -341,10 +344,8 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):
def _create(self, **kwargs) -> contracts.AccountView:
return facade.create_account_for_view(
- team_id=self.team.id,
team=self.team,
input=self._create_account_input(**kwargs),
- organization_id=self.organization.id,
user=self.user,
was_impersonated=False,
)
@@ -803,3 +804,56 @@ class TestCustomPropertySourceFacade(TeamScopedTestMixin, BaseTest):
with pytest.raises(facade.CustomPropertyValueSourceManaged):
facade.set_custom_property_value(self.team.id, account.id, self.definition.id, 42)
+
+
+class AccountUpdateWriteTest(TeamScopedTestMixin, BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.user = User.objects.create_user(
+ email="[email protected]", password=None, first_name="Mgr", is_email_verified=True
+ )
+
+ def test_update_account_replaces_properties_wholesale(self):
+ account = create_account(
+ team_id=self.team.pk,
+ created_by=self.user,
+ name="Acme",
+ _properties={"csm": {"id": self.user.id, "email": self.user.email}},
+ )
+ facade.update_account(account, properties={"stripe_customer_id": "cus_123"})
+ account.refresh_from_db()
+ assert account.properties.csm is None
+ assert account.properties.stripe_customer_id == "cus_123"
+
+ def test_update_account_leaves_properties_untouched_when_not_passed(self):
+ account = create_account(
+ team_id=self.team.pk,
+ created_by=self.user,
+ name="Acme",
+ _properties={"stripe_customer_id": "cus_123"},
+ )
+
+ facade.update_account(account, name="Renamed")
+
+ account.refresh_from_db()
+ assert account.name == "Renamed"
+ assert account.properties.stripe_customer_id == "cus_123"
+
+ def test_update_account_updates_name_and_external_id(self):
+ account = create_account(team_id=self.team.pk, created_by=self.user, name="Old")
+ facade.update_account(account, name="New", external_id="acme-1")
+ account.refresh_from_db()
+ assert account.name == "New"
+ assert account.external_id == "acme-1"
+
+
+class AccountCapToFieldLengthTest(SimpleTestCase):
+ @parameterized.expand([("name",), ("external_id",)])
+ def test_caps_value_to_field_max_length(self, field_name):
+ max_length = cast(models.CharField, Account._meta.get_field(field_name)).max_length
+ assert max_length is not None
+ result = facade._cap_to_field_length(field_name, "x" * (max_length + 50))
+ assert result == "x" * max_length
+
+ def test_leaves_value_within_limit_unchanged(self):
+ assert facade._cap_to_field_length("name", "Acme") == "Acme"
diff --git a/products/customer_analytics/backend/test/test_relationships.py b/products/customer_analytics/backend/test/test_relationships.py
index f2d81c1e0e84..b59b81ee0e53 100644
--- a/products/customer_analytics/backend/test/test_relationships.py
+++ b/products/customer_analytics/backend/test/test_relationships.py
@@ -9,12 +9,13 @@ from products.customer_analytics.backend.facade import (
)
from products.customer_analytics.backend.logic import relationships
from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition
+from products.customer_analytics.backend.test.factories import create_account
class TestRelationshipLogic(BaseTest):
def setUp(self):
super().setUp()
- self.account = Account.objects.create_account(team=self.team, name="Acme")
+ self.account = create_account(team_id=self.team.pk, name="Acme")
self.other_user = self._create_user("[email protected]")
def _create_definition(self, name="CSM", is_single_holder=True) -> AccountRelationshipDefinition:
@@ -91,10 +92,10 @@ 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,
+ self.account = create_account(
+ team_id=self.team.pk,
name="Acme",
- properties={"csm": {"id": self.user.id, "email": self.user.email}, "sfdc_id": "001xx"},
+ _properties={"csm": {"id": self.user.id, "email": self.user.email}, "sfdc_id": "001xx"},
)
def _get_active_rows_for_account(self):
@@ -116,7 +117,7 @@ class TestSyncFromAccountProperties(BaseTest):
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"})
+ facade.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
@@ -124,9 +125,7 @@ class TestSyncFromAccountProperties(BaseTest):
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}}
- )
+ facade.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
@@ -136,18 +135,18 @@ class TestSyncFromAccountProperties(BaseTest):
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]"}})
+ facade.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_users_outside_the_organization(self):
outsider = User.objects.create_user(email="[email protected]", password=None, first_name="Out")
- Account.objects.update_account(self.account, properties={"csm": {"id": outsider.id, "email": outsider.email}})
+ facade.update_account(self.account, properties={"csm": {"id": outsider.id, "email": outsider.email}})
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(
+ facade.update_account(
self.account,
properties={
"csm": {"id": self.user.id, "email": self.user.email},
@@ -165,7 +164,7 @@ class TestSyncFromAccountProperties(BaseTest):
class TestRelationshipFacade(BaseTest):
def setUp(self):
super().setUp()
- self.account = Account.objects.create_account(team=self.team, name="Acme")
+ self.account = create_account(team_id=self.team.pk, name="Acme")
def test_create_and_list_definitions_roundtrip(self):
created = facade.create_account_relationship_definition(
@@ -309,7 +308,7 @@ class TestRelationshipFacade(BaseTest):
team_id=self.team.id, name="CSM", created_by=self.user
)
assert definition.id is not None
- other_account = Account.objects.create_account(team=self.team, name="Other")
+ other_account = create_account(team_id=self.team.pk, name="Other")
assigned = facade.assign_account_relationship(
team_id=self.team.id,
account_id=self.account.id,
@@ -358,7 +357,7 @@ class TestWritePathSync(BaseTest):
)
def test_update_account_for_view_syncs_role_assign_and_clear(self):
- account = Account.objects.create_account(team=self.team, name="Acme")
+ account = create_account(team_id=self.team.pk, 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
@@ -370,12 +369,10 @@ class TestWritePathSync(BaseTest):
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,
)
@@ -384,7 +381,7 @@ class TestWritePathSync(BaseTest):
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")
+ account = create_account(team_id=self.team.pk, name="Acme", external_id="acme-1")
result = facade.update_external_account(
self.team.id,
"acme-1",