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): add account relationship assign/end API (#68994)

Arthur Moreira de Deuscd24fa4c3602
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index b6f4559db5c2..50bc7ba6b7fd 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -1796,3 +1796,52 @@ def list_account_relationships(
if not include_history:
queryset = queryset.filter(ended_at__isnull=True)
return [_to_account_relationship(relationship) for relationship in queryset]
+
+
+class AccountRelationshipDefinitionNotFound(Exception):
+ pass
+
+
+class AccountRelationshipAssigneeNotInOrganization(Exception):
+ pass
+
+
+def assign_account_relationship(
+ *, team_id: int, account_id: str | UUID, definition_id: str | UUID, user_id: int, created_by: "User"
+) -> contracts.AccountRelationship:
+ """Assign a user to an account relationship. Single-holder definitions hand off — the
+ previous active assignment is ended in the same transaction. Idempotent when the user
+ already actively holds the relationship.
+
+ Raises ``Account_DoesNotExist`` (→ 404), ``AccountRelationshipDefinitionNotFound`` and
+ ``AccountRelationshipAssigneeNotInOrganization`` (→ 400).
+ """
+ account = Account.objects.for_team(team_id).select_related("team").get(id=account_id)
+ definition = AccountRelationshipDefinition.objects.for_team(team_id).filter(id=definition_id).first()
+ if definition is None:
+ raise AccountRelationshipDefinitionNotFound(str(definition_id))
+ membership = (
+ OrganizationMembership.objects.select_related("user")
+ .filter(organization_id=account.team.organization_id, user_id=user_id)
+ .first()
+ )
+ if membership is None:
+ raise AccountRelationshipAssigneeNotInOrganization(str(user_id))
+ relationship = _relationships_logic.assign(
+ team_id=team_id, account=account, definition=definition, user=membership.user, created_by=created_by
+ )
+ return _to_account_relationship(relationship)
+
+
+def end_account_relationship(
+ *, team_id: int, account_id: str | UUID, relationship_id: str | UUID
+) -> contracts.AccountRelationship | None:
+ """End an active assignment. Returns None when no active assignment matches this account
+ (missing, another account's, or already ended) — mapped to 404."""
+ try:
+ relationship = _relationships_logic.end_relationship(
+ team_id=team_id, account_id=account_id, relationship_id=str(relationship_id)
+ )
+ except _relationships_logic.AccountRelationshipNotFound:
+ return None
+ return _to_account_relationship(relationship)
diff --git a/products/customer_analytics/backend/logic/relationships.py b/products/customer_analytics/backend/logic/relationships.py
index 566e703c8934..3cc9f31f1839 100644
--- a/products/customer_analytics/backend/logic/relationships.py
+++ b/products/customer_analytics/backend/logic/relationships.py
@@ -3,6 +3,8 @@ Assign/end transactions for account relationships, plus the transitional forward
the legacy JSON role keys. Called by the facade and product-internal account writers only.
"""
+from uuid import UUID
+
from django.db import transaction
from django.utils import timezone
@@ -59,14 +61,14 @@ def end_active(*, team_id: int, account: Account, definition: AccountRelationshi
)
-def end_relationship(*, team_id: int, relationship_id: str) -> AccountRelationship:
+def end_relationship(*, team_id: int, account_id: str | UUID, 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_related("definition", "user")
.select_for_update(of=("self",))
- .filter(id=relationship_id, ended_at__isnull=True)
+ .filter(id=relationship_id, account_id=account_id, ended_at__isnull=True)
.first()
)
if relationship is None:
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index af1210a1273f..31dec9649b45 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -573,3 +573,12 @@ class AccountRelationshipSerializer(DataclassSerializer):
dataclass = AccountRelationship
ref_name = "AccountRelationship"
fields = ["id", "definition", "user", "started_at", "ended_at"]
+
+
+class AccountRelationshipWriteSerializer(serializers.Serializer):
+ """Input for assigning a user to an account relationship."""
+
+ definition = serializers.UUIDField(help_text="Id of the relationship definition to assign.")
+ user = serializers.IntegerField(
+ help_text="PostHog user id of the assignee. Must be a member of the account's organization."
+ )
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 2c438be705b4..fe0b58035e41 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -20,6 +20,7 @@ from uuid import UUID
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework import mixins, status, viewsets
+from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
@@ -38,6 +39,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (
AccountNoteSerializer,
AccountRelationshipDefinitionSerializer,
AccountRelationshipSerializer,
+ AccountRelationshipWriteSerializer,
AccountSerializer,
CustomerJourneySerializer,
CustomerProfileConfigSerializer,
@@ -1100,3 +1102,39 @@ class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
include_history=request.query_params.get("include_history", "").lower() == "true",
)
return Response(AccountRelationshipSerializer(relationships, many=True).data)
+
+ @extend_schema(request=AccountRelationshipWriteSerializer, responses={201: AccountRelationshipSerializer})
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ account_id = self._accessible_account_id()
+ if account_id is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ write = AccountRelationshipWriteSerializer(data=request.data)
+ write.is_valid(raise_exception=True)
+ try:
+ relationship = api.assign_account_relationship(
+ team_id=self.team_id,
+ account_id=account_id,
+ definition_id=write.validated_data["definition"],
+ user_id=write.validated_data["user"],
+ created_by=cast(User, request.user),
+ )
+ except api.Account_DoesNotExist:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ except api.AccountRelationshipDefinitionNotFound:
+ raise ValidationError({"definition": "Relationship definition not found."})
+ except api.AccountRelationshipAssigneeNotInOrganization:
+ raise ValidationError({"user": "User is not a member of this organization."})
+ return Response(AccountRelationshipSerializer(relationship).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(request=None, responses={200: AccountRelationshipSerializer})
+ @action(methods=["POST"], detail=True)
+ def end(self, request: Request, *args, **kwargs) -> Response:
+ account_id = self._accessible_account_id()
+ if account_id is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ relationship = api.end_account_relationship(
+ team_id=self.team_id, account_id=account_id, relationship_id=self.kwargs["pk"]
+ )
+ if relationship is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(AccountRelationshipSerializer(relationship).data)
diff --git a/products/customer_analytics/backend/test/test_relationships.py b/products/customer_analytics/backend/test/test_relationships.py
index c6e811b7ca4e..4e174650931d 100644
--- a/products/customer_analytics/backend/test/test_relationships.py
+++ b/products/customer_analytics/backend/test/test_relationships.py
@@ -81,7 +81,9 @@ class TestRelationshipLogic(BaseTest):
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))
+ ended = relationships.end_relationship(
+ team_id=self.team.id, account_id=self.account.id, relationship_id=str(rel.id)
+ )
assert ended.ended_at is not None
@@ -242,7 +244,7 @@ class TestRelationshipFacade(BaseTest):
user=self.user,
created_by=self.user,
)
- relationships.end_relationship(team_id=self.team.id, relationship_id=str(rel.id))
+ relationships.end_relationship(team_id=self.team.id, account_id=self.account.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
@@ -252,6 +254,76 @@ class TestRelationshipFacade(BaseTest):
assert history[0].user is not None
assert history[0].user.email == self.user.email
+ def test_assign_and_end_roundtrip(self):
+ definition = facade.create_account_relationship_definition(
+ team_id=self.team.id, name="CSM", created_by=self.user
+ )
+ assert definition.id is not None
+ assigned = facade.assign_account_relationship(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ definition_id=definition.id,
+ user_id=self.user.id,
+ created_by=self.user,
+ )
+ assert assigned.ended_at is None
+ assert assigned.user is not None
+ assert assigned.user.email == self.user.email
+ ended = facade.end_account_relationship(
+ team_id=self.team.id, account_id=self.account.id, relationship_id=assigned.id
+ )
+ assert ended is not None
+ assert ended.ended_at is not None
+ assert (
+ facade.end_account_relationship(
+ team_id=self.team.id, account_id=self.account.id, relationship_id=assigned.id
+ )
+ is None
+ )
+
+ def test_assign_validates_definition_and_assignee(self):
+ definition = facade.create_account_relationship_definition(
+ team_id=self.team.id, name="CSM", created_by=self.user
+ )
+ assert definition.id is not None
+ outsider = User.objects.create_user("[email protected]", None, "")
+ with self.assertRaises(facade.AccountRelationshipDefinitionNotFound):
+ facade.assign_account_relationship(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ definition_id="00000000-0000-0000-0000-000000000000",
+ user_id=self.user.id,
+ created_by=self.user,
+ )
+ with self.assertRaises(facade.AccountRelationshipAssigneeNotInOrganization):
+ facade.assign_account_relationship(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ definition_id=definition.id,
+ user_id=outsider.id,
+ created_by=self.user,
+ )
+
+ def test_end_is_scoped_to_the_account(self):
+ definition = facade.create_account_relationship_definition(
+ 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")
+ assigned = facade.assign_account_relationship(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ definition_id=definition.id,
+ user_id=self.user.id,
+ created_by=self.user,
+ )
+ assert (
+ facade.end_account_relationship(
+ team_id=self.team.id, account_id=other_account.id, relationship_id=assigned.id
+ )
+ is None
+ )
+
def test_team_isolation(self):
other_team = Team.objects.create(organization=self.organization, name="other")
definition = facade.create_account_relationship_definition(
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 0e7f33295b4c..9f3195c56bd2 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -2233,7 +2233,9 @@ class TestAccountRelationshipViewSet(APIBaseTest):
ended = relationships_logic.assign(
team_id=self.team.id, account=self.account, definition=fde, user=self.user, created_by=self.user
)
- relationships_logic.end_relationship(team_id=self.team.id, relationship_id=str(ended.id))
+ relationships_logic.end_relationship(
+ team_id=self.team.id, account_id=self.account.id, relationship_id=str(ended.id)
+ )
response = self.client.get(self.endpoint)
@@ -2272,3 +2274,51 @@ class TestAccountRelationshipViewSet(APIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/accounts/{other_account.id}/relationships/")
self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
+
+ def test_assign_and_end_roundtrip(self):
+ definition = self._create_relationship_definition()
+
+ created = self.client.post(self.endpoint, {"definition": str(definition.id), "user": self.user.id})
+ self.assertEqual(status.HTTP_201_CREATED, created.status_code, created.json())
+ self.assertEqual(created.json()["definition"]["id"], str(definition.id))
+ self.assertEqual(created.json()["user"]["id"], self.user.id)
+ self.assertIsNone(created.json()["ended_at"])
+
+ ended = self.client.post(f"{self.endpoint}{created.json()['id']}/end/")
+ self.assertEqual(status.HTTP_200_OK, ended.status_code, ended.json())
+ self.assertIsNotNone(ended.json()["ended_at"])
+ self.assertEqual([], self.client.get(self.endpoint).json())
+
+ def test_assign_with_unknown_definition_returns_400(self):
+ response = self.client.post(
+ self.endpoint, {"definition": "00000000-0000-0000-0000-000000000000", "user": self.user.id}
+ )
+
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())
+ data = response.json()
+ self.assertEqual(data["attr"], "definition")
+ self.assertEqual(data["type"], "validation_error")
+
+ def test_assign_to_user_outside_organization_returns_400(self):
+ definition = self._create_relationship_definition()
+ outsider = User.objects.create_user("[email protected]", None, "")
+
+ response = self.client.post(self.endpoint, {"definition": str(definition.id), "user": outsider.id})
+
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())
+ data = response.json()
+ self.assertEqual(data["attr"], "user")
+ self.assertEqual(data["type"], "validation_error")
+
+ def test_end_already_ended_relationship_returns_404(self):
+ definition = self._create_relationship_definition()
+ rel = relationships_logic.assign(
+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user
+ )
+ relationships_logic.end_relationship(
+ team_id=self.team.id, account_id=self.account.id, relationship_id=str(rel.id)
+ )
+
+ response = self.client.post(f"{self.endpoint}{rel.id}/end/")
+
+ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index c7b73543e506..67e8cf78c3ea 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -308,6 +308,16 @@ export interface AccountRelationshipApi {
readonly ended_at: string | null
}
+/**
+ * Input for assigning a user to an account relationship.
+ */
+export interface AccountRelationshipWriteApi {
+ /** Id of the relationship definition to assign. */
+ definition: string
+ /** PostHog user id of the assignee. Must be a member of the account's organization. */
+ user: number
+}
+
/**
* Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link). Defaults to an empty object. Unknown keys are rejected.
* @nullable
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index 5afcca1be321..bb3151170056 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -15,6 +15,7 @@ import type {
AccountRelationshipApi,
AccountRelationshipDefinitionApi,
AccountRelationshipDefinitionsListParams,
+ AccountRelationshipWriteApi,
AccountsListParams,
AccountsNotebooksListParams,
AccountsRelationshipsListParams,
@@ -403,6 +404,40 @@ export const accountsRelationshipsList = async (
})
}
+export const getAccountsRelationshipsCreateUrl = (projectId: string, accountId: string) => {
+ return `/api/projects/${projectId}/accounts/${accountId}/relationships/`
+}
+
+export const accountsRelationshipsCreate = async (
+ projectId: string,
+ accountId: string,
+ accountRelationshipWriteApi: AccountRelationshipWriteApi,
+ options?: RequestInit
+): Promise<AccountRelationshipApi> => {
+ return apiMutator<AccountRelationshipApi>(getAccountsRelationshipsCreateUrl(projectId, accountId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(accountRelationshipWriteApi),
+ })
+}
+
+export const getAccountsRelationshipsEndCreateUrl = (projectId: string, accountId: string, id: string) => {
+ return `/api/projects/${projectId}/accounts/${accountId}/relationships/${id}/end/`
+}
+
+export const accountsRelationshipsEndCreate = async (
+ projectId: string,
+ accountId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AccountRelationshipApi> => {
+ return apiMutator<AccountRelationshipApi>(getAccountsRelationshipsEndCreateUrl(projectId, accountId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getAccountsRetrieveUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/accounts/${id}/`
}
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index 054eced9f790..b18b5f1452bb 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -159,6 +159,13 @@ export const AccountsNotebooksCreateBody = /* @__PURE__ */ zod.object({
text_content: zod.string().nullish().describe('Plain text representation of the notebook content for search.'),
})
+export const AccountsRelationshipsCreateBody = /* @__PURE__ */ zod
+ .object({
+ definition: zod.uuid().describe('Id of the relationship definition to assign.'),
+ user: zod.number().describe("PostHog user id of the assignee. Must be a member of the account's organization."),
+ })
+ .describe('Input for assigning a user to an account relationship.')
+
export const accountsUpdateBodyNameMax = 400
export const accountsUpdateBodyExternalIdMax = 400
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index aa0a5bebe411..df905613e5a5 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -220,6 +220,12 @@ tools:
Tag names to set on the account. Replaces the full existing tag set — pass the complete list, not a
delta. Tags are created on demand if they do not already exist for the team.
feature_flag: customer-analytics-csp
+ accounts-relationships-create:
+ operation: accounts_relationships_create
+ enabled: false
+ accounts-relationships-end-create:
+ operation: accounts_relationships_end_create
+ enabled: false
accounts-relationships-list:
operation: accounts_relationships_list
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 542f09bea262..b1cd271a10d1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -307,6 +307,16 @@ export namespace Schemas {
readonly ended_at: string | null;
}
+ /**
+ * Input for assigning a user to an account relationship.
+ */
+ export interface AccountRelationshipWrite {
+ /** Id of the relationship definition to assign. */
+ definition: string;
+ /** PostHog user id of the assignee. Must be a member of the account's organization. */
+ user: number;
+ }
+
export type BounceRatePageViewMode = typeof BounceRatePageViewMode[keyof typeof BounceRatePageViewMode];