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.

refactor(insights): edit retention and template entities as series (#126213)

Thomas Obermüller967393a901d8
diff --git a/frontend/src/scenes/dashboard/DashboardTemplateVariables.tsx b/frontend/src/scenes/dashboard/DashboardTemplateVariables.tsx
index b9be7b4d5167..b17486017fc7 100644
--- a/frontend/src/scenes/dashboard/DashboardTemplateVariables.tsx
+++ b/frontend/src/scenes/dashboard/DashboardTemplateVariables.tsx
@@ -3,10 +3,11 @@ import { useEffect } from 'react'
import { LemonLabel } from '@posthog/lemon-ui'
-import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'
+import { SeriesActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'
-import { FilterType } from '~/types'
+import { ChartDisplayCategory } from '~/types'
+import { seriesToTemplateVariableStep, templateVariableStepToSeries } from './dashboardTemplateEntities'
import { dashboardTemplateVariablesLogic } from './dashboardTemplateVariablesLogic'
import { newDashboardLogic } from './newDashboardLogic'
@@ -34,13 +35,10 @@ export function DashboardTemplateVariables(): JSX.Element {
<p className="text-sm text-secondary">{variable.description}</p>
</div>
<div>
- <ActionFilter
- filters={{
- events: [variable.default],
- }}
- setFilters={(filters: FilterType) => {
- setVariable(variable.name, filters)
- }}
+ <SeriesActionFilter
+ series={templateVariableStepToSeries(variable.default)}
+ onChange={(series) => setVariable(variable.name, seriesToTemplateVariableStep(series))}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
typeKey={'variable_' + variable.name}
hideDeleteBtn={true}
hideRename={true}
diff --git a/frontend/src/scenes/dashboard/dashboardTemplateEntities.test.ts b/frontend/src/scenes/dashboard/dashboardTemplateEntities.test.ts
new file mode 100644
index 000000000000..a88aee45a0a4
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboardTemplateEntities.test.ts
@@ -0,0 +1,132 @@
+import { SeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+import { BaseMathType, EntityTypes, TemplateVariableStep } from '~/types'
+
+import { seriesToTemplateVariableStep, templateVariableStepToSeries } from './dashboardTemplateEntities'
+
+const currentUrlContainsPricing = { key: '$current_url', value: 'pricing', operator: 'icontains', type: 'event' }
+
+describe('dashboardTemplateEntities', () => {
+ test.each<[string, TemplateVariableStep, Record<string, unknown>]>([
+ [
+ 'an event keeps its math, custom name and properties, and drops a stored event key',
+ {
+ id: '$pageview',
+ event: '$pageview',
+ math: BaseMathType.UniqueUsers,
+ type: EntityTypes.EVENTS,
+ order: 2,
+ name: '$pageview',
+ custom_name: 'Pricing page views',
+ properties: [currentUrlContainsPricing],
+ },
+ {
+ id: '$pageview',
+ math: BaseMathType.UniqueUsers,
+ type: EntityTypes.EVENTS,
+ order: 0,
+ name: '$pageview',
+ custom_name: 'Pricing page views',
+ properties: [currentUrlContainsPricing],
+ },
+ ],
+ [
+ 'an event the project never captured keeps its custom event flag',
+ { id: 'signed_up', custom_event: true, type: EntityTypes.EVENTS, name: 'signed_up' },
+ { id: 'signed_up', custom_event: true, type: EntityTypes.EVENTS, name: 'signed_up', order: 0 },
+ ],
+ [
+ 'an action keeps its element selector and comes back with a numeric id',
+ {
+ id: '42',
+ math: BaseMathType.UniqueUsers,
+ name: 'Clicked sign up',
+ custom_name: 'Sign ups',
+ order: 0,
+ type: EntityTypes.ACTIONS,
+ selector: 'button.signup',
+ href: '/signup',
+ url: 'https://example.com',
+ },
+ {
+ id: 42,
+ math: BaseMathType.UniqueUsers,
+ name: 'Clicked sign up',
+ custom_name: 'Sign ups',
+ order: 0,
+ type: EntityTypes.ACTIONS,
+ selector: 'button.signup',
+ href: '/signup',
+ url: 'https://example.com',
+ },
+ ],
+ [
+ 'a group keeps its operator and nested event and action',
+ {
+ type: EntityTypes.GROUPS,
+ name: 'Signed up or purchased',
+ math: BaseMathType.UniqueUsers,
+ operator: 'OR',
+ order: 0,
+ nestedFilters: [
+ { id: 'signed_up', type: EntityTypes.EVENTS, name: 'signed_up', order: 0 },
+ {
+ id: '12',
+ type: EntityTypes.ACTIONS,
+ name: 'Purchased',
+ order: 1,
+ properties: [currentUrlContainsPricing],
+ },
+ ],
+ } as TemplateVariableStep,
+ {
+ id: null,
+ type: EntityTypes.GROUPS,
+ name: 'Signed up or purchased',
+ math: BaseMathType.UniqueUsers,
+ operator: 'OR',
+ order: 0,
+ nestedFilters: [
+ { id: 'signed_up', type: EntityTypes.EVENTS, name: 'signed_up', order: 0 },
+ {
+ id: 12,
+ type: EntityTypes.ACTIONS,
+ name: 'Purchased',
+ order: 1,
+ properties: [currentUrlContainsPricing],
+ },
+ ],
+ },
+ ],
+ ])('%s', (_, stored, expected) => {
+ expect(seriesToTemplateVariableStep(templateVariableStepToSeries(stored))).toEqual(expected)
+ })
+
+ test.each<[string, SeriesNode[], Record<string, unknown> | undefined]>([
+ ['no rows store no step', [], undefined],
+ [
+ 'a row the picker built drops its node version and keeps its math',
+ [
+ {
+ kind: NodeKind.EventsNode,
+ event: '$pageview',
+ name: '$pageview',
+ math: 'total',
+ version: 1,
+ } as SeriesNode,
+ ],
+ { id: '$pageview', type: EntityTypes.EVENTS, name: '$pageview', math: 'total', order: 0 },
+ ],
+ [
+ 'an action row wins over an earlier event row and keeps its own index',
+ [
+ { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },
+ { kind: NodeKind.ActionsNode, id: 7, name: 'Purchased' },
+ ],
+ { id: 7, type: EntityTypes.ACTIONS, name: 'Purchased', order: 1 },
+ ],
+ ])('%s', (_, series, expected) => {
+ expect(seriesToTemplateVariableStep(series)).toEqual(expected)
+ })
+})
diff --git a/frontend/src/scenes/dashboard/dashboardTemplateEntities.ts b/frontend/src/scenes/dashboard/dashboardTemplateEntities.ts
index 3b1e81c4af26..2ebff1d6f1b1 100644
--- a/frontend/src/scenes/dashboard/dashboardTemplateEntities.ts
+++ b/frontend/src/scenes/dashboard/dashboardTemplateEntities.ts
@@ -1,3 +1,4 @@
+import { convertPropertyGroupToProperties } from 'lib/components/PropertyFilters/utils'
import { objectCleanWithEmpty } from 'lib/utils/objects'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'
import {
@@ -5,6 +6,15 @@ import {
calendarHeatmapMathTypes,
funnelsMathTypes,
} from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'
+import {
+ SeriesNode,
+ isActionsSeriesNode,
+ isEventsSeriesNode,
+ isGroupSeriesNode,
+ isWarehouseSeriesNode,
+ seriesNodeEntityType,
+ toActionId,
+} from 'scenes/insights/filters/ActionFilter/seriesNode'
import { cleanEntityProperties } from '~/queries/nodes/InsightQuery/utils/cleanProperties'
import { setLatestVersionsOnQuery } from '~/queries/schema/query-versions'
@@ -28,6 +38,7 @@ import {
FunnelDatawarehouseFilter,
LifecycleDatawarehouseFilter,
RetentionEntity,
+ TemplateVariableStep,
TrendsDataWarehouseFilter,
isDataWarehouseFilter,
isGroupFilter,
@@ -182,3 +193,79 @@ export const sanitizeRetentionEntity = (entity: RetentionEntity | undefined): Re
...('custom_name' in entity ? { custom_name } : {}),
}
}
+
+const STEP_IDENTITY_KEYS = ['type', 'id', 'order', 'index', 'nestedFilters', 'uuid']
+const NODE_IDENTITY_KEYS = ['kind', 'version', 'event', 'id', 'nodes']
+
+/** When the picker holds more than one row, the first row of the earliest type here is the one stored. */
+const TEMPLATE_STEP_TYPES = [EntityTypes.ACTIONS, EntityTypes.EVENTS, EntityTypes.DATA_WAREHOUSE, EntityTypes.GROUPS]
+
+type TemplateStep = TemplateVariableStep & { nestedFilters?: TemplateStep[] }
+
+function omitKeys(source: Record<string, any>, keys: string[]): Record<string, any> {
+ return Object.fromEntries(Object.entries(source).filter(([key]) => !keys.includes(key)))
+}
+
+export function templateVariableStepToSeries(step: TemplateVariableStep | undefined): SeriesNode[] {
+ return step ? [templateStepToSeriesNode(step)] : []
+}
+
+function templateStepToSeriesNode(step: TemplateStep): SeriesNode {
+ const shared = omitKeys(step, STEP_IDENTITY_KEYS)
+ if (Array.isArray(shared.properties)) {
+ shared.properties = convertPropertyGroupToProperties(shared.properties)
+ }
+
+ if (step.type === EntityTypes.ACTIONS) {
+ return { ...shared, kind: NodeKind.ActionsNode, id: toActionId(step.id) } as SeriesNode
+ }
+ if (step.type === EntityTypes.GROUPS) {
+ return {
+ ...shared,
+ kind: NodeKind.GroupNode,
+ nodes: (step.nestedFilters ?? []).map(templateStepToSeriesNode),
+ } as SeriesNode
+ }
+ if (step.type === EntityTypes.DATA_WAREHOUSE) {
+ // The table name is the node's key, and a step may carry it only as its `id`.
+ const tableName = shared.table_name ?? (typeof step.id === 'string' ? step.id : undefined)
+ return {
+ ...shared,
+ kind: NodeKind.DataWarehouseNode,
+ table_name: tableName,
+ id: tableName ?? step.id,
+ } as SeriesNode
+ }
+ return { ...shared, kind: NodeKind.EventsNode, event: step.id } as SeriesNode
+}
+
+export function seriesToTemplateVariableStep(series: SeriesNode[]): TemplateVariableStep | undefined {
+ for (const type of TEMPLATE_STEP_TYPES) {
+ const order = series.findIndex((node) => seriesNodeEntityType(node) === type)
+ if (order >= 0) {
+ return seriesNodeToTemplateStep(series[order], order)
+ }
+ }
+ return undefined
+}
+
+function seriesNodeToTemplateStep(node: SeriesNode, order: number): TemplateStep {
+ let id: string | number | null = null
+ if (isEventsSeriesNode(node)) {
+ id = node.event ?? null
+ } else if (isActionsSeriesNode(node)) {
+ id = node.id
+ } else if (isWarehouseSeriesNode(node)) {
+ id = node.table_name
+ }
+
+ return {
+ ...omitKeys(node, NODE_IDENTITY_KEYS),
+ ...(isGroupSeriesNode(node)
+ ? { nestedFilters: node.nodes.map((nested, nestedOrder) => seriesNodeToTemplateStep(nested, nestedOrder)) }
+ : {}),
+ id,
+ type: seriesNodeEntityType(node),
+ order,
+ } as TemplateStep
+}
diff --git a/frontend/src/scenes/dashboard/dashboardTemplateVariablesLogic.ts b/frontend/src/scenes/dashboard/dashboardTemplateVariablesLogic.ts
index a72e4bcfed81..d3685adaa7b3 100644
--- a/frontend/src/scenes/dashboard/dashboardTemplateVariablesLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboardTemplateVariablesLogic.ts
@@ -16,15 +16,7 @@ import { iframedToolbarBrowserLogic } from 'lib/components/IframedToolbarBrowser
import { PostHogAppToolbarEvent } from 'lib/components/IframedToolbarBrowser/utils'
import { isEmptyObject } from 'lib/utils/guards'
-import {
- ActionType,
- BaseMathType,
- DashboardTemplateVariableType,
- EntityType,
- EntityTypes,
- FilterType,
- TemplateVariableStep,
-} from '~/types'
+import { ActionType, BaseMathType, DashboardTemplateVariableType, EntityTypes, TemplateVariableStep } from '~/types'
export interface DashboardTemplateVariablesLogicProps {
variables: DashboardTemplateVariableType[]
@@ -85,9 +77,9 @@ export interface dashboardTemplateVariablesLogicActions {
}
setVariable: (
variableName: string,
- filterGroup: FilterType
+ step: TemplateVariableStep | undefined
) => {
- filterGroup: FilterType
+ step: TemplateVariableStep | undefined
variable_name: string
}
setVariableForPageview: (
@@ -139,9 +131,9 @@ export const dashboardTemplateVariablesLogic = kea<dashboardTemplateVariablesLog
})),
actions({
setVariables: (variables: DashboardTemplateVariableType[]) => ({ variables }),
- setVariable: (variableName: string, filterGroup: FilterType) => ({
+ setVariable: (variableName: string, step: TemplateVariableStep | undefined) => ({
variable_name: variableName,
- filterGroup,
+ step,
}),
setVariableFromAction: (variableName: string, action: ActionType) => ({ variableName, action }),
setVariableForPageview: (variableName: string, url: string) => ({ variableName, url }),
@@ -167,24 +159,14 @@ export const dashboardTemplateVariablesLogic = kea<dashboardTemplateVariablesLog
return { ...v, default: FALLBACK_EVENT } as unknown as DashboardTemplateVariableType
})
},
- setVariable: (state, { variable_name: variableName, filterGroup }): DashboardTemplateVariableType[] => {
- // There is only one type with contents at a time
- // So iterate through the types to find the first one with contents
- const typeWithContents: EntityType = Object.keys(filterGroup).filter(
- (group) => (filterGroup[group as EntityType] || [])?.length > 0
- )?.[0] as EntityType
-
- if (!typeWithContents) {
+ setVariable: (state, { variable_name: variableName, step }): DashboardTemplateVariableType[] => {
+ if (!step) {
return state
}
return state.map((v: DashboardTemplateVariableType) => {
- if (
- v.name === variableName &&
- filterGroup?.[typeWithContents]?.length &&
- filterGroup?.[typeWithContents]?.[0]
- ) {
- return { ...v, default: filterGroup[typeWithContents]?.[0] || {}, touched: true }
+ if (v.name === variableName) {
+ return { ...v, default: step, touched: true }
}
return { ...v }
})
@@ -272,10 +254,7 @@ export const dashboardTemplateVariablesLogic = kea<dashboardTemplateVariablesLog
href: action.steps?.[0]?.href,
url: action.steps?.[0]?.url,
}
- const filterGroup: FilterType = {
- actions: [step],
- }
- actions.setVariable(originalVariableName, filterGroup)
+ actions.setVariable(originalVariableName, step)
actions.setIsCurrentlySelectingElement(false)
},
setVariableForPageview: ({ variableName, url }) => {
@@ -295,10 +274,7 @@ export const dashboardTemplateVariablesLogic = kea<dashboardTemplateVariablesLog
},
],
}
- const filterGroup: FilterType = {
- events: [step],
- }
- actions.setVariable(variableName, filterGroup)
+ actions.setVariable(variableName, step)
actions.setIsCurrentlySelectingElement(false)
},
setVariableForScreenview: ({ variableName }) => {
@@ -310,10 +286,7 @@ export const dashboardTemplateVariablesLogic = kea<dashboardTemplateVariablesLog
name: '$screenview',
custom_name: variableName,
}
- const filterGroup: FilterType = {
- events: [step],
- }
- actions.setVariable(variableName, filterGroup)
+ actions.setVariable(variableName, step)
actions.setIsCurrentlySelectingElement(false)
},
toolbarMessageReceived: ({ type, payload }) => {
diff --git a/products/product_analytics/frontend/insights/retention/editor/RetentionCondition.tsx b/products/product_analytics/frontend/insights/retention/editor/RetentionCondition.tsx
index b6e07be0e49e..5d5a0853615d 100644
--- a/products/product_analytics/frontend/insights/retention/editor/RetentionCondition.tsx
+++ b/products/product_analytics/frontend/insights/retention/editor/RetentionCondition.tsx
@@ -9,17 +9,18 @@ import { DataWarehousePopoverField, TaxonomicFilterGroupType } from 'lib/compone
import { keyForInsightLogicProps } from 'lib/insights/sharedUtils'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { getOrdinalSuffix } from 'lib/utils/strings'
-import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'
+import { SeriesActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'
import { groupsModel } from '~/models/groupsModel'
-import { EditorFilterProps, EntityTypes, FilterType, RetentionPeriod, RetentionType } from '~/types'
+import { ChartDisplayCategory, EditorFilterProps, RetentionPeriod, RetentionType } from '~/types'
import { getRetentionPropertyFilterGroupTypes } from 'products/product_analytics/frontend/insights/editor/propertyTaxonomicGroupTypes'
import { AggregationSelect } from 'products/product_analytics/frontend/insights/shared/AggregationSelect'
import { dateOptionPlurals, dateOptions, retentionOptionDescriptions, retentionOptions } from '../constants'
import { MAX_BRACKETS, retentionLogic } from '../retentionLogic'
+import { retentionEntityToSeries, seriesToRetentionEntity } from './retentionEntitySeries'
const MAX_RANGE = 1000
@@ -34,33 +35,6 @@ const actionsTaxonomicGroupTypes = [
TaxonomicFilterGroupType.DataWarehouse,
]
-function retentionEntityToFilter(entity: Record<string, any> | undefined): FilterType {
- if (!entity) {
- return {}
- }
-
- if (entity.type === EntityTypes.ACTIONS) {
- return { actions: [entity] }
- }
- if (entity.type === EntityTypes.DATA_WAREHOUSE) {
- return { data_warehouse: [entity] }
- }
- return { events: [entity] }
-}
-
-function filterToRetentionEntity(newFilters: FilterType): Record<string, any> | undefined {
- if (newFilters.events && newFilters.events.length > 0) {
- return newFilters.events[0]
- }
- if (newFilters.actions && newFilters.actions.length > 0) {
- return newFilters.actions[0]
- }
- if (newFilters.data_warehouse && newFilters.data_warehouse.length > 0) {
- return newFilters.data_warehouse[0]
- }
- return undefined
-}
-
function CustomBrackets({ insightProps }: { insightProps: EditorFilterProps['insightProps'] }): JSX.Element {
const { retentionFilter, localCustomBrackets } = useValues(retentionLogic(insightProps))
const { updateInsightFilter, updateLocalCustomBracket, addCustomBracket, removeCustomBracket } = useActions(
@@ -178,14 +152,13 @@ export function RetentionCondition({ insightProps }: EditorFilterProps): JSX.Ele
)}
</div>
<div>who performed</div>
- <ActionFilter
+ <SeriesActionFilter
entitiesLimit={1}
mathAvailability={MathAvailability.None}
hideRename
- filters={retentionEntityToFilter(targetEntity)} // retention filters use target and returning entity instead of events
- setFilters={(newFilters: FilterType) => {
- updateInsightFilter({ targetEntity: filterToRetentionEntity(newFilters) })
- }}
+ series={retentionEntityToSeries(targetEntity)}
+ onChange={(series) => updateInsightFilter({ targetEntity: seriesToRetentionEntity(series) })}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
typeKey={`${keyForInsightLogicProps('new')(insightProps)}-targetEntity`}
propertiesTaxonomicGroupTypes={getRetentionPropertyFilterGroupTypes()}
actionsTaxonomicGroupTypes={actionsTaxonomicGroupTypes}
@@ -216,15 +189,14 @@ export function RetentionCondition({ insightProps }: EditorFilterProps): JSX.Ele
/>
<div>and then returned to perform</div>
- <ActionFilter
+ <SeriesActionFilter
entitiesLimit={1}
mathAvailability={MathAvailability.None}
hideRename
buttonCopy="Add graph series"
- filters={retentionEntityToFilter(returningEntity)}
- setFilters={(newFilters: FilterType) => {
- updateInsightFilter({ returningEntity: filterToRetentionEntity(newFilters) })
- }}
+ series={retentionEntityToSeries(returningEntity)}
+ onChange={(series) => updateInsightFilter({ returningEntity: seriesToRetentionEntity(series) })}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
typeKey={`${keyForInsightLogicProps('new')(insightProps)}-returningEntity`}
propertiesTaxonomicGroupTypes={getRetentionPropertyFilterGroupTypes()}
actionsTaxonomicGroupTypes={actionsTaxonomicGroupTypes}
diff --git a/products/product_analytics/frontend/insights/retention/editor/retentionEntitySeries.test.ts b/products/product_analytics/frontend/insights/retention/editor/retentionEntitySeries.test.ts
new file mode 100644
index 000000000000..a421fd38c46d
--- /dev/null
+++ b/products/product_analytics/frontend/insights/retention/editor/retentionEntitySeries.test.ts
@@ -0,0 +1,110 @@
+import { SeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+import { EntityTypes, PropertyFilterType, PropertyOperator, RetentionEntity } from '~/types'
+
+import { retentionEntityToSeries, seriesToRetentionEntity } from './retentionEntitySeries'
+
+const browserIsChrome = {
+ key: '$browser',
+ value: ['Chrome'],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+}
+
+describe('retentionEntitySeries', () => {
+ test.each<[string, Record<string, unknown>, Record<string, unknown>]>([
+ [
+ 'an event keeps its name, custom name and properties, and drops its stored uuid and kind',
+ {
+ id: '$pageview',
+ kind: NodeKind.EventsNode,
+ type: EntityTypes.EVENTS,
+ name: '$pageview',
+ custom_name: 'Viewed a page',
+ order: 3,
+ uuid: '0189e1f0-0000-0000-0000-000000000000',
+ properties: [browserIsChrome],
+ },
+ {
+ id: '$pageview',
+ type: EntityTypes.EVENTS,
+ name: '$pageview',
+ custom_name: 'Viewed a page',
+ order: 0,
+ properties: [browserIsChrome],
+ },
+ ],
+ [
+ 'all events keep a null id',
+ { id: null, type: EntityTypes.EVENTS, name: 'All events' },
+ { id: null, type: EntityTypes.EVENTS, name: 'All events', order: 0 },
+ ],
+ [
+ 'an action stored with a string id comes back with a numeric id',
+ { id: '12', type: EntityTypes.ACTIONS, name: 'Signed up', custom_name: 'Sign up' },
+ { id: 12, type: EntityTypes.ACTIONS, name: 'Signed up', custom_name: 'Sign up', order: 0 },
+ ],
+ [
+ 'a warehouse table keeps its popover fields',
+ {
+ id: 'stripe_charges',
+ type: EntityTypes.DATA_WAREHOUSE,
+ name: 'stripe_charges',
+ table_name: 'stripe_charges',
+ timestamp_field: 'created_at',
+ aggregation_target_field: 'customer_id',
+ },
+ {
+ id: 'stripe_charges',
+ type: EntityTypes.DATA_WAREHOUSE,
+ name: 'stripe_charges',
+ table_name: 'stripe_charges',
+ timestamp_field: 'created_at',
+ aggregation_target_field: 'customer_id',
+ order: 0,
+ },
+ ],
+ [
+ 'a warehouse table stored only by id gains its table name',
+ { id: 'stripe_charges', type: EntityTypes.DATA_WAREHOUSE, timestamp_field: 'created_at' },
+ {
+ id: 'stripe_charges',
+ type: EntityTypes.DATA_WAREHOUSE,
+ timestamp_field: 'created_at',
+ table_name: 'stripe_charges',
+ order: 0,
+ },
+ ],
+ [
+ 'an entity with no type reads as an event',
+ { id: 'signed_up', name: 'signed_up' },
+ { id: 'signed_up', type: EntityTypes.EVENTS, name: 'signed_up', order: 0 },
+ ],
+ ])('%s', (_, stored, expected) => {
+ expect(seriesToRetentionEntity(retentionEntityToSeries(stored as RetentionEntity))).toEqual(expected)
+ })
+
+ test.each<[string, SeriesNode[], Record<string, unknown> | undefined]>([
+ ['no rows store no entity', [], undefined],
+ [
+ 'a row the picker built drops its node version',
+ [{ kind: NodeKind.ActionsNode, id: 7, name: 'Purchased', version: 1 } as SeriesNode],
+ { id: 7, type: EntityTypes.ACTIONS, name: 'Purchased', order: 0 },
+ ],
+ [
+ 'an event row wins over an earlier action row and keeps its own index',
+ [
+ { kind: NodeKind.ActionsNode, id: 7, name: 'Purchased' },
+ { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },
+ ],
+ { id: '$pageview', type: EntityTypes.EVENTS, name: '$pageview', order: 1 },
+ ],
+ ])('%s', (_, series, expected) => {
+ expect(seriesToRetentionEntity(series)).toEqual(expected)
+ })
+
+ test('an absent entity shows no row', () => {
+ expect(retentionEntityToSeries(undefined)).toEqual([])
+ })
+})
diff --git a/products/product_analytics/frontend/insights/retention/editor/retentionEntitySeries.ts b/products/product_analytics/frontend/insights/retention/editor/retentionEntitySeries.ts
new file mode 100644
index 000000000000..4924b8007c9a
--- /dev/null
+++ b/products/product_analytics/frontend/insights/retention/editor/retentionEntitySeries.ts
@@ -0,0 +1,64 @@
+import { convertPropertyGroupToProperties } from 'lib/components/PropertyFilters/utils'
+import {
+ SeriesNode,
+ isActionsSeriesNode,
+ isEventsSeriesNode,
+ isWarehouseSeriesNode,
+ seriesNodeEntityType,
+ toActionId,
+} from 'scenes/insights/filters/ActionFilter/seriesNode'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+import { EntityTypes, RetentionEntity } from '~/types'
+
+const NODE_IDENTITY_KEYS = ['kind', 'version', 'event', 'id', 'nodes']
+
+/** When the picker holds more than one row, the first row of the earliest type here is the one stored. */
+const RETENTION_ENTITY_TYPES = [EntityTypes.EVENTS, EntityTypes.ACTIONS, EntityTypes.DATA_WAREHOUSE]
+
+export function retentionEntityToSeries(entity: RetentionEntity | undefined): SeriesNode[] {
+ if (!entity) {
+ return []
+ }
+ const { type, id, order, uuid, ...shared } = entity
+ if (Array.isArray(shared.properties)) {
+ shared.properties = convertPropertyGroupToProperties(shared.properties)
+ }
+
+ if (type === EntityTypes.ACTIONS) {
+ return [{ ...shared, kind: NodeKind.ActionsNode, id: toActionId(id) } as SeriesNode]
+ }
+ if (type === EntityTypes.DATA_WAREHOUSE) {
+ // The table name is the node's key, and an older entity may carry it only as its `id`.
+ const tableName = shared.table_name ?? (typeof id === 'string' ? id : undefined)
+ return [
+ { ...shared, kind: NodeKind.DataWarehouseNode, table_name: tableName, id: tableName ?? id } as SeriesNode,
+ ]
+ }
+ return [{ ...shared, kind: NodeKind.EventsNode, event: id } as SeriesNode]
+}
+
+export function seriesToRetentionEntity(series: SeriesNode[]): RetentionEntity | undefined {
+ for (const type of RETENTION_ENTITY_TYPES) {
+ const order = series.findIndex((node) => seriesNodeEntityType(node) === type)
+ if (order >= 0) {
+ return seriesNodeToRetentionEntity(series[order], order)
+ }
+ }
+ return undefined
+}
+
+function seriesNodeToRetentionEntity(node: SeriesNode, order: number): RetentionEntity {
+ const shared = Object.fromEntries(Object.entries(node).filter(([key]) => !NODE_IDENTITY_KEYS.includes(key)))
+
+ let id: RetentionEntity['id'] | null = null
+ if (isEventsSeriesNode(node)) {
+ id = node.event ?? null
+ } else if (isActionsSeriesNode(node)) {
+ id = node.id
+ } else if (isWarehouseSeriesNode(node)) {
+ id = node.table_name
+ }
+
+ return { ...shared, id, type: seriesNodeEntityType(node), order } as RetentionEntity
+}