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(customer-analytics): add workflow source mode to custom property modal (#67941)

Arthur Moreira de Deus2fff71b6f3ae
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
index db34405ef09e..4e7421a6aadb 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
@@ -1,6 +1,7 @@
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
+import { IconRefresh } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
@@ -9,11 +10,14 @@ import {
LemonSearchableSelect,
LemonSelect,
LemonSwitch,
+ LemonTag,
LemonTextArea,
+ Link,
} from '@posthog/lemon-ui'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
+import { urls } from 'scenes/urls'
import { CustomPropertySourceMode, customPropertyDefinitionsLogic } from './customPropertyDefinitionsLogic'
import { DISPLAY_TYPE_OPTIONS, isNumericDisplayType } from './customPropertyTypes'
@@ -21,6 +25,7 @@ import { DISPLAY_TYPE_OPTIONS, isNumericDisplayType } from './customPropertyType
const SOURCE_MODE_OPTIONS: { value: CustomPropertySourceMode; label: string }[] = [
{ value: 'manual', label: 'Manual' },
{ value: 'data_warehouse', label: 'Data warehouse' },
+ { value: 'workflow', label: 'Workflow' },
]
export function CustomPropertyModal(): JSX.Element {
@@ -32,17 +37,42 @@ export function CustomPropertyModal(): JSX.Element {
materializedViews,
selectedSourceColumns,
savedQueriesLoading,
+ definitionsLoading,
+ editingReferences,
+ newWorkflowUrlLoading,
} = useValues(customPropertyDefinitionsLogic)
- const { closeModal, submitCustomPropertyForm, setCustomPropertyFormValue } =
- useActions(customPropertyDefinitionsLogic)
+ const {
+ closeModal,
+ submitCustomPropertyForm,
+ setCustomPropertyFormValue,
+ loadDefinitions,
+ createWorkflowForProperty,
+ } = useActions(customPropertyDefinitionsLogic)
const showBigNumberSwitch = isNumericDisplayType(customPropertyForm.displayType)
const { sourceMode } = customPropertyForm
const hasExistingSource = !!editingDefinition?.source
const noViews = !savedQueriesLoading && materializedViews.length === 0
+ // While a workflow references the property it stays workflow-sourced no matter what is picked
+ // here, so the other options are locked until it's removed from the workflow(s).
+ const lockedToWorkflow = editingReferences.length > 0 && !hasExistingSource
+ const sourceModeOptions = SOURCE_MODE_OPTIONS.map((option) =>
+ option.value !== 'workflow' && lockedToWorkflow
+ ? {
+ ...option,
+ disabledReason:
+ 'This property is updated by a workflow. Remove it from the workflow to change the source.',
+ }
+ : option
+ )
+
const submitDisabledReason =
- sourceMode === 'data_warehouse' && noViews ? 'No materialized views are available' : undefined
+ sourceMode === 'data_warehouse' && noViews
+ ? 'No materialized views are available'
+ : sourceMode === 'workflow' && editingReferences.length === 0
+ ? 'Create a workflow that updates this property first'
+ : undefined
return (
<LemonModal
@@ -94,12 +124,7 @@ export function CustomPropertyModal(): JSX.Element {
)}
<LemonField name="sourceMode" label="Source">
{({ value, onChange }) => (
- <LemonSegmentedButton
- value={value}
- onChange={onChange}
- options={SOURCE_MODE_OPTIONS}
- fullWidth
- />
+ <LemonSegmentedButton value={value} onChange={onChange} options={sourceModeOptions} fullWidth />
)}
</LemonField>
{hasExistingSource && sourceMode !== 'data_warehouse' && (
@@ -194,6 +219,54 @@ export function CustomPropertyModal(): JSX.Element {
</LemonField>
</>
))}
+ {sourceMode === 'workflow' && (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between">
+ <span className="font-semibold">Workflows updating this property</span>
+ <LemonButton
+ size="small"
+ icon={<IconRefresh />}
+ tooltip="Refresh"
+ onClick={loadDefinitions}
+ loading={definitionsLoading}
+ />
+ </div>
+ {editingReferences.length > 0 ? (
+ <div className="flex flex-col gap-1">
+ {editingReferences.map((reference) => (
+ <div
+ key={reference.id}
+ className="flex items-center justify-between gap-2 border rounded p-2"
+ >
+ <Link
+ to={urls.workflow(reference.id, 'workflow')}
+ target="_blank"
+ targetBlankIcon
+ >
+ {reference.name}
+ </Link>
+ <LemonTag>{reference.status}</LemonTag>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="border rounded p-4 flex flex-col items-center gap-2 text-center">
+ <span className="text-secondary">
+ No workflows update this property yet. Create one with an "Update account property"
+ action that sets this property — the editor opens in a new tab. Once you save the
+ workflow there, refresh this list.
+ </span>
+ <LemonButton
+ type="primary"
+ onClick={createWorkflowForProperty}
+ loading={newWorkflowUrlLoading}
+ >
+ Create workflow
+ </LemonButton>
+ </div>
+ )}
+ </div>
+ )}
</Form>
</LemonModal>
)
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
index f43a38cd04c1..204ff1675ce8 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.test.ts
@@ -90,6 +90,7 @@ describe('customPropertyDefinitionsLogic', () => {
} as any
initKeaTests()
userLogic.mount()
+ jest.spyOn(window, 'open').mockReturnValue(null)
})
it('loads definitions on mount', async () => {
@@ -123,12 +124,24 @@ describe('customPropertyDefinitionsLogic', () => {
})
})
- it('derives the manual source mode when editing a definition without a source', async () => {
- useMocks(defaultMocks())
- mountLogic()
- await expectLogic(logic, () => logic.actions.openEditModal(buildDefinition())).toFinishAllListeners()
- expect(logic.values.customPropertyForm.sourceMode).toBe('manual')
- })
+ it.each([
+ [
+ 'workflow references',
+ { references: [{ id: 'flow-1', name: 'Flow', status: 'draft', type: 'workflow' }] },
+ 'workflow',
+ ],
+ ['no source or references', {}, 'manual'],
+ ] as [string, Partial<CustomPropertyDefinitionApi>, string][])(
+ 'derives the source mode when editing a definition with %s',
+ async (_, overrides, expectedMode) => {
+ useMocks(defaultMocks())
+ mountLogic()
+ await expectLogic(logic, () =>
+ logic.actions.openEditModal(buildDefinition(overrides))
+ ).toFinishAllListeners()
+ expect(logic.values.customPropertyForm.sourceMode).toBe(expectedMode)
+ }
+ )
it('creates a definition, reloads, and closes the modal', async () => {
useMocks(defaultMocks())
@@ -381,4 +394,52 @@ describe('customPropertyDefinitionsLogic', () => {
'closeSourceModal',
])
})
+
+ it('fails the workflow CTA with a field error when the name is missing', async () => {
+ useMocks(defaultMocks())
+ mountLogic()
+ logic.actions.openCreateModal()
+
+ await expectLogic(logic, () => logic.actions.createWorkflowForProperty()).toDispatchActions([
+ 'createWorkflowForPropertyFailure',
+ 'setCustomPropertyFormManualErrors',
+ ])
+ expect(window.open).not.toHaveBeenCalled()
+ })
+
+ it('creates the property and opens the new-workflow editor', async () => {
+ useMocks(defaultMocks())
+ mountLogic()
+ logic.actions.openCreateModal()
+ logic.actions.setCustomPropertyFormValues({ name: 'Health score', sourceMode: 'workflow' })
+
+ await expectLogic(logic, () => logic.actions.createWorkflowForProperty()).toDispatchActions([
+ // The definition must be created first — the workflow action references it by id.
+ 'setEditingDefinition',
+ 'createWorkflowForPropertySuccess',
+ ])
+ expect(window.open).toHaveBeenCalledWith('/workflows/new/workflow', '_blank')
+ })
+
+ it('opens the editor without re-creating an already-existing property', async () => {
+ let definitionCreated = false
+ useMocks({
+ ...defaultMocks(),
+ post: {
+ ...defaultMocks().post,
+ [DEFINITIONS_URL]: () => {
+ definitionCreated = true
+ return buildDefinition({ id: 'def-2' })
+ },
+ },
+ })
+ mountLogic()
+ logic.actions.openEditModal(buildDefinition())
+
+ await expectLogic(logic, () => logic.actions.createWorkflowForProperty()).toDispatchActions([
+ 'createWorkflowForPropertySuccess',
+ ])
+ expect(definitionCreated).toBe(false)
+ expect(window.open).toHaveBeenCalledWith('/workflows/new/workflow', '_blank')
+ })
})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
index 6774bb53d7b5..33f8be159a31 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/customPropertyDefinitionsLogic.ts
@@ -6,6 +6,7 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { projectLogic } from 'scenes/projectLogic'
+import { urls } from 'scenes/urls'
import type { DataWarehouseSavedQuery } from '~/types'
@@ -21,12 +22,13 @@ import {
import type {
CustomPropertyDefinitionApi,
CustomPropertyDisplayTypeEnumApi,
+ CustomPropertyReferenceApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
import type { customPropertyDefinitionsLogicType } from './customPropertyDefinitionsLogicType'
import { isNumericDisplayType } from './customPropertyTypes'
-export type CustomPropertySourceMode = 'manual' | 'data_warehouse'
+export type CustomPropertySourceMode = 'manual' | 'data_warehouse' | 'workflow'
export interface CustomPropertyFormValues {
name: string
@@ -92,6 +94,8 @@ const handleNameConflict = (error: unknown, setManualErrors: (errors: { name: st
return true
}
+class MissingNameError extends Error {}
+
export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogicType>([
path([
'products',
@@ -146,7 +150,7 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
},
],
}),
- loaders(({ values }) => ({
+ loaders(({ actions, values }) => ({
definitions: [
[] as CustomPropertyDefinitionApi[],
{
@@ -181,6 +185,29 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
},
},
],
+ newWorkflowUrl: [
+ null as string | null,
+ {
+ createWorkflowForProperty: async (): Promise<string> => {
+ const formValues = values.customPropertyForm
+ if (!formValues.name?.trim()) {
+ throw new MissingNameError()
+ }
+ // The property must exist first — the workflow action references it by id.
+ if (!values.editingDefinition) {
+ const definition = await customPropertyDefinitionsCreate(
+ String(values.currentProjectId),
+ serializeDefinition(formValues)
+ )
+ actions.setEditingDefinition(definition)
+ actions.loadDefinitions()
+ // Announce the side effect: the property now exists even if the modal is cancelled.
+ lemonToast.success('Custom property created')
+ }
+ return urls.workflowNew()
+ },
+ },
+ ],
})),
forms(({ actions, values }) => ({
customPropertyForm: {
@@ -283,6 +310,19 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
return (view?.columns ?? []).map((column) => column.name)
},
],
+ editingReferences: [
+ (s) => [s.definitions, s.editingDefinition],
+ (
+ definitions: CustomPropertyDefinitionApi[],
+ editingDefinition: CustomPropertyDefinitionApi | null
+ ): readonly CustomPropertyReferenceApi[] => {
+ if (!editingDefinition) {
+ return []
+ }
+ const fresh = definitions.find((definition) => definition.id === editingDefinition.id)
+ return fresh?.references ?? editingDefinition.references ?? []
+ },
+ ],
}),
listeners(({ actions, values }) => ({
openCreateModal: () => {
@@ -296,7 +336,11 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
description: definition.description ?? '',
displayType: definition.display_type,
isBigNumber: definition.is_big_number ?? false,
- sourceMode: definition.source ? 'data_warehouse' : 'manual',
+ sourceMode: definition.source
+ ? 'data_warehouse'
+ : definition.references?.length
+ ? 'workflow'
+ : 'manual',
savedQuery: definition.source?.saved_query ?? null,
sourceColumn: definition.source?.source_column ?? null,
keyColumn: definition.source?.key_column ?? null,
@@ -364,6 +408,25 @@ export const customPropertyDefinitionsLogic = kea<customPropertyDefinitionsLogic
posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.removeSource' })
lemonToast.error('Failed to remove sync')
},
+ createWorkflowForPropertySuccess: ({ newWorkflowUrl }) => {
+ if (newWorkflowUrl && window.open(newWorkflowUrl, '_blank')) {
+ lemonToast.success('Workflow editor opened in a new tab — save the workflow there, then refresh')
+ } else {
+ lemonToast.error('Could not open a new tab — check your popup blocker')
+ }
+ },
+ createWorkflowForPropertyFailure: ({ errorObject }) => {
+ if (errorObject instanceof MissingNameError) {
+ actions.setCustomPropertyFormManualErrors({ name: 'Name is required' })
+ return
+ }
+ // A name conflict is expected validation feedback, not an exception worth capturing.
+ if (handleNameConflict(errorObject, actions.setCustomPropertyFormManualErrors)) {
+ return
+ }
+ posthog.captureException(errorObject, { scope: 'customPropertyDefinitionsLogic.createWorkflow' })
+ lemonToast.error('Failed to create workflow')
+ },
loadSavedQueriesFailure: ({ error }) => {
posthog.captureException(error, { scope: 'customPropertyDefinitionsLogic.loadSavedQueries' })
lemonToast.error('Failed to load data warehouse views')