OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix(dashboard): cohort retention charts can be filtered by group
Carl-Gerhard Lindesvärdaf8c5f7d6b9c
diff --git a/packages/core/src/modules/chart/retention.service.test.ts b/packages/core/src/modules/chart/retention.service.test.tsindex c4855d896..d30b557f9 100644--- a/packages/core/src/modules/chart/retention.service.test.ts+++ b/packages/core/src/modules/chart/retention.service.test.ts@@ -226,6 +226,27 @@ describe('getRetentionCohort', () => {expect(cohortsOnly(rows)).toEqual(mutable(RETENTION_BLUEPRINT.cohortOn));});++ it('applies a group filter through the groups join', async () => {+ const rows = await getRetentionCohort(deps, {+ projectId: PROJECT_ID,+ firstEvent: ['app_open'],+ secondEvent: ['app_open'],+ criteria: 'on',+ interval: 'day',+ startDate: day.start,+ endDate: day.end,+ filters: [+ {+ name: 'group.name',+ operator: 'is',+ value: [RETENTION_FIXTURE.group.name],+ },+ ],+ });++ expect(cohortsOnly(rows)).toEqual(mutable(RETENTION_BLUEPRINT.groupNameOn));+ });});describe('getRetentionSeries', () => {diff --git a/packages/core/src/modules/chart/src/retention.sql.ts b/packages/core/src/modules/chart/src/retention.sql.tsindex 06b1bfb4d..7c5e49fa1 100644--- a/packages/core/src/modules/chart/src/retention.sql.ts+++ b/packages/core/src/modules/chart/src/retention.sql.ts@@ -8,7 +8,7 @@ import { type SqlFragment, sql } from '@openpanel/db/src/clickhouse/sql';import type { IChartEventFilter } from '../../report/report.constants';import { compiledText } from './compiled';import { formatClickhouseDate } from './dates';-import { CHART_TABLE } from './field-resolution';+import { buildGroupsQuery, CHART_TABLE } from './field-resolution';import { getEventFiltersWhereClause } from './filter-where';export type IRetentionInterval = 'minute' | 'hour' | 'day' | 'week' | 'month';@@ -162,15 +162,18 @@ export interface RetentionCohortQueryInput {filters: IChartEventFilter[];}+/** Qualifies the events columns that the groups join's `_g` also has (`name`, `properties`). */+const EVENTS_ALIAS = 'e';+/** `name = …` / `name IN (…)`; `sql.empty` means "any event". */function eventNameWhere(events: string[] | undefined): SqlFragment {if (!events || events.length === 0) {return sql.empty;}if (events.length === 1) {- return sql`AND name = ${sql.string(events[0] as string)}`;+ return sql`AND e.name = ${sql.string(events[0] as string)}`;}- return sql`AND name IN ${sql.array('String', events)}`;+ return sql`AND e.name IN ${sql.array('String', events)}`;}/**@@ -204,9 +207,15 @@ export function retentionCohortQuery((filter) =>filter.operator !== 'inCohort' && filter.operator !== 'notInCohort');- const source = sql.id(- needRawEvents ? CHART_TABLE.events : CHART_TABLE.cohortEventsMv+ const needsGroupJoin = filters.some((filter) =>+ filter.name.startsWith('group.'));+ const groupJoin = needsGroupJoin+ ? sql`ARRAY JOIN groups AS _group_id LEFT ANY JOIN (${buildGroupsQuery(projectId)}) AS _g ON _g.id = _group_id`+ : sql.empty;+ const source = sql`${sql.id(+ needRawEvents ? CHART_TABLE.events : CHART_TABLE.cohortEventsMv+ )} AS ${compiledText(EVENTS_ALIAS)} ${groupJoin}`;const baseConditions: SqlFragment[] = [sql`project_id = ${sql.string(projectId)}`,@@ -217,7 +226,13 @@ export function retentionCohortQuery(}if (filters.length > 0) {baseConditions.push(- ...Object.values(getEventFiltersWhereClause(filters, projectId))+ ...Object.values(+ getEventFiltersWhereClause(+ filters,+ projectId,+ needsGroupJoin ? EVENTS_ALIAS : undefined+ )+ ));}const baseWhere = sql.join(baseConditions, ' AND ');diff --git a/test/retention-fixtures.ts b/test/retention-fixtures.tsindex 8d5c2ddad..d953cdbb9 100644--- a/test/retention-fixtures.ts+++ b/test/retention-fixtures.ts@@ -22,6 +22,8 @@** => D0 cohort = {RU1,RU2,RU3} (size 3), D1 cohort = {RU4,RU5} (size 2)*+ * RU1 and RU2's events belong to the group "Retention Co" (group-filter case).+ ** WEEK scenario — window 2024-12-29 .. 2025-01-06 (crosses the year boundary,* which is exactly what the old toWeek() implementation got wrong)*@@ -60,6 +62,11 @@ export const RETENTION_FIXTURE = {end: '2025-01-06 23:59:59',cohort: '2024-12-29',},+ // Group attached to every RU1 and RU2 event, for the group-filter case+ group: {+ id: 'retention-group-co',+ name: 'Retention Co',+ },// Saved cohort used for the inCohort filter case (members: RU1, RU4)cohort: {id: 'retention-cohort-rc',@@ -95,6 +102,9 @@ export const RETENTION_BLUEPRINT = {{ cohort_interval: '2024-03-04', sum: 1, values: [1, 1, 1] },{ cohort_interval: '2024-03-05', sum: 1, values: [1, 1, 0] },],+ // app_open self-retention, day, criteria on, filtered to group "Retention Co"+ // {RU1, RU2}. Needs the groups join that defines `_g`.+ groupNameOn: [{ cohort_interval: '2024-03-04', sum: 2, values: [2, 1, 2] }],// Week-over-week active-user retention across the whole fixture.// - 2024-03-03: RU1-5 active, none active the next week -> 0% retained// - 2024-12-29: WU1+WU2 active, WU1 active next week -> 50% retained@@ -163,20 +173,21 @@ function buildEvents(projectId: string) {const us = { country: 'US' };const se = { country: 'SE' };+ const usInGroup = { ...us, groups: [RETENTION_FIXTURE.group.id] };return [- buildEvent(projectId, users.ru1, 'app_open', dayAt(day.d0), us),- buildEvent(projectId, users.ru1, 'app_open', dayAt(day.d1), us),- buildEvent(projectId, users.ru1, 'app_open', dayAt(day.d2), us),- buildEvent(projectId, users.ru2, 'app_open', dayAt(day.d0), us),- buildEvent(projectId, users.ru2, 'app_open', dayAt(day.d2), us),+ buildEvent(projectId, users.ru1, 'app_open', dayAt(day.d0), usInGroup),+ buildEvent(projectId, users.ru1, 'app_open', dayAt(day.d1), usInGroup),+ buildEvent(projectId, users.ru1, 'app_open', dayAt(day.d2), usInGroup),+ buildEvent(projectId, users.ru2, 'app_open', dayAt(day.d0), usInGroup),+ buildEvent(projectId, users.ru2, 'app_open', dayAt(day.d2), usInGroup),buildEvent(projectId, users.ru3, 'app_open', dayAt(day.d0), se),buildEvent(projectId, users.ru4, 'app_open', dayAt(day.d1), us),buildEvent(projectId, users.ru4, 'app_open', dayAt(day.d2), us),buildEvent(projectId, users.ru5, 'app_open', dayAt(day.d1), us),- buildEvent(projectId, users.ru1, 'purchase', dayAt(day.d1), us),- buildEvent(projectId, users.ru2, 'purchase', dayAt(day.d2), us),+ buildEvent(projectId, users.ru1, 'purchase', dayAt(day.d1), usInGroup),+ buildEvent(projectId, users.ru2, 'purchase', dayAt(day.d2), usInGroup),// 2024-12-30 (Mon) falls in the Sunday-aligned week starting 2024-12-29.buildEvent(projectId, users.wu1, 'app_open', '2024-12-30 12:00:00'),@@ -196,6 +207,21 @@ function buildCohortMembers(projectId: string) {}));}+function buildGroups(projectId: string) {+ return [+ {+ id: RETENTION_FIXTURE.group.id,+ project_id: projectId,+ type: 'company',+ name: RETENTION_FIXTURE.group.name,+ properties: {},+ created_at: RETENTION_FIXTURE.day.start,+ version: 1,+ deleted: 0,+ },+ ];+}+async function deleteFixtures(client: ChClient, projectId: string) {await Promise.all([client.command({@@ -209,6 +235,9 @@ async function deleteFixtures(client: ChClient, projectId: string) {client.command({query: `DELETE FROM cohort_members WHERE project_id = '${projectId}'`,}),+ client.command({+ query: `DELETE FROM groups WHERE project_id = '${projectId}'`,+ }),]);}@@ -226,6 +255,11 @@ export async function setupRetentionFixtures(projectId: string): Promise<void> {values: buildCohortMembers(projectId),format: 'JSONEachRow',});+ await client.insert({+ table: 'groups',+ values: buildGroups(projectId),+ format: 'JSONEachRow',+ });} finally {await client.close();}