:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(insights): edit insight series as query nodes (#115882)
Thomas Obermüller8cdfeca99d00
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries.ts b/frontend/src/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries.tsindex a99dab29945e..34027d5307a2 100644--- a/frontend/src/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries.ts+++ b/frontend/src/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries.ts@@ -1,5 +1,10 @@import { objectCleanWithEmpty } from 'lib/utils/objects'import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'+import {+ actorsOnlyMathTypes,+ calendarHeatmapMathTypes,+ funnelsMathTypes,+} from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'import {ActionsNode,@@ -18,12 +23,8 @@ import {ActionFilter,AnyDataWarehouseFilter,BaseMathType,- CalendarHeatmapMathType,EntityTypes,FunnelDatawarehouseFilter,- FunnelMathType,- GroupMathType,- HogQLMathType,LifecycleDatawarehouseFilter,RetentionEntity,TrendsDataWarehouseFilter,@@ -33,18 +34,6 @@ import {import { cleanEntityProperties } from './cleanProperties'-export const actorsOnlyMathTypes = [- BaseMathType.UniqueUsers,- BaseMathType.WeeklyActiveUsers,- BaseMathType.MonthlyActiveUsers,- GroupMathType.UniqueGroup,- HogQLMathType.HogQL,-]--const funnelsMathTypes = [FunnelMathType.FirstTimeForUser, FunnelMathType.FirstTimeForUserWithFilters]--const calendarHeatmapMathTypes = [CalendarHeatmapMathType.TotalCount, CalendarHeatmapMathType.UniqueUsers]-export type FilterTypeActionsAndEvents = {events?: ActionFilter[]actions?: ActionFilter[]diff --git a/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx b/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsxindex 99c975352b78..c0e8fde27a46 100644--- a/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx+++ b/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx@@ -3,27 +3,23 @@ import { useActions, useValues } from 'kea'import { LemonSwitch } from '@posthog/lemon-ui'import { DataWarehousePopoverField, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { SINGLE_SERIES_DISPLAY_TYPES } from 'lib/constants'+import { DISPLAY_TYPES_TO_CATEGORIES, SINGLE_SERIES_DISPLAY_TYPES } from 'lib/constants'import { getProjectEventExistence } from 'lib/utils/getAppContext'import { alphabet } from 'lib/utils/strings'-import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'-import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'+import { SeriesActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'import { insightLogic } from 'scenes/insights/insightLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'import { getInsightPropertyFilterGroupTypes } from 'scenes/insights/utils/propertyTaxonomicGroupTypes'import { groupsModel } from '~/models/groupsModel'-import { LifecycleQuery, NodeKind, StickinessQuery, TrendsQuery } from '~/queries/schema/schema-general'+import { NodeKind } from '~/queries/schema/schema-general'import { isInsightQueryNode } from '~/queries/utils'-import { ChartDisplayType, FilterType } from '~/types'+import { ChartDisplayType, InsightType } from '~/types'import { LifecycleSeriesHeader } from 'products/product_analytics/frontend/insights/lifecycle/LifecycleSeriesHeader'import { TrendsFormula } from 'products/product_analytics/frontend/insights/trends/filters/TrendsFormula'-import { actionsAndEventsToSeries } from '../InsightQuery/utils/actionsAndEventsToSeries'-import { queryNodeToFilter } from '../InsightQuery/utils/queryNodeToFilter'-const lifecycleDataWarehousePopoverFields: DataWarehousePopoverField[] = [{ key: 'timestamp_field', label: 'Timestamp', allowHogQL: true },{ key: 'created_at_field', label: 'Created at', allowHogQL: true },@@ -32,10 +28,18 @@ const lifecycleDataWarehousePopoverFields: DataWarehousePopoverField[] = [export function TrendsSeries(): JSX.Element | null {const { insightProps } = useValues(insightLogic)- const { querySource, isTrends, isLifecycle, isStickiness, display, hasFormula, series } = useValues(- insightVizDataLogic(insightProps)- )- const { updateQuerySource, setFormulaMode } = useActions(insightVizDataLogic(insightProps))+ const {+ querySource,+ isTrends,+ isLifecycle,+ isStickiness,+ display,+ hasFormula,+ series,+ isBreakdownSeries,+ seriesMathAvailability,+ } = useValues(insightVizDataLogic(insightProps))+ const { updateSeries, setFormulaMode } = useActions(insightVizDataLogic(insightProps))const { groupsTaxonomicTypes } = useValues(groupsModel)@@ -52,16 +56,6 @@ export function TrendsSeries(): JSX.Element | null {return null}- const filters = queryNodeToFilter(querySource)- const mathAvailability = isLifecycle- ? MathAvailability.None- : isStickiness- ? MathAvailability.ActorsOnly- : display === ChartDisplayType.CalendarHeatmap- ? MathAvailability.CalendarHeatmapOnly- : display === ChartDisplayType.BoxPlot- ? MathAvailability.BoxPlotOnly- : MathAvailability.Allconst supportsDataWarehouse =(isTrends && display !== ChartDisplayType.CalendarHeatmap) || isLifecycle || isStickiness@@ -87,30 +81,18 @@ export function TrendsSeries(): JSX.Element | null {return (<>{isLifecycle && <LifecycleSeriesHeader />}- <ActionFilter+ <SeriesActionFilterallowBehavioralPropertyFilter- filters={filters}- setFilters={(payload: Partial<FilterType>): void => {- if (isLifecycle) {- updateQuerySource({- series: actionsAndEventsToSeries(- payload as any,- true,- mathAvailability,- NodeKind.LifecycleDataWarehouseNode- ),- } as LifecycleQuery)- } else {- updateQuerySource({- series: actionsAndEventsToSeries(- payload as any,- true,- mathAvailability,- NodeKind.DataWarehouseNode- ),- } as TrendsQuery | StickinessQuery)- }- }}+ series={series ?? []}+ onChange={updateSeries}+ insightType={+ isLifecycle ? InsightType.LIFECYCLE : isStickiness ? InsightType.STICKINESS : InsightType.TRENDS+ }+ hasBreakdown={isBreakdownSeries}+ trendsDisplayCategory={+ isTrends ? DISPLAY_TYPES_TO_CATEGORIES[display || ChartDisplayType.ActionsLineGraph] : null+ }+ dataWarehouseNodeKind={isLifecycle ? NodeKind.LifecycleDataWarehouseNode : NodeKind.DataWarehouseNode}typeKey={keyForInsightLogicProps('new')(insightProps)}buttonCopy={hasFormula ? 'Variable' : 'Series'}showSeriesIndicator@@ -120,7 +102,7 @@ export function TrendsSeries(): JSX.Element | null {? 1: alphabet.length}- mathAvailability={mathAvailability}+ mathAvailability={seriesMathAvailability}propertiesTaxonomicGroupTypes={propertiesTaxonomicGroupTypes}actionsTaxonomicGroupTypes={[TaxonomicFilterGroupType.Events,diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx b/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsxindex b90ef17fe38c..0edeefe76b31 100644--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx@@ -6,6 +6,7 @@ import { LemonTag } from 'lib/lemon-ui/LemonTag'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { identifierToHuman } from 'lib/utils/strings'import { FLAG_EVALUATIONS_TABLE } from 'scenes/feature-flags/flagEvaluationsTable'+import { actorsOnlyMathTypes } from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'import {FLAG_EVALUATIONS_SERIES_FIELDS,withFlagCallsAggregationTarget,@@ -15,7 +16,7 @@ import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'import { urls } from 'scenes/urls'-import { actorsOnlyMathTypes, expandGroupNodes } from '~/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries'+import { expandGroupNodes } from '~/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries'import { nodeKindToInsightType } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'import { getDefaultQuery } from '~/queries/nodes/InsightViz/utils'import {diff --git a/frontend/src/scenes/insights/filters/ActionFilter/cleanSeriesNodes.test.ts b/frontend/src/scenes/insights/filters/ActionFilter/cleanSeriesNodes.test.tsnew file mode 100644index 000000000000..a6b654e27a5c--- /dev/null+++ b/frontend/src/scenes/insights/filters/ActionFilter/cleanSeriesNodes.test.ts@@ -0,0 +1,129 @@+import { NodeKind } from '~/queries/schema/schema-general'+import {+ BaseMathType,+ CalendarHeatmapMathType,+ FilterLogicalOperator,+ FunnelMathType,+ PropertyFilterType,+ PropertyMathType,+ PropertyOperator,+} from '~/types'++import { MathAvailability } from './ActionFilterRow/types'+import { cleanSeriesNodes } from './cleanSeriesNodes'+import { SeriesNode } from './seriesNode'++const pageview = { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' }++describe('cleanSeriesNodes', () => {+ it.each([+ {+ name: 'keeps math fields the picker does not edit',+ mathAvailability: MathAvailability.All,+ series: [+ {+ ...pageview,+ math: PropertyMathType.Sum,+ math_property: 'revenue',+ math_property_revenue_currency: { static: 'EUR' },+ math_multiplier: 0.01,+ },+ ],+ expected: [+ {+ ...pageview,+ math: PropertyMathType.Sum,+ math_property: 'revenue',+ math_property_revenue_currency: { static: 'EUR' },+ math_multiplier: 0.01,+ },+ ],+ },+ {+ name: 'keeps an actors math in stickiness',+ mathAvailability: MathAvailability.ActorsOnly,+ series: [{ ...pageview, math: 'unique_group', math_group_type_index: 1 }],+ expected: [{ ...pageview, math: 'unique_group', math_group_type_index: 1 }],+ },+ {+ name: 'drops math a funnel step cannot use',+ mathAvailability: MathAvailability.FunnelsOnly,+ series: [+ { ...pageview, math: BaseMathType.UniqueUsers },+ { ...pageview, math: FunnelMathType.FirstTimeForUser, math_property: '$browser' },+ ],+ expected: [pageview, { ...pageview, math: FunnelMathType.FirstTimeForUser }],+ },+ {+ name: 'drops math a calendar heatmap cannot use',+ mathAvailability: MathAvailability.CalendarHeatmapOnly,+ series: [+ { ...pageview, math: BaseMathType.WeeklyActiveUsers },+ { ...pageview, math: CalendarHeatmapMathType.UniqueUsers },+ ],+ expected: [pageview, { ...pageview, math: CalendarHeatmapMathType.UniqueUsers }],+ },+ {+ name: 'drops all math and keeps the exclusion step range',+ mathAvailability: MathAvailability.None,+ series: [{ ...pageview, math: BaseMathType.TotalCount, funnelFromStep: 0, funnelToStep: 2 }],+ expected: [{ ...pageview, funnelFromStep: 0, funnelToStep: 2 }],+ },+ {+ name: 'drops unset and empty fields',+ mathAvailability: MathAvailability.All,+ series: [+ {+ ...pageview,+ custom_name: '',+ properties: [],+ math: BaseMathType.TotalCount,+ math_property: undefined,+ math_hogql: undefined,+ },+ ],+ expected: [{ ...pageview, math: BaseMathType.TotalCount }],+ },+ {+ name: 'cleans the nodes inside a group',+ mathAvailability: MathAvailability.All,+ series: [+ {+ kind: NodeKind.GroupNode,+ operator: FilterLogicalOperator.Or,+ name: '$pageview',+ nodes: [+ {+ ...pageview,+ properties: [{ key: '$browser', value: 'Chrome', type: PropertyFilterType.Event }],+ },+ ],+ },+ ],+ expected: [+ {+ kind: NodeKind.GroupNode,+ operator: FilterLogicalOperator.Or,+ name: '$pageview',+ math: BaseMathType.TotalCount,+ nodes: [+ {+ ...pageview,+ math: BaseMathType.TotalCount,+ properties: [+ {+ key: '$browser',+ value: 'Chrome',+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ },+ ],+ },+ ],+ },+ ],+ },+ ])('$name', ({ mathAvailability, series, expected }) => {+ expect(cleanSeriesNodes(series as SeriesNode[], mathAvailability)).toStrictEqual(expected)+ })+})diff --git a/frontend/src/scenes/insights/filters/ActionFilter/cleanSeriesNodes.ts b/frontend/src/scenes/insights/filters/ActionFilter/cleanSeriesNodes.tsnew file mode 100644index 000000000000..41938fe712c2--- /dev/null+++ b/frontend/src/scenes/insights/filters/ActionFilter/cleanSeriesNodes.ts@@ -0,0 +1,109 @@+import { objectCleanWithEmpty } from 'lib/utils/objects'++import { cleanEntityProperties } from '~/queries/nodes/InsightQuery/utils/cleanProperties'+import { EntityNode, MathType } from '~/queries/schema/schema-general'+import { BaseMathType, CalendarHeatmapMathType, FunnelMathType, GroupMathType, HogQLMathType } from '~/types'++import { MathAvailability } from './ActionFilterRow/types'+import { SeriesNode, isGroupSeriesNode } from './seriesNode'++export const actorsOnlyMathTypes: readonly MathType[] = [+ BaseMathType.UniqueUsers,+ BaseMathType.WeeklyActiveUsers,+ BaseMathType.MonthlyActiveUsers,+ GroupMathType.UniqueGroup,+ HogQLMathType.HogQL,+]++export const funnelsMathTypes: readonly MathType[] = [+ FunnelMathType.FirstTimeForUser,+ FunnelMathType.FirstTimeForUserWithFilters,+]++export const calendarHeatmapMathTypes: readonly MathType[] = [+ CalendarHeatmapMathType.TotalCount,+ CalendarHeatmapMathType.UniqueUsers,+]++type SeriesMath = Pick<+ EntityNode,+ | 'math'+ | 'math_property'+ | 'math_property_type'+ | 'math_property_revenue_currency'+ | 'math_hogql'+ | 'math_group_type_index'+ | 'math_multiplier'+>++function allowedMath(seriesMath: SeriesMath, mathAvailability: MathAvailability): SeriesMath {+ const { math } = seriesMath+ switch (mathAvailability) {+ case MathAvailability.None:+ return {}+ case MathAvailability.FunnelsOnly:+ return math && funnelsMathTypes.includes(math) ? { math } : {}+ case MathAvailability.CalendarHeatmapOnly:+ return math && calendarHeatmapMathTypes.includes(math) ? { math } : {}+ case MathAvailability.ActorsOnly:+ // Stickiness counts actors, and the math selector has no option to show for any other math.+ if (!math || !actorsOnlyMathTypes.includes(math)) {+ return { math: BaseMathType.UniqueUsers }+ }+ return seriesMath+ default:+ return { ...seriesMath, math: math || BaseMathType.TotalCount }+ }+}++function cleanSeriesNode(node: SeriesNode, mathAvailability: MathAvailability, isFirstStep: boolean): SeriesNode {+ const {+ math,+ math_property,+ math_property_type,+ math_property_revenue_currency,+ math_hogql,+ math_group_type_index,+ math_multiplier,+ optionalInFunnel,+ name,+ custom_name,+ properties,+ ...rest+ } = node++ return objectCleanWithEmpty({+ ...rest,+ name: name || undefined,+ custom_name: custom_name || undefined,+ properties: cleanEntityProperties(properties),+ ...allowedMath(+ {+ math,+ math_property,+ math_property_type,+ math_property_revenue_currency,+ math_hogql,+ math_group_type_index,+ math_multiplier,+ },+ mathAvailability+ ),+ // The first step of a funnel cannot be optional.+ optionalInFunnel:+ mathAvailability === MathAvailability.FunnelsOnly && !isFirstStep && optionalInFunnel ? true : undefined,+ ...(isGroupSeriesNode(node)+ ? { nodes: node.nodes.map((nested) => cleanSeriesNode(nested, mathAvailability, false)) }+ : {}),+ }) as SeriesNode+}++/**+ * Prepares the series a picker emits for the query that stores them. Math the picker's+ * `MathAvailability` does not allow is dropped or replaced by that insight's default, unset and+ * empty fields go, and property filters are cleaned. Every other field is kept, including fields+ * the picker does not edit, such as `math_multiplier` or `funnelFromStep`.+ */+export function cleanSeriesNodes(series: SeriesNode[], mathAvailability: MathAvailability): SeriesNode[] {+ return series.map((node, index) => cleanSeriesNode(node, mathAvailability, index === 0))+}diff --git a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.ts b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.tsindex dc0e94ea0716..ce2eea00294d 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.ts@@ -2,7 +2,7 @@ import { expectLogic } from 'kea-test-utils'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import * as libUtils from 'lib/utils/dom'-import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'+import { SeriesEntityUpdate, entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'import { useMocks } from '~/mocks/jest'import { NodeKind } from '~/queries/schema/schema-general'@@ -222,6 +222,45 @@ describe('entityFilterLogic', () => {})})+ describe('updateSeriesMath resets property math settings', () => {+ const revenueSeries = {+ kind: NodeKind.EventsNode,+ event: 'purchase',+ name: 'purchase',+ math: 'sum',+ math_property: 'revenue',+ math_property_type: TaxonomicFilterGroupType.NumericalEventProperties,+ math_multiplier: 0.01,+ math_property_revenue_currency: { property: 'currency' },+ } as SeriesNode+ const revenueSettings = { math_multiplier: 0.01, math_property_revenue_currency: { property: 'currency' } }+ const noSettings = { math_multiplier: undefined, math_property_revenue_currency: undefined }++ it.each([+ [+ 'keeps them when the math changes on the same property',+ { math: 'avg', math_property: 'revenue', math_hogql: undefined },+ revenueSettings,+ ],+ [+ 'drops them when the math property changes',+ { math: 'sum', math_property: 'item_count', math_hogql: undefined },+ noSettings,+ ],+ [+ 'drops them when the math stops reading a property',+ { math: 'total', math_property: undefined, math_hogql: undefined },+ noSettings,+ ],+ ])('%s', (_name, update, expectedSettings) => {+ logic.actions.setLocalSeries([{ uuid: 'uuid-0', node: revenueSeries }])+ logic.actions.updateSeriesMath(0, update)++ const { math_multiplier, math_property_revenue_currency } = logic.values.series[0]+ expect({ math_multiplier, math_property_revenue_currency }).toEqual(expectedSettings)+ })+ })+describe('updateSeriesEntity across node kinds', () => {const personProperty: AnyPropertyFilter = {key: 'email',@@ -303,37 +342,130 @@ describe('entityFilterLogic', () => {})+ const sourcedDataWarehouseNode = {+ kind: NodeKind.DataWarehouseNode,+ id: 'payments',+ name: 'payments',+ table_name: 'payments',+ id_field: 'id',+ timestamp_field: 'created_at',+ distinct_id_field: 'customer_id',+ dw_source_type: 'Stripe',+ } as SeriesNode+ const limitedEventNode = {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ limit: 100,+ orderBy: ['timestamp DESC'],+ } as SeriesNode++ it.each([+ [+ 'drops limit and orderBy when an event becomes an action',+ limitedEventNode,+ { kind: NodeKind.ActionsNode, key: 7, name: 'Sign up' },+ { kind: NodeKind.ActionsNode, id: 7, name: 'Sign up' },+ ],+ [+ 'drops limit and orderBy when an event becomes a data warehouse series',+ limitedEventNode,+ { kind: NodeKind.DataWarehouseNode, key: 'payments', name: 'payments' },+ { kind: NodeKind.DataWarehouseNode, id: 'payments', name: 'payments', table_name: 'payments' },+ ],+ [+ 'drops the event when an event becomes a data warehouse series',+ eventNode,+ { kind: NodeKind.DataWarehouseNode, key: 'payments', name: 'payments' },+ {+ kind: NodeKind.DataWarehouseNode,+ id: 'payments',+ name: 'payments',+ table_name: 'payments',+ properties: [hogqlProperty],+ },+ ],+ [+ 'drops the warehouse fields when a data warehouse series becomes an event',+ sourcedDataWarehouseNode,+ { kind: NodeKind.EventsNode, key: '$pageview', name: '$pageview' },+ { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' },+ ],+ [+ 'drops the warehouse fields when a data warehouse series becomes an action',+ sourcedDataWarehouseNode,+ { kind: NodeKind.ActionsNode, key: 7, name: 'Sign up' },+ { kind: NodeKind.ActionsNode, id: 7, name: 'Sign up' },+ ],+ [+ 'drops the source type when the data warehouse table changes',+ sourcedDataWarehouseNode,+ { kind: NodeKind.DataWarehouseNode, key: 'orders', name: 'orders' },+ {+ kind: NodeKind.DataWarehouseNode,+ id: 'orders',+ name: 'orders',+ table_name: 'orders',+ id_field: 'id',+ timestamp_field: 'created_at',+ distinct_id_field: 'customer_id',+ },+ ],+ [+ 'keeps the source type when the data warehouse table is unchanged',+ sourcedDataWarehouseNode,+ { kind: NodeKind.DataWarehouseNode, key: 'payments', name: 'payments', timestamp_field: 'paid_at' },+ { ...sourcedDataWarehouseNode, timestamp_field: 'paid_at' },+ ],+ ] as [string, SeriesNode, SeriesEntityUpdate, Record<string, any>][])(+ '%s',+ (_name, initialNode, update, expectedNode) => {+ logic.actions.setLocalSeries([{ uuid: 'uuid-0', node: initialNode }])+ logic.actions.updateSeriesEntity(0, update)++ expect(logic.values.series[0]).toEqual(expectedNode)+ }+ )+const eventPropertyMath = {...eventNode,math: 'sum',math_property: 'revenue',math_property_type: TaxonomicFilterGroupType.NumericalEventProperties,+ math_multiplier: 0.01,} as SeriesNodeconst dataWarehousePropertyMath = {...dataWarehouseNode,math: 'sum',math_property: 'amount',math_property_type: TaxonomicFilterGroupType.DataWarehouseProperties,+ math_multiplier: 0.01,} as SeriesNode+ const droppedPropertyMath = {+ math: undefined,+ math_property: undefined,+ math_property_type: undefined,+ math_multiplier: undefined,+ }it.each([['drops property math when an event becomes a data warehouse series',eventPropertyMath,switchToPayments,- { math: undefined, math_property: undefined, math_property_type: undefined },+ droppedPropertyMath,],['drops property math when a data warehouse series becomes an event',dataWarehousePropertyMath,{ kind: NodeKind.EventsNode, key: '$pageview', name: '$pageview' },- { math: undefined, math_property: undefined, math_property_type: undefined },+ droppedPropertyMath,],['drops property math when the data warehouse table changes',dataWarehousePropertyMath,{ kind: NodeKind.DataWarehouseNode, key: 'orders', name: 'orders' },- { math: undefined, math_property: undefined, math_property_type: undefined },+ droppedPropertyMath,],['keeps property math when the data warehouse table is unchanged',@@ -343,6 +475,7 @@ describe('entityFilterLogic', () => {math: 'sum',math_property: 'amount',math_property_type: TaxonomicFilterGroupType.DataWarehouseProperties,+ math_multiplier: 0.01,},],[diff --git a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.tsindex 174798713135..1192dc402dca 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts@@ -67,6 +67,28 @@ export interface SelectedSeries {const PROPERTY_VALUE_MATHS = new Set<string>(Object.values(PropertyMathType))+// Fields that only the data warehouse node kinds define. The events and actions node schemas+// forbid unknown keys, so a query fails when one of these is left on an event or action series.+const WAREHOUSE_ONLY_FIELDS = [+ 'table_name',+ 'timestamp_field',+ 'id_field',+ 'distinct_id_field',+ 'aggregation_target_field',+ 'created_at_field',+ 'dw_source_type',+ 'events_join_key',+ 'data_warehouse_join_key',+] as const++// Fields only an events node defines. The actions and data warehouse node schemas forbid unknown+// keys, so a query fails when one of these is left on a series that stopped being an event.+const EVENTS_ONLY_FIELDS = ['event', 'limit', 'orderBy'] as const++// A multiplier and a revenue currency describe one math property, so they cannot carry over to+// another property. Otherwise the query would scale and currency-convert the wrong value.+const PROPERTY_MATH_SETTINGS = ['math_multiplier', 'math_property_revenue_currency'] as const+// math_property names a column or property on the entity the series aggregates, so it cannot// survive an entity switch. Property-value math (sum, avg, percentiles) is dropped with it —// the backend errors out on that math without a math_property.@@ -76,6 +98,9 @@ function dropStaleMath(node: Record<string, any>): void {}node.math_property = undefinednode.math_property_type = undefined+ PROPERTY_MATH_SETTINGS.forEach((field) => {+ node[field] = undefined+ })}function toLocalSeries(series: SeriesNode[]): LocalSeries[] {@@ -367,6 +392,9 @@ export const entityFilterLogic = kea<entityFilterLogicType>([}if (isWarehouseSeriesNodeKind(kind)) {+ EVENTS_ONLY_FIELDS.forEach((field) => {+ delete next[field]+ })applySeriesKey(next, kind, typeof key === 'undefined' ? seriesNodeKey(current) : key)dataWarehousePopoverFields.forEach(({ key: fieldKey }) => {const value = extra[fieldKey]@@ -389,6 +417,8 @@ export const entityFilterLogic = kea<entityFilterLogicType>([if (!isWarehouseSeriesNode(current) || next.table_name !== (current as any).table_name) {dropStaleMath(next)+ // The source type describes the previous table.+ delete next.dw_source_type}return withLatestVersion(next as SeriesNode)@@ -398,12 +428,14 @@ export const entityFilterLogic = kea<entityFilterLogicType>([return withLatestVersion({ ...next, ...extra } as SeriesNode)}- // Leaving the warehouse: its popover fields and column filters name a table- // an event or action series does not select from, so neither can carry over.+ // Leaving the warehouse: its fields, popover fields and column filters name a+ // table an event or action series does not select from, so none can carry over.+ WAREHOUSE_ONLY_FIELDS.forEach((field) => {+ delete next[field]+ })dataWarehousePopoverFields.forEach(({ key: fieldKey }) => {delete next[fieldKey]})- delete next.table_nameif (Array.isArray(current.properties)) {next.properties = current.properties.filter((property: AnyPropertyFilter) => property.type !== PropertyFilterType.DataWarehouse@@ -416,7 +448,9 @@ export const entityFilterLogic = kea<entityFilterLogicType>([if (kind === NodeKind.EventsNode) {delete next.id} else {- delete next.event+ EVENTS_ONLY_FIELDS.forEach((field) => {+ delete next[field]+ })}if (previousKind === NodeKind.GroupNode) {delete next.nodes@@ -433,7 +467,15 @@ export const entityFilterLogic = kea<entityFilterLogicType>([replaceAt(index, (node) => ({ ...node, properties }) as SeriesNode)},updateSeriesMath: ({ index, math }) => {- replaceAt(index, (node) => ({ ...node, ...math }) as SeriesNode)+ replaceAt(index, (node) => {+ const next: Record<string, any> = { ...node, ...math }+ if (next.math_property !== node.math_property) {+ PROPERTY_MATH_SETTINGS.forEach((field) => {+ next[field] = undefined+ })+ }+ return next as SeriesNode+ })},updateSeriesOptional: ({ index, optionalInFunnel }) => {replaceAt(index, (node) => ({ ...node, optionalInFunnel }) as SeriesNode)diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.tsindex ed1f85024af1..b89df9113f3d 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts@@ -3,6 +3,8 @@ import { expectLogic } from 'kea-test-utils'import { FEATURE_FLAGS, FunnelLayout } from 'lib/constants'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { getDefaultEventLabel, getDefaultEventName } from 'lib/utils/getAppContext'+import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'import { QuerySourceUpdate, insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'import { useMocks } from '~/mocks/jest'@@ -38,6 +40,8 @@ import { insightDataLogic } from './insightDataLogic'const Insight123 = '123' as InsightShortId+type PickerLogic = ReturnType<typeof entityFilterLogic.build>+describe('insightVizDataLogic', () => {let builtInsightVizDataLogic: ReturnType<typeof insightVizDataLogic.build>let builtInsightDataLogic: ReturnType<typeof insightDataLogic.build>@@ -583,6 +587,85 @@ describe('insightVizDataLogic', () => {})})+ describe('updateSeries', () => {+ const pageview = { kind: NodeKind.EventsNode, event: '$pageview', name: '$pageview' }+ const signUp = { kind: NodeKind.ActionsNode, id: 7, name: 'Sign up' }+ const added = { kind: NodeKind.EventsNode, event: getDefaultEventName(), name: getDefaultEventLabel() }++ it.each([+ {+ edit: 'adds a series with the default math',+ source: { kind: NodeKind.TrendsQuery, series: [{ ...pageview, math: BaseMathType.UniqueUsers }] },+ apply: (picker: PickerLogic) => picker.actions.addSeries(),+ expected: [+ { ...pageview, math: BaseMathType.UniqueUsers },+ { ...added, math: BaseMathType.TotalCount },+ ],+ },+ {+ edit: 'changes a math',+ source: { kind: NodeKind.TrendsQuery, series: [{ ...pageview, math: BaseMathType.TotalCount }] },+ apply: (picker: PickerLogic) =>+ picker.actions.updateSeriesMath(0, { math: BaseMathType.WeeklyActiveUsers, math_hogql: undefined }),+ expected: [{ ...pageview, math: BaseMathType.WeeklyActiveUsers }],+ },+ {+ edit: 'removes a series',+ source: {+ kind: NodeKind.TrendsQuery,+ series: [+ { ...pageview, math: BaseMathType.TotalCount },+ { ...signUp, math: BaseMathType.TotalCount },+ ],+ },+ apply: (picker: PickerLogic) => picker.actions.removeSeries(0),+ expected: [{ ...signUp, math: BaseMathType.TotalCount }],+ },+ {+ edit: 'reorders series',+ source: {+ kind: NodeKind.TrendsQuery,+ series: [+ { ...pageview, math: BaseMathType.TotalCount },+ { ...signUp, math: BaseMathType.TotalCount },+ ],+ },+ apply: (picker: PickerLogic) => picker.actions.setLocalSeries([...picker.values.localSeries].reverse()),+ expected: [+ { ...signUp, math: BaseMathType.TotalCount },+ { ...pageview, math: BaseMathType.TotalCount },+ ],+ },+ {+ edit: 'adds a stickiness series with an actors math',+ source: { kind: NodeKind.StickinessQuery, series: [{ ...pageview, math: BaseMathType.UniqueUsers }] },+ apply: (picker: PickerLogic) => picker.actions.addSeries(),+ expected: [+ { ...pageview, math: BaseMathType.UniqueUsers },+ { ...added, math: BaseMathType.UniqueUsers },+ ],+ },+ {+ edit: 'moves an optional funnel step to the start',+ source: { kind: NodeKind.FunnelsQuery, series: [pageview, { ...signUp, optionalInFunnel: true }] },+ apply: (picker: PickerLogic) => picker.actions.setLocalSeries([...picker.values.localSeries].reverse()),+ expected: [signUp, pageview],+ },+ ])('$edit', ({ source, apply, expected }) => {+ builtInsightDataLogic.actions.setQuery({ kind: NodeKind.InsightVizNode, source } as Node)+ const picker = entityFilterLogic({+ typeKey: 'insight-series',+ series: builtInsightVizDataLogic.values.series ?? [],+ onChange: builtInsightVizDataLogic.actions.updateSeries,+ })+ picker.mount()++ apply(picker)++ expect(builtInsightVizDataLogic.values.series).toEqual(expected)+ })+ })+describe('updateDateRange', () => {it('does not inject the interval side effect into a paths v2 query, which has no interval field', async () => {builtInsightDataLogic.actions.setQuery({diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex 1f28b8fc1f55..271bfafe6a7e 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -26,12 +26,15 @@ import {FLAG_EVALUATIONS_TABLE,insightReachesPastFlagEvaluationsRetention,} from 'scenes/feature-flags/flagEvaluationsTable'+import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'+import { cleanSeriesNodes } from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'import {FLAG_CALLS_SERIES_NAME,flagCallsBreakdownFromEventBreakdown,readsFlagCalls,withFlagCallsAggregationTarget,} from 'scenes/insights/filters/ActionFilter/flagCallsSeries'+import type { SeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { insightLogic } from 'scenes/insights/insightLogic'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'@@ -290,6 +293,7 @@ export interface insightVizDataLogicValues {retentionFilter: RetentionFilter | nullsamplingFactor: number | null | undefinedseries: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode<DataWarehouseNode>)[] | null | undefined+ seriesMathAvailability: MathAvailabilityshouldShowSessionAnalysisWarning: booleanshowAlertThresholdLines: boolean | null | undefinedshowAnnotations: boolean | null | undefined@@ -478,6 +482,9 @@ export interface insightVizDataLogicActions {updateQuerySource: (querySource: QuerySourceUpdate) => {querySource: QuerySourceUpdate}+ updateSeries: (series: SeriesNode[]) => {+ series: SeriesNode[]+ }updateVizSpecificOptions: (vizSpecificOptions: VizSpecificOptions) => {vizSpecificOptions: VizSpecificOptions}@@ -1219,6 +1226,12 @@ export interface insightVizDataLogicMeta {breakdownFilter: BreakdownFilter | null | undefined) => booleanisBreakdownSeries: (breakdownFilter: BreakdownFilter | null | undefined) => boolean+ seriesMathAvailability: (+ isFunnels: boolean,+ isLifecycle: boolean,+ isStickiness: boolean,+ display: ChartDisplayType | null | undefined+ ) => MathAvailabilityisSingleSeriesDefinition: (isTrends: boolean,formula: string | null | undefined,@@ -1417,6 +1430,7 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([actions({saveInsight: (redirectToViewMode = true) => ({ redirectToViewMode }),updateQuerySource: (querySource: QuerySourceUpdate) => ({ querySource }),+ updateSeries: (series: SeriesNode[]) => ({ series }),updateInsightFilter: (insightFilter: InsightFilter) => ({ insightFilter }),updateDateRange: (dateRange: DateRange, ignoreDebounce: boolean = false) => ({ dateRange, ignoreDebounce }),/** Apply a drag-to-zoom date range to the insight's query. Both dates are bucket starts;@@ -2350,6 +2364,26 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([return !!breakdownFilter?.breakdown || (breakdownFilter?.breakdowns?.length ?? 0) > 0},],+ seriesMathAvailability: [+ (s) => [s.isFunnels, s.isLifecycle, s.isStickiness, s.display],+ (+ isFunnels: boolean,+ isLifecycle: boolean,+ isStickiness: boolean,+ display: ChartDisplayType | null | undefined+ ): MathAvailability =>+ isFunnels+ ? MathAvailability.FunnelsOnly+ : isLifecycle+ ? MathAvailability.None+ : isStickiness+ ? MathAvailability.ActorsOnly+ : display === ChartDisplayType.CalendarHeatmap+ ? MathAvailability.CalendarHeatmapOnly+ : display === ChartDisplayType.BoxPlot+ ? MathAvailability.BoxPlotOnly+ : MathAvailability.All,+ ],// Whether there's only one event/action series defined in the query.// Ignores breakdowns which create multiple visual outputs from the same series.@@ -2782,6 +2816,11 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([} as InsightQueryNode),} as Node)},+ updateSeries: ({ series }) => {+ actions.updateQuerySource({+ series: cleanSeriesNodes(series, values.seriesMathAvailability),+ } as QuerySourceUpdate)+ },zoomDateRange: ({ dateFrom, dateTo }) => {posthog.capture('insight drag to zoomed', { query_kind: values.querySource?.kind })diff --git a/products/product_analytics/frontend/insights/funnels/editor/FunnelsQuerySteps.tsx b/products/product_analytics/frontend/insights/funnels/editor/FunnelsQuerySteps.tsxindex edad0be246f9..0f50d2b55ec7 100644--- a/products/product_analytics/frontend/insights/funnels/editor/FunnelsQuerySteps.tsx+++ b/products/product_analytics/frontend/insights/funnels/editor/FunnelsQuerySteps.tsx@@ -4,43 +4,30 @@ import { useActions, useValues } from 'kea'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { getProjectEventExistence } from 'lib/utils/getAppContext'-import { ActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'-import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'+import { SeriesActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'import { getInsightPropertyFilterGroupTypes } from 'scenes/insights/utils/propertyTaxonomicGroupTypes'import { groupsModel } from '~/models/groupsModel'-import { actionsAndEventsToSeries } from '~/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries'-import { queryNodeToFilter } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'-import { FunnelsQuery, NodeKind } from '~/queries/schema/schema-general'+import { NodeKind } from '~/queries/schema/schema-general'import { isInsightQueryNode } from '~/queries/utils'-import { EditorFilterProps, FilterType } from '~/types'+import { EditorFilterProps, InsightType } from '~/types'import { FunnelDataWarehouseStepDefinitionPopover } from './FunnelDataWarehouseStepDefinitionPopover'export const FUNNEL_STEP_COUNT_LIMIT = 30export function FunnelsQuerySteps({ insightProps }: EditorFilterProps): JSX.Element | null {- const { series, querySource } = useValues(insightVizDataLogic(insightProps))- const { updateQuerySource } = useActions(insightVizDataLogic(insightProps))+ const { series, querySource, isBreakdownSeries, seriesMathAvailability } = useValues(+ insightVizDataLogic(insightProps)+ )+ const { updateSeries } = useActions(insightVizDataLogic(insightProps))const { hasPageview, hasScreen } = getProjectEventExistence()- const actionFilters = isInsightQueryNode(querySource) ? queryNodeToFilter(querySource) : null- const setActionFilters = (payload: Partial<FilterType>): void => {- updateQuerySource({- series: actionsAndEventsToSeries(- payload as any,- true,- MathAvailability.FunnelsOnly,- NodeKind.FunnelsDataWarehouseNode- ),- } as FunnelsQuery)- }-const { groupsTaxonomicTypes } = useValues(groupsModel)- if (!actionFilters) {+ if (!isInsightQueryNode(querySource)) {return null}@@ -51,13 +38,16 @@ export function FunnelsQuerySteps({ insightProps }: EditorFilterProps): JSX.Elemreturn (<><div className="FunnelsQuerySteps">- <ActionFilter+ <SeriesActionFilterallowBehavioralPropertyFilterbordered={false}- filters={actionFilters}- setFilters={setActionFilters}+ series={filterSteps}+ onChange={updateSeries}+ insightType={InsightType.FUNNELS}+ hasBreakdown={isBreakdownSeries}+ dataWarehouseNodeKind={NodeKind.FunnelsDataWarehouseNode}typeKey={keyForInsightLogicProps('new')(insightProps)}- mathAvailability={MathAvailability.FunnelsOnly}+ mathAvailability={seriesMathAvailability}hideDeleteBtn={filterSteps.length === 1}buttonCopy="Add step"showSeriesIndicator={showSeriesIndicator}diff --git a/products/product_analytics/frontend/insights/funnels/filters/FunnelExclusionsFilter/FunnelExclusionsFilter.tsx b/products/product_analytics/frontend/insights/funnels/filters/FunnelExclusionsFilter/FunnelExclusionsFilter.tsxindex 2b19074cc1aa..8c10dc9b4315 100644--- a/products/product_analytics/frontend/insights/funnels/filters/FunnelExclusionsFilter/FunnelExclusionsFilter.tsx+++ b/products/product_analytics/frontend/insights/funnels/filters/FunnelExclusionsFilter/FunnelExclusionsFilter.tsx@@ -2,15 +2,11 @@ import { useActions, useValues } from 'kea'import { useRef } from 'react'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-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 { insightLogic } from 'scenes/insights/insightLogic'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'-import { legacyEntityToNode } from '~/queries/nodes/InsightQuery/utils/actionsAndEventsToSeries'-import { ActionsNode, EventsNode } from '~/queries/schema/schema-general'-import { ActionFilter as ActionFilterType, EntityTypes, FilterType } from '~/types'-import { funnelDataLogic } from 'products/product_analytics/frontend/insights/funnels/funnelDataLogic'import { ExclusionRow } from './ExclusionRow'@@ -18,39 +14,21 @@ import { ExclusionRowSuffix } from './ExclusionRowSuffix'export function FunnelExclusionsFilter(): JSX.Element {const { insightProps } = useValues(insightLogic)- const { exclusionFilters, exclusionDefaultStepRange, isFunnelWithEnoughSteps } = useValues(- funnelDataLogic(insightProps)- )- const { updateInsightFilter } = useActions(funnelDataLogic(insightProps))+ const { funnelsFilter, newExclusionDefaults, isFunnelWithEnoughSteps } = useValues(funnelDataLogic(insightProps))+ const { updateExclusions } = useActions(funnelDataLogic(insightProps))const ref = useRef(null)- const setFilters = (filters: Partial<FilterType>): void => {- const exclusions = filters.events?.map((entity) => {- const baseEntity = legacyEntityToNode(entity as ActionFilterType, true, MathAvailability.None) as- | EventsNode- | ActionsNode- return { ...baseEntity, funnelFromStep: entity.funnel_from_step, funnelToStep: entity.funnel_to_step }- })- updateInsightFilter({ exclusions })- }-const typeKey = `${keyForInsightLogicProps('new')(insightProps)}-FunnelExclusionsFilter`return (<div data-attr="funnel-exclusions-filter">- <ActionFilter+ <SeriesActionFilterref={ref}- setFilters={setFilters}- filters={exclusionFilters}+ series={funnelsFilter?.exclusions ?? []}+ onChange={updateExclusions}typeKey={typeKey}- addFilterDefaultOptions={{- id: '$pageview',- name: '$pageview',- type: EntityTypes.EVENTS,- funnel_from_step: exclusionDefaultStepRange.funnelFromStep,- funnel_to_step: exclusionDefaultStepRange.funnelToStep,- }}+ newSeriesDefaults={newExclusionDefaults}disabled={!isFunnelWithEnoughSteps}buttonCopy="Add exclusion"actionsTaxonomicGroupTypes={[TaxonomicFilterGroupType.Events]}diff --git a/products/product_analytics/frontend/insights/funnels/funnelDataLogic.test.ts b/products/product_analytics/frontend/insights/funnels/funnelDataLogic.test.tsindex 402c3596494c..a753ac263f1f 100644--- a/products/product_analytics/frontend/insights/funnels/funnelDataLogic.test.ts+++ b/products/product_analytics/frontend/insights/funnels/funnelDataLogic.test.ts@@ -3,11 +3,18 @@ import { expectLogic } from 'kea-test-utils'import timekeeper from 'timekeeper'import { FunnelLayout } from 'lib/constants'+import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'import { AGGREGATION_LABEL_FOR_CUSTOM_DATA_WAREHOUSE } from 'scenes/insights/filters/aggregationTargetUtils'import { teamLogic } from 'scenes/teamLogic'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'-import { DataNode, FunnelsQuery, FunnelsQuerySeriesNodeUnion, NodeKind } from '~/queries/schema/schema-general'+import {+ DataNode,+ FunnelExclusion,+ FunnelsQuery,+ FunnelsQuerySeriesNodeUnion,+ NodeKind,+} from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import {EntityType,@@ -36,6 +43,8 @@ import {import { funnelDataLogic } from './funnelDataLogic'import { dimPreviousPeriodColor, getVisibilityKey } from './funnelUtils'+type PickerLogic = ReturnType<typeof entityFilterLogic.build>+let logic: ReturnType<typeof funnelDataLogic.build>let builtDataNodeLogic: ReturnType<typeof dataNodeLogic.build>@@ -252,6 +261,81 @@ describe('funnelDataLogic', () => {})})+ describe('exclusions', () => {+ const steps: FunnelsQuerySeriesNodeUnion[] = [+ { kind: NodeKind.EventsNode, event: '$pageview' },+ { kind: NodeKind.EventsNode, event: 'signed_up' },+ { kind: NodeKind.EventsNode, event: 'paid' },+ ]+ const autocaptureExclusion: FunnelExclusion = {+ kind: NodeKind.EventsNode,+ event: '$autocapture',+ name: '$autocapture',+ funnelFromStep: 1,+ funnelToStep: 2,+ }+ const actionExclusion: FunnelExclusion = {+ kind: NodeKind.ActionsNode,+ id: 7,+ name: 'Sign up',+ funnelFromStep: 0,+ funnelToStep: 1,+ }++ it.each([+ {+ edit: 'adds a pageview exclusion across the whole funnel',+ exclusions: [autocaptureExclusion],+ apply: (picker: PickerLogic) => picker.actions.addSeries(),+ expected: [+ autocaptureExclusion,+ {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ funnelFromStep: 0,+ funnelToStep: 2,+ },+ ],+ },+ {+ edit: 'keeps the step range when the event changes',+ exclusions: [autocaptureExclusion],+ apply: (picker: PickerLogic) =>+ picker.actions.updateSeriesEntity(0, {+ kind: NodeKind.EventsNode,+ key: 'logged_out',+ name: 'logged_out',+ }),+ expected: [{ ...autocaptureExclusion, event: 'logged_out', name: 'logged_out' }],+ },+ {+ edit: 'keeps an action exclusion when another exclusion is removed',+ exclusions: [autocaptureExclusion, actionExclusion],+ apply: (picker: PickerLogic) => picker.actions.removeSeries(0),+ expected: [actionExclusion],+ },+ ])('$edit', async ({ exclusions, apply, expected }) => {+ logic.actions.updateQuerySource({+ kind: NodeKind.FunnelsQuery,+ series: steps,+ funnelsFilter: { exclusions },+ } as FunnelsQuery)+ const picker = entityFilterLogic({+ typeKey: 'funnel-exclusions',+ series: logic.values.funnelsFilter?.exclusions ?? [],+ onChange: logic.actions.updateExclusions,+ newSeriesDefaults: logic.values.newExclusionDefaults,+ })+ picker.mount()++ apply(picker)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.funnelsFilter?.exclusions).toEqual(expected)+ })+ })+describe('based on insightDataLogic', () => {describe('results', () => {it('for standard funnel', async () => {diff --git a/products/product_analytics/frontend/insights/funnels/funnelDataLogic.ts b/products/product_analytics/frontend/insights/funnels/funnelDataLogic.tsindex 6a776412a6cb..184480512def 100644--- a/products/product_analytics/frontend/insights/funnels/funnelDataLogic.ts+++ b/products/product_analytics/frontend/insights/funnels/funnelDataLogic.ts@@ -15,6 +15,9 @@ import {} from 'scenes/dashboard/dashboardBreakdownColors'import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'import { getColorFromToken } from 'scenes/dataThemeLogic'+import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'+import { cleanSeriesNodes } from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'+import type { SeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'import { AGGREGATION_LABEL_FOR_CUSTOM_DATA_WAREHOUSE } from 'scenes/insights/filters/aggregationTargetUtils'import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'@@ -29,8 +32,7 @@ import {} from 'scenes/insights/utils'import { Noun, groupsModel } from '~/models/groupsModel'-import { seriesNodeToFilter } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'-import { FunnelExclusionSteps } from '~/queries/schema/schema-general'+import { FunnelExclusion, FunnelExclusionEventsNode, FunnelExclusionSteps } from '~/queries/schema/schema-general'import { FunnelsFilter, FunnelsQuery, FunnelsQueryResponse, NodeKind } from '~/queries/schema/schema-general'import type {AnyDataWarehouseNode,@@ -68,7 +70,6 @@ import {InsightLogicProps,StepOrderValue,TrendResult,- FilterType,} from '~/types'import type { BreakdownKeyType, FunnelStep, IntervalType, LabelGroupType } from '~/types'@@ -301,7 +302,6 @@ export interface funnelDataLogicValues {conversionWindowUnit: FunnelConversionWindowTimeUnit | nulldisableFunnelBreakdownBaseline: booleanexclusionDefaultStepRange: FunnelExclusionSteps- exclusionFilters: FilterTypeflattenedBreakdowns: FlattenedFunnelStepByBreakdown[]funnelVizType: FunnelVizTypegetFunnelsColor: (dataset: FlattenedFunnelStepByBreakdown | FunnelStepWithConversionMetrics) => string@@ -348,6 +348,7 @@ export interface funnelDataLogicValues {isStepsFunnel: boolean | nullisTimeToConvertFunnel: boolean | nullisTrendsFunnel: boolean | null+ newExclusionDefaults: Partial<FunnelExclusionEventsNode>numericBinCount: numberquerySource: FunnelsQuery | nullresultCustomizations: Record<string, ResultCustomizationByValue> | undefined@@ -394,6 +395,9 @@ export interface funnelDataLogicActions {toggleLegendBreakdownVisibility: (breakdown: string) => {breakdown: string}+ updateExclusions: (exclusions: SeriesNode[]) => {+ exclusions: SeriesNode[]+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -578,7 +582,7 @@ export interface funnelDataLogicMeta {isFunnelWithEnoughSteps: (series: FunnelsQuerySeriesNodeUnion[] | null) => booleanisFunnelWithIncompleteDataWarehouseStep: (series: FunnelsQuerySeriesNodeUnion[] | null) => booleanexclusionDefaultStepRange: (querySource: FunnelsQuery | null) => FunnelExclusionSteps- exclusionFilters: (funnelsFilter: FunnelsFilter | null | undefined) => FilterType+ newExclusionDefaults: (exclusionDefaultStepRange: FunnelExclusionSteps) => Partial<FunnelExclusionEventsNode>}}@@ -637,6 +641,7 @@ export const funnelDataLogic = kea<funnelDataLogicType>([funnelWindowIntervalUnit,}),commitConversionWindow: true,+ updateExclusions: (exclusions: SeriesNode[]) => ({ exclusions }),}),reducers({@@ -1497,20 +1502,22 @@ export const funnelDataLogic = kea<funnelDataLogicType>([funnelToStep: (querySource.series || []).length > 1 ? querySource.series.length - 1 : 1,}),],- exclusionFilters: [- (s) => [s.funnelsFilter],- (funnelsFilter: FunnelsFilter | null | undefined): FilterType => ({- events: funnelsFilter?.exclusions?.map(({ funnelFromStep, funnelToStep, ...rest }, index) => ({- funnel_from_step: funnelFromStep,- funnel_to_step: funnelToStep,- order: index,- ...seriesNodeToFilter(rest),- })),+ newExclusionDefaults: [+ (s) => [s.exclusionDefaultStepRange],+ (exclusionDefaultStepRange: FunnelExclusionSteps): Partial<FunnelExclusionEventsNode> => ({+ event: '$pageview',+ name: '$pageview',+ ...exclusionDefaultStepRange,}),],})),listeners(({ actions, values }) => ({+ updateExclusions: ({ exclusions }) => {+ actions.updateInsightFilter({+ exclusions: cleanSeriesNodes(exclusions, MathAvailability.None) as FunnelExclusion[],+ })+ },setHiddenLegendBreakdowns: ({ hiddenLegendBreakdowns }) => {actions.updateInsightFilter({ hiddenLegendBreakdowns })},