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(workflows): add account relationship changed trigger (#83814)

Arthur Moreira de Deusfc34b0c09e37
diff --git a/products/customer_analytics/backend/events.py b/products/customer_analytics/backend/events.py
index 2197f8e9faae..3ec04698067e 100644
--- a/products/customer_analytics/backend/events.py
+++ b/products/customer_analytics/backend/events.py
@@ -14,7 +14,7 @@ from posthog.models.group_type_mapping import get_group_types_for_project
from posthog.models.tag import Tag
from posthog.models.user import User
-from products.customer_analytics.backend.models import Account, CustomPropertyDefinition
+from products.customer_analytics.backend.models import Account, AccountRelationshipDefinition, CustomPropertyDefinition
EVENT_SOURCE = "customer_analytics_events"
@@ -108,3 +108,33 @@ def emit_account_custom_property_changed(
token=account.team.api_token,
event_source=EVENT_SOURCE,
).raise_for_status()
+
+
+def emit_account_relationship_changed(
+ account: Account,
+ definition: AccountRelationshipDefinition,
+ previous_user: User | None,
+ current_user: User | None,
+ actor: User | None,
+ workflow_id: str | None = None,
+) -> None:
+ capture_batch_internal(
+ events=[
+ {
+ "event": "$account_relationship_changed",
+ "distinct_id": _event_distinct_id(account, actor),
+ "properties": {
+ **_base_event_properties(account, actor, workflow_id),
+ "relationship_id": str(definition.id),
+ "relationship_name": definition.name,
+ "change_type": "assigned" if current_user else "unassigned",
+ "previous_user_id": previous_user.id if previous_user else None,
+ "previous_user_email": previous_user.email if previous_user else None,
+ "current_user_id": current_user.id if current_user else None,
+ "current_user_email": current_user.email if current_user else None,
+ },
+ }
+ ],
+ token=account.team.api_token,
+ event_source=EVENT_SOURCE,
+ ).raise_for_status()
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index e88ee655ab33..f274fb3ecc7d 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -599,7 +599,7 @@ def _apply_external_tags(account: Account, tags: list[str], mode: str, workflow_
def _apply_external_relationship_assignments(
- account: Account, assignments: dict[str, int | None]
+ account: Account, assignments: dict[str, int | None], workflow_id: str | None = None
) -> contracts.ExternalAccountUpdateResult | None:
"""Apply provided relationship assignments, keyed by definition UUID (None ends the
active assignment). Each non-None user id is resolved against an
@@ -649,10 +649,20 @@ def _apply_external_relationship_assignments(
for definition, assignee in resolved:
if assignee is None:
- _relationships_logic.end_active(team_id=account.team_id, account=account, definition=definition)
+ _relationships_logic.end_active(
+ team_id=account.team_id,
+ account=account,
+ definition=definition,
+ workflow_id=workflow_id,
+ )
else:
_relationships_logic.assign(
- team_id=account.team_id, account=account, definition=definition, user=assignee, created_by=None
+ team_id=account.team_id,
+ account=account,
+ definition=definition,
+ user=assignee,
+ created_by=None,
+ workflow_id=workflow_id,
)
return None
@@ -689,7 +699,9 @@ def update_external_account(
try:
with transaction.atomic():
- error_result = _apply_external_relationship_assignments(account, relationship_assignments)
+ error_result = _apply_external_relationship_assignments(
+ account, relationship_assignments, workflow_id=workflow_id
+ )
if error_result is not None:
return error_result
if tags is not None:
@@ -4005,13 +4017,20 @@ def assign_account_relationship(
def end_account_relationship(
- *, team_id: int, account_id: str | UUID, relationship_id: str | UUID
+ *,
+ team_id: int,
+ account_id: str | UUID,
+ relationship_id: str | UUID,
+ actor: "User | None" = None,
) -> 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)
+ team_id=team_id,
+ account_id=account_id,
+ relationship_id=str(relationship_id),
+ actor=actor,
)
except _relationships_logic.AccountRelationshipNotFound:
return None
diff --git a/products/customer_analytics/backend/logic/relationships.py b/products/customer_analytics/backend/logic/relationships.py
index dc73d2a4dc87..c7b024ee5857 100644
--- a/products/customer_analytics/backend/logic/relationships.py
+++ b/products/customer_analytics/backend/logic/relationships.py
@@ -8,8 +8,10 @@ from uuid import UUID
from django.db import transaction
from django.utils import timezone
+from posthog.exceptions_capture import capture_exception
from posthog.models.user import User
+from products.customer_analytics.backend.events import emit_account_relationship_changed
from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinition
@@ -24,41 +26,91 @@ def assign(
definition: AccountRelationshipDefinition,
user: User,
created_by: User | None,
+ workflow_id: str | None = None,
+ emit_event: bool = True,
) -> 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
- )
+ AccountRelationship.objects.for_team(team_id)
+ .filter(account=account, definition=definition, ended_at__isnull=True)
+ .select_related("user")
)
existing = next((rel for rel in active if rel.user_id == user.id), None)
if existing is not None:
return existing
+
+ previous_user = active[0].user if definition.is_single_holder and active else None
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(
+ for relationship in active:
+ relationship.ended_at = timezone.now()
+ relationship.save(update_fields=["ended_at"])
+ relationship = AccountRelationship.objects.for_team(team_id).create(
team_id=team_id, account=account, definition=definition, user=user, created_by=created_by
)
+ if emit_event:
+ _schedule_relationship_changed_event(
+ account=account,
+ definition=definition,
+ previous_user=previous_user,
+ current_user=user,
+ actor=created_by,
+ workflow_id=workflow_id,
+ )
+ return relationship
-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_active(
+ *,
+ team_id: int,
+ account: Account,
+ definition: AccountRelationshipDefinition,
+ actor: User | None = None,
+ workflow_id: str | None = None,
+ emit_event: bool = True,
+) -> int:
+ with transaction.atomic():
+ active = list(
+ AccountRelationship.objects.for_team(team_id)
+ .select_related("user")
+ .select_for_update(of=("self",))
+ .filter(account=account, definition=definition, ended_at__isnull=True)
+ )
+ if not active:
+ return 0
+ updated = (
+ AccountRelationship.objects.for_team(team_id)
+ .filter(id__in=[rel.id for rel in active])
+ .update(ended_at=timezone.now())
+ )
+ if emit_event:
+ for relationship in active:
+ _schedule_relationship_changed_event(
+ account=account,
+ definition=definition,
+ previous_user=relationship.user,
+ current_user=None,
+ actor=actor,
+ workflow_id=workflow_id,
+ )
+ return updated
-def end_relationship(*, team_id: int, account_id: str | UUID, relationship_id: str) -> AccountRelationship:
+def end_relationship(
+ *,
+ team_id: int,
+ account_id: str | UUID,
+ relationship_id: str,
+ actor: User | None = None,
+ workflow_id: str | None = None,
+ emit_event: bool = True,
+) -> 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", "user")
+ .select_related("definition", "user", "account__team")
.select_for_update(of=("self",))
.filter(id=relationship_id, account_id=account_id, ended_at__isnull=True)
.first()
@@ -67,4 +119,40 @@ def end_relationship(*, team_id: int, account_id: str | UUID, relationship_id: s
raise AccountRelationshipNotFound(relationship_id)
relationship.ended_at = timezone.now()
relationship.save(update_fields=["ended_at"])
+ if emit_event:
+ _schedule_relationship_changed_event(
+ account=relationship.account,
+ definition=relationship.definition,
+ previous_user=relationship.user,
+ current_user=None,
+ actor=actor,
+ workflow_id=workflow_id,
+ )
return relationship
+
+
+def _schedule_relationship_changed_event(
+ *,
+ account: Account,
+ definition: AccountRelationshipDefinition,
+ previous_user: User | None,
+ current_user: User | None,
+ actor: User | None,
+ workflow_id: str | None,
+) -> None:
+ """Emit only after the relationship write commits, without failing the write on capture errors."""
+
+ def emit() -> None:
+ try:
+ emit_account_relationship_changed(
+ account=account,
+ definition=definition,
+ previous_user=previous_user,
+ current_user=current_user,
+ actor=actor,
+ workflow_id=workflow_id,
+ )
+ except Exception as error:
+ capture_exception(error)
+
+ transaction.on_commit(emit)
diff --git a/products/customer_analytics/backend/management/commands/backfill_account_relationships.py b/products/customer_analytics/backend/management/commands/backfill_account_relationships.py
index 725ca2082bf7..2408b38cfc0e 100644
--- a/products/customer_analytics/backend/management/commands/backfill_account_relationships.py
+++ b/products/customer_analytics/backend/management/commands/backfill_account_relationships.py
@@ -107,7 +107,12 @@ class Command(BaseCommand):
if _has_active_holder(team_id, account, definition):
continue
relationships_logic.assign(
- team_id=team_id, account=account, definition=definition, user=user, created_by=None
+ team_id=team_id,
+ account=account,
+ definition=definition,
+ user=user,
+ created_by=None,
+ emit_event=False,
)
assigned += 1
return assigned
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 d76dc965da7d..59180602aae0 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
@@ -207,6 +207,7 @@ class Command(BaseCommand):
definition=definition,
user=user_pool[(index + offset) % len(user_pool)],
created_by=creator,
+ emit_event=False,
)
@transaction.atomic
diff --git a/products/customer_analytics/backend/max_tools.py b/products/customer_analytics/backend/max_tools.py
index 5b734468b8b5..f5a7a900969f 100644
--- a/products/customer_analytics/backend/max_tools.py
+++ b/products/customer_analytics/backend/max_tools.py
@@ -335,7 +335,12 @@ class UpsertAccountTool(MaxTool):
for name, user_id in assignments.items():
definition = definitions[name]
if user_id is None:
- relationships_logic.end_active(team_id=self._team.id, account=account, definition=definition)
+ relationships_logic.end_active(
+ team_id=self._team.id,
+ account=account,
+ definition=definition,
+ actor=self._user,
+ )
continue
relationships_logic.assign(
team_id=self._team.id,
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index f4c32149df0a..1c30b90b3e75 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -1842,7 +1842,10 @@ class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
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"]
+ team_id=self.team_id,
+ account_id=account_id,
+ relationship_id=self.kwargs["pk"],
+ actor=cast(User, request.user),
)
if relationship is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
diff --git a/products/customer_analytics/backend/test/test_events.py b/products/customer_analytics/backend/test/test_events.py
index 7b8a06a8b9f0..4d004d203031 100644
--- a/products/customer_analytics/backend/test/test_events.py
+++ b/products/customer_analytics/backend/test/test_events.py
@@ -13,6 +13,7 @@ from products.customer_analytics.backend.facade import (
api as facade,
contracts,
)
+from products.customer_analytics.backend.models import AccountRelationshipDefinition
from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
@@ -272,3 +273,140 @@ class TestAccountCustomPropertyChangedEvent(BaseTest):
assert event["distinct_id"] == self.user.distinct_id
assert event["properties"]["actor_type"] == "user"
assert event["properties"]["actor_email"] == self.user.email
+
+
+@patch("products.customer_analytics.backend.events.capture_batch_internal")
+class TestAccountRelationshipChangedEvent(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")
+ self.definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name="CSM"
+ )
+ self.other_user = self._create_user("[email protected]")
+ create_group_type_mapping(team=self.team, project=self.team.project, group_type="account", group_type_index=1)
+ config = self.team.customer_analytics_config
+ config.account_group_type_index = 1
+ config.save()
+
+ def _assign(self, user=None):
+ with self.captureOnCommitCallbacks(execute=True):
+ return facade.assign_account_relationship(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ definition_id=self.definition.id,
+ user_id=(user or self.user).id,
+ created_by=self.user,
+ )
+
+ def test_first_assignment_emits_with_current_assignee(self, mock_capture):
+ self._assign()
+
+ mock_capture.assert_called_once()
+ kwargs = mock_capture.call_args.kwargs
+ assert kwargs["token"] == self.team.api_token
+ (event,) = kwargs["events"]
+ assert event["event"] == "$account_relationship_changed"
+ assert event["distinct_id"] == self.user.distinct_id
+ properties = event["properties"]
+ assert properties["relationship_id"] == str(self.definition.id)
+ assert properties["relationship_name"] == "CSM"
+ assert properties["change_type"] == "assigned"
+ assert properties["previous_user_id"] is None
+ assert properties["previous_user_email"] is None
+ assert properties["current_user_id"] == self.user.id
+ assert properties["current_user_email"] == self.user.email
+ assert properties["account_id"] == str(self.account.id)
+ assert properties["account_external_id"] == "acme-1"
+ assert properties["account_name"] == "Acme Corp"
+ assert properties["actor_type"] == "user"
+ assert properties["$groups"] == {"account": "acme-1"}
+
+ def test_reassignment_emits_one_event_with_previous_and_current_assignees(self, mock_capture):
+ self._assign()
+ mock_capture.reset_mock()
+
+ self._assign(self.other_user)
+
+ mock_capture.assert_called_once()
+ (event,) = mock_capture.call_args.kwargs["events"]
+ properties = event["properties"]
+ assert properties["change_type"] == "assigned"
+ assert properties["previous_user_id"] == self.user.id
+ assert properties["previous_user_email"] == self.user.email
+ assert properties["current_user_id"] == self.other_user.id
+ assert properties["current_user_email"] == self.other_user.email
+
+ def test_ending_assignment_emits_with_previous_assignee(self, mock_capture):
+ relationship = self._assign()
+ mock_capture.reset_mock()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ facade.end_account_relationship(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ relationship_id=relationship.id,
+ actor=self.user,
+ )
+
+ mock_capture.assert_called_once()
+ (event,) = mock_capture.call_args.kwargs["events"]
+ properties = event["properties"]
+ assert properties["change_type"] == "unassigned"
+ assert properties["previous_user_id"] == self.user.id
+ assert properties["previous_user_email"] == self.user.email
+ assert properties["current_user_id"] is None
+ assert properties["current_user_email"] is None
+
+ def test_assigning_same_user_emits_nothing(self, mock_capture):
+ self._assign()
+ mock_capture.reset_mock()
+
+ self._assign()
+
+ mock_capture.assert_not_called()
+
+ def test_no_event_when_transaction_rolls_back(self, mock_capture):
+ with self.captureOnCommitCallbacks(execute=True):
+ try:
+ with transaction.atomic():
+ facade.assign_account_relationship(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ definition_id=self.definition.id,
+ user_id=self.user.id,
+ created_by=self.user,
+ )
+ raise RuntimeError("boom")
+ except RuntimeError:
+ pass
+
+ mock_capture.assert_not_called()
+
+ def test_capture_failure_is_reported_not_raised(self, mock_capture):
+ mock_capture.return_value = CaptureInternalResult(status_code=503, error={"error": "transport_error"})
+
+ with patch(
+ "products.customer_analytics.backend.logic.relationships.capture_exception"
+ ) as mock_capture_exception:
+ relationship = self._assign()
+
+ mock_capture_exception.assert_called_once()
+ assert relationship.ended_at is None
+
+ def test_workflow_assignment_sets_workflow_actor(self, mock_capture):
+ with self.captureOnCommitCallbacks(execute=True):
+ result = facade.update_external_account(
+ self.team.id,
+ "acme-1",
+ relationship_assignments={str(self.definition.id): self.user.id},
+ tags=None,
+ tags_mode="add",
+ workflow_id=WORKFLOW_ID,
+ )
+ assert result.error is None
+
+ mock_capture.assert_called_once()
+ (event,) = mock_capture.call_args.kwargs["events"]
+ assert event["properties"]["actor_type"] == "workflow"
+ assert event["properties"]["workflow_id"] == WORKFLOW_ID
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/accountRelationshipDefinitionsLogic.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/accountRelationshipDefinitionsLogic.ts
new file mode 100644
index 000000000000..b61c36ec09c9
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/accountRelationshipDefinitionsLogic.ts
@@ -0,0 +1,96 @@
+import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import { accountRelationshipDefinitionsList } from 'products/customer_analytics/frontend/generated/api'
+import type { AccountRelationshipDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountRelationshipDefinitionsLogicValues {
+ currentProjectId: number | null // projectLogic
+ definitions: AccountRelationshipDefinitionApi[]
+ definitionsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountRelationshipDefinitionsLogicActions {
+ loadCurrentProjectSuccess: (
+ currentProject: null | import('~/types').ProjectType,
+ payload?: any
+ ) => {
+ currentProject: null | import('~/types').ProjectType
+ payload?: any
+ } // projectLogic
+ loadDefinitions: () => any
+ loadDefinitionsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDefinitionsSuccess: (
+ definitions: AccountRelationshipDefinitionApi[],
+ payload?: any
+ ) => {
+ definitions: AccountRelationshipDefinitionApi[]
+ payload?: any
+ }
+}
+
+export type accountRelationshipDefinitionsLogicType = MakeLogicType<
+ accountRelationshipDefinitionsLogicValues,
+ accountRelationshipDefinitionsLogicActions
+>
+
+export const accountRelationshipDefinitionsLogic = kea<accountRelationshipDefinitionsLogicType>([
+ path([
+ 'products',
+ 'workflows',
+ 'frontend',
+ 'Workflows',
+ 'hogflows',
+ 'registry',
+ 'triggers',
+ 'accountRelationshipDefinitionsLogic',
+ ]),
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId']],
+ actions: [projectLogic, ['loadCurrentProjectSuccess']],
+ })),
+ loaders(({ values }) => ({
+ definitions: [
+ [] as AccountRelationshipDefinitionApi[],
+ {
+ loadDefinitions: async (): Promise<AccountRelationshipDefinitionApi[]> => {
+ if (!values.currentProjectId) {
+ return []
+ }
+ try {
+ const response = await accountRelationshipDefinitionsList(String(values.currentProjectId))
+ return response.results
+ } catch (error) {
+ posthog.captureException(error, { scope: 'accountRelationshipDefinitionsLogic.load' })
+ return values.definitions
+ }
+ },
+ },
+ ],
+ })),
+ listeners(({ actions }) => ({
+ loadDefinitionsFailure: ({ error }) => {
+ posthog.captureException(error, {
+ scope: 'accountRelationshipDefinitionsLogic.load',
+ })
+ },
+ // The logic can mount before the project resolves; retry the load once it does.
+ loadCurrentProjectSuccess: () => {
+ actions.loadDefinitions()
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadDefinitions()
+ }),
+])
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.test.ts
index ddb5376871e4..c06dca144b34 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.test.ts
@@ -3,11 +3,15 @@ import { PropertyType } from '~/types'
import {
accountCustomPropertyChangedFilters,
accountCustomPropertyFrequencyOptions,
+ accountRelationshipChangedFilters,
+ accountRelationshipFrequencyOptions,
accountTagAddedFilters,
customPropertyDisplayTypeToPropertyType,
getAccountCustomPropertyChangedConditions,
getAccountCustomPropertyValueFilters,
+ getAccountRelationshipChangeType,
getSelectedPropertyNames,
+ getSelectedRelationshipNames,
getSelectedTags,
} from './customer_analytics'
import { EventTriggerConfig, getRegisteredTriggerTypes } from './triggerTypeRegistry'
@@ -21,7 +25,7 @@ describe('customer analytics triggers', () => {
return triggerType
}
- it.each(['account_tag_added', 'account_custom_property_changed'])(
+ it.each(['account_tag_added', 'account_custom_property_changed', 'account_relationship_changed'])(
'%s buildConfig produces a config recognized by matchConfig',
(value) => {
const triggerType = getTriggerType(value)
@@ -29,11 +33,17 @@ describe('customer analytics triggers', () => {
}
)
- it('the two account triggers do not claim each other configs', () => {
- const tagTrigger = getTriggerType('account_tag_added')
- const propertyTrigger = getTriggerType('account_custom_property_changed')
- expect(propertyTrigger.matchConfig!(tagTrigger.buildConfig())).toBe(false)
- expect(tagTrigger.matchConfig!(propertyTrigger.buildConfig())).toBe(false)
+ it("the account triggers do not claim each other's configs", () => {
+ const triggers = [
+ getTriggerType('account_tag_added'),
+ getTriggerType('account_custom_property_changed'),
+ getTriggerType('account_relationship_changed'),
+ ]
+ for (const trigger of triggers) {
+ for (const otherTrigger of triggers) {
+ expect(trigger.matchConfig!(otherTrigger.buildConfig())).toBe(trigger === otherTrigger)
+ }
+ }
})
it.each([
@@ -172,14 +182,87 @@ describe('customer analytics triggers', () => {
expect(customPropertyDisplayTypeToPropertyType(displayType)).toBe(expected)
})
+ it.each([
+ {
+ name: 'array value',
+ properties: [
+ { key: 'relationship_name', value: ['CSM', 'Account owner'], operator: 'exact', type: 'event' },
+ ],
+ expected: ['CSM', 'Account owner'],
+ },
+ {
+ name: 'scalar value',
+ properties: [{ key: 'relationship_name', value: 'CSM', operator: 'exact', type: 'event' }],
+ expected: ['CSM'],
+ },
+ { name: 'no relationship filter', properties: [], expected: [] },
+ {
+ name: 'non-string values',
+ properties: [{ key: 'relationship_name', value: [1, null], operator: 'exact', type: 'event' }],
+ expected: [],
+ },
+ ])('getSelectedRelationshipNames handles $name', ({ properties, expected }) => {
+ const config: EventTriggerConfig = { type: 'event', filters: { properties } }
+ expect(getSelectedRelationshipNames(config)).toEqual(expected)
+ })
+
+ it('omits the relationship filter when no relationships are selected', () => {
+ expect(accountRelationshipChangedFilters([]).properties).toEqual([])
+ expect(accountRelationshipChangedFilters(['CSM']).properties).toEqual([
+ { key: 'relationship_name', value: ['CSM'], operator: 'exact', type: 'event' },
+ ])
+ })
+
+ it('preserves the change type filter when the relationship selection changes', () => {
+ const changeTypeFilter = { key: 'change_type', value: 'assigned', operator: 'exact', type: 'event' }
+ const filters = accountRelationshipChangedFilters(['CSM'], {
+ properties: [changeTypeFilter],
+ filter_test_accounts: true,
+ })
+ const config: EventTriggerConfig = { type: 'event', filters }
+
+ expect(filters.properties).toEqual([
+ { key: 'relationship_name', value: ['CSM'], operator: 'exact', type: 'event' },
+ changeTypeFilter,
+ ])
+ expect(filters.filter_test_accounts).toBe(true)
+ expect(getAccountRelationshipChangeType(config)).toBe('assigned')
+ })
+
+ it('replaces the change type filter without changing the selected relationships', () => {
+ const filters = accountRelationshipChangedFilters(['CSM'], {}, 'unassigned')
+
+ expect(filters.properties).toEqual([
+ { key: 'relationship_name', value: ['CSM'], operator: 'exact', type: 'event' },
+ { key: 'change_type', value: 'unassigned', operator: 'exact', type: 'event' },
+ ])
+ })
+
+ it('clears the change type filter without changing the selected relationships', () => {
+ const filters = accountRelationshipChangedFilters(
+ ['CSM'],
+ {
+ properties: [{ key: 'change_type', value: 'assigned', operator: 'exact', type: 'event' }],
+ },
+ null
+ )
+
+ expect(filters.properties).toEqual([
+ { key: 'relationship_name', value: ['CSM'], operator: 'exact', type: 'event' },
+ ])
+ })
+
// The hash templates are evaluated as Hog against the trigger event at runtime — a typo'd
// property reference resolves to null for every event and masks all accounts as one.
- it('frequency hashes key on the account and property from the trigger event', () => {
- const maskingOptions = accountCustomPropertyFrequencyOptions.filter((option) => option.value !== null)
+ it.each([
+ { options: accountCustomPropertyFrequencyOptions, field: 'event.properties.property_name' },
+ { options: accountRelationshipFrequencyOptions, field: 'event.properties.relationship_name' },
+ ])('frequency hashes key on the account and changed field from the trigger event', ({ options, field }) => {
+ const maskingOptions = options.filter((option) => option.value !== null)
expect(maskingOptions.length).toBeGreaterThan(0)
for (const option of maskingOptions) {
expect(option.value).toContain('event.properties.account_id')
- expect(option.value).toContain('event.properties.property_name')
+ expect(option.value).toContain(field)
}
})
})
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.tsx
index b1caca9eb51e..73d361453703 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
-import { IconBolt, IconPencil, IconPlusSmall, IconX } from '@posthog/icons'
-import { LemonButton, LemonInputSelect } from '@posthog/lemon-ui'
+import { IconBolt, IconPencil, IconPerson, IconPlusSmall, IconX } from '@posthog/icons'
+import { LemonButton, LemonInputSelect, LemonSelect } from '@posthog/lemon-ui'
import { CodeSnippet } from 'lib/components/CodeSnippet'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
@@ -14,6 +14,7 @@ import { PropertyDefinition, PropertyDefinitionType, PropertyType } from '~/type
import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
import { HogFlowPropertyFilters } from 'products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters'
import { accountCustomPropertyDefinitionsLogic } from 'products/workflows/frontend/Workflows/hogflows/registry/triggers/accountCustomPropertyDefinitionsLogic'
+import { accountRelationshipDefinitionsLogic } from 'products/workflows/frontend/Workflows/hogflows/registry/triggers/accountRelationshipDefinitionsLogic'
import {
type EventTriggerConfig,
type TriggerFrequencyOption,
@@ -23,6 +24,7 @@ import { workflowLogic } from 'products/workflows/frontend/Workflows/workflowLog
const ACCOUNT_TAG_ADDED_EVENT = '$account_tag_added'
const ACCOUNT_CUSTOM_PROPERTY_CHANGED_EVENT = '$account_custom_property_changed'
+const ACCOUNT_RELATIONSHIP_CHANGED_EVENT = '$account_relationship_changed'
function getEventId(config: EventTriggerConfig): string | null {
const [firstEvent] = config.filters?.events ?? []
@@ -447,3 +449,151 @@ registerTriggerType({
frequencyOptions: accountCustomPropertyFrequencyOptions,
frequencyDescription: 'Limit how often each account can enter this workflow',
})
+
+const ONCE_PER_ACCOUNT_RELATIONSHIP_HASH =
+ "{concat(event.properties.account_id, '-', event.properties.relationship_name)}"
+const ONCE_PER_ACCOUNT_RELATIONSHIP_PER_DAY_HASH =
+ "{concat(event.properties.account_id, '-', event.properties.relationship_name, '-', formatDateTime(now(), '%Y-%m-%d'))}"
+
+export const accountRelationshipFrequencyOptions: TriggerFrequencyOption[] = [
+ { value: null, label: 'Every time the trigger fires' },
+ { value: ONCE_PER_ACCOUNT_RELATIONSHIP_HASH, label: 'Once per account and relationship' },
+ {
+ value: ONCE_PER_ACCOUNT_RELATIONSHIP_PER_DAY_HASH,
+ label: 'Once per account and relationship per calendar day',
+ fixedTtl: CALENDAR_DAY_TTL,
+ },
+]
+
+export function getSelectedRelationshipNames(config: EventTriggerConfig): string[] {
+ const nameProperty = (config.filters?.properties ?? []).find(
+ (property: any) => property?.key === 'relationship_name'
+ )
+ if (!nameProperty) {
+ return []
+ }
+ const values = Array.isArray(nameProperty.value) ? nameProperty.value : [nameProperty.value]
+ return values.filter((name: unknown): name is string => typeof name === 'string')
+}
+
+const RELATIONSHIP_CHANGE_TYPES = ['assigned', 'unassigned'] as const
+export type AccountRelationshipChangeType = (typeof RELATIONSHIP_CHANGE_TYPES)[number]
+
+function isAccountRelationshipChangeType(value: unknown): value is AccountRelationshipChangeType {
+ return typeof value === 'string' && RELATIONSHIP_CHANGE_TYPES.includes(value as AccountRelationshipChangeType)
+}
+
+export function getAccountRelationshipChangeType(config: EventTriggerConfig): AccountRelationshipChangeType | null {
+ const property = (config.filters?.properties ?? []).find((candidate: any) => candidate?.key === 'change_type')
+ const value = Array.isArray(property?.value) ? property.value[0] : property?.value
+ return isAccountRelationshipChangeType(value) ? value : null
+}
+
+export function accountRelationshipChangedFilters(
+ names: string[],
+ existingFilters: EventTriggerConfig['filters'] = {},
+ changeType: AccountRelationshipChangeType | null = getAccountRelationshipChangeType({
+ type: 'event',
+ filters: existingFilters,
+ })
+): EventTriggerConfig['filters'] {
+ return {
+ ...existingFilters,
+ events: [{ id: ACCOUNT_RELATIONSHIP_CHANGED_EVENT, type: 'events', name: 'Account relationship changed' }],
+ properties: [
+ ...(names.length > 0 ? [{ key: 'relationship_name', value: names, operator: 'exact', type: 'event' }] : []),
+ ...(changeType ? [{ key: 'change_type', value: changeType, operator: 'exact', type: 'event' }] : []),
+ ],
+ }
+}
+
+const RELATIONSHIP_TRIGGER_EVENT_TEMPLATES = [
+ '{event.properties.relationship_name}',
+ '{event.properties.change_type}',
+ '{event.properties.previous_user_id}',
+ '{event.properties.previous_user_email}',
+ '{event.properties.current_user_id}',
+ '{event.properties.current_user_email}',
+ '{event.properties.account_external_id}',
+ '{event.properties.account_name}',
+]
+
+function StepTriggerConfigurationAccountRelationshipChanged({ node }: { node: any }): JSX.Element {
+ const { setWorkflowActionConfig } = useActions(workflowLogic)
+ const { definitions, definitionsLoading } = useValues(accountRelationshipDefinitionsLogic)
+ const config = node.data.config as EventTriggerConfig
+ const selectedNames = getSelectedRelationshipNames(config)
+ const changeType = getAccountRelationshipChangeType(config)
+
+ return (
+ <div className="flex flex-col gap-2 w-full">
+ <p className="mb-0 text-sm text-muted-alt">
+ This trigger runs when an account relationship is assigned or unassigned. Leave empty to run for any
+ relationship.
+ </p>
+ <LemonField.Pure label="Relationships">
+ <LemonInputSelect
+ mode="multiple"
+ value={selectedNames}
+ loading={definitionsLoading}
+ placeholder="Any relationship"
+ options={definitions.map((definition) => ({ key: definition.name, label: definition.name }))}
+ onChange={(value) =>
+ setWorkflowActionConfig(node.data.id, {
+ type: 'event',
+ filters: accountRelationshipChangedFilters(value, config.filters),
+ })
+ }
+ data-attr="account-relationship-changed-trigger-relationships"
+ />
+ </LemonField.Pure>
+ <LemonField.Pure
+ label="Change type"
+ info="Limit this trigger to relationships that were assigned or unassigned."
+ >
+ <LemonSelect<AccountRelationshipChangeType | null>
+ value={changeType}
+ placeholder="Any change type"
+ allowClear
+ options={[
+ { label: 'Assigned', value: 'assigned' },
+ { label: 'Unassigned', value: 'unassigned' },
+ ]}
+ onChange={(value) =>
+ setWorkflowActionConfig(node.data.id, {
+ type: 'event',
+ filters: accountRelationshipChangedFilters(selectedNames, config.filters, value),
+ })
+ }
+ data-attr="account-relationship-change-type-filter"
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Available in steps" help="Reference the change from any step, filter, or condition">
+ <div className="flex flex-col gap-1">
+ {RELATIONSHIP_TRIGGER_EVENT_TEMPLATES.map((template) => (
+ <CodeSnippet key={template} compact thing="template">
+ {template}
+ </CodeSnippet>
+ ))}
+ </div>
+ </LemonField.Pure>
+ </div>
+ )
+}
+
+registerTriggerType({
+ value: 'account_relationship_changed',
+ label: 'Account relationship changed',
+ icon: <IconPerson />,
+ description: 'Trigger when an account relationship is assigned or unassigned',
+ group: 'Customer analytics',
+ featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,
+ matchConfig: (config) => config.type === 'event' && getEventId(config) === ACCOUNT_RELATIONSHIP_CHANGED_EVENT,
+ buildConfig: () => ({
+ type: 'event',
+ filters: accountRelationshipChangedFilters([]),
+ }),
+ ConfigComponent: StepTriggerConfigurationAccountRelationshipChanged,
+ frequencyOptions: accountRelationshipFrequencyOptions,
+ frequencyDescription: 'Limit how often each account can enter this workflow',
+})