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(experiments): edit experiment metric series as query nodes (#115906)

Thomas Obermüller6eda3292e6ac
diff --git a/frontend/src/scenes/experiments/ExperimentForm/ExposureCriteriaPanel.tsx b/frontend/src/scenes/experiments/ExperimentForm/ExposureCriteriaPanel.tsx
index e3a35352cf7d..5596ad3c9b3d 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/ExposureCriteriaPanel.tsx
+++ b/frontend/src/scenes/experiments/ExperimentForm/ExposureCriteriaPanel.tsx
@@ -6,12 +6,12 @@ import { LemonButton, LemonCollapse, LemonSelect, LemonTag, Tooltip } from '@pos
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-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 { teamLogic } from 'scenes/teamLogic'
import { ExperimentEventExposureConfig, ExperimentExposureCriteria, NodeKind } from '~/queries/schema/schema-general'
-import type { Experiment, FilterType } from '~/types'
+import { ChartDisplayCategory, type Experiment } from '~/types'
import { SelectableCard } from 'products/experiments/frontend/components/SelectableCard'
@@ -23,7 +23,7 @@ import {
resolvedExposureEvent,
} from '../exposureContract'
import { commonActionFilterProps } from '../Metrics/Selectors'
-import { exposureConfigToFilter, filterToExposureConfig } from '../utils'
+import { exposureConfigToSeries, seriesToExposureConfig } from '../utils'
const DEFAULT_EXPOSURE_CONFIG: ExperimentEventExposureConfig = {
kind: NodeKind.ExperimentEventExposureConfig,
@@ -51,13 +51,14 @@ function InclusionActionFilter({
onChange: ExposureCriteriaPanelProps['onChange']
}): JSX.Element {
return (
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={exposureConfigToFilter(experiment.exposure_criteria?.exposure_config || DEFAULT_EXPOSURE_CONFIG)}
- setFilters={({ events, actions }: Partial<FilterType>): void => {
- const entity = events?.[0] || actions?.[0]
- if (entity) {
- onChange({ exposure_config: filterToExposureConfig(entity) })
+ series={exposureConfigToSeries(experiment.exposure_criteria?.exposure_config || DEFAULT_EXPOSURE_CONFIG)}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
+ onChange={(series) => {
+ const exposureConfig = seriesToExposureConfig(series)
+ if (exposureConfig) {
+ onChange({ exposure_config: exposureConfig })
}
}}
typeKey="experiment-exposure-config"
@@ -81,15 +82,16 @@ function ActivationActionFilter({
onChange: ExposureCriteriaPanelProps['onChange']
}): JSX.Element {
return (
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={exposureConfigToFilter(
+ series={exposureConfigToSeries(
experiment.exposure_criteria?.activation_config || DEFAULT_ACTIVATION_CONFIG
)}
- setFilters={({ events, actions }: Partial<FilterType>): void => {
- const entity = events?.[0] || actions?.[0]
- if (entity) {
- onChange({ activation_config: filterToExposureConfig(entity) })
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
+ onChange={(series) => {
+ const activationConfig = seriesToExposureConfig(series)
+ if (activationConfig) {
+ onChange({ activation_config: activationConfig })
}
}}
typeKey="experiment-activation-config"
diff --git a/frontend/src/scenes/experiments/ExperimentMetricForm.test.tsx b/frontend/src/scenes/experiments/ExperimentMetricForm.test.tsx
index 50849f728980..02283250c567 100644
--- a/frontend/src/scenes/experiments/ExperimentMetricForm.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentMetricForm.test.tsx
@@ -18,24 +18,21 @@ jest.mock('~/layout/scenes/components/SceneContent', () => ({
}))
jest.mock('scenes/insights/filters/ActionFilter/ActionFilter', () => ({
- ActionFilter: ({ dataWarehousePopoverFields, setFilters }: Record<string, any>) => (
+ SeriesActionFilter: ({ dataWarehousePopoverFields, dataWarehouseNodeKind, onChange }: Record<string, any>) => (
<button
data-attr="select-data-warehouse-step"
onClick={() =>
- setFilters({
- actions: [],
- events: [],
- data_warehouse: [
- {
- id: 'stripe_charges',
- name: 'Stripe charges',
- timestamp_field: 'created_at',
- data_warehouse_join_key: 'customer_id',
- events_join_key: 'distinct_id',
- order: 0,
- },
- ],
- })
+ onChange([
+ {
+ kind: dataWarehouseNodeKind,
+ id: 'stripe_charges',
+ table_name: 'stripe_charges',
+ name: 'Stripe charges',
+ timestamp_field: 'created_at',
+ data_warehouse_join_key: 'customer_id',
+ events_join_key: 'distinct_id',
+ },
+ ])
}
>
{dataWarehousePopoverFields.map(({ key }: { key: string }) => key).join(',')}
diff --git a/frontend/src/scenes/experiments/ExperimentMetricForm.tsx b/frontend/src/scenes/experiments/ExperimentMetricForm.tsx
index b426e8dad215..7602d63ef433 100644
--- a/frontend/src/scenes/experiments/ExperimentMetricForm.tsx
+++ b/frontend/src/scenes/experiments/ExperimentMetricForm.tsx
@@ -13,7 +13,8 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { Link } from 'lib/lemon-ui/Link'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'
+import { SeriesActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'
+import { SeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
@@ -33,7 +34,12 @@ import {
isExperimentRatioMetric,
isExperimentRetentionMetric,
} from '~/queries/schema/schema-general'
-import { ExperimentMetricGoal, ExperimentMetricMathType, FilterType, FunnelConversionWindowTimeUnit } from '~/types'
+import {
+ ChartDisplayCategory,
+ ExperimentMetricGoal,
+ ExperimentMetricMathType,
+ FunnelConversionWindowTimeUnit,
+} from '~/types'
import { ExperimentMetricConversionWindowFilter } from './ExperimentMetricConversionWindowFilter'
import { ExperimentMetricFunnelOrderSelector } from './ExperimentMetricFunnelOrderSelector'
@@ -43,8 +49,7 @@ import {
} from './ExperimentMetricOutlierHandling'
import { ExperimentMetricThreshold, isThresholdAvailableForMath } from './ExperimentMetricThreshold'
import { EXPOSURE_DEFAULT_EVENT, getActivationConfig, isDefaultExposureConfig } from './exposureContract'
-import { filterToMetricConfig, filterToMetricSource } from './metricQueryUtils'
-import { createFilterForSource, getFilter } from './metricQueryUtils'
+import { seriesToMetricConfig, seriesToMetricSource } from './metricQueryUtils'
import { commonActionFilterProps } from './Metrics/Selectors'
import {
getAllowedMathTypes,
@@ -168,8 +173,8 @@ export function ExperimentMetricForm({
return 'events'
}
- const handleSetFilters = ({ actions, events, data_warehouse }: Partial<FilterType>): void => {
- const metricConfig = filterToMetricConfig(metric.metric_type, actions, events, data_warehouse)
+ const handleSetSeries = (series: SeriesNode[]): void => {
+ const metricConfig = seriesToMetricConfig(metric.metric_type, series)
if (metricConfig) {
const updatedMetric = { ...metric, ...metricConfig }
/**
@@ -266,8 +271,6 @@ export function ExperimentMetricForm({
},
]
- const metricFilter = getFilter(metric)
-
// dependencies for the loadEventCount useEffect call
const meanSource = isExperimentMeanMetric(metric) ? metric.source : null
const funnelSeries = isExperimentFunnelMetric(metric) ? metric.series : null
@@ -362,10 +365,12 @@ export function ExperimentMetricForm({
{isExperimentMeanMetric(metric) && (
<>
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={metricFilter}
- setFilters={handleSetFilters}
+ series={[metric.source]}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
+ dataWarehouseNodeKind={NodeKind.ExperimentDataWarehouseNode}
+ onChange={handleSetSeries}
typeKey="experiment-metric"
buttonCopy="Add graph series"
showSeriesIndicator={false}
@@ -409,10 +414,12 @@ export function ExperimentMetricForm({
)}
{isExperimentFunnelMetric(metric) && (
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={metricFilter}
- setFilters={handleSetFilters}
+ series={metric.series}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
+ dataWarehouseNodeKind={NodeKind.ExperimentDataWarehouseNode}
+ onChange={handleSetSeries}
typeKey="experiment-metric"
buttonCopy="Add step"
showSeriesIndicator={false}
@@ -432,15 +439,13 @@ export function ExperimentMetricForm({
<div className="space-y-4">
<div>
<LemonLabel className="mb-1">Numerator (what you're measuring)</LemonLabel>
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={createFilterForSource(metric.numerator)}
- setFilters={(filters) => {
- const source = filterToMetricSource(
- filters.actions,
- filters.events,
- filters.data_warehouse
- )
+ series={[metric.numerator]}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
+ dataWarehouseNodeKind={NodeKind.ExperimentDataWarehouseNode}
+ onChange={(series) => {
+ const source = seriesToMetricSource(series)
if (source) {
handleSetMetric({
...metric,
@@ -462,15 +467,13 @@ export function ExperimentMetricForm({
</div>
<div>
<LemonLabel className="mb-1">Denominator (what you're dividing by)</LemonLabel>
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={createFilterForSource(metric.denominator)}
- setFilters={(filters) => {
- const source = filterToMetricSource(
- filters.actions,
- filters.events,
- filters.data_warehouse
- )
+ series={[metric.denominator]}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
+ dataWarehouseNodeKind={NodeKind.ExperimentDataWarehouseNode}
+ onChange={(series) => {
+ const source = seriesToMetricSource(series)
if (source) {
handleSetMetric({
...metric,
@@ -552,15 +555,13 @@ export function ExperimentMetricForm({
: "Retention starts from each user's first exposure to the experiment."}
</div>
) : (
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={createFilterForSource(metric.start_event)}
- setFilters={(filters) => {
- const source = filterToMetricSource(
- filters.actions,
- filters.events,
- filters.data_warehouse
- )
+ series={[metric.start_event]}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
+ dataWarehouseNodeKind={NodeKind.ExperimentDataWarehouseNode}
+ onChange={(series) => {
+ const source = seriesToMetricSource(series)
if (source) {
handleSetMetric({ ...metric, start_event: source })
}
@@ -586,15 +587,13 @@ export function ExperimentMetricForm({
<IconInfo className="ml-1 text-muted" />
</Tooltip>
</LemonLabel>
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={createFilterForSource(metric.completion_event)}
- setFilters={(filters) => {
- const source = filterToMetricSource(
- filters.actions,
- filters.events,
- filters.data_warehouse
- )
+ series={[metric.completion_event]}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
+ dataWarehouseNodeKind={NodeKind.ExperimentDataWarehouseNode}
+ onChange={(series) => {
+ const source = seriesToMetricSource(series)
if (source) {
handleSetMetric({ ...metric, completion_event: source })
}
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExposureCriteria.tsx b/frontend/src/scenes/experiments/ExperimentView/ExposureCriteria.tsx
index 0a3d48d025b4..659a2f3dd88e 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExposureCriteria.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExposureCriteria.tsx
@@ -6,19 +6,19 @@ import { LemonModal } from '@posthog/lemon-ui'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-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 { teamLogic } from 'scenes/teamLogic'
import { ExperimentExposureCriteria, NodeKind } from '~/queries/schema/schema-general'
-import { FilterType } from '~/types'
+import { ChartDisplayCategory } from '~/types'
import { SelectableCard } from 'products/experiments/frontend/components/SelectableCard'
import { experimentLogic } from '../experimentLogic'
import { EXPOSURE_DEFAULT_EVENT, getActivationConfig } from '../exposureContract'
import { commonActionFilterProps } from '../Metrics/Selectors'
-import { exposureConfigToFilter, filterToExposureConfig } from '../utils'
+import { exposureConfigToSeries, seriesToExposureConfig } from '../utils'
import { exposureCriteriaModalLogic } from './exposureCriteriaModalLogic'
type ExposureCriteriaModalProps = {
@@ -151,15 +151,16 @@ export function ExposureCriteriaModal({ onSave }: ExposureCriteriaModalProps): J
</div>
{isCustom && exposureCriteria?.exposure_config && (
<div className="mb-4">
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={exposureConfigToFilter(exposureCriteria.exposure_config)}
- setFilters={({ events, actions }: Partial<FilterType>): void => {
- const entity = events?.[0] || actions?.[0]
- if (entity) {
+ series={exposureConfigToSeries(exposureCriteria.exposure_config)}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
+ onChange={(series) => {
+ const exposureConfig = seriesToExposureConfig(series)
+ if (exposureConfig) {
setExposureCriteria({
...exposureCriteria,
- exposure_config: filterToExposureConfig(entity),
+ exposure_config: exposureConfig,
})
}
}}
@@ -177,15 +178,16 @@ export function ExposureCriteriaModal({ onSave }: ExposureCriteriaModalProps): J
)}
{isActivation && exposureCriteria?.activation_config && (
<div className="mb-4">
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={exposureConfigToFilter(exposureCriteria.activation_config)}
- setFilters={({ events, actions }: Partial<FilterType>): void => {
- const entity = events?.[0] || actions?.[0]
- if (entity) {
+ series={exposureConfigToSeries(exposureCriteria.activation_config)}
+ trendsDisplayCategory={ChartDisplayCategory.TimeSeries}
+ onChange={(series) => {
+ const activationConfig = seriesToExposureConfig(series)
+ if (activationConfig) {
setExposureCriteria({
...exposureCriteria,
- activation_config: filterToExposureConfig(entity),
+ activation_config: activationConfig,
})
}
}}
diff --git a/frontend/src/scenes/experiments/metricQueryUtils.test.ts b/frontend/src/scenes/experiments/metricQueryUtils.test.ts
index 3339158083a6..9f29103190d2 100644
--- a/frontend/src/scenes/experiments/metricQueryUtils.test.ts
+++ b/frontend/src/scenes/experiments/metricQueryUtils.test.ts
@@ -1,30 +1,29 @@
import { EXPERIMENT_DEFAULT_DURATION, FunnelLayout } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
+import { getDefaultEventLabel, getDefaultEventName } from 'lib/utils/getAppContext'
+import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'
+import { SeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'
import type {
ActionsNode,
EventsNode,
ExperimentDataWarehouseNode,
+ ExperimentFunnelMetricStep,
ExperimentMetric,
} from '~/queries/schema/schema-general'
import { ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'
import { setLatestVersionsOnQuery } from '~/queries/utils'
+import { initKeaTests } from '~/test/init'
import {
ChartDisplayType,
ExperimentMetricMathType,
+ FilterLogicalOperator,
PropertyFilterType,
PropertyMathType,
PropertyOperator,
} from '~/types'
-import {
- createFilterForSource,
- filterToMetricConfig,
- filterToMetricSource,
- getFilter,
- getMathProperties,
- getQuery,
-} from './metricQueryUtils'
+import { getMathProperties, getQuery, seriesToMetricConfig, seriesToMetricSource } from './metricQueryUtils'
// getQuery builds date_from/date_to from dayjs() at call time, formatted to the minute.
// The expected values below recompute dayjs() independently, so a minute rollover between
@@ -38,385 +37,220 @@ afterAll(() => {
jest.useRealTimers()
})
-describe('getFilter', () => {
- it('returns the correct filter for an event', () => {
- const metric: ExperimentMetric = {
- kind: NodeKind.ExperimentMetric,
- metric_type: ExperimentMetricType.MEAN,
- source: {
- kind: NodeKind.EventsNode,
- event: '$pageview',
- name: '$pageview',
- math: ExperimentMetricMathType.TotalCount,
- math_property: undefined,
- math_hogql: undefined,
- properties: [{ key: '$browser', value: ['Chrome'], operator: 'exact', type: 'event' }],
- } as EventsNode,
- }
- const filter = getFilter(metric)
- expect(filter).toEqual({
- events: [
- {
- id: '$pageview',
- name: '$pageview',
- event: '$pageview',
- type: 'events',
- math: ExperimentMetricMathType.TotalCount,
- math_property: undefined,
- math_hogql: undefined,
- properties: [{ key: '$browser', value: ['Chrome'], operator: 'exact', type: 'event' }],
- kind: NodeKind.EventsNode,
- },
- ],
- actions: [],
- data_warehouse: [],
- })
- })
- it('returns the correct filter for an action', () => {
- const metric: ExperimentMetric = {
- kind: NodeKind.ExperimentMetric,
- metric_type: ExperimentMetricType.MEAN,
- source: {
- kind: NodeKind.ActionsNode,
- id: 8,
- name: 'jan-16-running payment action',
- math: ExperimentMetricMathType.TotalCount,
- math_property: undefined,
- math_hogql: undefined,
- properties: [{ key: '$lib', type: 'event', value: ['python'], operator: 'exact' }],
- } as ActionsNode,
+describe('seriesToMetricSource', () => {
+ const pickedTable = {
+ table_name: 'stripe_charges',
+ name: 'stripe_charges',
+ timestamp_field: 'created_at',
+ events_join_key: 'distinct_id',
+ data_warehouse_join_key: 'customer_id',
+ math: ExperimentMetricMathType.Sum,
+ math_property: 'amount',
+ }
+
+ it.each([NodeKind.ExperimentDataWarehouseNode, NodeKind.DataWarehouseNode] as const)(
+ 'stores a table picked as %s as an experiment warehouse node, without the id the picker mirrors',
+ (kind) => {
+ const series = [{ ...pickedTable, kind, id: 'stripe_charges' }] as SeriesNode[]
+
+ expect(seriesToMetricSource(series)).toEqual({
+ ...pickedTable,
+ kind: NodeKind.ExperimentDataWarehouseNode,
+ })
}
- const filter = getFilter(metric)
- expect(filter).toEqual({
- events: [],
- actions: [
- {
- id: 8,
- name: 'jan-16-running payment action',
- type: 'actions',
- math: ExperimentMetricMathType.TotalCount,
- math_property: undefined,
- math_hogql: undefined,
- properties: [{ key: '$lib', type: 'event', value: ['python'], operator: 'exact' }],
- kind: NodeKind.ActionsNode,
- },
- ],
- data_warehouse: [],
- })
- })
-})
+ )
-describe('filterToMetricSource', () => {
- it('returns EventsNode when events are provided', () => {
- const events = [
- {
- id: '$pageview',
- name: '$pageview',
- math: ExperimentMetricMathType.TotalCount,
- math_property: 'revenue',
- math_hogql: 'sum(revenue)',
- properties: [],
- },
- ]
-
- const result = filterToMetricSource(undefined, events, undefined)
+ // Regression: an empty/null `event` must fall back to `name` so the event isn't dropped.
+ it.each([
+ ['empty string event (numerator path)', ''],
+ ['null event (denominator path)', null],
+ ])('recovers event from name when the node has %s', (_label, event) => {
+ const series: SeriesNode[] = [{ kind: NodeKind.EventsNode, event, name: 'purchase' }]
- expect(result).toEqual({
+ expect(seriesToMetricSource(series)).toEqual({
kind: NodeKind.EventsNode,
- event: '$pageview',
- name: '$pageview',
+ event: 'purchase',
+ name: 'purchase',
math: ExperimentMetricMathType.TotalCount,
- math_property: 'revenue',
- math_hogql: 'sum(revenue)',
- properties: [],
})
})
- it('returns ActionsNode when actions are provided', () => {
- const actions = [
- {
- id: 123,
- name: 'signup_action',
- math: ExperimentMetricMathType.Sum,
- math_property: 'value',
- properties: [],
- },
- ]
-
- const result = filterToMetricSource(actions, undefined, undefined)
-
- expect(result).toEqual({
- kind: NodeKind.ActionsNode,
- id: 123,
- name: 'signup_action',
+ it('keeps the session property math type and fixed properties the backend reads', () => {
+ const node: EventsNode = {
+ kind: NodeKind.EventsNode,
+ event: '$pageview',
+ name: '$pageview',
math: ExperimentMetricMathType.Sum,
- math_property: 'value',
- math_hogql: undefined,
- properties: [],
- })
- })
+ math_property: '$pageview_count',
+ math_property_type: 'session_properties',
+ fixedProperties: [
+ {
+ key: '$browser',
+ value: ['Chrome'],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ },
+ ],
+ }
- it('returns ExperimentDataWarehouseNode when data_warehouse is provided', () => {
- const dataWarehouse = [
- {
- id: 'user_events',
- name: 'User Events',
- timestamp_field: 'created_at',
- events_join_key: 'user_id',
- data_warehouse_join_key: 'customer_id',
- math: ExperimentMetricMathType.Avg,
- math_property: 'session_duration',
- properties: [],
- },
- ]
+ expect(seriesToMetricSource([node])).toEqual(node)
+ })
- const result = filterToMetricSource(undefined, undefined, dataWarehouse)
+ it.each([
+ ['no series', []],
+ ['a group', [{ kind: NodeKind.GroupNode, operator: FilterLogicalOperator.Or, nodes: [] }]],
+ ])('returns null for %s', (_label, series) => {
+ expect(seriesToMetricSource(series as SeriesNode[])).toBeNull()
+ })
+})
- expect(result).toEqual({
+describe('seriesToMetricConfig', () => {
+ const funnelSteps: ExperimentFunnelMetricStep[] = [
+ { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },
+ { kind: NodeKind.ActionsNode, id: 7, name: 'Signed up' },
+ {
kind: NodeKind.ExperimentDataWarehouseNode,
- name: 'User Events',
- table_name: 'user_events',
+ table_name: 'stripe_charges',
+ name: 'stripe_charges',
timestamp_field: 'created_at',
- events_join_key: 'user_id',
+ events_join_key: 'distinct_id',
data_warehouse_join_key: 'customer_id',
- math: ExperimentMetricMathType.Avg,
- math_property: 'session_duration',
- math_hogql: undefined,
- properties: [],
+ },
+ ]
+ const [pageviewStep, actionStep, tableStep] = funnelSteps
+
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ it.each<[string, (logic: ReturnType<typeof entityFilterLogic.build>) => void, ExperimentFunnelMetricStep[]]>([
+ [
+ 'adding a step',
+ (logic) => logic.actions.addSeries(),
+ [...funnelSteps, { kind: NodeKind.EventsNode, event: getDefaultEventName(), name: getDefaultEventLabel() }],
+ ],
+ [
+ 'picking a table for a step',
+ (logic) =>
+ logic.actions.updateSeriesEntity(0, {
+ kind: NodeKind.ExperimentDataWarehouseNode,
+ key: 'invoices',
+ name: 'invoices',
+ timestamp_field: 'paid_at',
+ data_warehouse_join_key: 'customer_id',
+ events_join_key: 'distinct_id',
+ }),
+ [
+ {
+ kind: NodeKind.ExperimentDataWarehouseNode,
+ table_name: 'invoices',
+ name: 'invoices',
+ timestamp_field: 'paid_at',
+ data_warehouse_join_key: 'customer_id',
+ events_join_key: 'distinct_id',
+ },
+ actionStep,
+ tableStep,
+ ],
+ ],
+ [
+ 'picking an event for a table step',
+ (logic) => logic.actions.updateSeriesEntity(2, { kind: NodeKind.EventsNode, key: 'paid', name: 'paid' }),
+ [pageviewStep, actionStep, { kind: NodeKind.EventsNode, event: 'paid', name: 'paid' }],
+ ],
+ [
+ 'renaming an action step',
+ (logic) => {
+ logic.actions.selectSeries(1, logic.values.localSeries[1].node, logic.values.localSeries[1].uuid)
+ logic.actions.renameSeries('Signup')
+ },
+ [pageviewStep, { ...actionStep, custom_name: 'Signup' }, tableStep],
+ ],
+ ['removing a step', (logic) => logic.actions.removeSeries(1), [pageviewStep, tableStep]],
+ [
+ 'reordering the steps',
+ (logic) => logic.actions.setLocalSeries([...logic.values.localSeries].reverse()),
+ [tableStep, actionStep, pageviewStep],
+ ],
+ ])('stores the funnel steps the picker emits after %s', (_label, edit, expectedSteps) => {
+ const onChange = jest.fn()
+ const logic = entityFilterLogic({
+ series: funnelSteps,
+ onChange,
+ typeKey: 'experiment-metric',
+ dataWarehouseNodeKind: NodeKind.ExperimentDataWarehouseNode,
+ dataWarehousePopoverFields: [
+ { key: 'timestamp_field', label: 'Timestamp Field' },
+ { key: 'data_warehouse_join_key', label: 'Data Warehouse Join Key' },
+ { key: 'events_join_key', label: 'Events Join Key' },
+ ],
})
- })
-
- it('returns null when no sources are provided', () => {
- const result = filterToMetricSource(undefined, undefined, undefined)
- expect(result).toBeNull()
- })
-
- it('prioritizes events over actions and data_warehouse', () => {
- const events = [{ id: 'event1', name: 'Event 1' }]
- const actions = [{ id: 1, name: 'Action 1' }]
- const dataWarehouse = [{ id: 'table1', name: 'Table 1' }]
-
- const result = filterToMetricSource(actions, events, dataWarehouse)
-
- expect(result?.kind).toBe(NodeKind.EventsNode)
- expect(result?.name).toBe('Event 1')
- })
-
- it('uses default math when not provided', () => {
- const events = [{ id: '$pageview', name: '$pageview' }]
-
- const result = filterToMetricSource(undefined, events, undefined)
-
- expect(result?.math).toBe(ExperimentMetricMathType.TotalCount)
- })
-
- // Regression: an empty/null `id` must fall back to `name` so the event isn't dropped.
- it.each([
- ['empty string id (numerator path)', ''],
- ['null id (denominator path)', null],
- ])('recovers event from name when id is %s', (_label, id) => {
- const events = [{ id, name: 'purchase', math: ExperimentMetricMathType.Sum, math_property: 'value' }]
+ logic.mount()
- const result = filterToMetricSource(undefined, events, undefined)
+ edit(logic)
- expect(result).toMatchObject({
- kind: NodeKind.EventsNode,
- event: 'purchase',
- name: 'purchase',
+ expect(seriesToMetricConfig(ExperimentMetricType.FUNNEL, onChange.mock.lastCall[0])).toEqual({
+ metric_type: ExperimentMetricType.FUNNEL,
+ series: expectedSteps,
})
})
-})
-describe('filterToMetricConfig', () => {
- it('returns FUNNEL metric config when funnel type is provided', () => {
- const events = [
- { id: 'step1', custom_name: 'Signed up', properties: [], order: 0 },
- { id: 'step2', custom_name: '', properties: [], order: 1 },
- ]
- const actions = [{ id: 123, name: 'action1', custom_name: 'Activated', properties: [], order: 2 }]
- const dataWarehouse = [
+ it('drops math and the optional flag from funnel steps', () => {
+ const series: SeriesNode[] = [
+ { kind: NodeKind.EventsNode, event: '$pageview', math: ExperimentMetricMathType.TotalCount },
{
- id: 'stripe_charges',
- name: 'Stripe charges',
- custom_name: 'Paid',
- timestamp_field: 'created_at',
- events_join_key: 'distinct_id',
- data_warehouse_join_key: 'customer_id',
- properties: [],
- order: 3,
+ kind: NodeKind.EventsNode,
+ event: 'purchase',
+ math: ExperimentMetricMathType.Sum,
+ math_property: 'amount',
+ optionalInFunnel: true,
},
]
- const result = filterToMetricConfig(ExperimentMetricType.FUNNEL, actions, events, dataWarehouse)
-
- expect(result).toEqual({
+ expect(seriesToMetricConfig(ExperimentMetricType.FUNNEL, series)).toEqual({
metric_type: ExperimentMetricType.FUNNEL,
series: [
- { kind: NodeKind.EventsNode, event: 'step1', custom_name: 'Signed up', properties: [] },
- { kind: NodeKind.EventsNode, event: 'step2', properties: [] },
- { kind: NodeKind.ActionsNode, id: 123, name: 'action1', custom_name: 'Activated', properties: [] },
- {
- kind: NodeKind.ExperimentDataWarehouseNode,
- table_name: 'stripe_charges',
- name: 'Stripe charges',
- custom_name: 'Paid',
- timestamp_field: 'created_at',
- events_join_key: 'distinct_id',
- data_warehouse_join_key: 'customer_id',
- properties: [],
- },
+ { kind: NodeKind.EventsNode, event: '$pageview' },
+ { kind: NodeKind.EventsNode, event: 'purchase' },
],
})
})
- it('keeps a data warehouse step in a FUNNEL metric config', () => {
- const events = [{ id: '$pageview', properties: [], order: 1 }]
- const dataWarehouse = [
+ it('keeps a renamed step of every kind and drops an empty rename', () => {
+ const series = [
+ { kind: NodeKind.EventsNode, event: 'step1', custom_name: 'Signed up' },
+ { kind: NodeKind.EventsNode, event: 'step2', custom_name: '' },
+ { kind: NodeKind.ActionsNode, id: 123, name: 'action1', custom_name: 'Activated' },
{
+ kind: NodeKind.ExperimentDataWarehouseNode,
id: 'stripe_charges',
+ table_name: 'stripe_charges',
name: 'Stripe charges',
+ custom_name: 'Paid',
timestamp_field: 'created_at',
events_join_key: 'distinct_id',
data_warehouse_join_key: 'customer_id',
- properties: [],
- order: 0,
},
- ]
-
- const result = filterToMetricConfig(ExperimentMetricType.FUNNEL, undefined, events, dataWarehouse)
+ ] as SeriesNode[]
- expect(result).toEqual({
+ expect(seriesToMetricConfig(ExperimentMetricType.FUNNEL, series)).toEqual({
metric_type: ExperimentMetricType.FUNNEL,
series: [
+ { kind: NodeKind.EventsNode, event: 'step1', custom_name: 'Signed up' },
+ { kind: NodeKind.EventsNode, event: 'step2' },
+ { kind: NodeKind.ActionsNode, id: 123, name: 'action1', custom_name: 'Activated' },
{
kind: NodeKind.ExperimentDataWarehouseNode,
table_name: 'stripe_charges',
name: 'Stripe charges',
+ custom_name: 'Paid',
timestamp_field: 'created_at',
events_join_key: 'distinct_id',
data_warehouse_join_key: 'customer_id',
- custom_name: undefined,
- properties: [],
},
- { kind: NodeKind.EventsNode, event: '$pageview', properties: [] },
],
})
})
-
- it('returns MEAN metric config when mean type is provided with events', () => {
- const events = [
- { id: 'purchase', name: 'Purchase Event', math: ExperimentMetricMathType.Sum, math_property: 'revenue' },
- ]
-
- const result = filterToMetricConfig(ExperimentMetricType.MEAN, undefined, events, undefined)
-
- expect(result).toEqual({
- metric_type: ExperimentMetricType.MEAN,
- source: {
- kind: NodeKind.EventsNode,
- event: 'purchase',
- name: 'Purchase Event',
- math: ExperimentMetricMathType.Sum,
- math_property: 'revenue',
- math_hogql: undefined,
- properties: undefined,
- },
- })
- })
-
- it('keeps funnel step order stable when filter order is missing', () => {
- const events = [{ id: 'first_event' }]
- const dataWarehouse = [
- {
- id: 'stripe_charges',
- name: 'Stripe charges',
- timestamp_field: 'created_at',
- events_join_key: 'distinct_id',
- data_warehouse_join_key: 'customer_id',
- },
- ]
-
- const result = filterToMetricConfig(ExperimentMetricType.FUNNEL, undefined, events, dataWarehouse)
-
- expect(result).toEqual({
- metric_type: ExperimentMetricType.FUNNEL,
- series: [
- expect.objectContaining({ kind: NodeKind.EventsNode, event: 'first_event' }),
- expect.objectContaining({
- kind: NodeKind.ExperimentDataWarehouseNode,
- table_name: 'stripe_charges',
- }),
- ],
- })
- })
-
- it('returns undefined when no valid sources are provided', () => {
- const result = filterToMetricConfig(ExperimentMetricType.MEAN, undefined, undefined, undefined)
- expect(result).toBeUndefined()
- })
-
- it('returns undefined for unsupported metric types', () => {
- const events = [{ id: 'event1', name: 'Event 1' }]
- const result = filterToMetricConfig('UNSUPPORTED' as ExperimentMetricType, undefined, events, undefined)
- expect(result).toBeUndefined()
- })
-})
-
-describe('createFilterForSource', () => {
- it('creates filter for EventsNode source', () => {
- const source: EventsNode = {
- kind: NodeKind.EventsNode,
- event: '$pageview',
- name: '$pageview',
- math: ExperimentMetricMathType.TotalCount,
- properties: [],
- }
-
- const result = createFilterForSource(source)
-
- expect(result.events).toHaveLength(1)
- expect(result.actions).toHaveLength(0)
- expect(result.data_warehouse).toHaveLength(0)
- expect(result.events?.[0]?.id).toBe('$pageview')
- expect(result.events?.[0]?.type).toBe('events')
- })
-
- it('creates filter for ActionsNode source', () => {
- const source: ActionsNode = {
- kind: NodeKind.ActionsNode,
- id: 123,
- name: 'signup_action',
- math: ExperimentMetricMathType.TotalCount,
- }
-
- const result = createFilterForSource(source)
-
- expect(result.events).toHaveLength(0)
- expect(result.actions).toHaveLength(1)
- expect(result.data_warehouse).toHaveLength(0)
- expect(result.actions?.[0]?.id).toBe(123)
- expect(result.actions?.[0]?.type).toBe('actions')
- })
-
- it('creates filter for ExperimentDataWarehouseNode source', () => {
- const source: ExperimentDataWarehouseNode = {
- kind: NodeKind.ExperimentDataWarehouseNode,
- name: 'revenue_table',
- table_name: 'revenue_table',
- timestamp_field: 'created_at',
- events_join_key: 'user_id',
- data_warehouse_join_key: 'customer_id',
- math: ExperimentMetricMathType.Sum,
- }
-
- const result = createFilterForSource(source)
-
- expect(result.events).toHaveLength(0)
- expect(result.actions).toHaveLength(0)
- expect(result.data_warehouse).toHaveLength(1)
- expect(result.data_warehouse?.[0]?.id).toBe('revenue_table')
- expect(result.data_warehouse?.[0]?.type).toBe('data_warehouse')
- })
})
describe('getQuery', () => {
@@ -701,122 +535,6 @@ describe('getQuery', () => {
})
describe('Data Warehouse Support', () => {
- describe('getFilter with data warehouse nodes', () => {
- it('returns the correct filter for a data warehouse mean metric', () => {
- const metric: ExperimentMetric = {
- kind: NodeKind.ExperimentMetric,
- metric_type: ExperimentMetricType.MEAN,
- source: {
- kind: NodeKind.ExperimentDataWarehouseNode,
- table_name: 'user_events',
- timestamp_field: 'created_at',
- events_join_key: 'user_id',
- data_warehouse_join_key: 'user_id',
- name: 'user_events',
- math: ExperimentMetricMathType.TotalCount,
- properties: [
- {
- key: 'event_type',
- value: ['purchase'],
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- },
- ],
- } as ExperimentDataWarehouseNode,
- }
- const filter = getFilter(metric)
- expect(filter).toEqual({
- events: [],
- actions: [],
- data_warehouse: [
- {
- id: 'user_events',
- name: 'user_events',
- type: 'data_warehouse',
- table_name: 'user_events',
- timestamp_field: 'created_at',
- events_join_key: 'user_id',
- data_warehouse_join_key: 'user_id',
- id_field: 'user_id',
- aggregation_target_field: 'user_id',
- math: ExperimentMetricMathType.TotalCount,
- properties: [
- {
- key: 'event_type',
- value: ['purchase'],
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- },
- ],
- kind: NodeKind.ExperimentDataWarehouseNode,
- },
- ],
- })
- })
-
- it('keeps data warehouse fields when converting a funnel metric to filters', () => {
- const metric: ExperimentMetric = {
- kind: NodeKind.ExperimentMetric,
- metric_type: ExperimentMetricType.FUNNEL,
- series: [
- {
- kind: NodeKind.EventsNode,
- event: '$pageview',
- name: '$pageview',
- } as EventsNode,
- {
- kind: NodeKind.ActionsNode,
- id: 42,
- name: 'subscription_action',
- } as ActionsNode,
- {
- kind: NodeKind.ExperimentDataWarehouseNode,
- table_name: 'stripe_charges',
- name: 'Stripe charges',
- timestamp_field: 'created_at',
- events_join_key: 'distinct_id',
- data_warehouse_join_key: 'customer_id',
- } as ExperimentDataWarehouseNode,
- ],
- }
- const filter = getFilter(metric)
- expect(filter).toEqual({
- events: [
- {
- id: '$pageview',
- name: '$pageview',
- event: '$pageview',
- type: 'events',
- order: 0,
- kind: NodeKind.EventsNode,
- },
- ],
- actions: [
- {
- id: 42,
- name: 'subscription_action',
- type: 'actions',
- order: 1,
- kind: NodeKind.ActionsNode,
- },
- ],
- data_warehouse: [
- expect.objectContaining({
- kind: NodeKind.ExperimentDataWarehouseNode,
- type: 'data_warehouse',
- table_name: 'stripe_charges',
- timestamp_field: 'created_at',
- events_join_key: 'distinct_id',
- data_warehouse_join_key: 'customer_id',
- id_field: 'customer_id',
- aggregation_target_field: 'distinct_id',
- order: 2,
- }),
- ],
- })
- })
- })
-
describe('getQuery with data warehouse nodes', () => {
it('returns the correct query for a data warehouse mean metric', () => {
const metric: ExperimentMetric = {
@@ -960,91 +678,6 @@ describe('Data Warehouse Support', () => {
expect(query).toBeUndefined()
})
})
-
- describe('Edge cases and validation', () => {
- it('handles empty data warehouse properties gracefully', () => {
- const metric: ExperimentMetric = {
- kind: NodeKind.ExperimentMetric,
- metric_type: ExperimentMetricType.MEAN,
- source: {
- kind: NodeKind.ExperimentDataWarehouseNode,
- table_name: '',
- timestamp_field: '',
- events_join_key: '',
- data_warehouse_join_key: '',
- name: '',
- math: ExperimentMetricMathType.TotalCount,
- } as ExperimentDataWarehouseNode,
- }
- const filter = getFilter(metric)
- expect(filter.data_warehouse).toHaveLength(1)
- expect(filter.data_warehouse?.[0]?.table_name).toBe('')
- })
-
- it('preserves custom names and properties for data warehouse nodes in mean metrics', () => {
- const metric: ExperimentMetric = {
- kind: NodeKind.ExperimentMetric,
- metric_type: ExperimentMetricType.MEAN,
- source: {
- kind: NodeKind.ExperimentDataWarehouseNode,
- table_name: 'analytics_events',
- timestamp_field: 'event_time',
- events_join_key: 'user_uuid',
- data_warehouse_join_key: 'user_external_id',
- name: 'analytics_events',
- custom_name: 'Custom Analytics Event',
- properties: [
- {
- key: 'category',
- value: ['conversion'],
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- },
- {
- key: 'value',
- value: [100],
- operator: PropertyOperator.GreaterThanOrEqual,
- type: PropertyFilterType.Event,
- },
- ],
- math: ExperimentMetricMathType.TotalCount,
- math_property: 'conversion_value',
- math_hogql: 'sum(conversion_value)',
- } as ExperimentDataWarehouseNode,
- }
- const filter = getFilter(metric)
- expect(filter.data_warehouse?.[0]).toEqual({
- id: 'analytics_events',
- name: 'analytics_events',
- type: 'data_warehouse',
- table_name: 'analytics_events',
- timestamp_field: 'event_time',
- events_join_key: 'user_uuid',
- data_warehouse_join_key: 'user_external_id',
- id_field: 'user_external_id',
- aggregation_target_field: 'user_uuid',
- custom_name: 'Custom Analytics Event',
- properties: [
- {
- key: 'category',
- value: ['conversion'],
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- },
- {
- key: 'value',
- value: [100],
- operator: PropertyOperator.GreaterThanOrEqual,
- type: PropertyFilterType.Event,
- },
- ],
- math: ExperimentMetricMathType.TotalCount,
- math_property: 'conversion_value',
- math_hogql: 'sum(conversion_value)',
- kind: NodeKind.ExperimentDataWarehouseNode,
- })
- })
- })
})
describe('getMathProperties', () => {
diff --git a/frontend/src/scenes/experiments/metricQueryUtils.ts b/frontend/src/scenes/experiments/metricQueryUtils.ts
index 8604be337fa2..fbd97087bbbc 100644
--- a/frontend/src/scenes/experiments/metricQueryUtils.ts
+++ b/frontend/src/scenes/experiments/metricQueryUtils.ts
@@ -3,7 +3,16 @@ import { match } from 'ts-pattern'
import { EXPERIMENT_DEFAULT_DURATION, FEATURE_FLAGS, FunnelLayout } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { isNotNil } from 'lib/utils/guards'
import { objectCleanWithEmpty } from 'lib/utils/objects'
+import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'
+import { cleanSeriesNodes } from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'
+import {
+ SeriesNode,
+ isActionsSeriesNode,
+ isEventsSeriesNode,
+ isWarehouseSeriesNode,
+} from 'scenes/insights/filters/ActionFilter/seriesNode'
import type {
ActionsNode,
@@ -12,11 +21,10 @@ import type {
DateRange,
EntityNode,
EventsNode,
- ExperimentDataWarehouseNode,
ExperimentEventExposureConfig,
ExperimentFunnelMetric,
- ExperimentFunnelMetricStep,
ExperimentMetric,
+ ExperimentMetricSource,
ExperimentMetricTypeProps,
FunnelsDataWarehouseNode,
FunnelsFilter,
@@ -26,9 +34,9 @@ import type {
TrendsFilter,
TrendsQuery,
} from '~/queries/schema/schema-general'
-import { ExperimentMetricSource, ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'
+import { ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'
import { setLatestVersionsOnQuery } from '~/queries/utils'
-import type { FilterType, IntervalType, MultivariateFlagVariant } from '~/types'
+import type { IntervalType, MultivariateFlagVariant } from '~/types'
import { ChartDisplayType, ExperimentMetricMathType, PropertyFilterType, PropertyOperator } from '~/types'
import { EXPOSURE_DEFAULT_EVENT, EXPOSURE_FEATURE_FLAG_PROPERTY, featureFlagVariantProperty } from './exposureContract'
@@ -248,265 +256,54 @@ const getFunnelSeries = (
)
/**
- * Creates an empty filter structure
+ * The picker mirrors a warehouse table's name onto `id`, which `ExperimentDataWarehouseNode` does
+ * not accept, so a table keeps only `table_name`. A group has no experiment equivalent and gives null.
*/
-const createEmptyFilter = (): FilterType => ({
- events: [],
- actions: [],
- data_warehouse: [],
-})
-
-/**
- * Helper function to create a filter from a single source
- */
-export const createFilterForSource = (source: ExperimentMetricSource): FilterType => {
- return match(source)
- .with({ kind: NodeKind.EventsNode }, (eventSource) => ({
- events: [createSourceNode(eventSource)],
- actions: [],
- data_warehouse: [],
- }))
- .with({ kind: NodeKind.ActionsNode }, (actionSource) => ({
- events: [],
- actions: [createSourceNode(actionSource)],
- data_warehouse: [],
- }))
- .with({ kind: NodeKind.ExperimentDataWarehouseNode }, (dwSource) => ({
- events: [],
- actions: [],
- data_warehouse: [createSourceNode(dwSource)],
- }))
- .otherwise(() => createEmptyFilter())
-}
-
-/**
- * takes a metric and returns a filter that can be used as part of a query.
- */
-export const getFilter = (metric: ExperimentMetric): FilterType => {
- return match(metric)
- .with({ metric_type: ExperimentMetricType.MEAN }, (meanMetric) => createFilterForSource(meanMetric.source))
- .with({ metric_type: ExperimentMetricType.FUNNEL }, (funnelMetric) => {
- /**
- * we create a source node for each step on the funnel series.
- */
- const funnelSteps = funnelMetric.series.map((step, index) => {
- const type =
- step.kind === NodeKind.EventsNode
- ? 'events'
- : step.kind === NodeKind.ActionsNode
- ? 'actions'
- : 'data_warehouse'
-
- return {
- ...createSourceNode(step),
- order: index,
- type,
- }
- })
-
- return {
- events: funnelSteps.filter((step) => step.type === 'events'),
- actions: funnelSteps.filter((step) => step.type === 'actions'),
- data_warehouse: funnelSteps.filter((step) => step.type === 'data_warehouse'),
- }
- })
- .with({ metric_type: ExperimentMetricType.RATIO }, (ratioMetric) => {
- // For ratio metrics, we need to combine numerator and denominator filters
- const numeratorFilter = createFilterForSource(ratioMetric.numerator)
- const denominatorFilter = createFilterForSource(ratioMetric.denominator)
-
- return {
- events: [...(numeratorFilter.events || []), ...(denominatorFilter.events || [])],
- actions: [...(numeratorFilter.actions || []), ...(denominatorFilter.actions || [])],
- data_warehouse: [
- ...(numeratorFilter.data_warehouse || []),
- ...(denominatorFilter.data_warehouse || []),
- ],
- }
- })
- .otherwise(() => createEmptyFilter())
+const toExperimentSourceNode = (node: SeriesNode): ExperimentMetricSource | null => {
+ if (isEventsSeriesNode(node) || isActionsSeriesNode(node)) {
+ return node
+ }
+ if (isWarehouseSeriesNode(node)) {
+ const { id: _id, ...warehouseNode } = node as SeriesNode & { id?: string }
+ return { ...warehouseNode, kind: NodeKind.ExperimentDataWarehouseNode } as ExperimentMetricSource
+ }
+ return null
}
/**
- * Enhanced version of ExperimentMetricSource with legacy filter properties
- * This type represents what createSourceNode actually returns - a node with additional
- * filter-compatible properties needed for the legacy filter system
- */
-type ExperimentMetricSourceWithType =
- | (EventsNode & { type: 'events'; id: string; name: string })
- | (ActionsNode & { type: 'actions'; id: number; name: string })
- | (ExperimentDataWarehouseNode & {
- type: 'data_warehouse'
- id: string
- name: string
- id_field: string
- aggregation_target_field: string
- })
-
-/**
- * Converts filter data to a metric source (EventsNode, ActionsNode, or ExperimentDataWarehouseNode)
- * Used for ratio metrics and mean metrics to support all source types
+ * Turns the series a single-source picker emits into a metric source, with total count as the
+ * default math. Returns null when the picker holds no event, action or table.
*/
-export function filterToMetricSource(
- actions: Record<string, any>[] | undefined,
- events: Record<string, any>[] | undefined,
- data_warehouse: Record<string, any>[] | undefined
-): ExperimentMetricSource | null {
- if (events?.[0]) {
- return {
- kind: NodeKind.EventsNode,
- // Fall back to `name` when taxonomic selection leaves `id` empty/null.
- event: events[0].id || events[0].name,
- name: events[0].name,
- math: events[0].math || ExperimentMetricMathType.TotalCount,
- math_property: events[0].math_property,
- math_hogql: events[0].math_hogql,
- math_group_type_index: events[0].math_group_type_index,
- properties: events[0].properties,
- }
- }
-
- if (actions?.[0]) {
- return {
- kind: NodeKind.ActionsNode,
- id: actions[0].id,
- name: actions[0].name,
- math: actions[0].math || ExperimentMetricMathType.TotalCount,
- math_property: actions[0].math_property,
- math_hogql: actions[0].math_hogql,
- math_group_type_index: actions[0].math_group_type_index,
- properties: actions[0].properties,
- }
- }
-
- if (data_warehouse?.[0]) {
- return {
- kind: NodeKind.ExperimentDataWarehouseNode,
- name: data_warehouse[0].name,
- table_name: data_warehouse[0].table_name || data_warehouse[0].id,
- timestamp_field: data_warehouse[0].timestamp_field,
- events_join_key: data_warehouse[0].events_join_key,
- data_warehouse_join_key: data_warehouse[0].data_warehouse_join_key,
- math: data_warehouse[0].math || ExperimentMetricMathType.TotalCount,
- math_property: data_warehouse[0].math_property,
- math_hogql: data_warehouse[0].math_hogql,
- math_group_type_index: data_warehouse[0].math_group_type_index,
- properties: data_warehouse[0].properties,
- }
+export function seriesToMetricSource(series: SeriesNode[]): ExperimentMetricSource | null {
+ const [node] = cleanSeriesNodes(series.slice(0, 1), MathAvailability.All)
+ const source = node ? toExperimentSourceNode(node) : null
+ if (source?.kind === NodeKind.EventsNode) {
+ // Fall back to `name` when taxonomic selection leaves `event` empty/null.
+ return { ...source, event: source.event || source.name }
}
-
- return null
+ return source
}
/**
- * Converts filter format to metric configuration
- * This is the reverse operation of getFilter
+ * Turns the series the metric picker emits into the part of the metric it edits: the funnel
+ * steps, which carry no math, or the mean metric's source.
*/
-export function filterToMetricConfig(
+export function seriesToMetricConfig(
metricType: ExperimentMetricType,
- actions: Record<string, any>[] | undefined,
- events: Record<string, any>[] | undefined,
- data_warehouse: Record<string, any>[] | undefined
+ series: SeriesNode[]
): ExperimentMetricTypeProps | undefined {
return match(metricType)
.with(ExperimentMetricType.FUNNEL, () => {
- // Combine all supported source types and sort by order
- const eventSteps =
- events?.map(
- (event) =>
- ({
- kind: NodeKind.EventsNode,
- event: event.id,
- custom_name: event.custom_name || undefined,
- properties: event.properties,
- order: event.order,
- }) as EventsNode & { order?: number }
- ) || []
-
- const actionSteps =
- actions?.map(
- (action) =>
- ({
- kind: NodeKind.ActionsNode,
- id: action.id,
- name: action.name,
- custom_name: action.custom_name || undefined,
- properties: action.properties,
- order: action.order,
- }) as ActionsNode & { order?: number }
- ) || []
-
- const dataWarehouseSteps =
- data_warehouse?.map(
- (dataWarehouse) =>
- ({
- kind: NodeKind.ExperimentDataWarehouseNode,
- table_name: dataWarehouse.table_name || dataWarehouse.id,
- name: dataWarehouse.name,
- timestamp_field: dataWarehouse.timestamp_field,
- events_join_key: dataWarehouse.events_join_key,
- data_warehouse_join_key: dataWarehouse.data_warehouse_join_key,
- custom_name: dataWarehouse.custom_name || undefined,
- properties: dataWarehouse.properties,
- order: dataWarehouse.order,
- }) as ExperimentDataWarehouseNode & { order?: number }
- ) || []
-
- const combinedSteps = [...eventSteps, ...actionSteps, ...dataWarehouseSteps]
- .map((step, index) => ({ ...step, order: step.order ?? index }))
- .sort((a, b) => a.order - b.order)
-
- // Remove the temporary order field
- const series = combinedSteps.map(({ order, ...step }) => step as ExperimentFunnelMetricStep)
-
- return series.length > 0
- ? {
- metric_type: ExperimentMetricType.FUNNEL as const,
- series,
- }
- : undefined
+ const steps = cleanSeriesNodes(series, MathAvailability.None).map(toExperimentSourceNode).filter(isNotNil)
+ return steps.length > 0 ? { metric_type: ExperimentMetricType.FUNNEL as const, series: steps } : undefined
})
.with(ExperimentMetricType.MEAN, () => {
- const source = filterToMetricSource(actions, events, data_warehouse)
- return source
- ? {
- metric_type: ExperimentMetricType.MEAN as const,
- source,
- }
- : undefined
+ const source = seriesToMetricSource(series)
+ return source ? { metric_type: ExperimentMetricType.MEAN as const, source } : undefined
})
.otherwise(() => undefined)
}
-/**
- * this is a type adapter between metrics and filters.
- * takes an experiment mean metric source or funnel metric step and returns a source node that can be used in a filter
- */
-const createSourceNode = (step: ExperimentFunnelMetricStep | ExperimentMetricSource): ExperimentMetricSourceWithType =>
- match(step)
- .with({ kind: NodeKind.EventsNode }, (eventStep) => ({
- ...eventStep,
- type: 'events' as const,
- id: eventStep.event || '',
- name: eventStep.name || eventStep.event || '',
- }))
- .with({ kind: NodeKind.ActionsNode }, (actionStep) => ({
- ...actionStep,
- type: 'actions' as const,
- id: actionStep.id,
- name: actionStep.name || '',
- }))
- .with({ kind: NodeKind.ExperimentDataWarehouseNode }, (dwStep) => ({
- ...dwStep,
- type: 'data_warehouse' as const,
- id: dwStep.table_name,
- name: dwStep.name || dwStep.table_name,
- // Map ExperimentDataWarehouseNode fields to FunnelDatawarehouseFilter fields
- id_field: dwStep.data_warehouse_join_key,
- aggregation_target_field: dwStep.events_join_key,
- }))
- .exhaustive()
-
/**
* converts the experiment exposure config in to an events node
*/
diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.ts
index ff64b549d5d6..4e66c0c9cd0c 100644
--- a/frontend/src/scenes/experiments/utils.test.ts
+++ b/frontend/src/scenes/experiments/utils.test.ts
@@ -1,16 +1,20 @@
+import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'
+
import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json'
import {
CachedNewExperimentQueryResponse,
ExperimentEventExposureConfig,
+ ExperimentExposureConfig,
ExperimentMetric,
ExperimentMetricType,
NodeKind,
ProductKey,
} from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
import {
AccessControlLevel,
+ EventPropertyFilter,
Experiment,
- ExperimentMetricMathType,
FeatureFlagBucketingIdentifier,
FeatureFlagEvaluationRuntime,
FeatureFlagType,
@@ -19,16 +23,14 @@ import {
PropertyOperator,
} from '~/types'
-import { filterToMetricConfig } from './metricQueryUtils'
import { getNiceTickValues } from './MetricsView/shared/utils'
import {
type ExperimentSavedMetric,
FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON,
FUNNEL_SERVER_SIDE_COMPLETION_REASON,
NOT_A_FUNNEL_REASON,
- exposureConfigToFilter,
+ exposureConfigToSeries,
featureFlagEligibleForExperiment,
- filterToExposureConfig,
getBaselineVariantKey,
getDisplayOrderedIndices,
getEventCountQuery,
@@ -39,6 +41,7 @@ import {
isLegacyExperimentQuery,
metricResults,
percentageDistribution,
+ seriesToExposureConfig,
sharedMetricsToExperimentMetrics,
toConcurrencyPayload,
toExperimentWritePayload,
@@ -366,227 +369,70 @@ describe('getBaselineVariantKey', () => {
})
})
-describe('exposureConfigToFilter', () => {
- it('returns the correct filter for an exposure config', () => {
- const exposureConfig = {
- kind: NodeKind.ExperimentEventExposureConfig,
- event: '$feature_flag_called',
- properties: [
- {
- key: '$feature_flag_response',
- value: ['test'],
- operator: 'exact',
- type: 'event',
- },
- ],
- } as ExperimentEventExposureConfig
- const filter = exposureConfigToFilter(exposureConfig)
- expect(filter).toEqual({
- events: [
- {
- id: '$feature_flag_called',
- name: '$feature_flag_called',
- kind: 'EventsNode',
- type: 'events',
- properties: [
- {
- key: '$feature_flag_response',
- value: ['test'],
- operator: 'exact',
- type: 'event',
- },
- ],
- },
- ],
- actions: [],
- data_warehouse: [],
- })
- })
-})
+describe('exposure config series', () => {
+ const viewedFilter: EventPropertyFilter = {
+ key: '$feature_flag_response',
+ value: ['test'],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ }
+ const eventConfig: ExperimentEventExposureConfig = {
+ kind: NodeKind.ExperimentEventExposureConfig,
+ event: '$feature_flag_called',
+ properties: [viewedFilter],
+ }
+ const actionConfig: ExperimentExposureConfig = {
+ kind: NodeKind.ActionsNode,
+ id: 7,
+ name: 'Signed up',
+ properties: [],
+ }
-describe('filterToExposureConfig', () => {
- it('returns the correct exposure config for an event', () => {
- const event = {
- id: '$feature_flag_called',
- name: '$feature_flag_called',
- kind: 'EventsNode',
- type: 'events',
- properties: [
- {
- key: '$feature_flag_response',
- value: ['test'],
- operator: 'exact',
- type: 'event',
- },
- ],
- }
- const exposureConfig = filterToExposureConfig(event)
- expect(exposureConfig).toEqual({
- kind: NodeKind.ExperimentEventExposureConfig,
- event: '$feature_flag_called',
- properties: [
- {
- key: '$feature_flag_response',
- value: ['test'],
- operator: 'exact',
- type: 'event',
- },
- ],
- })
+ beforeEach(() => {
+ initKeaTests()
})
-})
-describe('filterToMetricConfig', () => {
- it('returns the correct metric config for an event', () => {
- const event = {
- kind: NodeKind.EventsNode,
- id: '$pageview',
- name: '$pageview',
- type: 'events',
- order: 0,
- uuid: 'b2aa47bc-c39b-4743-a2a2-ab88f78faf11',
- properties: [
- {
- key: '$browser',
- value: ['Chrome'],
- operator: 'exact',
- type: 'event',
- },
- ],
- } as Record<string, any>
- const metricConfig = filterToMetricConfig(ExperimentMetricType.MEAN, undefined, [event], undefined)
- expect(metricConfig).toEqual({
- metric_type: ExperimentMetricType.MEAN,
- source: {
- kind: NodeKind.EventsNode,
- event: '$pageview',
- name: '$pageview',
- math: 'total',
- math_property: undefined,
- math_hogql: undefined,
- properties: [
- {
- key: '$browser',
- value: ['Chrome'],
- operator: 'exact',
- type: 'event',
- },
- ],
- },
- })
- })
- it('returns the correct metric config for an action', () => {
- const action = {
- id: '8',
- name: 'jan-16-running payment action',
- kind: NodeKind.ActionsNode,
- type: 'actions',
- math: 'total',
- properties: [
- {
- key: '$lib',
- type: 'event',
- value: ['python'],
- operator: 'exact',
- },
- ],
- order: 0,
- uuid: '29c01ac4-ebc3-4cb8-9d82-287c0487056e',
- } as Record<string, any>
- const metricConfig = filterToMetricConfig(ExperimentMetricType.MEAN, [action], undefined, undefined)
- expect(metricConfig).toEqual({
- metric_type: ExperimentMetricType.MEAN,
- source: {
- kind: NodeKind.ActionsNode,
- id: '8',
- name: 'jan-16-running payment action',
- math: 'total',
- math_property: undefined,
- math_hogql: undefined,
- properties: [{ key: '$lib', type: 'event', value: ['python'], operator: 'exact' }],
- },
- })
- })
- it('returns the correct metric config for a data warehouse metric', () => {
- const dataWarehouse = {
- kind: NodeKind.EventsNode,
- id: 'mysql_payments',
- name: 'mysql_payments',
- type: 'data_warehouse',
- timestamp_field: 'timestamp',
- events_join_key: 'person.properties.email',
- data_warehouse_join_key: 'customer.email',
- } as Record<string, any>
- const metricConfig = filterToMetricConfig(ExperimentMetricType.MEAN, undefined, undefined, [dataWarehouse])
- expect(metricConfig).toEqual({
- metric_type: ExperimentMetricType.MEAN,
- source: {
- kind: NodeKind.ExperimentDataWarehouseNode,
- table_name: 'mysql_payments',
- name: 'mysql_payments',
- timestamp_field: 'timestamp',
- events_join_key: 'person.properties.email',
- data_warehouse_join_key: 'customer.email',
- math: ExperimentMetricMathType.TotalCount,
- math_property: undefined,
- math_hogql: undefined,
- properties: undefined,
- },
+ it.each<[string, ExperimentExposureConfig, (logic: ReturnType<typeof entityFilterLogic.build>) => void, any]>([
+ [
+ 'clearing the exposure event filters',
+ eventConfig,
+ (logic) => logic.actions.updateSeriesProperties(0, []),
+ { kind: NodeKind.ExperimentEventExposureConfig, event: '$feature_flag_called', properties: [] },
+ ],
+ [
+ 'picking an action for an event',
+ eventConfig,
+ (logic) => logic.actions.updateSeriesEntity(0, { kind: NodeKind.ActionsNode, key: 42, name: 'Bought' }),
+ { kind: NodeKind.ActionsNode, id: 42, name: 'Bought', properties: [viewedFilter] },
+ ],
+ [
+ 'picking an event for an action',
+ actionConfig,
+ (logic) =>
+ logic.actions.updateSeriesEntity(0, { kind: NodeKind.EventsNode, key: 'viewed', name: 'viewed' }),
+ { kind: NodeKind.ExperimentEventExposureConfig, event: 'viewed', properties: [] },
+ ],
+ ['removing the exposure event', eventConfig, (logic) => logic.actions.removeSeries(0), undefined],
+ ])('stores the config the picker emits after %s', (_label, config, edit, expected) => {
+ const onChange = jest.fn()
+ const logic = entityFilterLogic({
+ series: exposureConfigToSeries(config),
+ onChange,
+ typeKey: 'experiment-exposure-config',
})
+ logic.mount()
+
+ edit(logic)
+
+ expect(seriesToExposureConfig(onChange.mock.lastCall[0])).toEqual(expected)
})
- it('returns the correct metric config for a data warehouse metric with properties', () => {
- const dataWarehouse = {
- kind: NodeKind.EventsNode,
- id: 'mysql_payments',
- name: 'mysql_payments',
- type: 'data_warehouse',
- timestamp_field: 'timestamp',
- events_join_key: 'person.properties.email',
- data_warehouse_join_key: 'customer.email',
- properties: [
- {
- key: 'amount',
- value: 100,
- operator: PropertyOperator.GreaterThan,
- type: PropertyFilterType.Event,
- },
- {
- key: 'currency',
- value: 'USD',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- },
- ],
- } as Record<string, any>
- const metricConfig = filterToMetricConfig(ExperimentMetricType.MEAN, undefined, undefined, [dataWarehouse])
- expect(metricConfig).toEqual({
- metric_type: ExperimentMetricType.MEAN,
- source: {
- kind: NodeKind.ExperimentDataWarehouseNode,
- table_name: 'mysql_payments',
- name: 'mysql_payments',
- timestamp_field: 'timestamp',
- events_join_key: 'person.properties.email',
- data_warehouse_join_key: 'customer.email',
- math: ExperimentMetricMathType.TotalCount,
- math_property: undefined,
- math_hogql: undefined,
- properties: [
- {
- key: 'amount',
- value: 100,
- operator: PropertyOperator.GreaterThan,
- type: PropertyFilterType.Event,
- },
- {
- key: 'currency',
- value: 'USD',
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- },
- ],
- },
- })
+
+ it('gives no config for a warehouse table', () => {
+ expect(
+ seriesToExposureConfig([
+ { kind: NodeKind.DataWarehouseNode, id: 'invoices', table_name: 'invoices', name: 'invoices' } as any,
+ ])
+ ).toBeUndefined()
})
})
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index 1fbb83b6057b..c1c5b909f57a 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -5,13 +5,13 @@ import { EXPERIMENT_DEFAULT_DURATION, FunnelLayout, MAX_EXPERIMENT_VARIANTS } fr
import { dayjs } from 'lib/dayjs'
import { uuid } from 'lib/utils/dom'
import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'
+import { SeriesNode, isActionsSeriesNode, isEventsSeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'
import {
AnyDataWarehouseNode,
AnyEntityNode,
Breakdown,
CachedNewExperimentQueryResponse,
- EventsNode,
ExperimentEventExposureConfig,
ExperimentExposureConfig,
ExperimentFunnelMetricStep,
@@ -39,7 +39,6 @@ import {
ExperimentMetricMathType,
FeatureFlagBasicType,
FeatureFlagType,
- FilterType,
FunnelConversionWindowTimeUnit,
FunnelVizType,
MultivariateFlagVariant,
@@ -699,70 +698,44 @@ export function getExperimentMetricFromInsight(insight: InsightModel | null): Ex
return undefined
}
-/**
- * Used when setting a custom exposure criteria
- */
-export function exposureConfigToFilter(exposure_config: ExperimentExposureConfig): FilterType {
- if (exposure_config.kind === NodeKind.ExperimentEventExposureConfig) {
- return {
- events: [
- {
- id: exposure_config.event,
- name: exposure_config.event,
- kind: NodeKind.EventsNode,
- type: 'events',
- properties: exposure_config.properties,
- } as EventsNode,
- ],
- actions: [],
- data_warehouse: [],
- }
+export function exposureConfigToSeries(exposureConfig: ExperimentExposureConfig): SeriesNode[] {
+ if (exposureConfig.kind === NodeKind.ExperimentEventExposureConfig) {
+ return [
+ {
+ kind: NodeKind.EventsNode,
+ event: exposureConfig.event,
+ name: exposureConfig.event,
+ properties: exposureConfig.properties,
+ },
+ ]
}
- if (exposure_config.kind === NodeKind.ActionsNode) {
- return {
- events: [],
- actions: [
- {
- id: exposure_config.id,
- name: exposure_config.name || '',
- kind: NodeKind.ActionsNode,
- type: 'actions' as const,
- properties: exposure_config.properties,
- },
- ],
- data_warehouse: [],
- }
+ if (exposureConfig.kind === NodeKind.ActionsNode) {
+ return [exposureConfig]
}
-
- return {}
+ return []
}
/**
- * Used when setting a custom exposure criteria
+ * Only an event or an action can mark exposure, so any other series gives no config.
*/
-export function filterToExposureConfig(entity: Record<string, any> | undefined): ExperimentExposureConfig | undefined {
- if (!entity) {
- return undefined
- }
-
- // Check type first since ActionFilter may set kind incorrectly
- if (entity.type === 'actions') {
+export function seriesToExposureConfig(series: SeriesNode[]): ExperimentExposureConfig | undefined {
+ const [node] = series
+ if (isEventsSeriesNode(node)) {
return {
- kind: NodeKind.ActionsNode,
- id: entity.id,
- name: entity.name,
- properties: entity.properties,
+ kind: NodeKind.ExperimentEventExposureConfig,
+ // "All events" leaves `event` null, which the API rejects as an exposure event.
+ event: node.event as string,
+ properties: node.properties ?? [],
}
}
-
- if (entity.type === 'events' || entity.kind === NodeKind.EventsNode) {
+ if (isActionsSeriesNode(node)) {
return {
- kind: NodeKind.ExperimentEventExposureConfig,
- event: entity.id,
- properties: entity.properties,
+ kind: NodeKind.ActionsNode,
+ id: node.id,
+ name: node.name,
+ properties: node.properties,
}
}
-
return undefined
}
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
index b989920b11f6..7e2dfda5a0ce 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx
@@ -803,9 +803,9 @@ export function ActionFilterRow({
isWarehouseSeriesNode(node)
? {
kind: NodeKind.HogQLQuery,
- query: `select ${
- (node as { aggregation_target_field?: string }).aggregation_target_field
- } from ${node.table_name}`,
+ // The SQL check appends the filter expression to this select list. Select a
+ // constant, because only some warehouse node kinds carry an aggregation target.
+ query: `select 1 from ${node.table_name}`,
}
: undefined
}
diff --git a/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsx b/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsx
index 0a050b7656f1..4cc5afa4ebd4 100644
--- a/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsx
+++ b/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsx
@@ -5,18 +5,18 @@ import { LemonBanner } from '@posthog/lemon-ui'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'
import { EXPERIMENT_DEFAULT_DURATION } from 'lib/constants'
-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 { cleanSeriesNodes } from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'
import { getHogQLValue } from 'scenes/insights/filters/aggregationTarget'
import { teamLogic } from 'scenes/teamLogic'
-import { actionsAndEventsToSeries } from '~/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries'
-import { queryNodeToFilter } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'
import { Query } from '~/queries/Query/Query'
-import { ExperimentFunnelsQuery, NodeKind } from '~/queries/schema/schema-general'
+import { ExperimentFunnelsQuery, FunnelsQuery, NodeKind } from '~/queries/schema/schema-general'
+import { hasBreakdownFilter } from '~/queries/utils'
import { commonActionFilterProps } from '~/scenes/experiments/Metrics/Selectors'
import { sharedMetricLogic } from '~/scenes/experiments/SharedMetrics/sharedMetricLogic'
-import { BreakdownAttributionType, FilterType } from '~/types'
+import { BreakdownAttributionType, InsightType } from '~/types'
import {
LegacyFunnelAttributionSelect,
@@ -44,25 +44,22 @@ export function LegacySharedFunnelsMetricForm(): JSX.Element {
return (
<>
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={queryNodeToFilter(sharedMetricQuery.funnels_query)}
- setFilters={({ actions, events, data_warehouse }: Partial<FilterType>): void => {
+ series={sharedMetricQuery.funnels_query.series}
+ insightType={InsightType.FUNNELS}
+ hasBreakdown={hasBreakdownFilter(sharedMetricQuery.funnels_query.breakdownFilter)}
+ onChange={(series) => {
if (!sharedMetric?.query) {
return
}
- const series = actionsAndEventsToSeries(
- { actions, events, data_warehouse } as any,
- true,
- MathAvailability.None
- )
setSharedMetric({
query: {
...sharedMetricQuery,
funnels_query: {
...sharedMetricQuery.funnels_query,
- series,
+ series: cleanSeriesNodes(series, MathAvailability.None) as FunnelsQuery['series'],
},
},
})
diff --git a/products/experiments/frontend/legacy/sharedMetrics/LegacySharedTrendsMetricForm.tsx b/products/experiments/frontend/legacy/sharedMetrics/LegacySharedTrendsMetricForm.tsx
index 71f656735326..f5f2a5c48ead 100644
--- a/products/experiments/frontend/legacy/sharedMetrics/LegacySharedTrendsMetricForm.tsx
+++ b/products/experiments/frontend/legacy/sharedMetrics/LegacySharedTrendsMetricForm.tsx
@@ -5,22 +5,26 @@ import { IconCheckCircle } from '@posthog/icons'
import { LemonBanner, LemonTabs, LemonTag } from '@posthog/lemon-ui'
import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'
-import { EXPERIMENT_DEFAULT_DURATION } from 'lib/constants'
+import { DISPLAY_TYPES_TO_CATEGORIES, EXPERIMENT_DEFAULT_DURATION } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
-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 { cleanSeriesNodes } from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'
import { teamLogic } from 'scenes/teamLogic'
-import { actionsAndEventsToSeries } from '~/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries'
-import { queryNodeToFilter } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'
import { Query } from '~/queries/Query/Query'
-import { ExperimentTrendsQuery, InsightQueryNode, NodeKind } from '~/queries/schema/schema-general'
+import { ExperimentTrendsQuery, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
+import { hasBreakdownFilter } from '~/queries/utils'
import { commonActionFilterProps } from '~/scenes/experiments/Metrics/Selectors'
import { sharedMetricLogic } from '~/scenes/experiments/SharedMetrics/sharedMetricLogic'
-import { BaseMathType, ChartDisplayType, FilterType } from '~/types'
+import { BaseMathType, ChartDisplayCategory, ChartDisplayType, InsightType } from '~/types'
import { LEGACY_EXPERIMENT_ALLOWED_MATH_TYPES } from 'products/experiments/frontend/constants'
+function displayCategory(query: TrendsQuery): ChartDisplayCategory {
+ return DISPLAY_TYPES_TO_CATEGORIES[query.trendsFilter?.display || ChartDisplayType.ActionsLineGraph]
+}
+
export function LegacySharedTrendsMetricForm(): JSX.Element {
const { sharedMetric } = useValues(sharedMetricLogic)
const { setSharedMetric } = useActions(sharedMetricLogic)
@@ -45,21 +49,22 @@ export function LegacySharedTrendsMetricForm(): JSX.Element {
label: 'Main metric',
content: (
<>
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={queryNodeToFilter(sharedMetricQuery.count_query)}
- setFilters={({ actions, events, data_warehouse }: Partial<FilterType>): void => {
- const series = actionsAndEventsToSeries(
- { actions, events, data_warehouse } as any,
- true,
- MathAvailability.All
- )
+ series={sharedMetricQuery.count_query.series}
+ insightType={InsightType.TRENDS}
+ hasBreakdown={hasBreakdownFilter(sharedMetricQuery.count_query.breakdownFilter)}
+ trendsDisplayCategory={displayCategory(sharedMetricQuery.count_query)}
+ onChange={(series) => {
setSharedMetric({
query: {
...sharedMetricQuery,
count_query: {
...sharedMetricQuery.count_query,
- series,
+ series: cleanSeriesNodes(
+ series,
+ MathAvailability.All
+ ) as TrendsQuery['series'],
},
},
})
@@ -197,27 +202,24 @@ export function LegacySharedTrendsMetricForm(): JSX.Element {
</div>
{sharedMetricQuery.exposure_query && (
<>
- <ActionFilter
+ <SeriesActionFilter
bordered
- filters={queryNodeToFilter(
- sharedMetricQuery.exposure_query as InsightQueryNode
+ series={sharedMetricQuery.exposure_query.series}
+ insightType={InsightType.TRENDS}
+ hasBreakdown={hasBreakdownFilter(
+ sharedMetricQuery.exposure_query.breakdownFilter
)}
- setFilters={({
- actions,
- events,
- data_warehouse,
- }: Partial<FilterType>): void => {
- const series = actionsAndEventsToSeries(
- { actions, events, data_warehouse } as any,
- true,
- MathAvailability.All
- )
+ trendsDisplayCategory={displayCategory(sharedMetricQuery.exposure_query)}
+ onChange={(series) => {
setSharedMetric({
query: {
...sharedMetricQuery,
exposure_query: {
...sharedMetricQuery.exposure_query,
- series,
+ series: cleanSeriesNodes(
+ series,
+ MathAvailability.All
+ ) as TrendsQuery['series'],
},
},
})