: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
feat(cross-project-dashboards): add usage tracking events (#113126)
Yasen050f47bf59c7
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 807b41898400..903d9fbe4f6a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3023,6 +3023,9 @@ importers:kea-router:specifier: 'catalog:'version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ posthog-js:+ specifier: 'catalog:'+ version: 1.438.1(@types/[email protected])([email protected])react:specifier: 18.3.1version: 18.3.1diff --git a/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.test.ts b/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.test.tsindex 77945b135197..a45544fafe8c 100644--- a/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.test.ts+++ b/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.test.ts@@ -1,4 +1,5 @@import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { organizationLogic } from 'scenes/organizationLogic'@@ -9,7 +10,7 @@ import { insightsList } from 'products/product_analytics/frontend/generated/api'import { addCrossProjectTileLogic } from './addCrossProjectTileLogic'import { crossProjectDashboardLogic } from './crossProjectDashboardLogic'-import { crossProjectDashboardsRetrieve } from './generated/api'+import { crossProjectDashboardsRetrieve, crossProjectDashboardsTilesCreate } from './generated/api'jest.mock('lib/lemon-ui/LemonDialog', () => ({ LemonDialog: { open: jest.fn() } }))@@ -21,11 +22,13 @@ jest.mock('products/product_analytics/frontend/generated/api', () => ({jest.mock('./generated/api', () => ({__esModule: true,crossProjectDashboardsRetrieve: jest.fn(),+ crossProjectDashboardsTilesCreate: jest.fn(),}))const mockedDialogOpen = LemonDialog.open as jest.Mockconst mockedInsightsList = insightsList as jest.Mockconst mockedRetrieve = crossProjectDashboardsRetrieve as jest.Mock+const mockedTileCreate = crossProjectDashboardsTilesCreate as jest.Mockconst DASHBOARD_ID = '01a0f19d-1c44-715a-a679-188869bd033f'@@ -69,6 +72,24 @@ describe('addCrossProjectTileLogic', () => {expect(dashboardLogic.values.layoutEditMode).toBe(false)})+ it('reports an added insight with the tile and project counts the dashboard has after the add', async () => {+ mockedInsightsList.mockResolvedValue({ results: [], next: null })+ mockedTileCreate.mockResolvedValue({ ...TILE, id: 'tile-2', project_id: 54, insight_id: 7 })+ const capture = jest.spyOn(posthog, 'capture')++ logic.actions.setProjectId(54)+ logic.actions.setInsight({ id: 7, name: 'Signups' })+ logic.actions.addTile()+ await expectLogic(logic).toFinishAllListeners()++ expect(capture).toHaveBeenCalledWith('cross project dashboard insight added', {+ dashboard_id: DASHBOARD_ID,+ tile_count: 2,+ project_count: 2,+ used_search: false,+ })+ })+it('finds an insight past the first page by searching the selected project and loading more', async () => {// One insight per page, numbered by offset, with a second page only for the search.mockedInsightsList.mockImplementation(async (_projectId, params) => ({diff --git a/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.ts b/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.tsindex e3824d65c5ea..2469e5643a34 100644--- a/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.ts+++ b/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.ts@@ -9,6 +9,7 @@ import { organizationLogic } from 'scenes/organizationLogic'import { insightsList } from 'products/product_analytics/frontend/generated/api'import { crossProjectDashboardLogic } from './crossProjectDashboardLogic'+import { crossProjectDashboardTracking } from './crossProjectDashboardTracking'import { crossProjectDashboardsTilesCreate } from './generated/api'export interface InsightOption {@@ -264,6 +265,12 @@ export const addCrossProjectTileLogic = kea<addCrossProjectTileLogicType>([secondaryButton: { children: 'Keep editing' },})},+ openModal: () => {+ crossProjectDashboardTracking.addInsightOpened(+ props.dashboardId,+ crossProjectDashboardLogic.findMounted({ id: props.dashboardId })?.values.tiles ?? []+ )+ },setProjectId: () => {actions.loadInsights()},@@ -277,17 +284,27 @@ export const addCrossProjectTileLogic = kea<addCrossProjectTileLogicType>([actions.closeModal()return}+ const projectId = values.projectId+ const usedSearch = !!values.insightSearch.trim()try {await crossProjectDashboardsTilesCreate(organizationId, props.dashboardId, {- project_id: values.projectId,+ project_id: projectId,insight_id: values.selectedInsight.id,} as any)+ const tilesBefore =+ crossProjectDashboardLogic.findMounted({ id: props.dashboardId })?.values.tiles ?? []+ crossProjectDashboardTracking.insightAdded(+ props.dashboardId,+ [...tilesBefore, { project_id: projectId }],+ usedSearch+ )actions.closeModal()// findMounted, not a direct reference: referencing another logic's actions// mounts it and fires its afterMount.crossProjectDashboardLogic.findMounted({ id: props.dashboardId })?.actions.loadDashboard()} catch (error: any) {lemonToast.error(error?.detail || 'Could not add that insight. Try again.')+ crossProjectDashboardTracking.insightAddFailed(props.dashboardId, error?.status)actions.addTileFailure()}},diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.ts b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.tsindex c40a77b10188..a5b620e15eda 100644--- a/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.ts+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.ts@@ -1,5 +1,6 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { lemonToast } from 'lib/lemon-ui/LemonToast'@@ -167,6 +168,20 @@ describe('crossProjectDashboardLogic', () => {})})+ it('reports one view per visit, not one per saved change', async () => {+ const capture = jest.spyOn(posthog, 'capture')+ await mountWith({})++ logic.actions.setDates('-7d', null)+ logic.actions.setInterval('week')+ await expectLogic(logic).toFinishAllListeners()++ const views = capture.mock.calls.filter(([event]) => event === 'cross project dashboard viewed')+ expect(views).toEqual([+ ['cross project dashboard viewed', { dashboard_id: DASHBOARD_ID, tile_count: 1, project_count: 1 }],+ ])+ })+it('keeps both of two quick filter edits instead of letting the second overwrite the first', async () => {await mountWith({})diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.ts b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.tsindex 2ef2bcdb965a..9c0dd2b2679d 100644--- a/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.ts+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.ts@@ -12,6 +12,7 @@ import { urls } from 'scenes/urls'import type { AnyPropertyFilter, IntervalType, TeamBasicType } from '~/types'+import { crossProjectDashboardTracking } from './crossProjectDashboardTracking'import { changedTileLayouts, layoutsDiffer, layoutsForTiles, type ResponsiveTileLayouts } from './crossProjectLayouts'import { findMissingPropertyKeys, propertyKeysIn } from './crossProjectPropertyKeys'import {@@ -321,6 +322,8 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([let saves: Promise<boolean> = Promise.resolve(true)// Undo stays clickable while its toast closes, and a second restore of the same tile fails as a duplicate.const restoringTileIds = new Set<string>()+ // Saves and tile edits also land through loadDashboardSuccess, and only the first load is a view.+ let viewTracked = falseconst saveDashboard = (changes: () => PatchedCrossProjectDashboardApi,errorMessage: string@@ -365,8 +368,16 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([}return {+ loadDashboardSuccess: ({ dashboard }) => {+ if (dashboard && !viewTracked) {+ viewTracked = true+ crossProjectDashboardTracking.viewed(props.id, dashboard.tiles)+ }+ },updateDashboard: async ({ details }) => {- await saveDashboard(() => details, 'Could not save that change. Try again.')+ if (await saveDashboard(() => details, 'Could not save that change. Try again.')) {+ crossProjectDashboardTracking.edited(props.id, details.name !== undefined ? 'name' : 'description')+ }},deleteDashboard: () => {const organizationId = organizationLogic.values.currentOrganization?.id@@ -375,21 +386,28 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([}openDeleteCrossProjectDashboardDialog(values.dashboard.name, async () => {await crossProjectDashboardsDestroy(organizationId, props.id)+ crossProjectDashboardTracking.deleted(props.id, 'dashboard')router.actions.push(combineUrl(urls.dashboards(), { tab: DashboardsTab.CrossProject }).url)})},setDates: async ({ dateFrom, dateTo }) => {- await saveFilters((filters) => {+ const saved = await saveFilters((filters) => {// An unset bound is dropped, so the stored blob carries only the bounds actually chosen// and each tile keeps its own insight's value for the other one.dateFrom ? (filters.date_from = dateFrom) : delete filters.date_fromdateTo ? (filters.date_to = dateTo) : delete filters.date_to}, 'Could not apply that date range. Try again.')+ if (saved) {+ crossProjectDashboardTracking.edited(props.id, 'date_range')+ }},setInterval: async ({ interval }) => {- await saveFilters((filters) => {+ const saved = await saveFilters((filters) => {interval ? (filters.interval = interval) : delete filters.interval}, 'Could not apply that interval. Try again.')+ if (saved) {+ crossProjectDashboardTracking.edited(props.id, 'interval')+ }},enterLayoutEdit: () => {lemonToast.info('Now editing the dashboard. Press E or click Save to persist changes.')@@ -417,6 +435,7 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([applySavedTiles(saved)actions.exitLayoutEdit()lemonToast.success('Dashboard saved')+ crossProjectDashboardTracking.edited(props.id, 'layout')} catch (error: any) {lemonToast.error(error?.detail || 'Could not save the layout. Try again.')actions.saveLayoutFailed()@@ -449,6 +468,7 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([if (saved) {// Checked here rather than on open: the answer only changes when the filter does.actions.checkPropertyKeys()+ crossProjectDashboardTracking.edited(props.id, 'property_filter')}},setTileOverride: async ({ tileId, overrides }) => {@@ -462,6 +482,7 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([})applySavedTiles([saved])lemonToast.success('Tile filters saved')+ crossProjectDashboardTracking.edited(props.id, 'tile_filters')} catch (error: any) {lemonToast.error(error?.detail || 'Could not save the tile filters. Try again.')}@@ -475,6 +496,7 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([applySavedTiles([await crossProjectDashboardsTilesPartialUpdate(organizationId, props.id, tileId, { color }),])+ crossProjectDashboardTracking.edited(props.id, 'tile_color')} catch (error: any) {lemonToast.error(error?.detail || 'Could not change the tile color. Try again.')}@@ -487,9 +509,14 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([const removedTile = values.tiles.find((tile) => tile.id === tileId)try {await crossProjectDashboardsTilesDestroy(organizationId, props.id, tileId)+ crossProjectDashboardTracking.tileRemoved(props.id)if (removedTile) {lemonToast.info('Tile removed from the dashboard', {- button: { label: 'Undo', action: () => actions.restoreTile(removedTile) },+ button: {+ label: 'Undo',+ action: () => actions.restoreTile(removedTile),+ dataAttr: 'cross-project-dashboard-tile-undo',+ },})}} catch (error: any) {@@ -513,6 +540,7 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([filters_overrides: tile.filters_overrides,})lemonToast.success('Tile restored')+ crossProjectDashboardTracking.tileRestored(props.id)} catch (error: any) {lemonToast.error(error?.detail || 'Could not restore the tile. Add the insight again.')} finally {diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardTracking.ts b/products/cross_project_dashboards/frontend/crossProjectDashboardTracking.tsnew file mode 100644index 000000000000..5d32348e0c5d--- /dev/null+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardTracking.ts@@ -0,0 +1,76 @@+import posthog from 'posthog-js'++import type { TileUnavailableReason } from './crossProjectTileFetch'++// pinned: event names and property keys. Usage dashboards and funnels query them, so a rename breaks them.+const EVENTS = {+ viewed: 'cross project dashboard viewed',+ created: 'cross project dashboard created',+ deleted: 'cross project dashboard deleted',+ edited: 'cross project dashboard edited',+ addInsightOpened: 'cross project dashboard add insight opened',+ insightAdded: 'cross project dashboard insight added',+ insightAddFailed: 'cross project dashboard insight add failed',+ tileRemoved: 'cross project dashboard tile removed',+ tileRestored: 'cross project dashboard tile restored',+ tileUnavailable: 'cross project dashboard tile unavailable',+} as const++export type CrossProjectDashboardChange =+ | 'name'+ | 'description'+ | 'date_range'+ | 'interval'+ | 'property_filter'+ | 'layout'+ | 'tile_color'+ | 'tile_filters'++export type CrossProjectDashboardDeleteSource = 'dashboard' | 'list'++interface TileReference {+ project_id: number+}++/** A dashboard with tiles from two or more projects is the one the feature exists for. */+function composition(tiles: readonly TileReference[]): { tile_count: number; project_count: number } {+ return { tile_count: tiles.length, project_count: new Set(tiles.map((tile) => tile.project_id)).size }+}++export const crossProjectDashboardTracking = {+ viewed: (dashboardId: string, tiles: readonly TileReference[]): void => {+ posthog.capture(EVENTS.viewed, { dashboard_id: dashboardId, ...composition(tiles) })+ },+ created: (dashboardId: string): void => {+ posthog.capture(EVENTS.created, { dashboard_id: dashboardId })+ },+ deleted: (dashboardId: string, source: CrossProjectDashboardDeleteSource): void => {+ posthog.capture(EVENTS.deleted, { dashboard_id: dashboardId, source })+ },+ edited: (dashboardId: string, change: CrossProjectDashboardChange): void => {+ posthog.capture(EVENTS.edited, { dashboard_id: dashboardId, change })+ },+ addInsightOpened: (dashboardId: string, tiles: readonly TileReference[]): void => {+ posthog.capture(EVENTS.addInsightOpened, { dashboard_id: dashboardId, ...composition(tiles) })+ },+ /** `tiles` is the dashboard after the add, so the counts include the new tile. */+ insightAdded: (dashboardId: string, tiles: readonly TileReference[], usedSearch: boolean): void => {+ posthog.capture(EVENTS.insightAdded, {+ dashboard_id: dashboardId,+ ...composition(tiles),+ used_search: usedSearch,+ })+ },+ insightAddFailed: (dashboardId: string, status: number | undefined): void => {+ posthog.capture(EVENTS.insightAddFailed, { dashboard_id: dashboardId, status: status ?? null })+ },+ tileRemoved: (dashboardId: string): void => {+ posthog.capture(EVENTS.tileRemoved, { dashboard_id: dashboardId })+ },+ tileRestored: (dashboardId: string): void => {+ posthog.capture(EVENTS.tileRestored, { dashboard_id: dashboardId })+ },+ tileUnavailable: (reason: TileUnavailableReason): void => {+ posthog.capture(EVENTS.tileUnavailable, { reason })+ },+}diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardsListLogic.ts b/products/cross_project_dashboards/frontend/crossProjectDashboardsListLogic.tsindex dc4f3506dace..39d37fa49109 100644--- a/products/cross_project_dashboards/frontend/crossProjectDashboardsListLogic.ts+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardsListLogic.ts@@ -5,6 +5,7 @@ import { router } from 'kea-router'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { organizationLogic } from 'scenes/organizationLogic'+import { crossProjectDashboardTracking } from './crossProjectDashboardTracking'import {crossProjectDashboardsCreate,crossProjectDashboardsDestroy,@@ -108,6 +109,7 @@ export const crossProjectDashboardsListLogic = kea<crossProjectDashboardsListLogconst created = await crossProjectDashboardsCreate(organizationId, {name: values.newName.trim(),} as any)+ crossProjectDashboardTracking.created(created.id)actions.closeNewModal()router.actions.push(`/cross-project-dashboards/${created.id}`)} catch (error: any) {@@ -122,6 +124,7 @@ export const crossProjectDashboardsListLogic = kea<crossProjectDashboardsListLog}openDeleteCrossProjectDashboardDialog(dashboard.name, async () => {await crossProjectDashboardsDestroy(organizationId, dashboard.id)+ crossProjectDashboardTracking.deleted(dashboard.id, 'list')actions.loadDashboards()})},diff --git a/products/cross_project_dashboards/frontend/crossProjectTileFetch.ts b/products/cross_project_dashboards/frontend/crossProjectTileFetch.tsindex 24f0931796f9..b95ce4860b8d 100644--- a/products/cross_project_dashboards/frontend/crossProjectTileFetch.ts+++ b/products/cross_project_dashboards/frontend/crossProjectTileFetch.ts@@ -3,6 +3,8 @@ import type { InsightModel } from '~/types'import { insightsRetrieve } from 'products/product_analytics/frontend/generated/api'import type { InsightsRetrieveParams } from 'products/product_analytics/frontend/generated/api.schemas'+import { crossProjectDashboardTracking } from './crossProjectDashboardTracking'+export type TileUnavailableReason = 'no-access' | 'not-found' | 'failed'export interface TileFetchResult {@@ -50,13 +52,10 @@ export async function fetchCrossProjectTile(// InsightCard needs an InsightModel. The endpoint returns one, but its schema leaves out `saved`.return { insight: insight as unknown as InsightModel, unavailable: null }} catch (error: any) {- if (error?.status === 403) {- return { insight: null, unavailable: 'no-access' }- }- if (error?.status === 404) {- return { insight: null, unavailable: 'not-found' }- }- return { insight: null, unavailable: 'failed' }+ const unavailable: TileUnavailableReason =+ error?.status === 403 ? 'no-access' : error?.status === 404 ? 'not-found' : 'failed'+ crossProjectDashboardTracking.tileUnavailable(unavailable)+ return { insight: null, unavailable }} finally {releaseSlot()}diff --git a/products/cross_project_dashboards/package.json b/products/cross_project_dashboards/package.jsonindex c36b14cb7247..da7d1bd54c5a 100644--- a/products/cross_project_dashboards/package.json+++ b/products/cross_project_dashboards/package.json@@ -8,7 +8,8 @@"clsx": "^2.1.1","kea": "catalog:","kea-loaders": "catalog:",- "kea-router": "catalog:"+ "kea-router": "catalog:",+ "posthog-js": "catalog:"},"devDependencies": {"@testing-library/react": "^14.3.1",