: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): flatten account variables and prefill external_id (#64926)
Arthur Moreira de Deus80a338365857
diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.tsindex c3c8f2563d48..d8728ccef913 100644--- a/nodejs/src/cdp/async-functions/customer_analytics.ts+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts@@ -50,16 +50,16 @@ registerAsyncFunction('postHogGetAccount', {external_id: args[0]?.external_id ?? 'mock-external-id',name: 'Mock Account',properties: {- csm: null,- account_executive: null,- account_owner: null,- stripe_customer_id: null,- hubspot_deal_id: null,- billing_id: null,- sfdc_id: null,- zendesk_id: null,- slack_channel_id: null,- usage_dashboard_link: null,+ csm: { id: 1, email: '[email protected]' },+ account_executive: { id: 2, email: '[email protected]' },+ account_owner: { id: 3, email: '[email protected]' },+ stripe_customer_id: 'cus_mock',+ hubspot_deal_id: 'deal_mock',+ billing_id: 'bill_mock',+ sfdc_id: 'sfdc_mock',+ zendesk_id: 'zd_mock',+ slack_channel_id: 'C0MOCK',+ usage_dashboard_link: 'https://example.com/dashboard',},},}diff --git a/nodejs/src/schema/hogflow.ts b/nodejs/src/schema/hogflow.tsindex 9cb639d9863f..20d9f94b4051 100644--- a/nodejs/src/schema/hogflow.ts+++ b/nodejs/src/schema/hogflow.ts@@ -16,12 +16,14 @@ const _commonActionFields = {key: z.string(),result_path: z.string().optional().nullable(), // The path within the action result to store, e.g. 'response.user.id'spread: z.boolean().optional().nullable(), // When true, spread object result into multiple variables as {key}_{property}+ label: z.string().optional().nullable(), // Display label for the auto-created workflow variable}),z.array(z.object({key: z.string(),result_path: z.string().optional().nullable(),spread: z.boolean().optional().nullable(),+ label: z.string().optional().nullable(),})),])diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsxindex e92f5d67446f..e62e994d68ef 100644--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx@@ -30,7 +30,7 @@ import { getFormattedNodes } from './react_flow_utils/autolayout'import { BOTTOM_HANDLE_POSITION, NODE_HEIGHT, NODE_WIDTH, TOP_HANDLE_POSITION } from './react_flow_utils/constants'import { getSmartStepPath } from './react_flow_utils/SmartEdge'import { getHogFlowStep } from './steps/HogFlowSteps'-import { StepViewNodeHandle } from './steps/types'+import { CyclotronInputType, StepViewNodeHandle } from './steps/types'import type { DropzoneNode, HogFlow, HogFlowAction, HogFlowActionEdge, HogFlowActionNode } from './types'const getEdgeId = (edge: HogFlow['edges'][number]): string =>@@ -143,6 +143,7 @@ export type HogFlowEditorActionMetrics = {export type CreateActionType = Pick<HogFlowAction, 'type' | 'config' | 'name' | 'description'> & {branchEdges?: numberoutput_variable?: HogFlowAction['output_variable']+ getDefaultInputs?: () => Record<string, CyclotronInputType> | undefined}export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([@@ -649,6 +650,14 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([? (values.nodeToBeAdded as HogFlowActionNode).data: (values.nodeToBeAdded as CreateActionType)+ let config = partialNewAction.config+ if (!isHogFlowActionNode) {+ const dynamicInputs = (partialNewAction as CreateActionType).getDefaultInputs?.()+ if (dynamicInputs && 'inputs' in config) {+ config = { ...config, inputs: { ...config.inputs, ...dynamicInputs } }+ }+ }+const newAction = {id: isHogFlowActionNode? (values.nodeToBeAdded as HogFlowActionNode).id@@ -656,7 +665,7 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([type: partialNewAction.type,name: partialNewAction.name,description: partialNewAction.description,- config: partialNewAction.config,+ config,created_at: Date.now(),updated_at: Date.now(),...(!isHogFlowActionNode && (partialNewAction as CreateActionType).output_variable@@ -796,7 +805,12 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([} else if (!updatedVariables?.some((v) => v.key === prefix)) {updatedVariables = [...(updatedVariables || []),- { key: prefix, label: prefix, type: 'string' as const, default: '' },+ {+ key: prefix,+ label: outputVar.label ?? prefix,+ type: 'string' as const,+ default: '',+ },]}}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 49b9a219df99..0a3b1640883e 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@@ -1,8 +1,12 @@-import './customer_analytics'-import { FEATURE_FLAGS } from 'lib/constants'+import { GroupType, GroupTypeIndex } from '~/types'+import { getRegisteredActionNodeCategories } from './actionNodeRegistry'+import { buildAccountExternalIdInputs } from './customer_analytics'++const groupTypesMap = (...entries: [GroupTypeIndex, string][]): Map<GroupTypeIndex, GroupType> =>+ new Map(entries.map(([index, groupType]) => [index, { group_type: groupType, group_type_index: index }]))describe('customer analytics action registry', () => {const getCategory = (): ReturnType<typeof getRegisteredActionNodeCategories>[number] => {@@ -25,9 +29,45 @@ describe('customer analytics action registry', () => {})})- it('stores the account in a single variable without spreading', () => {+ it('flattens the requested account fields into prefixed variables', () => {const node = getCategory().nodes.find((n) => n.name === 'Get account')- expect(node?.output_variable).toEqual({ key: 'account', result_path: null })+ const outputVars = node?.output_variable+ if (!Array.isArray(outputVars)) {+ throw new Error('Get account output_variable should be an array of field mappings')+ }++ expect(outputVars).toContainEqual({ key: 'account', result_path: null, label: 'Account' })+ expect(outputVars).toContainEqual({+ key: 'account_csm_email',+ result_path: 'properties.csm.email',+ label: 'CSM email',+ })+ expect(outputVars).toContainEqual({+ key: 'account_executive_id',+ result_path: 'properties.account_executive.id',+ label: 'Account executive ID',+ })+ expect(outputVars).toContainEqual({+ key: 'account_slack_channel_id',+ result_path: 'properties.slack_channel_id',+ label: 'Slack channel ID',+ })++ expect(outputVars.map((v) => v.key)).toEqual([+ 'account',+ 'account_csm_email',+ 'account_csm_id',+ 'account_executive_email',+ 'account_executive_id',+ 'account_owner_email',+ 'account_owner_id',+ 'account_stripe_customer_id',+ 'account_hubspot_deal_id',+ 'account_billing_id',+ 'account_sfdc_id',+ 'account_zendesk_id',+ 'account_slack_channel_id',+ ])})it('wires the Update account node to its hog function template', () => {@@ -37,4 +77,30 @@ describe('customer analytics action registry', () => {config: { template_id: 'template-posthog-update-account' },})})++ it.each(['Get account', 'Update account'])('gives %s a dynamic external_id default resolver', (name) => {+ const node = getCategory().nodes.find((n) => n.name === name)+ expect(typeof node?.getDefaultInputs).toBe('function')+ })++ describe('buildAccountExternalIdInputs', () => {+ it('builds a name-based group key expression from the account group type index', () => {+ const inputs = buildAccountExternalIdInputs(2, groupTypesMap([0, 'project'], [2, 'organization']))+ expect(inputs).toEqual({ external_id: { value: '{groups["organization"].id}' } })+ })++ it('quotes the group type so a name with template delimiters is escaped, not injected', () => {+ const malicious = '"].id} + inject {groups["x'+ const inputs = buildAccountExternalIdInputs(0, groupTypesMap([0, malicious]))+ expect(inputs).toEqual({ external_id: { value: `{groups[${JSON.stringify(malicious)}].id}` } })+ })++ it.each([null, undefined])('returns undefined when the account group type index is %s', (index) => {+ expect(buildAccountExternalIdInputs(index, groupTypesMap([0, 'organization']))).toBeUndefined()+ })++ it('returns undefined when the configured index has no matching group type', () => {+ expect(buildAccountExternalIdInputs(3, groupTypesMap([0, 'organization']))).toBeUndefined()+ })+ })})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.tsindex 360843fc27cc..7f95a8538654 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts@@ -1,6 +1,29 @@import { FEATURE_FLAGS } from 'lib/constants'+import { teamLogic } from 'scenes/teamLogic'++import { groupsModel } from '~/models/groupsModel'+import { GroupType, GroupTypeIndex } from '~/types'import { registerActionNodeCategory } from 'products/workflows/frontend/Workflows/hogflows/registry/actions/actionNodeRegistry'+import { CyclotronInputType } from 'products/workflows/frontend/Workflows/hogflows/steps/types'++export const buildAccountExternalIdInputs = (+ accountGroupTypeIndex: number | null | undefined,+ groupTypes: Map<GroupTypeIndex, GroupType>+): Record<string, CyclotronInputType> | undefined => {+ if (accountGroupTypeIndex === null || accountGroupTypeIndex === undefined) {+ return undefined+ }+ const groupType = groupTypes.get(accountGroupTypeIndex as GroupTypeIndex)?.group_type+ // Quote the group type as a property key — an ingested name with template delimiters must not break out of the Hog expression.+ return groupType ? { external_id: { value: `{groups[${JSON.stringify(groupType)}].id}` } } : undefined+}++const getAccountExternalIdDefaultInputs = (): Record<string, CyclotronInputType> | undefined =>+ buildAccountExternalIdInputs(+ teamLogic.findMounted()?.values.currentTeam?.customer_analytics_config?.account_group_type_index,+ groupsModel.findMounted()?.values.groupTypes ?? new Map()+ )registerActionNodeCategory({label: 'Customer analytics',@@ -11,15 +34,53 @@ registerActionNodeCategory({name: 'Get account',description: 'Fetch a Customer analytics account into a workflow variable.',config: { template_id: 'template-posthog-get-account', inputs: {} },- // No `spread`: the editor's spread helper (hogFlowEditorLogic) hardcodes ticket field- // names, so it can't flatten an account. Store the whole object in one variable instead.- output_variable: { key: 'account', result_path: null },+ getDefaultInputs: getAccountExternalIdDefaultInputs,+ output_variable: [+ { key: 'account', result_path: null, label: 'Account' },+ { key: 'account_csm_email', result_path: 'properties.csm.email', label: 'CSM email' },+ { key: 'account_csm_id', result_path: 'properties.csm.id', label: 'CSM ID' },+ {+ key: 'account_executive_email',+ result_path: 'properties.account_executive.email',+ label: 'Account executive email',+ },+ {+ key: 'account_executive_id',+ result_path: 'properties.account_executive.id',+ label: 'Account executive ID',+ },+ {+ key: 'account_owner_email',+ result_path: 'properties.account_owner.email',+ label: 'Account owner email',+ },+ { key: 'account_owner_id', result_path: 'properties.account_owner.id', label: 'Account owner ID' },+ {+ key: 'account_stripe_customer_id',+ result_path: 'properties.stripe_customer_id',+ label: 'Stripe customer ID',+ },+ {+ key: 'account_hubspot_deal_id',+ result_path: 'properties.hubspot_deal_id',+ label: 'HubSpot deal ID',+ },+ { key: 'account_billing_id', result_path: 'properties.billing_id', label: 'Billing ID' },+ { key: 'account_sfdc_id', result_path: 'properties.sfdc_id', label: 'Salesforce ID' },+ { key: 'account_zendesk_id', result_path: 'properties.zendesk_id', label: 'Zendesk ID' },+ {+ key: 'account_slack_channel_id',+ result_path: 'properties.slack_channel_id',+ label: 'Slack channel ID',+ },+ ],},{type: 'function',name: 'Update account',description: 'Assign role contacts or tag a Customer analytics account.',config: { template_id: 'template-posthog-update-account', inputs: {} },+ getDefaultInputs: getAccountExternalIdDefaultInputs,output_variable: { key: 'account', result_path: null },},],diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsxindex 280c89b30df0..5ed35fe2dc7d 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/HogFlowFunctionConfiguration.tsx@@ -43,8 +43,13 @@ export function HogFlowFunctionConfiguration({const engagementEventsEnabled = !!currentTeam?.workflows_config?.capture_workflows_engagement_eventsuseEffect(() => {// oxlint-disable-next-line exhaustive-deps- if (template && Object.keys(inputs ?? {}).length === 0) {- setInputs(templateToConfiguration(template).inputs ?? {})+ if (template) {+ const defaults = templateToConfiguration(template).inputs ?? {}+ const currentInputs = inputs ?? {}+ const hasMissingDefaults = Object.keys(defaults).some((key) => !(key in currentInputs))+ if (hasMissingDefaults) {+ setInputs({ ...defaults, ...currentInputs })+ }}}, [templateId])diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.tsindex 390992c7d652..9c4b72a70ba6 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts@@ -33,12 +33,14 @@ const _commonActionFields = {key: z.string(),result_path: z.string().optional().nullable(), // The path within the action result to store, e.g. 'body.user.id'spread: z.boolean().optional().nullable(), // When true, spread object result into multiple variables as {key}_{property}+ label: z.string().optional().nullable(), // Display label for the auto-created workflow variable}),z.array(z.object({key: z.string(),result_path: z.string().optional().nullable(),spread: z.boolean().optional().nullable(),+ label: z.string().optional().nullable(),})),])