:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): add account tag added trigger (#69502)
Arthur Moreira de Deusb5fc7df24ad8
diff --git a/COMPROMISES.md b/COMPROMISES.mdnew file mode 100644index 000000000000..c2bec5a859b0--- /dev/null+++ b/COMPROMISES.md@@ -0,0 +1,18 @@+# Compromises++Deliberate scope cuts on in-flight work, with the follow-up they imply.++## Account tag workflow trigger: no loop detection or throttling yet++Workflow-driven tag adds intentionally emit `$account_tag_added` so workflows can chain (e.g. MRR-threshold workflow tags the account → tag-triggered workflow emails the CSM). The flip side: two workflows whose actions add/remove each other's trigger tags (`tags_mode: set`/`remove` deletes rows, so re-adding fires again) can loop indefinitely, rate-limited only by workflow execution latency. Nothing detects or breaks such cycles today — the runtime's step cap is per-invocation and its dedup is per-event-uuid, and each loop iteration is a fresh event.++Events already carry the attribution a guard needs (`actor_type: "workflow"` + `workflow_id`, forwarded via the `X-PostHog-Hog-Flow-Id` header from the CDP worker). Follow-up options, in rough order of value:++1. **Static pre-save warning:** `HogFlow.trigger` and `HogFlow.actions` are JSON, so a per-team graph (edge A→B when A's `template-posthog-update-account` action writes tags intersecting B's trigger tags) can be cycle-checked on save/activate. Templated tag inputs (`{event.properties...}`) force conservative "any tag" edges, so this should warn, not block.+2. **Runtime backstop:** a chain-depth property incremented when a workflow-attributed event triggers another workflow (cap at N hops), or a throttle keyed on `(account, tag, workflow)`.++## Account tag events: emission blocks the request thread post-commit++`$account_tag_added` is emitted synchronously inside `transaction.on_commit` (`_schedule_account_tags_added` in `facade/api.py`): one batched `capture_batch_internal` HTTP call per tag write, after the group-type lookup (Redis-cached). Happy path is single-digit ms; the degraded case (capture-rs slow or down) blocks the request for up to the 2s timeout times retries. A Celery offload was tried and reverted (`b6c62469ee9`) as too much overhead for this volume — tag adds are low-frequency, and this matches how conversation ticket events already emit.++Revisit if account tagging becomes bulk/high-frequency (e.g. CRM syncs tagging thousands of accounts). Cheapest fixes then: cap the worst case (`timeout=1, max_attempts=1` — drops instead of retries during a blip), or prebuild the payload in-request and POST from a small module-level thread pool so no ORM touches the worker thread.diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.tsindex 1b8059baeaae..31afb8a0135f 100644--- a/nodejs/src/cdp/async-functions/customer_analytics.ts+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts@@ -1,6 +1,7 @@import { DateTime } from 'luxon'import { CyclotronInvocationQueueParametersFetchSchema } from '~/cdp/schema/cyclotron'+import { HogFlow } from '~/cdp/schema/hogflow'import { captureException } from '~/common/utils/posthog'import { Team } from '~/types'@@ -92,15 +93,22 @@ registerAsyncFunction('postHogUpdateAccount', {const team = await getTeamWithSecretToken(context, 'postHogUpdateAccount')+ const headers: Record<string, string> = {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${team.secret_api_token}`,+ }++ const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow+ if (hogFlow?.id) {+ headers['X-PostHog-Hog-Flow-Id'] = hogFlow.id+ }+result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({type: 'fetch',url: `${context.siteUrl}/api/customer_analytics/external/account`,method: 'PATCH',body: JSON.stringify({ external_id: externalId, ...updates }),- headers: {- 'Content-Type': 'application/json',- Authorization: `Bearer ${team.secret_api_token}`,- },+ headers,})},diff --git a/products/customer_analytics/backend/events.py b/products/customer_analytics/backend/events.pynew file mode 100644index 000000000000..7a769b1dcc25--- /dev/null+++ b/products/customer_analytics/backend/events.py@@ -0,0 +1,70 @@+"""+Emit PostHog analytics events for account changes.++These events power workflow triggers (e.g. "when the 'churn risk' tag is added+to an account, notify its CSM"). Events are sent to the customer's PostHog+project via their team's API token.+"""++from typing import Any++from posthog.api.capture import capture_batch_internal+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++EVENT_SOURCE = "customer_analytics_events"+++def _account_groups(account: Account) -> dict[str, str] | None:+ """Map the team's account group type to this account's external_id.++ The ``$groups`` entry lets downstream account workflow actions prefill+ ``external_id`` via ``{groups.<type>.id}`` with zero manual input.+ """+ if not account.external_id:+ return None+ group_type_index = account.team.customer_analytics_config.account_group_type_index+ if group_type_index is None:+ return None+ group_types = get_group_types_for_project(account.team.project_id, caller_tag="customer_analytics/events")+ for mapping in group_types:+ if mapping["group_type_index"] == group_type_index:+ return {mapping["group_type"]: account.external_id}+ return None+++def emit_account_tags_added(+ account: Account, tags: list[Tag], actor: User | None, workflow_id: str | None = None+) -> None:+ if not tags:+ return++ properties: dict[str, Any] = {+ "account_id": str(account.id),+ "account_external_id": account.external_id,+ "account_name": account.name,+ "actor_type": "user" if actor else ("workflow" if workflow_id else "system"),+ "actor_id": actor.id if actor else None,+ "actor_email": actor.email if actor else None,+ "workflow_id": workflow_id,+ }+ groups = _account_groups(account)+ if groups:+ properties["$groups"] = groups++ distinct_id = actor.distinct_id if actor and actor.distinct_id else f"account:{account.id}"+ capture_batch_internal(+ events=[+ {+ "event": "$account_tag_added",+ "distinct_id": distinct_id,+ "properties": {**properties, "tag": tag.name, "tag_id": str(tag.id)},+ }+ for tag in tags+ ],+ 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.pyindex f3ac4ea0c297..4a49d7a56389 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -27,7 +27,6 @@ from django.db.models import Prefetch, Qfrom celery import current_appfrom pydantic import ValidationError as PydanticValidationError-from posthog.api.tagged_item import set_tags_on_objectfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import OrganizationMembership, Tagfrom posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activity@@ -36,6 +35,7 @@ from posthog.models.tagged_item import TaggedItemfrom products.customer_analytics.backend.account_urls import build_account_deeplink as build_account_deeplinkfrom products.customer_analytics.backend.constants import ACCOUNT_ASSIGNMENT_ROLE_FIELDS+from products.customer_analytics.backend.events import emit_account_tags_addedfrom products.customer_analytics.backend.logic import (custom_property_values as _custom_property_values_logic,relationships as _relationships_logic,@@ -293,16 +293,20 @@ def get_external_account(team_id: int, external_id: str) -> contracts.ExternalAcreturn _to_external_account(account)-def _apply_external_tags(account: Account, tags: list[str], mode: str) -> None:+def _apply_external_tags(account: Account, tags: list[str], mode: str, workflow_id: str | None = None) -> None:normalized = list({tagify(t) for t in tags})if mode == "remove":account.tagged_items.filter(tag__name__in=normalized).delete()elif mode == "set":- set_tags_on_object(normalized, account)+ _set_tags(normalized, account, workflow_id=workflow_id)else:+ added_tags: list[Tag] = []for tag_name in normalized:tag, _ = Tag.objects.get_or_create(name=tag_name, team_id=account.team_id)- account.tagged_items.get_or_create(tag_id=tag.id)+ _, created = account.tagged_items.get_or_create(tag_id=tag.id)+ if created:+ added_tags.append(tag)+ _schedule_account_tags_added(account, added_tags, actor=None, workflow_id=workflow_id)def _apply_external_relationship_assignments(@@ -371,6 +375,7 @@ def update_external_account(relationship_assignments: dict[str, int | None],tags: list[str] | None,tags_mode: str,+ workflow_id: str | None = None,) -> contracts.ExternalAccountUpdateResult:"""Apply relationship assignments and tags to an account, transactionally, for theexternal API.@@ -397,7 +402,7 @@ def update_external_account(if error_result is not None:return error_resultif tags is not None:- _apply_external_tags(account, tags, tags_mode)+ _apply_external_tags(account, tags, tags_mode, workflow_id=workflow_id)except Exception as e:capture_exception(e, {"team_id": team_id, "external_id": external_id, "account_id": str(account.id)})return contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.UPDATE_FAILED)@@ -517,29 +522,53 @@ def _format_pydantic_errors(exc: PydanticValidationError) -> list[str]:return messages-def _set_tags(tags: list[str] | None, obj) -> None:- """Replace ``obj``'s tags, creating/deleting ``TaggedItem`` rows individually so each- change emits its own activity-log entry (the account activity stream depends on this).+def _set_tags(+ tags: list[str] | None, account: Account, actor: "User | None" = None, workflow_id: str | None = None+) -> None:+ """Replace the account's tags, creating/deleting ``TaggedItem`` rows individually so+ each change emits its own activity-log entry (the account activity stream depends on+ this).Mirrors ``posthog.api.tagged_item.set_tags_on_object`` + ``cleanup_orphan_tags`` butstays on pure-model imports so the facade keeps DRF off its import path. ``None`` means"tags not supplied" — leave them untouched (matches the serializer mixin).- Sets ``obj.prefetched_tags`` to the resulting rows so a freshly-written account renders- its new tags without re-reading a stale prefetch (the mixin did the same)."""+ Sets ``account.prefetched_tags`` to the resulting rows so a freshly-written account+ renders its new tags without re-reading a stale prefetch (the mixin did the same)."""if tags is None:returndeduped_tags = list({tagify(t) for t in tags})tagged_item_objects = []+ added_tags: list[Tag] = []for tag in deduped_tags:- tag_instance, _ = Tag.objects.get_or_create(name=tag, team_id=obj.team_id)- tagged_item_instance, _ = obj.tagged_items.get_or_create(tag_id=tag_instance.id)+ tag_instance, _ = Tag.objects.get_or_create(name=tag, team_id=account.team_id)+ tagged_item_instance, created = account.tagged_items.get_or_create(tag_id=tag_instance.id)tagged_item_instance.tag = tag_instancetagged_item_objects.append(tagged_item_instance)- for tagged_item in obj.tagged_items.exclude(tag__name__in=deduped_tags):+ if created:+ added_tags.append(tag_instance)+ for tagged_item in account.tagged_items.exclude(tag__name__in=deduped_tags):tagged_item.delete()- Tag.objects.filter(Q(team_id=obj.team_id) & Q(tagged_items__isnull=True)).delete()- obj.prefetched_tags = tagged_item_objects+ Tag.objects.filter(Q(team_id=account.team_id) & Q(tagged_items__isnull=True)).delete()+ account.prefetched_tags = tagged_item_objects # type: ignore[attr-defined]+ _schedule_account_tags_added(account, added_tags, actor, workflow_id=workflow_id)+++def _schedule_account_tags_added(+ account: Account, tags: list[Tag], actor: "User | None", workflow_id: str | None = None+) -> None:+ """Single emission point for $account_tag_added: post-commit, newly created rows only —+ so a workflow re-adding its own trigger tag fires nothing."""+ if not tags:+ return++ def emit() -> None:+ try:+ emit_account_tags_added(account, tags, actor, workflow_id=workflow_id)+ except Exception as e:+ capture_exception(e)++ transaction.on_commit(emit)def _log_activity_swallowing(@@ -1321,7 +1350,7 @@ def create_account_for_view(external_id=input.external_id,properties=input.properties,)- _set_tags(input.tags, account)+ _set_tags(input.tags, account, actor=user)if any(field in (account._properties or {}) for field in ACCOUNT_ASSIGNMENT_ROLE_FIELDS):_relationships_logic.sync_from_account_properties(account, created_by=user)except PydanticValidationError as exc:@@ -1367,7 +1396,7 @@ def update_account_for_view(try:with transaction.atomic():account = Account.objects.update_account(account, **update_kwargs)- _set_tags(input.tags, account)+ _set_tags(input.tags, account, actor=user)if input.properties_provided:_relationships_logic.sync_from_account_properties(account, created_by=user)except PydanticValidationError as exc:diff --git a/products/customer_analytics/backend/max_tools.py b/products/customer_analytics/backend/max_tools.pyindex 12a98451aed7..31f0a2338fd0 100644--- a/products/customer_analytics/backend/max_tools.py+++ b/products/customer_analytics/backend/max_tools.py@@ -8,12 +8,12 @@ from django.utils import timezonefrom asgiref.sync import sync_to_asyncfrom pydantic import BaseModel, ConfigDict, Field-from posthog.api.tagged_item import set_tags_on_objectfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import OrganizationMembershipfrom posthog.rbac.user_access_control import AccessControlLevelfrom posthog.scopes import APIScopeObject+from products.customer_analytics.backend.facade.api import _set_tagsfrom products.customer_analytics.backend.logic import relationships as relationships_logicfrom products.customer_analytics.backend.models import Account, AccountRelationshipDefinitionfrom products.notebooks.backend.models import Notebook, ResourceNotebook@@ -281,7 +281,7 @@ class UpsertAccountTool(MaxTool):properties=properties,)if action.tags is not None:- set_tags_on_object(action.tags, account)+ _set_tags(action.tags, account, actor=self._user)if action.relationships:self._apply_relationship_assignments(account, action.relationships)return account@@ -300,7 +300,7 @@ class UpsertAccountTool(MaxTool):with transaction.atomic():account = Account.objects.update_account(account, **update_kwargs)if action.tags is not None:- set_tags_on_object(action.tags, account)+ _set_tags(action.tags, account, actor=self._user)if action.relationships:self._apply_relationship_assignments(account, action.relationships)return accountdiff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.pyindex 77b7cd665537..fb7a504399b4 100644--- a/products/customer_analytics/backend/presentation/views/external.py+++ b/products/customer_analytics/backend/presentation/views/external.py@@ -10,6 +10,7 @@ transactional write, org-membership resolution, tag application, and exceptioncapture live behind ``facade.api``."""+import uuidimport hashlibfrom typing import Any@@ -70,6 +71,25 @@ def _customer_analytics_enabled(team: Team) -> bool:)+HOG_FLOW_ID_HEADER = "X-PostHog-Hog-Flow-Id"+++def _workflow_id_from_request(request: Request) -> str | None:+ """The originating HogFlow workflow id, when the request comes from a workflow step.++ The header is caller-supplied, so only a well-formed UUID is accepted; worst case is a+ token holder attributing a write to another workflow id within its own team.+ """+ hog_flow_id = request.headers.get(HOG_FLOW_ID_HEADER)+ if not hog_flow_id:+ return None+ try:+ uuid.UUID(hog_flow_id)+ except (ValueError, TypeError):+ return None+ return hog_flow_id++def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Response]:"""Extract Bearer token from Authorization header and validate against a team."""auth_header = request.headers.get("Authorization", "")@@ -230,6 +250,7 @@ class ExternalAccountView(APIView):relationship_assignments=data.get("relationships") or {},tags=data["tags"] if "tags" in data else None,tags_mode=data.get("tags_mode", "add"),+ workflow_id=_workflow_id_from_request(request),)if result.account is None:return _update_error_response(result)diff --git a/products/customer_analytics/backend/test/test_events.py b/products/customer_analytics/backend/test/test_events.pynew file mode 100644index 000000000000..f15140e35e2c--- /dev/null+++ b/products/customer_analytics/backend/test/test_events.py@@ -0,0 +1,114 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.db import transaction++from posthog.api.capture import CaptureInternalResult+from posthog.rbac.user_access_control import UserAccessControl+from posthog.test.persons import create_group_type_mapping++from products.customer_analytics.backend.facade import (+ api as facade,+ contracts,+)+from products.customer_analytics.backend.test.factories import create_account+++@patch("products.customer_analytics.backend.events.capture_batch_internal")+class TestAccountTagAddedEvent(BaseTest):+ def setUp(self):+ super().setUp()+ self.account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")++ def _add_tags(self, tags, tags_mode="add"):+ with self.captureOnCommitCallbacks(execute=True):+ result = facade.update_external_account(+ self.team.id, "acme-1", relationship_assignments={}, tags=tags, tags_mode=tags_mode+ )+ assert result.error is None++ def test_external_tag_add_emits_one_event_with_account_groups(self, mock_capture):+ 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()++ self._add_tags(["enterprise"])++ 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_tag_added"+ assert event["distinct_id"] == f"account:{self.account.id}"+ properties = event["properties"]+ assert properties["tag"] == "enterprise"+ 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"] == "system"+ assert properties["$groups"] == {"account": "acme-1"}++ def test_re_adding_existing_tag_emits_nothing(self, mock_capture):+ self._add_tags(["enterprise"])+ mock_capture.reset_mock()++ self._add_tags(["enterprise"])++ mock_capture.assert_not_called()++ def test_set_mode_emits_only_newly_added_tags(self, mock_capture):+ self._add_tags(["old"])+ mock_capture.reset_mock()++ self._add_tags(["old", "new"], tags_mode="set")++ mock_capture.assert_called_once()+ (event,) = mock_capture.call_args.kwargs["events"]+ assert event["properties"]["tag"] == "new"++ def test_view_update_emits_with_user_actor(self, mock_capture):+ with self.captureOnCommitCallbacks(execute=True):+ facade.update_account_for_view(+ team_id=self.team.id,+ account_id=str(self.account.id),+ input=contracts.UpdateAccountInput(tags=["enterprise"]),+ user_access_control=UserAccessControl(user=self.user, team=self.team),+ required_level="editor",+ organization_id=self.organization.id,+ user=self.user,+ was_impersonated=False,+ )++ mock_capture.assert_called_once()+ (event,) = mock_capture.call_args.kwargs["events"]+ assert event["properties"]["actor_type"] == "user"+ assert event["properties"]["actor_email"] == self.user.email++ def test_event_without_account_group_type_has_no_groups(self, mock_capture):+ self._add_tags(["enterprise"])++ mock_capture.assert_called_once()+ (event,) = mock_capture.call_args.kwargs["events"]+ assert "$groups" not in event["properties"]++ def test_no_event_when_transaction_rolls_back(self, mock_capture):+ with self.captureOnCommitCallbacks(execute=True):+ try:+ with transaction.atomic():+ facade.update_external_account(+ self.team.id, "acme-1", relationship_assignments={}, tags=["enterprise"], tags_mode="add"+ )+ 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.facade.api.capture_exception") as mock_capture_exception:+ self._add_tags(["enterprise"])++ mock_capture_exception.assert_called_once()diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.pyindex 54c749c0889e..0f246c8f8cb2 100644--- a/products/customer_analytics/backend/test/test_external.py+++ b/products/customer_analytics/backend/test/test_external.py@@ -221,6 +221,22 @@ class TestExternalAccountAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["tags"], ["enterprise"])+ @patch("products.customer_analytics.backend.events.capture_batch_internal")+ def test_patch_with_workflow_header_attributes_tag_added_event(self, mock_capture):+ workflow_id = str(uuid4())+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.patch(+ self.url,+ data={"external_id": "acme-1", "tags": ["vip"]},+ format="json",+ HTTP_X_POSTHOG_HOG_FLOW_ID=workflow_id,+ **self._auth_headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ (event,) = mock_capture.call_args.kwargs["events"]+ self.assertEqual(event["properties"]["actor_type"], "workflow")+ self.assertEqual(event["properties"]["workflow_id"], workflow_id)+def test_patch_does_not_update_other_team_account(self):other_team = Team.objects.create(organization=self.organization, name="Other")other_team.secret_api_token = generate_random_token_secret()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.tsnew file mode 100644index 000000000000..8ae8a1598de3--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.test.ts@@ -0,0 +1,46 @@+import { accountTagAddedFilters, getSelectedTags } from './customer_analytics'+import { EventTriggerConfig, getRegisteredTriggerTypes } from './triggerTypeRegistry'++describe('customer analytics triggers', () => {+ const getTriggerType = (): ReturnType<typeof getRegisteredTriggerTypes>[number] => {+ const triggerType = getRegisteredTriggerTypes().find((t) => t.value === 'account_tag_added')+ if (!triggerType) {+ throw new Error('account_tag_added trigger type not registered')+ }+ return triggerType+ }++ it('buildConfig produces a config recognized by matchConfig', () => {+ const triggerType = getTriggerType()+ expect(triggerType.matchConfig!(triggerType.buildConfig())).toBe(true)+ })++ it.each([+ {+ name: 'array value',+ properties: [{ key: 'tag', value: ['vip', 'enterprise'], operator: 'exact', type: 'event' }],+ expected: ['vip', 'enterprise'],+ },+ {+ name: 'scalar value',+ properties: [{ key: 'tag', value: 'vip', operator: 'exact', type: 'event' }],+ expected: ['vip'],+ },+ { name: 'no tag property', properties: [], expected: [] },+ {+ name: 'non-string values',+ properties: [{ key: 'tag', value: [1, null], operator: 'exact', type: 'event' }],+ expected: [],+ },+ ])('getSelectedTags handles $name', ({ properties, expected }) => {+ const config: EventTriggerConfig = { type: 'event', filters: { properties } }+ expect(getSelectedTags(config)).toEqual(expected)+ })++ it('omits the tag property filter when no tags are selected', () => {+ expect(accountTagAddedFilters([]).properties).toEqual([])+ expect(accountTagAddedFilters(['vip']).properties).toEqual([+ { key: 'tag', value: ['vip'], operator: 'exact', type: 'event' },+ ])+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.tsxnew file mode 100644index 000000000000..6b0155f2e205--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.tsx@@ -0,0 +1,85 @@+import { useActions, useValues } from 'kea'++import { IconBolt } from '@posthog/icons'+import { LemonInputSelect } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { LemonField } from 'lib/lemon-ui/LemonField'++import { tagsModel } from '~/models/tagsModel'++import {+ type EventTriggerConfig,+ registerTriggerType,+} from 'products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry'+import { workflowLogic } from 'products/workflows/frontend/Workflows/workflowLogic'++const ACCOUNT_TAG_ADDED_EVENT = '$account_tag_added'++function getEventId(config: EventTriggerConfig): string | null {+ const [firstEvent] = config.filters?.events ?? []+ return typeof firstEvent?.id === 'string' ? firstEvent.id : null+}++export function getSelectedTags(config: EventTriggerConfig): string[] {+ const tagProperty = (config.filters?.properties ?? []).find((property: any) => property?.key === 'tag')+ if (!tagProperty) {+ return []+ }+ const values = Array.isArray(tagProperty.value) ? tagProperty.value : [tagProperty.value]+ return values.filter((tag: unknown): tag is string => typeof tag === 'string')+}++export function accountTagAddedFilters(tags: string[]): EventTriggerConfig['filters'] {+ return {+ events: [{ id: ACCOUNT_TAG_ADDED_EVENT, type: 'events', name: 'Account tag added' }],+ properties: tags.length > 0 ? [{ key: 'tag', value: tags, operator: 'exact', type: 'event' }] : [],+ }+}++function StepTriggerConfigurationAccountTagAdded({ node }: { node: any }): JSX.Element {+ const { setWorkflowActionConfig } = useActions(workflowLogic)+ const { tags, tagsLoading } = useValues(tagsModel)+ const config = node.data.config as EventTriggerConfig+ const selectedTags = getSelectedTags(config)++ return (+ <div className="flex flex-col gap-2 w-full">+ <p className="mb-0 text-sm text-muted-alt">+ This trigger runs when a tag is added to an account. Leave empty to run for any tag.+ </p>+ <LemonField.Pure label="Tags">+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={selectedTags}+ loading={tagsLoading}+ placeholder="Any tag"+ options={tags.map((tag: string) => ({ key: tag, label: tag }))}+ onChange={(value) =>+ setWorkflowActionConfig(node.data.id, {+ type: 'event',+ filters: accountTagAddedFilters(value),+ })+ }+ data-attr="account-tag-added-trigger-tags"+ />+ </LemonField.Pure>+ </div>+ )+}++registerTriggerType({+ value: 'account_tag_added',+ label: 'Account tag added',+ icon: <IconBolt />,+ description: 'Trigger when a tag is added to an account',+ group: 'Customer analytics',+ featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,+ matchConfig: (config) => config.type === 'event' && getEventId(config) === ACCOUNT_TAG_ADDED_EVENT,+ buildConfig: () => ({+ type: 'event',+ filters: accountTagAddedFilters([]),+ }),+ ConfigComponent: StepTriggerConfigurationAccountTagAdded,+})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.tsindex 451eb63cce82..f41587592d85 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.ts@@ -1,3 +1,4 @@import './conversations'+import './customer_analytics'import './data_warehouse_table'import './surveys'