: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(customer-analytics): add create-account workflow node (#74706)
Arthur Moreira de Deus2121a54a1f82
diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.tsindex 638d5b447ac3..806183d3d038 100644--- a/nodejs/src/cdp/async-functions/customer_analytics.ts+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts@@ -184,3 +184,60 @@ registerAsyncFunction('postHogSetAccountProperties', {}},})++registerAsyncFunction('postHogCreateAccount', {+ execute: async (args, context, result) => {+ const [opts] = args as [Record<string, any> | undefined]+ const externalId = opts?.external_id++ if (!externalId || typeof externalId !== 'string') {+ throw new Error("[HogFunction] - postHogCreateAccount call missing 'external_id' property")+ }++ const team = await getTeamWithSecretToken(context, 'postHogCreateAccount')++ 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: 'POST',+ body: JSON.stringify({ external_id: externalId }),+ headers,+ })+ },++ mock: (args, logs) => {+ logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: `Async function 'postHogCreateAccount' was mocked with arguments:`,+ })+ logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: `postHogCreateAccount(${JSON.stringify(args[0], null, 2)})`,+ })++ return {+ status: 201,+ body: {+ id: 'mock-account-id',+ external_id: args[0]?.external_id ?? 'mock-external-id',+ name: 'Mock Account',+ properties: {},+ tags: [],+ relationships: {},+ custom_properties: {},+ },+ }+ },+})diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.tsindex 76ff30697689..36022060795a 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-accounts.template.test.ts@@ -1,6 +1,7 @@import { parseJSON } from '~/common/utils/json-parse'import { TemplateTester } from '../../test/test-helpers'+import { template as createAccountTemplate } from './posthog-create-account.template'import { template as getAccountTemplate } from './posthog-get-account.template'import { template as tagAccountTemplate } from './posthog-tag-account.template'import { template as updateAccountPropertyTemplate } from './posthog-update-account-property.template'@@ -18,6 +19,14 @@ describe('posthog customer analytics account templates', () => {failurePrefix: 'Failed to fetch account (400):',successLog: 'Fetched account acme-1',},+ {+ name: 'create account',+ template: createAccountTemplate,+ inputs: { external_id: 'acme-1' },+ failurePrefix: 'Failed to create account (400):',+ // A 200 means the account already existed — creation is a no-op.+ successLog: 'Account acme-1 already exists — skipped creation',+ },{name: 'update account',template: updateAccountTemplate,@@ -107,6 +116,40 @@ describe('posthog customer analytics account templates', () => {})})+ describe('create account', () => {+ const tester = new TemplateTester(createAccountTemplate)++ beforeEach(async () => {+ await tester.beforeEach()+ })++ it('logs the created line on 201', async () => {+ let response = await tester.invoke({ external_id: 'acme-1' })++ const body = parseJSON((response.invocation.queueParameters as any).body)+ expect(body).toEqual({ external_id: 'acme-1' })++ response = await tester.invokeFetchResponse(response.invocation, {+ status: 201,+ body: { id: 'account-id', external_id: 'acme-1' },+ })++ expect(response.error).toBeUndefined()+ expect(response.finished).toBe(true)+ expect(response.logs.filter((log) => log.level === 'info').map((log) => log.message)).toContain(+ 'Created account acme-1'+ )+ })++ it('fails with a descriptive error when the event has no group of the account group type', async () => {+ const response = await tester.invoke({ external_id: '' })++ expect(response.error).toEqual(+ 'Account external ID is required — the triggering event has no group of the configured account group type'+ )+ })+ })+describe('update account relationships queued fetch body', () => {const tester = new TemplateTester(updateAccountRelationshipsTemplate)diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-account.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-account.template.tsnew file mode 100644index 000000000000..51edc290da5b--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-create-account.template.ts@@ -0,0 +1,49 @@+import { HogFunctionTemplate } from '~/cdp/types'++import { hogApiErrorMessageFn } from './api-error'++export const template: HogFunctionTemplate = {+ free: true,+ status: 'hidden',+ type: 'destination',+ id: 'template-posthog-create-account',+ name: 'Create account',+ description:+ 'Create a Customer analytics account for the triggering event’s group, if one does not exist. The account name comes from the group’s name property.',+ icon_url: '/static/posthog-icon.svg',+ category: ['Custom'],+ code_language: 'hog',+ code: `+${hogApiErrorMessageFn}++if (empty(inputs.external_id)) {+ throw Error('Account external ID is required — the triggering event has no group of the configured account group type')+}++let response := postHogCreateAccount({+ 'external_id': inputs.external_id+})++if (response.status >= 400) {+ throw Error(f'Failed to create account ({response.status}): {apiErrorMessage(response)}')+}++if (response.status == 200) {+ print(f'Account {inputs.external_id} already exists — skipped creation')+} else {+ print(f'Created account {inputs.external_id}')+}+return response.body+`,+ inputs_schema: [+ {+ key: 'external_id',+ type: 'string',+ label: 'Account external ID',+ secret: false,+ required: true,+ description:+ 'The external ID for the account — the group key the account is linked to. Defaults to the triggering event’s group of the configured account group type.',+ },+ ],+}diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.tsindex f8b59806d8f7..95fa7700eb8f 100644--- a/nodejs/src/cdp/templates/index.ts+++ b/nodejs/src/cdp/templates/index.ts@@ -23,6 +23,7 @@ import { template as posthogGroupIdentifyTemplate } from './_destinations/posthoimport { template as posthogUpdatePersonPropertiesTemplate } from './_destinations/posthog_capture/posthog-update-person-properties.template'import { 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 posthogCreateAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-create-account.template'import { template as posthogGetAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-get-account.template'import { template as posthogTagAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-tag-account.template'import { template as posthogUpdateAccountPropertyTemplate } from './_destinations/posthog_customer_analytics/posthog-update-account-property.template'@@ -79,6 +80,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [posthogSetHogflowVariableTemplate,posthogGetTicketTemplate,posthogUpdateTicketTemplate,+ posthogCreateAccountTemplate,posthogGetAccountTemplate,posthogTagAccountTemplate,posthogUpdateAccountRelationshipsTemplate,diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 752224d6a12c..8c986d0bfbeb 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -33,7 +33,8 @@ from pydantic import ValidationError as PydanticValidationErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Integration, OrganizationMembership, Tag-from posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activity+from posthog.models.activity_logging.activity_log import AuditableScope, Detail, Trigger, changes_between, log_activity+from posthog.models.group.util import get_group_by_keyfrom posthog.models.tag import tagifyfrom posthog.models.tagged_item import TaggedItemfrom posthog.models.team import Team@@ -385,6 +386,39 @@ def get_external_account(team_id: int, external_id: str) -> contracts.ExternalAcreturn _to_external_account(account)+def _account_name_from_group(team: Team, external_id: str) -> str:+ """Resolve the new account's name from its group's ``name`` property, falling back to the+ group key. The name is cosmetic, so a failed lookup must not fail account creation."""+ group_type_index = team.customer_analytics_config.account_group_type_index+ if group_type_index is None:+ return external_id+ try:+ group = get_group_by_key(team.pk, group_type_index, external_id)+ except Exception as e:+ capture_exception(e, {"team_id": team.pk, "external_id": external_id})+ return external_id+ name = (group.group_properties or {}).get("name") if group is not None else None+ return str(name) if name else external_id+++def create_external_account(+ team: Team, *, external_id: str, workflow_id: str | None = None+) -> tuple[contracts.ExternalAccount, bool]:+ """Get-or-create an account by external id for the external API. Returns the account and+ whether it was created; an existing account is returned untouched. The name comes from the+ matching group's ``name`` property (fallback: the external id). Attribution goes to the+ originating workflow (activity-log trigger) — there is no acting user on this path.+ Raises ``AccountPropertiesValidationError`` / ``AccountConflictError`` (concurrent create)."""+ existing = _get_external_account_by_external_id(team.pk, external_id)+ if existing is not None:+ return _to_external_account(existing), False+ trigger = Trigger(job_type="hog_flow", job_id=workflow_id, payload={}) if workflow_id else None+ account = create_account(+ team=team, name=_account_name_from_group(team, external_id), external_id=external_id, trigger=trigger+ )+ return _to_external_account(account), True++def list_external_accounts(team_id: int,*,@@ -747,11 +781,14 @@ def _log_activity_swallowing(user: "User | None",was_impersonated: bool,previous=None,+ trigger: Trigger | None = None,) -> None:"""Replicates ``posthog.api.utils.log_activity_from_viewset`` — including its blanket``except: pass`` — for the account / customer-journey write paths."""try:detail_kwargs: dict[str, Any] = {"name": name}+ if trigger is not None:+ detail_kwargs["trigger"] = triggerif previous is not None:detail_kwargs["changes"] = changes_between(cast(AuditableScope, scope), previous=previous, current=instance)log_activity(@@ -2045,6 +2082,7 @@ def create_account(tags: list[str] | None = None,slack_summary_cadence: str | None = None,was_impersonated: bool = False,+ trigger: Trigger | None = None,) -> Account:"""The single account-creation write path: validates properties, sets tags, shadows roleassignments into the relationships table, and logs activity. Product-internal — it returns@@ -2077,6 +2115,7 @@ def create_account(team_id=team.pk,user=created_by,was_impersonated=was_impersonated,+ trigger=trigger,)return accountdiff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.pyindex 5cc8f04c2a27..519282f852d5 100644--- a/products/customer_analytics/backend/presentation/views/external.py+++ b/products/customer_analytics/backend/presentation/views/external.py@@ -7,6 +7,14 @@ Authorization header. The bulk account list instead authenticates via a projectsecret API key carrying the ``account:read`` scope, because the team token isreadable by every project member and must not unlock a team-wide account export.+The team token deliberately grants single-account writes (create, tags,+relationships, custom property values) without per-user ``account`` scope checks:+workflow executions have no acting user to authorize, and the token is only+readable by members of the project whose accounts it writes. Security reviewers+periodically flag this as a write-permission bypass — it is the accepted model+for this surface, matching the resource-level scoping note in the product's+CLAUDE.md.+The view holds only HTTP concerns — Bearer auth, throttles, the feature-flag gate,request validation, and mapping facade results to responses. Data access, thetransactional write, org-membership resolution, tag application, and exception@@ -262,9 +270,55 @@ class ExternalAccountUpdateSerializer(serializers.Serializer):raise serializers.ValidationError({field: "Assignee id must be a user id"})+class ExternalAccountCreateSerializer(serializers.Serializer):+ external_id = serializers.CharField(+ max_length=400,+ help_text=(+ "External ID (group key) for the account. An account with this ID already existing is a no-op. "+ "The account name is derived from the matching group's `name` property, falling back to this ID."+ ),+ )+++class ExternalAccountAssignmentSerializer(serializers.Serializer):+ user_id = serializers.IntegerField(help_text="PostHog user id of the assigned user.")+ email = serializers.CharField(help_text="Email address of the assigned user.")+++class ExternalAccountSerializer(serializers.Serializer):+ id = serializers.CharField(help_text="Account UUID.")+ external_id = serializers.CharField(+ allow_null=True, help_text="External account key — the group key the account is linked to."+ )+ name = serializers.CharField(help_text="Human-readable account name.")+ properties = serializers.DictField(+ child=serializers.JSONField(help_text="Property value: a string, a role-assignment object, or null."),+ help_text="Typed account properties: role assignments (csm, account_executive, account_owner) and external-system ids.",+ )+ tags = serializers.ListField(+ child=serializers.CharField(), help_text="Tag names on the account, sorted alphabetically."+ )+ relationships = serializers.DictField(+ child=ExternalAccountAssignmentSerializer(many=True),+ help_text=(+ "Active relationship assignments keyed by definition name (e.g. 'CSM'). "+ "Definitions with no active assignment are omitted."+ ),+ )+ custom_properties = serializers.DictField(+ child=serializers.JSONField(help_text="The property's active scalar value, or null when unset."),+ help_text="Every team custom property definition keyed by name, with the account's active value or null.",+ )+++class ExternalAccountErrorSerializer(serializers.Serializer):+ error = serializers.CharField(help_text="What went wrong with the request.")++class ExternalAccountView(APIView):"""GET /api/customer_analytics/external/account?external_id=<external_id> — Fetch account data+ POST /api/customer_analytics/external/account — Create an account (no-op if it already exists)PATCH /api/customer_analytics/external/account — Update an account's role contacts and tagsAuthenticated via Bearer token (team secret_api_token) in Authorization header.@@ -291,6 +345,53 @@ class ExternalAccountView(APIView):return Response(_external_account_body(account))+ @extend_schema(+ request=ExternalAccountCreateSerializer,+ responses={+ 201: OpenApiResponse(response=ExternalAccountSerializer, description="Account created."),+ 200: OpenApiResponse(+ response=ExternalAccountSerializer, description="Account already existed — creation skipped."+ ),+ 400: OpenApiResponse(response=ExternalAccountErrorSerializer, description="Invalid request body."),+ 401: OpenApiResponse(+ response=ExternalAccountErrorSerializer, description="Missing or invalid Bearer token."+ ),+ },+ )+ def post(self, request: Request) -> Response:+ team, error = _authenticate_team(request)+ if error:+ return error++ assert team is not None++ serializer = ExternalAccountCreateSerializer(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)++ try:+ account, created = facade.create_external_account(+ team,+ external_id=external_id,+ workflow_id=_workflow_id_from_request(request),+ )+ except facade.AccountConflictError:+ # Lost a concurrent-create race; the account exists now, so honor no-op semantics.+ existing = facade.get_external_account(team.id, external_id)+ if existing is None:+ return Response({"error": "Failed to create account"}, status=status.HTTP_400_BAD_REQUEST)+ account, created = existing, False++ return Response(+ _external_account_body(account),+ status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,+ )+def patch(self, request: Request) -> Response:team, error = _authenticate_team(request)if error:diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.pyindex d9170589f3eb..4dcabea5e51d 100644--- a/products/customer_analytics/backend/test/test_external.py+++ b/products/customer_analytics/backend/test/test_external.py@@ -9,9 +9,12 @@ from rest_framework import statusfrom rest_framework.test import APIClientfrom posthog.models import Organization, Team, User+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.utils import generate_random_token_secret+from posthog.test.persons import create_groupfrom products.customer_analytics.backend.models import (+ Account,AccountRelationship,AccountRelationshipDefinition,CustomPropertyValue,@@ -327,6 +330,79 @@ class TestExternalAccountAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn(unknown_uuid, response.json()["error"])+ # -- Create (POST) ----------------------------------------------------++ def _post(self, payload, token=None, **extra):+ return self.client.post(self.url, data=payload, format="json", **self._auth_headers(token), **extra)++ def test_post_requires_auth(self):+ response = self.client.post(self.url, data={"external_id": "new-1"}, format="json")+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_post_creates_account_named_after_its_group(self):+ self.team.customer_analytics_config.account_group_type_index = 0+ self.team.customer_analytics_config.save()+ create_group(team=self.team, group_type_index=0, group_key="new-1", group_properties={"name": "New Corp"})++ response = self._post({"external_id": "new-1"})++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ body = response.json()+ self.assertEqual(body["external_id"], "new-1")+ self.assertEqual(body["name"], "New Corp")+ account = Account.objects.for_team(self.team.id).get(external_id="new-1")+ self.assertEqual(account.name, "New Corp")+ self.assertIsNone(account.created_by)++ @parameterized.expand(+ [+ ("no_group_type_configured", False, False),+ ("group_missing", True, False),+ ("group_has_no_name_property", True, True),+ ]+ )+ def test_post_name_falls_back_to_external_id(self, _name, configure_group_type, create_nameless_group):+ if configure_group_type:+ self.team.customer_analytics_config.account_group_type_index = 0+ self.team.customer_analytics_config.save()+ if create_nameless_group:+ create_group(team=self.team, group_type_index=0, group_key="new-1", group_properties={"plan": "free"})++ response = self._post({"external_id": "new-1"})++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["name"], "new-1")++ def test_post_existing_account_is_a_noop(self):+ response = self._post({"external_id": "acme-1"})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["name"], "Acme Corp")+ self.account.refresh_from_db()+ self.assertEqual(self.account.name, "Acme Corp")++ @parameterized.expand([("missing", {}), ("blank", {"external_id": " "})])+ def test_post_requires_external_id(self, _name, payload):+ response = self._post(payload)+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_post_with_workflow_header_attributes_activity_to_workflow(self):+ workflow_id = str(uuid4())+ response = self._post({"external_id": "new-1"}, HTTP_X_POSTHOG_HOG_FLOW_ID=workflow_id)+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ log = ActivityLog.objects.get(team_id=self.team.id, scope="Account", activity="created")+ self.assertIsNone(log.user)+ detail = log.detail+ assert detail is not None+ self.assertEqual(detail["trigger"]["job_type"], "hog_flow")+ self.assertEqual(detail["trigger"]["job_id"], workflow_id)++ def test_post_does_not_see_other_teams_account(self):+ other_team = Team.objects.create(organization=self.organization, name="Other")+ create_account(team_id=other_team.id, name="Other Team Corp", external_id="shared-key")+ response = self._post({"external_id": "shared-key"})+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(Account.objects.for_team(self.team.id).get(external_id="shared-key").name, "shared-key")+class TestExternalAccountCustomPropertiesAPI(APIBaseTest):def setUp(self):diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.tsindex f874f8bdef7c..75474b861715 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts@@ -98,6 +98,14 @@ registerActionNodeCategory({label: 'Customer analytics',featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,nodes: [+ {+ type: 'function',+ name: 'Create account',+ description: "Create a Customer analytics account for the event's group, if one doesn't exist yet.",+ config: { template_id: 'template-posthog-create-account', inputs: {} },+ getDefaultInputs: getAccountExternalIdDefaultInputs,+ output_variable: { key: 'account', result_path: null, label: 'Account' },+ },{type: 'function',name: 'Get account',