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): account custom property changed trigger with account-keyed frequency (#73336)

Arthur Moreira de Deus5608e22ab2e1
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/accountCustomPropertyDefinitionsLogic.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/accountCustomPropertyDefinitionsLogic.ts
new file mode 100644
index 000000000000..c0933e4e806c
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/accountCustomPropertyDefinitionsLogic.ts
@@ -0,0 +1,108 @@
+import { MakeLogicType, afterMount, connect, kea, listeners, path, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import { customPropertyDefinitionsList } from 'products/customer_analytics/frontend/generated/api'
+import type { CustomPropertyDefinitionApi } 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 accountCustomPropertyDefinitionsLogicValues {
+ currentProjectId: number | null // projectLogic
+ accountPropertyNames: string[]
+ definitions: CustomPropertyDefinitionApi[]
+ definitionsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountCustomPropertyDefinitionsLogicActions {
+ 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: CustomPropertyDefinitionApi[],
+ payload?: any
+ ) => {
+ definitions: CustomPropertyDefinitionApi[]
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountCustomPropertyDefinitionsLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ accountPropertyNames: (definitions: CustomPropertyDefinitionApi[]) => string[]
+ }
+}
+
+export type accountCustomPropertyDefinitionsLogicType = MakeLogicType<
+ accountCustomPropertyDefinitionsLogicValues,
+ accountCustomPropertyDefinitionsLogicActions,
+ Record<string, any>,
+ accountCustomPropertyDefinitionsLogicMeta
+>
+
+export const accountCustomPropertyDefinitionsLogic = kea<accountCustomPropertyDefinitionsLogicType>([
+ path([
+ 'products',
+ 'workflows',
+ 'frontend',
+ 'Workflows',
+ 'hogflows',
+ 'registry',
+ 'triggers',
+ 'accountCustomPropertyDefinitionsLogic',
+ ]),
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId']],
+ actions: [projectLogic, ['loadCurrentProjectSuccess']],
+ })),
+ loaders(({ values }) => ({
+ definitions: [
+ [] as CustomPropertyDefinitionApi[],
+ {
+ loadDefinitions: async (): Promise<CustomPropertyDefinitionApi[]> => {
+ if (!values.currentProjectId) {
+ return []
+ }
+ const response = await customPropertyDefinitionsList(String(values.currentProjectId))
+ return response.results
+ },
+ },
+ ],
+ })),
+ selectors({
+ accountPropertyNames: [
+ (s) => [s.definitions],
+ (definitions: CustomPropertyDefinitionApi[]): string[] =>
+ definitions
+ .filter((definition) => (definition.target_type ?? 'account') === 'account')
+ .map((definition) => definition.name),
+ ],
+ }),
+ listeners(({ actions }) => ({
+ loadDefinitionsFailure: ({ error }) => {
+ posthog.captureException(error, { scope: 'accountCustomPropertyDefinitionsLogic.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 8ae8a1598de3..a48a55f6d76b 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
@@ -1,18 +1,34 @@
-import { accountTagAddedFilters, getSelectedTags } from './customer_analytics'
+import {
+ accountCustomPropertyChangedFilters,
+ accountCustomPropertyFrequencyOptions,
+ accountTagAddedFilters,
+ getSelectedPropertyNames,
+ 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')
+ const getTriggerType = (value: string): ReturnType<typeof getRegisteredTriggerTypes>[number] => {
+ const triggerType = getRegisteredTriggerTypes().find((t) => t.value === value)
if (!triggerType) {
- throw new Error('account_tag_added trigger type not registered')
+ throw new Error(`${value} 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(['account_tag_added', 'account_custom_property_changed'])(
+ '%s buildConfig produces a config recognized by matchConfig',
+ (value) => {
+ const triggerType = getTriggerType(value)
+ expect(triggerType.matchConfig!(triggerType.buildConfig())).toBe(true)
+ }
+ )
+
+ 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.each([
@@ -43,4 +59,44 @@ describe('customer analytics triggers', () => {
{ key: 'tag', value: ['vip'], operator: 'exact', type: 'event' },
])
})
+
+ it.each([
+ {
+ name: 'array value',
+ properties: [{ key: 'property_name', value: ['Plan', 'MRR'], operator: 'exact', type: 'event' }],
+ expected: ['Plan', 'MRR'],
+ },
+ {
+ name: 'scalar value',
+ properties: [{ key: 'property_name', value: 'Plan', operator: 'exact', type: 'event' }],
+ expected: ['Plan'],
+ },
+ { name: 'no property filter', properties: [], expected: [] },
+ {
+ name: 'non-string values',
+ properties: [{ key: 'property_name', value: [1, null], operator: 'exact', type: 'event' }],
+ expected: [],
+ },
+ ])('getSelectedPropertyNames handles $name', ({ properties, expected }) => {
+ const config: EventTriggerConfig = { type: 'event', filters: { properties } }
+ expect(getSelectedPropertyNames(config)).toEqual(expected)
+ })
+
+ it('omits the property filter when no properties are selected', () => {
+ expect(accountCustomPropertyChangedFilters([]).properties).toEqual([])
+ expect(accountCustomPropertyChangedFilters(['Plan']).properties).toEqual([
+ { key: 'property_name', value: ['Plan'], 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)
+ 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')
+ }
+ })
})
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 6b0155f2e205..a319332ad5da 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/customer_analytics.tsx
@@ -1,20 +1,24 @@
import { useActions, useValues } from 'kea'
-import { IconBolt } from '@posthog/icons'
-import { LemonInputSelect } from '@posthog/lemon-ui'
+import { IconBolt, IconPencil } from '@posthog/icons'
+import { LemonBanner, LemonInputSelect } from '@posthog/lemon-ui'
+import { CodeSnippet } from 'lib/components/CodeSnippet'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { tagsModel } from '~/models/tagsModel'
+import { accountCustomPropertyDefinitionsLogic } from 'products/workflows/frontend/Workflows/hogflows/registry/triggers/accountCustomPropertyDefinitionsLogic'
import {
type EventTriggerConfig,
+ type TriggerFrequencyOption,
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'
+const ACCOUNT_CUSTOM_PROPERTY_CHANGED_EVENT = '$account_custom_property_changed'
function getEventId(config: EventTriggerConfig): string | null {
const [firstEvent] = config.filters?.events ?? []
@@ -83,3 +87,109 @@ registerTriggerType({
}),
ConfigComponent: StepTriggerConfigurationAccountTagAdded,
})
+
+// Account events carry no person (they use a synthetic distinct_id), so the generic person-keyed
+// frequency hashes would resolve empty and mask globally — key on the event's account instead.
+const ONCE_PER_ACCOUNT_PROPERTY_HASH = "{concat(event.properties.account_id, '-', event.properties.property_name)}"
+const ONCE_PER_ACCOUNT_PROPERTY_PER_DAY_HASH =
+ "{concat(event.properties.account_id, '-', event.properties.property_name, '-', formatDateTime(now(), '%Y-%m-%d'))}"
+const CALENDAR_DAY_TTL = 24 * 60 * 60
+
+export const accountCustomPropertyFrequencyOptions: TriggerFrequencyOption[] = [
+ { value: null, label: 'Every time the trigger fires' },
+ { value: ONCE_PER_ACCOUNT_PROPERTY_HASH, label: 'Once per account and property' },
+ {
+ value: ONCE_PER_ACCOUNT_PROPERTY_PER_DAY_HASH,
+ label: 'Once per account and property per calendar day',
+ fixedTtl: CALENDAR_DAY_TTL,
+ },
+]
+
+export function getSelectedPropertyNames(config: EventTriggerConfig): string[] {
+ const nameProperty = (config.filters?.properties ?? []).find((property: any) => property?.key === 'property_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')
+}
+
+export function accountCustomPropertyChangedFilters(names: string[]): EventTriggerConfig['filters'] {
+ return {
+ events: [
+ { id: ACCOUNT_CUSTOM_PROPERTY_CHANGED_EVENT, type: 'events', name: 'Account custom property changed' },
+ ],
+ properties: names.length > 0 ? [{ key: 'property_name', value: names, operator: 'exact', type: 'event' }] : [],
+ }
+}
+
+const TRIGGER_EVENT_TEMPLATES = [
+ '{event.properties.property_name}',
+ '{event.properties.previous_value}',
+ '{event.properties.current_value}',
+ '{event.properties.account_external_id}',
+ '{event.properties.account_name}',
+]
+
+function StepTriggerConfigurationAccountCustomPropertyChanged({ node }: { node: any }): JSX.Element {
+ const { setWorkflowActionConfig } = useActions(workflowLogic)
+ const { accountPropertyNames, definitionsLoading } = useValues(accountCustomPropertyDefinitionsLogic)
+ const config = node.data.config as EventTriggerConfig
+ const selectedNames = getSelectedPropertyNames(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 custom property value changes. Leave empty to run for any property.
+ </p>
+ <LemonField.Pure label="Properties">
+ <LemonInputSelect
+ mode="multiple"
+ value={selectedNames}
+ loading={definitionsLoading}
+ placeholder="Any property"
+ options={accountPropertyNames.map((name: string) => ({ key: name, label: name }))}
+ onChange={(value) =>
+ setWorkflowActionConfig(node.data.id, {
+ type: 'event',
+ filters: accountCustomPropertyChangedFilters(value),
+ })
+ }
+ data-attr="account-custom-property-changed-trigger-properties"
+ />
+ </LemonField.Pure>
+ {selectedNames.length !== 1 && (
+ <LemonBanner type="info">
+ The workflow starts once per changed property. If two matching properties change at the same time,
+ two separate runs start.
+ </LemonBanner>
+ )}
+ <LemonField.Pure label="Available in steps" help="Reference the change from any step, filter, or condition">
+ <div className="flex flex-col gap-1">
+ {TRIGGER_EVENT_TEMPLATES.map((template) => (
+ <CodeSnippet key={template} compact thing="template">
+ {template}
+ </CodeSnippet>
+ ))}
+ </div>
+ </LemonField.Pure>
+ </div>
+ )
+}
+
+registerTriggerType({
+ value: 'account_custom_property_changed',
+ label: 'Account property changed',
+ icon: <IconPencil />,
+ description: 'Trigger when an account custom property value changes',
+ group: 'Customer analytics',
+ featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,
+ matchConfig: (config) => config.type === 'event' && getEventId(config) === ACCOUNT_CUSTOM_PROPERTY_CHANGED_EVENT,
+ buildConfig: () => ({
+ type: 'event',
+ filters: accountCustomPropertyChangedFilters([]),
+ }),
+ ConfigComponent: StepTriggerConfigurationAccountCustomPropertyChanged,
+ frequencyOptions: accountCustomPropertyFrequencyOptions,
+ frequencyDescription: 'Limit how often each account can enter this workflow',
+})
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.ts
index 58e88f109ebe..bbb3670d3fc8 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.ts
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.ts
@@ -10,6 +10,14 @@ export type EventTriggerConfig = {
}
}
+export type TriggerFrequencyOption = {
+ /** trigger_masking hash template (a Hog expression over the trigger event's globals), or null for no masking */
+ value: string | null
+ label: string
+ /** Pin the masking TTL to this many seconds and hide the TTL picker (e.g. calendar-day options) */
+ fixedTtl?: number
+}
+
export type TriggerTypeDefinition = {
value: string
label: string
@@ -26,6 +34,14 @@ export type TriggerTypeDefinition = {
ConfigComponent?: React.ComponentType<{ node: any }>
/** Validate the trigger config, returning errors if invalid. Triggers without this use generic validation. */
validate?: (config: any) => { valid: boolean; errors: Record<string, string> } | null
+ /**
+ * Show the frequency (trigger_masking) section below the config panel with these options.
+ * The generic event trigger's person-keyed options usually don't fit registered triggers —
+ * e.g. account events carry no person, so a person-keyed hash would mask globally.
+ */
+ frequencyOptions?: TriggerFrequencyOption[]
+ /** Copy under the "Frequency" heading; defaults to the generic person-centric wording */
+ frequencyDescription?: string
}
const triggerTypeDefinitions: TriggerTypeDefinition[] = []
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
index 3c02596499c3..59662c678fda 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx
@@ -45,7 +45,7 @@ import 'products/workflows/frontend/Workflows/hogflows/registry/triggers'
import { workflowLogic } from '../../workflowLogic'
import { HogFlowEventFilters, WORKFLOW_OPERATOR_ALLOWLIST } from '../filters/HogFlowFilters'
-import { getRegisteredTriggerTypes } from '../registry/triggers/triggerTypeRegistry'
+import { TriggerFrequencyOption, getRegisteredTriggerTypes } from '../registry/triggers/triggerTypeRegistry'
import { HogFlowAction } from '../types'
import { batchTriggerLogic, getAudienceDedupeKey } from './batchTriggerLogic'
import { HogFlowFunctionConfiguration } from './components/HogFlowFunctionConfiguration'
@@ -204,7 +204,7 @@ function TriggerTypeDropdownItem({
}
export function StepTriggerConfiguration({ node }: { node: Node<TriggerAction> }): JSX.Element {
- const { setWorkflowActionConfig } = useActions(workflowLogic)
+ const { setWorkflowActionConfig, setWorkflowValue } = useActions(workflowLogic)
const { actionValidationErrorsById } = useValues(workflowLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -281,6 +281,11 @@ export function StepTriggerConfiguration({ node }: { node: Node<TriggerAction> }
const registeredMatch = getRegisteredTriggerTypes().find((t) => t.matchConfig?.(node.data.config))
const handleSelect = (value: string): void => {
+ // The frequency hash lives on the workflow, not the trigger config, and hashes are
+ // trigger-specific ({person.id} vs event-keyed) — a stale one silently disables masking.
+ if (value !== displayType) {
+ setWorkflowValue('trigger_masking', null)
+ }
const registered = getRegisteredTriggerTypes().find((t) => t.value === value)
if (registered) {
setWorkflowActionConfig(node.id, registered.buildConfig())
@@ -332,7 +337,18 @@ export function StepTriggerConfiguration({ node }: { node: Node<TriggerAction> }
{type === 'schedule' && <ScheduleStatusBadge />}
</div>
{registeredMatch?.ConfigComponent ? (
- <registeredMatch.ConfigComponent node={node} />
+ <>
+ <registeredMatch.ConfigComponent node={node} />
+ {registeredMatch.frequencyOptions ? (
+ <>
+ <LemonDivider />
+ <FrequencySection
+ options={registeredMatch.frequencyOptions}
+ description={registeredMatch.frequencyDescription}
+ />
+ </>
+ ) : null}
+ </>
) : node.data.config.type === 'event' ? (
<StepTriggerConfigurationEvents action={node.data} config={node.data.config} />
) : node.data.config.type === 'webhook' ? (
@@ -687,10 +703,10 @@ function StepTriggerConfigurationTrackingPixel({
const MASKING_HASH_PER_PERSON_PER_DAY = "{concat(toString(person.id), '-', formatDateTime(now(), '%Y-%m-%d'))}"
const CALENDAR_DAY_TTL = 24 * 60 * 60
-const FREQUENCY_OPTIONS = [
+const FREQUENCY_OPTIONS: TriggerFrequencyOption[] = [
{ value: null, label: 'Every time the trigger fires' },
{ value: '{person.id}', label: 'One time' },
- { value: MASKING_HASH_PER_PERSON_PER_DAY, label: 'Once per calendar day' },
+ { value: MASKING_HASH_PER_PERSON_PER_DAY, label: 'Once per calendar day', fixedTtl: CALENDAR_DAY_TTL },
]
const TTL_OPTIONS = [
@@ -726,40 +742,45 @@ function TTLSelect({
)
}
-function FrequencySection(): JSX.Element {
+function FrequencySection({
+ options = FREQUENCY_OPTIONS,
+ description = 'Limit how often users can enter this workflow',
+}: {
+ options?: TriggerFrequencyOption[]
+ description?: string
+}): JSX.Element {
const { setWorkflowValue } = useActions(workflowLogic)
const { workflow } = useValues(workflowLogic)
+ const selectedOption = options.find((option) => option.value === (workflow.trigger_masking?.hash ?? null))
+
return (
<div className="flex flex-col w-full py-2">
<span className="flex gap-1">
<IconClock className="text-lg" />
<span className="text-md font-semibold">Frequency</span>
</span>
- <p>Limit how often users can enter this workflow</p>
+ <p>{description}</p>
<LemonField.Pure>
<div className="flex flex-wrap gap-1 items-center">
<LemonSelect
- options={FREQUENCY_OPTIONS}
+ options={options.map(({ value, label }) => ({ value, label }))}
value={workflow.trigger_masking?.hash ?? null}
- onChange={(val) =>
+ onChange={(val) => {
+ const option = options.find((candidate) => candidate.value === val)
setWorkflowValue(
'trigger_masking',
val
? {
hash: val,
- ttl:
- val === MASKING_HASH_PER_PERSON_PER_DAY
- ? CALENDAR_DAY_TTL
- : (workflow.trigger_masking?.ttl ?? 60 * 30),
+ ttl: option?.fixedTtl ?? workflow.trigger_masking?.ttl ?? 60 * 30,
}
: null
)
- }
+ }}
/>
- {workflow.trigger_masking?.hash &&
- workflow.trigger_masking.hash !== MASKING_HASH_PER_PERSON_PER_DAY ? (
+ {workflow.trigger_masking?.hash && !selectedOption?.fixedTtl ? (
<TTLSelect
value={workflow.trigger_masking.ttl}
onChange={(val) =>