Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat(dashboard): funnels can break down by a property from any step (#549)

Carl-Gerhard Lindesvärda8f242e24048
diff --git a/apps/start/e2e/reports-funnel-step-breakdown.spec.ts b/apps/start/e2e/reports-funnel-step-breakdown.spec.ts
new file mode 100644
index 000000000..1cbc29df9
--- /dev/null
+++ b/apps/start/e2e/reports-funnel-step-breakdown.spec.ts
@@ -0,0 +1,91 @@
+import { expect, test } from './fixtures';
+import {
+ addEvent,
+ closeSidebar,
+ eventSeries,
+ openSidebar,
+ pickChartType,
+ reportInput,
+ shot,
+ trackProblems,
+ trpcQuery,
+ waitForChart,
+} from './reports-helpers';
+
+const SHOP = 'acme-shop';
+const STEPS = ['product_viewed', 'add_to_cart', 'checkout_started', 'purchase'];
+const PURCHASE_STEP = 4;
+const DID_NOT_REACH = `Did not reach step ${PURCHASE_STEP}`;
+
+interface FunnelSerie {
+ breakdowns: string[];
+ steps: { count: number }[];
+}
+
+// `payment` is only set on `purchase`, so breaking down from the first step
+// would put everyone in "Not set".
+test('a funnel breaks down by a property that only exists on its last step', async ({
+ page,
+}) => {
+ test.setTimeout(300_000);
+ const problems = trackProblems(page);
+ await page.goto(`/acme/${SHOP}/reports`);
+ await page.waitForLoadState('networkidle');
+ await openSidebar(page);
+ await closeSidebar(page);
+ await pickChartType(page, 'Linear', 'Funnel');
+ for (const step of STEPS) {
+ await addEvent(page, step);
+ }
+
+ const sheet = await openSidebar(page);
+ await sheet.getByRole('button', { name: 'Select breakdown' }).click();
+ await page.getByRole('menuitem', { name: 'Event properties' }).click();
+ await page.getByPlaceholder('Search').last().fill('payment');
+ await page
+ .locator('[data-radix-popper-content-wrapper]')
+ .getByText('payment', { exact: true })
+ .first()
+ .click();
+ await sheet
+ .getByRole('combobox')
+ .filter({ hasText: '1. product_viewed' })
+ .click();
+ await page
+ .getByRole('option', { name: `${PURCHASE_STEP}. purchase` })
+ .click();
+ await shot(page, 'funnel-step-breakdown-sidebar');
+ await closeSidebar(page);
+ await waitForChart(page);
+ await shot(page, 'funnel-step-breakdown');
+
+ const { current } = await trpcQuery<{ current: FunnelSerie[] }>(
+ page,
+ 'chart.funnel',
+ reportInput(SHOP, {
+ chartType: 'funnel',
+ series: eventSeries(STEPS),
+ breakdowns: [{ name: 'properties.payment', step: PURCHASE_STEP }],
+ })
+ );
+ const segments = current.filter(
+ (serie) => serie.breakdowns[0] !== DID_NOT_REACH
+ );
+ expect(segments.length).toBeGreaterThan(1);
+ for (const serie of segments) {
+ const counts = serie.steps.map((step) => step.count);
+ expect(new Set(counts).size, serie.breakdowns.join()).toBe(1);
+ }
+ const dropped = current.find(
+ (serie) => serie.breakdowns[0] === DID_NOT_REACH
+ );
+ expect(dropped?.steps.at(-1)?.count).toBe(0);
+
+ const editorText = await page.locator('#report-editor').innerText();
+ expect(editorText).toContain(DID_NOT_REACH);
+ for (const serie of segments) {
+ expect(editorText).toContain(serie.breakdowns[0] as string);
+ }
+ expect(problems.pageErrors).toEqual([]);
+ expect(problems.responses).toEqual([]);
+});
diff --git a/apps/start/src/components/report/report-slice.test.ts b/apps/start/src/components/report/report-slice.test.ts
new file mode 100644
index 000000000..9f94781f0
--- /dev/null
+++ b/apps/start/src/components/report/report-slice.test.ts
@@ -0,0 +1,41 @@
+import type { IReport } from '@openpanel/core/modules/report/report.constants';
+import { describe, expect, test } from 'vitest';
+import reducer, { removeEvent, setReport } from './reportSlice';
+
+const event = (id: string) => ({
+ id,
+ type: 'event' as const,
+ name: id,
+ segment: 'event' as const,
+ filters: [],
+});
+
+function funnelWithStep(step: number) {
+ return reducer(
+ undefined,
+ setReport({
+ projectId: 'project',
+ name: 'Funnel',
+ chartType: 'funnel',
+ lineType: 'monotone',
+ interval: 'day',
+ range: '30d',
+ previous: false,
+ metric: 'sum',
+ series: [event('a'), event('b'), event('c')],
+ breakdowns: [{ id: 'b0', name: 'properties.variant', step }],
+ } as IReport)
+ );
+}
+
+describe('breakdown step', () => {
+ test('is cleared when removing a series leaves it past the last step', () => {
+ const state = reducer(funnelWithStep(3), removeEvent({ id: 'c' }));
+ expect(state.breakdowns[0]?.step).toBeUndefined();
+ });
+
+ test('is kept while it still points at a step', () => {
+ const state = reducer(funnelWithStep(2), removeEvent({ id: 'c' }));
+ expect(state.breakdowns[0]?.step).toBe(2);
+ });
+});
diff --git a/apps/start/src/components/report/reportSlice.ts b/apps/start/src/components/report/reportSlice.ts
index 58e391875..3349f7343 100644
--- a/apps/start/src/components/report/reportSlice.ts
+++ b/apps/start/src/components/report/reportSlice.ts
@@ -57,6 +57,19 @@ const initialState: InitialState = {
visibleSeries: undefined,
};
+// A breakdown step past the last event series would silently fall back to the
+// first step in the query, so drop it to keep the editor and the chart in step.
+function clearStaleBreakdownSteps(state: InitialState) {
+ const eventCount = state.series.filter(
+ (item) => item.type === 'event'
+ ).length;
+ for (const breakdown of state.breakdowns) {
+ if (breakdown.step && breakdown.step > eventCount) {
+ breakdown.step = undefined;
+ }
+ }
+}
+
export const reportSlice = createSlice({
name: 'report',
initialState,
@@ -130,6 +143,7 @@ export const reportSlice = createSlice({
state.series = state.series.filter((event) => {
return event.id !== action.payload.id;
});
+ clearStaleBreakdownSteps(state);
},
changeEvent: (state, action: PayloadAction<IChartEventItem>) => {
state.dirty = true;
@@ -139,6 +153,7 @@ export const reportSlice = createSlice({
}
return event;
});
+ clearStaleBreakdownSteps(state);
},
// Previous
diff --git a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
index 1fa8ac14c..d15145d38 100644
--- a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
+++ b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
@@ -6,11 +6,21 @@ import { ReportBreakdownMore } from './ReportBreakdownMore';
import type { ReportEventMoreProps } from './ReportEventMore';
import { ColorSquare } from '@/components/color-square';
import { Button } from '@/components/ui/button';
+import { Combobox } from '@/components/ui/combobox';
import { useDispatch, useSelector } from '@/redux';
export function ReportBreakdowns() {
const selectedBreakdowns = useSelector((state) => state.report.breakdowns);
+ const chartType = useSelector((state) => state.report.chartType);
+ const series = useSelector((state) => state.report.series);
const dispatch = useDispatch();
+ const stepItems = series
+ .filter((item) => item.type === 'event')
+ .map((item, index) => ({
+ label: `${index + 1}. ${item.displayName || item.name}`,
+ value: String(index + 1),
+ }));
+ const showStep = chartType === 'funnel' && stepItems.length > 1;
const handleMore = (breakdown: IChartBreakdown) => {
const callback: ReportEventMoreProps['onClick'] = (action) => {
@@ -62,6 +72,29 @@ export function ReportBreakdowns() {
</PropertiesCombobox>
<ReportBreakdownMore onClick={handleMore(item)} />
</div>
+ {showStep && !item.name.startsWith('group.') && (
+ <div className="flex items-center justify-between gap-2 border-t p-2 px-4">
+ <span className="text-muted-foreground text-sm">
+ From step
+ </span>
+ <Combobox
+ align="end"
+ items={stepItems}
+ onChange={(value) =>
+ dispatch(
+ changeBreakdown({
+ ...item,
+ step: value === '1' ? undefined : Number(value),
+ })
+ )
+ }
+ placeholder="Select step"
+ value={String(
+ item.step && item.step <= stepItems.length ? item.step : 1
+ )}
+ />
+ </div>
+ )}
</div>
);
})}
diff --git a/packages/core/src/modules/chart/funnel.step-breakdown.test.ts b/packages/core/src/modules/chart/funnel.step-breakdown.test.ts
new file mode 100644
index 000000000..da55536f8
--- /dev/null
+++ b/packages/core/src/modules/chart/funnel.step-breakdown.test.ts
@@ -0,0 +1,177 @@
+import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
+import { createClient } from '@openpanel/db/src/clickhouse/client';
+import { TEST_CLICKHOUSE_URL } from '../../../../../test/databases';
+import { buildEvent } from '../../../../../test/fixtures';
+import { testServiceDeps } from '../../../test/service-deps';
+import type { ServiceDeps } from '../../services';
+import type { IReportInput } from '../report/report.constants';
+import { getFunnel, getFunnelProfileIds } from './funnel.service';
+
+/**
+ * Funnel landing → signup → purchase; only `signup` carries `variant`, and
+ * variant A signups carry `duration` 30.
+ *
+ * user events, in order
+ * u1 landing, signup A, purchase
+ * u2 landing, signup A, purchase
+ * u3 landing, signup B
+ * u4 landing, signup B, purchase
+ * u5 landing
+ * u6 signup A (never enters the funnel)
+ * u7 signup B, landing, signup A, purchase (in sequence the signup is A)
+ */
+const PROJECT_ID = 'test-funnel-step-breakdown';
+const START = '2024-03-04 00:00:00';
+const END = '2024-03-04 23:59:59';
+
+type Step = 'landing' | 'signup' | 'purchase';
+type JourneyEvent = Step | [Step, string];
+const JOURNEYS: Record<string, JourneyEvent[]> = {
+ u1: ['landing', ['signup', 'A'], 'purchase'],
+ u2: ['landing', ['signup', 'A'], 'purchase'],
+ u3: ['landing', ['signup', 'B']],
+ u4: ['landing', ['signup', 'B'], 'purchase'],
+ u5: ['landing'],
+ u6: [['signup', 'A']],
+ u7: [['signup', 'B'], 'landing', ['signup', 'A'], 'purchase'],
+};
+
+function buildEvents() {
+ return Object.entries(JOURNEYS).flatMap(([user, journey]) =>
+ journey.map((journeyEvent, index) => {
+ const [step, variant] =
+ typeof journeyEvent === 'string' ? [journeyEvent] : journeyEvent;
+ return buildEvent(
+ new Date(),
+ PROJECT_ID,
+ crypto.randomUUID(),
+ step,
+ `profile-${user}`,
+ `session-${user}`,
+ 0,
+ 0,
+ {
+ created_at: `2024-03-04 10:0${index}:00`,
+ properties: variant ? { variant } : {},
+ duration: variant === 'A' ? 30 : 0,
+ }
+ );
+ })
+ );
+}
+
+function funnelInput(
+ breakdowns: IReportInput['breakdowns']
+): Parameters<typeof getFunnel>[1] {
+ return {
+ projectId: PROJECT_ID,
+ startDate: START,
+ endDate: END,
+ timezone: 'UTC',
+ series: (['landing', 'signup', 'purchase'] as const).map((name, index) => ({
+ id: String(index + 1),
+ type: 'event' as const,
+ name,
+ displayName: name,
+ segment: 'user' as const,
+ filters: [],
+ })),
+ breakdowns,
+ chartType: 'funnel',
+ interval: 'day',
+ range: 'custom',
+ previous: false,
+ metric: 'sum',
+ options: { type: 'funnel', funnelWindow: 24, funnelGroup: 'session_id' },
+ };
+}
+
+async function stepCountsBySegment(breakdowns: IReportInput['breakdowns']) {
+ const result = await getFunnel(deps, funnelInput(breakdowns));
+ return Object.fromEntries(
+ result.map((serie) => [
+ serie.breakdowns.join('|'),
+ serie.steps.map((step) => step.count),
+ ])
+ );
+}
+
+let deps: ServiceDeps;
+
+async function withClient(
+ run: (client: ReturnType<typeof createClient>) => Promise<unknown>
+) {
+ const client = createClient({ url: TEST_CLICKHOUSE_URL });
+ try {
+ await run(client);
+ } finally {
+ await client.close();
+ }
+}
+
+describe('funnel breakdown by a property of one step', () => {
+ beforeAll(async () => {
+ deps = await testServiceDeps();
+ await withClient(async (client) => {
+ await client.command({
+ query: `DELETE FROM events WHERE project_id = '${PROJECT_ID}'`,
+ });
+ await client.insert({
+ table: 'events',
+ values: buildEvents(),
+ format: 'JSONEachRow',
+ });
+ });
+ });
+
+ afterAll(async () => {
+ await withClient((client) =>
+ client.command({
+ query: `DELETE FROM events WHERE project_id = '${PROJECT_ID}'`,
+ })
+ );
+ });
+
+ it('attributes to the first step by default', async () => {
+ expect(await stepCountsBySegment([{ name: 'properties.variant' }])).toEqual(
+ { 'Not set': [6, 5, 4] }
+ );
+ });
+
+ it('segments every step by the chosen step, read from the event in the sequence, with a bucket for who never reached it', async () => {
+ expect(
+ await stepCountsBySegment([{ name: 'properties.variant', step: 2 }])
+ ).toEqual({
+ A: [3, 3, 3],
+ B: [2, 2, 1],
+ 'Did not reach step 2': [1, 0, 0],
+ });
+ });
+
+ it('segments by a numeric column of the chosen step', async () => {
+ expect(await stepCountsBySegment([{ name: 'duration', step: 2 }])).toEqual({
+ '30': [3, 3, 3],
+ '0': [2, 2, 1],
+ 'Did not reach step 2': [1, 0, 0],
+ });
+ });
+
+ it('lists the users of a step bucket', async () => {
+ const profilesAt = (breakdownValue: string, targetLevel: number) =>
+ getFunnelProfileIds(deps, {
+ projectId: PROJECT_ID,
+ startDate: START,
+ endDate: END,
+ timezone: 'UTC',
+ series: funnelInput([]).series,
+ breakdowns: [{ name: 'properties.variant', step: 2 }],
+ breakdownValues: [breakdownValue],
+ targetLevel,
+ showDropoffs: false,
+ limit: 10,
+ }).then((ids) => ids.sort());
+
+ expect(await profilesAt('Did not reach step 2', 1)).toEqual(['profile-u5']);
+ expect(await profilesAt('B', 3)).toEqual(['profile-u4']);
+ });
+});
diff --git a/packages/core/src/modules/chart/src/funnel.sql.test.ts b/packages/core/src/modules/chart/src/funnel.sql.test.ts
index 7d9b0aaaf..1db54007d 100644
--- a/packages/core/src/modules/chart/src/funnel.sql.test.ts
+++ b/packages/core/src/modules/chart/src/funnel.sql.test.ts
@@ -279,7 +279,8 @@ describe('funnel.sql / buildFunnelBase — unknown breakdowns', () => {
// Both sides must resolve the same breakdown to the same b_N index,
// otherwise the breakdownValues filter targets the wrong column.
- const attribution = 'argMinIf(`profile.properties.plan`, created_at,';
+ const attribution =
+ "tuple(ifNull(toString(`profile.properties.plan`), ''))";
expect(render(chart).sql).toContain(attribution);
expect(render(profiles).sql).toContain(attribution);
await explain(chart);
@@ -342,14 +343,14 @@ describe('funnel.sql / funnel CTE — step pre-filter', () => {
});
describe('funnel.sql / buildFunnelBase — breakdown attribution', () => {
- // The breakdown value must be read at the user's FIRST funnel step, not used
+ // The breakdown value must be read from the user's funnel sequence, not used
// as a windowFunnel GROUP BY key. Per-row grouping splits a user's steps
// across buckets whenever the property isn't identical on every step, so the
// sequence never connects and downstream steps show 0.
it('attributes event-property breakdowns at the entry step', async () => {
const sql = await chartSql([breakdown('properties.experiment')]);
expect(await chartText([breakdown('properties.experiment')])).toContain(
- "argMinIf(properties['experiment'], created_at,"
+ "tuple(ifNull(toString(properties['experiment']), ''))"
);
// The windowFunnel aggregation groups by the primary key only; b_0 is an
// aggregate, not a grouping key. (The outer chart GROUP BY level, b_0 is
@@ -368,7 +369,7 @@ describe('funnel.sql / buildFunnelBase — breakdown attribution', () => {
// A user in three groups should appear in all three funnels, so group.*
// breakdowns keep the ARRAY JOIN fan-out and per-row GROUP BY.
const sql = await chartSql([breakdown('group.plan')]);
- expect(sql).not.toContain('argMinIf');
+ expect(sql).not.toContain('step_events');
expect(sql).toMatch(/GROUP BY session_id, b_0/);
});
diff --git a/packages/core/src/modules/chart/src/funnel.sql.ts b/packages/core/src/modules/chart/src/funnel.sql.ts
index f1f6a8da9..65db59c56 100644
--- a/packages/core/src/modules/chart/src/funnel.sql.ts
+++ b/packages/core/src/modules/chart/src/funnel.sql.ts
@@ -44,12 +44,28 @@ export type FunnelGroup = (typeof FUNNEL_GROUPS)[number];
/** Display label for null/empty breakdown values (e.g. property not set). */
export const EMPTY_BREAKDOWN_LABEL = 'Not set';
+export function didNotReachStepLabel(step: number): string {
+ return `Did not reach step ${step}`;
+}
+
+/** The 1-based step a breakdown reads its value from; out-of-range falls back to the first. */
+function breakdownStep(breakdown: IChartBreakdown, stepCount: number): number {
+ const step = breakdown.step ?? 1;
+ return step <= stepCount ? step : 1;
+}
+
/** What the profiles join may select: the joinable columns plus the key. */
const FUNNEL_JOIN_COLUMNS = [...JOINABLE_PROFILE_COLUMNS, 'id'];
/** The funnel CTE's events alias — `getSelectPropertyKey` needs the same one. */
const EVENTS_ALIAS = 'events';
+/** The per-group array of step matches the breakdown replays read. */
+const STEP_EVENTS_ALIAS = 'step_events';
+
+/** The step bitmask in `step_events` is a UInt64. */
+const MAX_SEQUENCED_STEPS = 64;
+
// windowFunnel runs in its default (>=) ordering on purpose. 'strict_increase'
// resets step 1 on every matching row and then rejects a later step at the
// same millisecond, so a track() followed by a screen_view in the same ms
@@ -131,13 +147,86 @@ export function funnelStepConditions(
}
/**
- * Attribute each breakdown to its value at the user's FIRST funnel step, as a
- * per-group aggregate (argMinIf) — not by adding it to the windowFunnel GROUP
- * BY. Grouping the sequence by a per-row value splits a user's steps across
- * buckets whenever the value isn't identical on every step (e.g. an experiment
- * tag set on the entry event but absent on the conversion event): the later
- * step lands in a separate bucket, the windowFunnel sequence never connects,
- * and downstream steps show 0.
+ * Each user's step matches as `(timestamp, step, breakdown values)`, in the
+ * order windowFunnel processes them: by time, then by step. A row matching
+ * several steps appears once per step. Rows are aggregated as a step bitmask
+ * and expanded afterwards, because building a small array per row was most of
+ * the query's cost.
+ */
+function matchedStepEvents(
+ stepConditions: SqlFragment[],
+ values: SqlFragment[]
+): SqlFragment {
+ if (stepConditions.length > MAX_SEQUENCED_STEPS) {
+ throw new Error(
+ `Funnel breakdowns support at most ${MAX_SEQUENCED_STEPS} steps`
+ );
+ }
+ const stepMask = stepConditions
+ .map(
+ (condition, index) =>
+ sql`toUInt64(${condition}) * ${sql.uint64(2n ** BigInt(index))}`
+ )
+ .reduce((sum, term) => sql`${sum} + ${term}`);
+ const valueTuple = sql`tuple(${sql.join(
+ values.map((value) => sql`ifNull(toString(${value}), '')`)
+ )})`;
+ const rows = sql`groupArray((toInt64(toUnixTimestamp64Milli(created_at)), ${stepMask}, ${valueTuple}))`;
+ return sql`arraySort(e -> (e.1, e.2), arrayFlatten(arrayMap(matched_row -> arrayMap(step_index -> (matched_row.1, step_index, matched_row.3), arrayFilter(step_index -> bitTest(matched_row.2, step_index - 1), range(1, ${sql.uint64(stepConditions.length)} + 1))), ${rows}))) AS ${compiledText(STEP_EVENTS_ALIAS)}`;
+}
+
+/**
+ * Replays windowFunnel over `step_events` so a breakdown reads its value from
+ * the event in the chain that reached the user's deepest level, not just any
+ * event matching the step. Each level keeps its chain's start time and the
+ * value picked up at `step`; a step extends the previous level's chain when it
+ * lands inside the window, exactly as windowFunnel does, and the first chain
+ * to reach a new deepest level wins.
+ */
+function valueAtStepInSequence(input: {
+ valueIndex: number;
+ step: number;
+ stepCount: number;
+ windowMilliseconds: number;
+}): SqlFragment {
+ const stepCount = sql.uint64(input.stepCount);
+ const step = sql.uint64(input.step);
+ const valueIndex = sql.uint64(input.valueIndex);
+ const window = sql.uint64(input.windowMilliseconds);
+ const carried = sql`if(e.2 = ${step}, tupleElement(e.3, ${valueIndex}), if(e.2 = 1, '', acc.2[e.2 - 1]))`;
+ return sql`arrayFold((acc, e) -> if(e.2 = 1 OR (acc.1[e.2 - 1] >= 0 AND e.1 <= acc.1[e.2 - 1] + ${window}), (arrayMap((chain_start, level_index) -> if(level_index = e.2, if(e.2 = 1, e.1, acc.1[e.2 - 1]), chain_start), acc.1, range(1, ${stepCount} + 1)), arrayMap((chain_value, level_index) -> if(level_index = e.2, ${carried}, chain_value), acc.2, range(1, ${stepCount} + 1)), if(e.2 > acc.3, e.2, acc.3), if(e.2 > acc.3, ${carried}, acc.4)), acc), ${compiledText(STEP_EVENTS_ALIAS)}, (arrayWithConstant(${stepCount}, toInt64(-1)), arrayWithConstant(${stepCount}, ''), toUInt64(0), '')).4`;
+}
+
+function breakdownExpression(
+ input: FunnelBaseInput,
+ breakdown: IChartBreakdown,
+ profilePropertyKeys: string[]
+): SqlFragment {
+ const cohortId = extractCohortId(breakdown.name);
+ const cohortName = cohortId
+ ? input.cohortMetadata.get(cohortId)?.name
+ : undefined;
+ return fragmentWithProfileRefs(
+ getSelectPropertyKey(
+ breakdown.name,
+ input.projectId,
+ cohortId ?? undefined,
+ cohortName
+ ),
+ profilePropertyKeys
+ );
+}
+
+/**
+ * Breakdowns are per-group aggregates read from the user's funnel sequence,
+ * not windowFunnel GROUP BY keys. Grouping the sequence by a per-row value
+ * splits a user's steps across buckets whenever the value isn't identical on
+ * every step (e.g. an experiment tag set on the entry event but absent on the
+ * conversion event), so downstream steps show 0.
+ *
+ * With a later step, users who never reached it get their own bucket, since a
+ * property that only exists on that step would otherwise lump them into
+ * "Not set" with users whose value really is empty.
*
* `group.*` breakdowns are the exception: their ARRAY JOIN fans each event out
* per group, and grouping by the group value is intentional — a user in three
@@ -146,28 +235,35 @@ export function funnelStepConditions(
function breakdownSelects(
input: FunnelBaseInput,
profilePropertyKeys: string[],
- firstStepCondition: SqlFragment
+ stepConditions: SqlFragment[]
): SqlFragment[] {
- return input.breakdowns.map((breakdown, index) => {
- const cohortId = extractCohortId(breakdown.name);
- const cohortName = cohortId
- ? input.cohortMetadata.get(cohortId)?.name
- : undefined;
- const expression = fragmentWithProfileRefs(
- getSelectPropertyKey(
- breakdown.name,
- input.projectId,
- cohortId ?? undefined,
- cohortName
- ),
- profilePropertyKeys
- );
+ const sequenced = input.breakdowns.filter(
+ (breakdown) => !breakdown.name.startsWith('group.')
+ );
+ const selects = input.breakdowns.map((breakdown, index) => {
const alias = compiledText(`b_${index}`);
if (breakdown.name.startsWith('group.')) {
- return sql`${expression} as ${alias}`;
+ return sql`${breakdownExpression(input, breakdown, profilePropertyKeys)} as ${alias}`;
}
- return sql`argMinIf(${expression}, created_at, ${firstStepCondition}) as ${alias}`;
+ const step = breakdownStep(breakdown, stepConditions.length);
+ const value = valueAtStepInSequence({
+ valueIndex: sequenced.indexOf(breakdown) + 1,
+ step,
+ stepCount: stepConditions.length,
+ windowMilliseconds: input.funnelWindowMilliseconds,
+ });
+ if (step === 1) {
+ return sql`${value} as ${alias}`;
+ }
+ return sql`if(level >= ${sql.uint64(step)}, ${value}, ${sql.string(didNotReachStepLabel(step))}) as ${alias}`;
});
+ if (sequenced.length === 0) {
+ return selects;
+ }
+ const values = sequenced.map((breakdown) =>
+ breakdownExpression(input, breakdown, profilePropertyKeys)
+ );
+ return [matchedStepEvents(stepConditions, values), ...selects];
}
/**
@@ -276,11 +372,7 @@ export function funnelBase(input: FunnelBaseInput): FunnelBase {
projectId,
profileKeys.keys
);
- const selects = breakdownSelects(
- input,
- profileKeys.keys,
- conditions[0] as SqlFragment
- );
+ const selects = breakdownSelects(input, profileKeys.keys, conditions);
const primaryKey = sql.id(group, FUNNEL_GROUPS);
const cteSelects: SqlFragment[] = [
diff --git a/packages/core/src/modules/report/report.constants.ts b/packages/core/src/modules/report/report.constants.ts
index ae086f508..350d5beb3 100644
--- a/packages/core/src/modules/report/report.constants.ts
+++ b/packages/core/src/modules/report/report.constants.ts
@@ -774,6 +774,14 @@ export const zChartEventItem = z.discriminatedUnion('type', [
export const zChartBreakdown = z.object({
id: z.string().optional(),
name: z.string(),
+ step: z
+ .number()
+ .int()
+ .min(1)
+ .optional()
+ .describe(
+ 'Funnel only: 1-based step whose event the value is read from. Defaults to the first step.'
+ ),
});
export const zChartSeries = z