: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 Update account customer analytics workflow action (#64371)
Arthur Moreira de Deus9197412bbb5f
diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.tsindex 3e0703f0f4f9..c3c8f2563d48 100644--- a/nodejs/src/cdp/async-functions/customer_analytics.ts+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts@@ -65,3 +65,52 @@ registerAsyncFunction('postHogGetAccount', {}},})++registerAsyncFunction('postHogUpdateAccount', {+ execute: async (args, context, result) => {+ const [opts] = args as [Record<string, any> | undefined]+ const externalId = opts?.external_id+ const updates = opts?.updates || {}++ if (!externalId || typeof externalId !== 'string') {+ throw new Error("[HogFunction] - postHogUpdateAccount call missing 'external_id' property")+ }++ const team = await context.teamManager.getTeam(context.invocation.teamId)+ if (!team) {+ throw new Error(`Team ${context.invocation.teamId} not found`)+ }+ if (!team.secret_api_token) {+ throw new Error(`Team ${context.invocation.teamId} has no secret API token configured`)+ }++ 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}`,+ },+ })+ },++ mock: (args, logs) => {+ logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: `Async function 'postHogUpdateAccount' was mocked with arguments:`,+ })+ logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: `postHogUpdateAccount(${JSON.stringify(args[0], null, 2)})`,+ })++ return {+ status: 200,+ body: { ok: true },+ }+ },+})diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex 2dedc2009074..add383481843 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -995,6 +995,42 @@ describe('Hog Executor', () => {const result = await executor.execute(createAccountInvocation())expect(result.error).toContain('has no secret API token configured')})++ it('postHogUpdateAccount queues a PATCH with external_id merged into the body', async () => {+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ secret_api_token: 'test-secret-token',+ } as any)++ mockExecHogForAsyncFunction('postHogUpdateAccount', [+ { external_id: 'acme-1', updates: { tags: ['enterprise'], tags_mode: 'add' } },+ ])++ const result = await executor.execute(createAccountInvocation())++ expect(result.invocation.queueParameters).toEqual({+ type: 'fetch',+ url: `${hub.SITE_URL}/api/customer_analytics/external/account`,+ method: 'PATCH',+ body: JSON.stringify({ external_id: 'acme-1', tags: ['enterprise'], tags_mode: 'add' }),+ headers: {+ 'Content-Type': 'application/json',+ Authorization: 'Bearer test-secret-token',+ },+ })+ })++ it('postHogUpdateAccount errors when external_id is missing', async () => {+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ secret_api_token: 'test-secret-token',+ } as any)++ mockExecHogForAsyncFunction('postHogUpdateAccount', [{ updates: { tags: ['enterprise'] } }])++ const result = await executor.execute(createAccountInvocation())+ expect(result.error).toContain("missing 'external_id'")+ })})describe('produceToWarehouseWebhooks', () => {diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.tsnew file mode 100644index 000000000000..e8738c06adb4--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-update-account.template.ts@@ -0,0 +1,113 @@+import { HogFunctionTemplate } from '~/cdp/types'++export const template: HogFunctionTemplate = {+ free: true,+ status: 'hidden',+ type: 'destination',+ id: 'template-posthog-update-account',+ name: 'Update account',+ description: 'Assign role contacts (CSM, account executive, account owner) or tag a Customer analytics account.',+ icon_url: '/static/posthog-icon.svg',+ category: ['Custom'],+ code_language: 'hog',+ code: `+if (empty(inputs.external_id)) {+ throw Error('Account external ID is required')+}++let updates := {}++if (not empty(inputs.csm)) {+ updates.csm := inputs.csm+}++if (not empty(inputs.account_executive)) {+ updates.account_executive := inputs.account_executive+}++if (not empty(inputs.account_owner)) {+ updates.account_owner := inputs.account_owner+}++if (not empty(inputs.tags)) {+ updates.tags := inputs.tags+ updates.tags_mode := (not empty(inputs.tags_mode)) ? inputs.tags_mode : 'add'+}++let response := postHogUpdateAccount({+ 'external_id': inputs.external_id,+ 'updates': updates+})++if (response.status == 404) {+ throw Error(f'Account not found: {inputs.external_id}')+}++if (response.status >= 400) {+ throw Error(f'Failed to update account: {response.status}')+}++return response.body+`,+ inputs_schema: [+ {+ key: 'external_id',+ type: 'string',+ label: 'Account external ID',+ secret: false,+ required: true,+ description:+ 'The external ID of the account to update — the group key the account is linked to. Available from trigger event or group properties.',+ },+ {+ key: 'csm',+ type: 'posthog_assignee',+ label: 'Customer success manager',+ secret: false,+ required: false,+ description:+ 'Assign a CSM to the account. Only users can be assigned, not roles. Leave empty to keep current.',+ },+ {+ key: 'account_executive',+ type: 'posthog_assignee',+ label: 'Account executive',+ secret: false,+ required: false,+ description:+ 'Assign an account executive to the account. Only users can be assigned, not roles. Leave empty to keep current.',+ },+ {+ key: 'account_owner',+ type: 'posthog_assignee',+ label: 'Account owner',+ secret: false,+ required: false,+ description:+ 'Assign an account owner to the account. Only users can be assigned, not roles. Leave empty to keep current.',+ },+ {+ key: 'tags',+ type: 'posthog_ticket_tags',+ label: 'Tags',+ secret: false,+ required: false,+ description: 'Tags to apply to the account. Leave empty to keep current tags.',+ },+ {+ key: 'tags_mode',+ type: 'choice',+ label: 'Tag mode',+ secret: false,+ required: false,+ default: 'add',+ choices: [+ { label: 'Add to existing tags', value: 'add' },+ { label: 'Replace all tags', value: 'set' },+ { label: 'Remove these tags', value: 'remove' },+ ],+ description:+ 'How the tags above are applied. Add (default) is safe when multiple workflows tag the same account.',+ },+ ],+}diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.tsindex ba9132bd5ea5..70a27beda4bb 100644--- a/nodejs/src/cdp/templates/index.ts+++ b/nodejs/src/cdp/templates/index.ts@@ -23,6 +23,7 @@ import { template as posthogUpdatePersonPropertiesTemplate } from './_destinatioimport { template as posthogGetTicketTemplate } from './_destinations/posthog_conversations/posthog-get-ticket.template'import { template as posthogUpdateTicketTemplate } from './_destinations/posthog_conversations/posthog-update-ticket.template'import { template as posthogGetAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-get-account.template'+import { template as posthogUpdateAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-update-account.template'import { template as posthogSetHogflowVariableTemplate } from './_destinations/posthog_workflows/posthog-set-variable.template'import { template as redditAdsTemplate } from './_destinations/reddit_ads/reddit.template'import { template as snapchatAdsTemplate } from './_destinations/snapchat_ads/snapchat.template'@@ -74,6 +75,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [posthogGetTicketTemplate,posthogUpdateTicketTemplate,posthogGetAccountTemplate,+ posthogUpdateAccountTemplate,hubspotCompanyTemplate,accoilTemplate,klimeTemplate,diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.pyindex bbf62c59ad4d..ead96ef2eb1a 100644--- a/posthog/cdp/validation.py+++ b/posthog/cdp/validation.py@@ -38,6 +38,7 @@ def register_supported_function(name: str) -> None:register_supported_function("postHogGetTicket")register_supported_function("postHogUpdateTicket")register_supported_function("postHogGetAccount")+register_supported_function("postHogUpdateAccount")# Globals that the realtime transformer actually populates at runtime.diff --git a/products/customer_analytics/backend/api/external.py b/products/customer_analytics/backend/api/external.pyindex e70245a261fb..51b45c66bd46 100644--- a/products/customer_analytics/backend/api/external.py+++ b/products/customer_analytics/backend/api/external.py@@ -8,21 +8,28 @@ via the team secret API token passed as a Bearer token in the Authorization headimport hashlibfrom typing import Any+from django.db import transactionfrom django.db.models import Qimport structlogimport posthoganalytics-from rest_framework import status+from rest_framework import serializers, statusfrom rest_framework.permissions import AllowAnyfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.throttling import SimpleRateThrottlefrom rest_framework.views import APIView-from posthog.models import Team+from posthog.api.tagged_item import set_tags_on_object+from posthog.exceptions_capture import capture_exception+from posthog.models import OrganizationMembership, Tag, Team+from posthog.models.tag import tagifyfrom products.customer_analytics.backend.constants import CUSTOMER_ANALYTICS_CSP_FLAGfrom products.customer_analytics.backend.models import Account+from products.customer_analytics.backend.models.account import AccountProperties++ASSIGNMENT_ROLE_FIELDS = ("csm", "account_executive", "account_owner")logger = structlog.get_logger(__name__)@@ -91,6 +98,7 @@ def _serialize_account(account: Account) -> dict[str, Any]:"external_id": account.external_id,"name": account.name,"properties": account.properties.model_dump(mode="json"),+ "tags": sorted(account.tagged_items.values_list("tag__name", flat=True)),}@@ -101,9 +109,54 @@ def _get_account_by_external_id(team: Team, external_id: str) -> Account | None:return None+class ExternalAccountUpdateSerializer(serializers.Serializer):+ external_id = serializers.CharField(max_length=400)+ # Each role accepts a `posthog_assignee` value `{type, id}`, `null` to clear, or is+ # omitted to leave unchanged. Roles (RBAC) are rejected — accounts assign users only.+ # `validate` normalizes a provided assignment down to the user id; the view resolves+ # the email against an org membership so the stored `{id, email}` is always trusted.+ csm = serializers.JSONField(required=False, allow_null=True)+ account_executive = serializers.JSONField(required=False, allow_null=True)+ account_owner = serializers.JSONField(required=False, allow_null=True)+ tags = serializers.ListField(child=serializers.CharField(max_length=200), required=False, max_length=100)+ tags_mode = serializers.ChoiceField(choices=["add", "set", "remove"], required=False, default="add")++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ for field in ASSIGNMENT_ROLE_FIELDS:+ if field in attrs and attrs[field] is not None:+ attrs[field] = self._normalize_assignee(field, attrs[field])+ return attrs++ def _normalize_assignee(self, field: str, value: Any) -> int:+ if not isinstance(value, dict):+ raise serializers.ValidationError({field: "Must be an assignee object or null"})+ if value.get("type") != "user":+ raise serializers.ValidationError({field: "Accounts can only be assigned to users, not roles"})+ raw_id = value.get("id")+ if not isinstance(raw_id, (int, str)):+ raise serializers.ValidationError({field: "Assignee id must be a user id"})+ try:+ return int(raw_id)+ except (TypeError, ValueError):+ raise serializers.ValidationError({field: "Assignee id must be a user id"})+++def _apply_tags(account: Account, tags: list[str], mode: str) -> 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)+ else:+ 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)++class ExternalAccountView(APIView):"""GET /api/customer_analytics/external/account?external_id=<external_id> — Fetch account data+ PATCH /api/customer_analytics/external/account — Update an account's role contacts and tagsAuthenticated via Bearer token (team secret_api_token) in Authorization header."""@@ -128,3 +181,75 @@ class ExternalAccountView(APIView):return Response({"error": "Account not found"}, status=status.HTTP_404_NOT_FOUND)return Response(_serialize_account(account))++ def patch(self, request: Request) -> Response:+ team, error = _authenticate_team(request)+ if error:+ return error++ assert team is not None++ serializer = ExternalAccountUpdateSerializer(data=request.data)+ if not serializer.is_valid():+ return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)+ data = serializer.validated_data++ external_id = data["external_id"].strip()+ if not external_id:+ return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)++ account = _get_account_by_external_id(team, external_id)+ if account is None:+ return Response({"error": "Account not found"}, status=status.HTTP_404_NOT_FOUND)++ # Role assignments and tags must be all-or-nothing — a tag failure must not leave the+ # role-contact changes committed. Validation errors return before any write happens.+ try:+ with transaction.atomic():+ error = self._apply_role_assignments(team, account, data)+ if error:+ return error+ if "tags" in data:+ _apply_tags(account, data["tags"], data.get("tags_mode", "add"))+ except Exception as e:+ capture_exception(e, {"account_id": str(account.id)})+ return Response({"error": "Failed to update account"}, status=status.HTTP_400_BAD_REQUEST)++ account.refresh_from_db()+ return Response(_serialize_account(account))++ def _apply_role_assignments(self, team: Team, account: Account, data: dict[str, Any]) -> Response | None:+ properties = dict(account._properties or {})+ changed = False++ for field in ASSIGNMENT_ROLE_FIELDS:+ if field not in data:+ continue+ user_id = data[field]+ if user_id is None:+ properties[field] = None+ else:+ membership = (+ OrganizationMembership.objects.select_related("user")+ .filter(organization_id=team.organization_id, user_id=user_id)+ .first()+ )+ if membership is None:+ return Response(+ {"error": f"{field}: user is not a member of this organization"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ properties[field] = {"id": membership.user.id, "email": membership.user.email}+ changed = True++ if not changed:+ return None++ try:+ account.properties = AccountProperties.model_validate(properties)+ except Exception as e:+ capture_exception(e, {"account_id": str(account.id)})+ return Response({"error": "Invalid account properties"}, status=status.HTTP_400_BAD_REQUEST)++ account.save(update_fields=["_properties", "updated_at"])+ return Nonediff --git a/products/customer_analytics/backend/api/test_external.py b/products/customer_analytics/backend/api/test_external.pyindex f3a6058bc966..63ac9fd9ec6c 100644--- a/products/customer_analytics/backend/api/test_external.py+++ b/products/customer_analytics/backend/api/test_external.py@@ -5,7 +5,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom rest_framework.test import APIClient-from posthog.models import Team+from posthog.models import Organization, Team, Userfrom posthog.models.utils import generate_random_token_secretfrom products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties@@ -34,6 +34,9 @@ class TestExternalAccountAPI(APIBaseTest):def _get(self, external_id="acme-1", token=None):return self.client.get(self.url, data={"external_id": external_id}, **self._auth_headers(token))+ def _patch(self, payload, token=None):+ return self.client.patch(self.url, data=payload, format="json", **self._auth_headers(token))+# -- Authentication ---------------------------------------------------def test_get_requires_auth(self):@@ -108,3 +111,106 @@ class TestExternalAccountAPI(APIBaseTest):response = self._get(token=other_team.secret_api_token)self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ # -- PATCH account ----------------------------------------------------++ def test_patch_requires_auth(self):+ response = self.client.patch(self.url, data={"external_id": "acme-1"}, format="json")+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_patch_requires_external_id(self):+ response = self._patch({"tags": ["enterprise"]})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_patch_account_not_found(self):+ response = self._patch({"external_id": "does-not-exist", "tags": ["enterprise"]})+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_patch_assigns_role_and_resolves_email(self):+ response = self._patch({"external_id": "acme-1", "csm": {"type": "user", "id": self.user.id}})+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ self.account.refresh_from_db()+ csm = self.account.properties.csm+ assert csm is not None+ self.assertEqual(csm.id, self.user.id)+ self.assertEqual(csm.email, self.user.email)++ def test_patch_clears_role_with_null(self):+ self.account.properties = AccountProperties(csm=AccountAssignment(id=self.user.id, email=self.user.email))+ self.account.save(update_fields=["_properties"])++ response = self._patch({"external_id": "acme-1", "csm": None})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.account.refresh_from_db()+ self.assertIsNone(self.account.properties.csm)++ def test_patch_preserves_unmentioned_properties(self):+ self.account.properties = AccountProperties(stripe_customer_id="cus_123")+ self.account.save(update_fields=["_properties"])++ response = self._patch({"external_id": "acme-1", "csm": {"type": "user", "id": self.user.id}})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.account.refresh_from_db()+ csm = self.account.properties.csm+ assert csm is not None+ self.assertEqual(self.account.properties.stripe_customer_id, "cus_123")+ self.assertEqual(csm.id, self.user.id)++ def test_patch_rejects_role_assignee(self):+ response = self._patch({"external_id": "acme-1", "csm": {"type": "role", "id": "some-role-uuid"}})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_patch_rejects_non_member_user(self):+ other_org = Organization.objects.create(name="Outsiders")+ outsider = User.objects.create_and_join(other_org, "[email protected]", None)+ response = self._patch({"external_id": "acme-1", "csm": {"type": "user", "id": outsider.id}})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.account.refresh_from_db()+ self.assertIsNone(self.account.properties.csm)++ def test_patch_adds_tags_by_default(self):+ self._patch({"external_id": "acme-1", "tags": ["enterprise"]})+ response = self._patch({"external_id": "acme-1", "tags": ["priority"]})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["tags"], ["enterprise", "priority"])++ def test_patch_sets_tags_replacing_existing(self):+ self._patch({"external_id": "acme-1", "tags": ["enterprise"]})+ response = self._patch({"external_id": "acme-1", "tags": ["priority"], "tags_mode": "set"})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["tags"], ["priority"])++ def test_patch_removes_tags(self):+ self._patch({"external_id": "acme-1", "tags": ["enterprise", "priority"]})+ response = self._patch({"external_id": "acme-1", "tags": ["priority"], "tags_mode": "remove"})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["tags"], ["enterprise"])++ 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()+ other_team.save(update_fields=["secret_api_token"])++ response = self._patch({"external_id": "acme-1", "tags": ["enterprise"]}, token=other_team.secret_api_token)+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_patch_rolls_back_role_assignment_when_tags_fail(self):+ with patch(+ "products.customer_analytics.backend.api.external._apply_tags",+ side_effect=Exception("boom"),+ ):+ response = self._patch(+ {"external_id": "acme-1", "csm": {"type": "user", "id": self.user.id}, "tags": ["enterprise"]}+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.account.refresh_from_db()+ self.assertIsNone(self.account.properties.csm)++ def test_patch_cannot_change_external_id_or_name(self):+ # external_id only identifies the account; renaming/rebinding is not exposed to workflows.+ response = self._patch({"external_id": "acme-1", "name": "Renamed", "new_external_id": "acme-2", "csm": None})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.account.refresh_from_db()+ self.assertEqual(self.account.external_id, "acme-1")+ self.assertEqual(self.account.name, "Acme Corp")diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.tsindex 93c8353feecb..49b9a219df99 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts@@ -29,4 +29,12 @@ describe('customer analytics action registry', () => {const node = getCategory().nodes.find((n) => n.name === 'Get account')expect(node?.output_variable).toEqual({ key: 'account', result_path: null })})++ it('wires the Update account node to its hog function template', () => {+ const node = getCategory().nodes.find((n) => n.name === 'Update account')+ expect(node).toMatchObject({+ type: 'function',+ config: { template_id: 'template-posthog-update-account' },+ })+ })})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.tsindex 20a2bf3cb79b..360843fc27cc 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts@@ -15,5 +15,12 @@ registerActionNodeCategory({// names, so it can't flatten an account. Store the whole object in one variable instead.output_variable: { key: 'account', result_path: null },},+ {+ type: 'function',+ name: 'Update account',+ description: 'Assign role contacts or tag a Customer analytics account.',+ config: { template_id: 'template-posthog-update-account', inputs: {} },+ output_variable: { key: 'account', result_path: null },+ },],})