: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
chore(marketing): extract dashboard metric helpers (#104655)
Javier Bahamondes36ae9870894c
diff --git a/products/marketing_analytics/frontend/dashboard/cards/metricCardSpec.ts b/products/marketing_analytics/frontend/dashboard/cards/metricCardSpec.tsnew file mode 100644index 000000000000..d778f88d0fb9--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/cards/metricCardSpec.ts@@ -0,0 +1,31 @@+import { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'+import { WebOverviewItem } from '~/queries/schema/schema-general'++export interface MetricNotice {+ kind: 'notice'+ key: string+ title: string+ message: string+ /** Stands in the value's place for a metric that exists but cannot be computed here. */+ value?: string+ action?: { label: string; onClick: () => void; dataAttr: string }+}++export type MetricCardSpec = { kind: 'metric'; item: OverviewMetricCardItem } | MetricNotice++/** Percent change the way the cards want it: whole percent, and undefined when there is no+ * baseline to divide by. The backend sends a sentinel for that case, which the grid already hides. */+export function pctChange(value: number | undefined, previous: number | undefined): number | undefined {+ if (value === undefined || previous === undefined || previous === 0) {+ return undefined+ }+ return Math.round(((value - previous) / previous) * 100)+}++/** Picks named keys out of a WebOverviewQuery response, keeping the requested order. */+export function pickOverviewItems(results: WebOverviewItem[] | undefined, keys: string[]): MetricCardSpec[] {+ return keys.flatMap((key) => {+ const item = results?.find((result) => result.key === key)+ return item ? [{ kind: 'metric' as const, item: item as OverviewMetricCardItem }] : []+ })+}diff --git a/products/marketing_analytics/frontend/dashboard/charts/seriesFocus.ts b/products/marketing_analytics/frontend/dashboard/charts/seriesFocus.tsnew file mode 100644index 000000000000..52f013e25c39--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/charts/seriesFocus.ts@@ -0,0 +1,39 @@+import { ChartTheme } from '@posthog/quill-charts'++/** Low enough to recede, high enough that the line is still traceable. */+const DIMMED_ALPHA = 0.18++/** The chart hands colours to the canvas unresolved, so an explicit colour has to be concrete. */+export function dimColor(color: string, alpha: number): string {+ const hex = color.trim()+ const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex)+ if (match) {+ const body = match[1]+ const full = body.length === 3 ? [...body].map((char) => char + char).join('') : body+ const [r, g, b] = [0, 2, 4].map((offset) => parseInt(full.slice(offset, offset + 2), 16))+ return `rgba(${r}, ${g}, ${b}, ${alpha})`+ }+ const rgb = /^rgba?\(([^)]+)\)$/i.exec(hex)+ if (rgb) {+ const [r, g, b] = rgb[1].split(',').map((part) => part.trim())+ return `rgba(${r}, ${g}, ${b}, ${alpha})`+ }+ return color+}++export function focusedSeries(+ focused: string | null,+ name: string,+ index: number,+ theme: ChartTheme+): { color: string } | null {+ if (!focused) {+ return null+ }+ const palette = theme.colors ?? []+ const color = palette[index % Math.max(palette.length, 1)]+ if (!color) {+ return null+ }+ return { color: focused === name ? color : dimColor(color, DIMMED_ALPHA) }+}diff --git a/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.test.ts b/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.test.tsnew file mode 100644index 000000000000..00318d8516e0--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.test.ts@@ -0,0 +1,75 @@+import { WebOverviewItem } from '~/queries/schema/schema-general'+import { CompareLabelType, TrendResult } from '~/types'++import { ratioItem, seriesTotal, sumTrendSeries } from './marketingDashboardMetrics'++const result = (+ order: number,+ aggregated_value: number,+ compare_label?: TrendResult['compare_label']+): TrendResult => ({+ action: null,+ count: aggregated_value,+ data: [aggregated_value],+ days: ['2026-01-01'],+ label: `Series ${order}`,+ labels: ['1 Jan'],+ order,+ aggregated_value,+ compare_label,+})++describe('marketingDashboardMetrics', () => {+ // The conversion value query asks for the sum first and the average second, so picking by+ // position rather than by series order would swap the two cards.+ it('picks a series by its order, not its position', () => {+ const results = [result(1, 42), result(0, 13700)]++ expect(seriesTotal(results, 0).value).toBe(13700)+ expect(seriesTotal(results, 1).value).toBe(42)+ })++ it('keeps the compared period apart from the current one', () => {+ const results = [result(0, 13700), result(0, 9100, CompareLabelType.Previous)]++ expect(seriesTotal(results, 0)).toEqual({ value: 13700, previous: 9100 })+ })++ // An absent series has no value to show, which the cards render as N/A rather than as zero.+ it('reports no value for a series the response never returned', () => {+ expect(seriesTotal([result(0, 13700)], 1)).toEqual({})+ expect(seriesTotal(undefined, 0)).toEqual({})+ })++ it('sums multiple goals without mixing their compared periods', () => {+ expect(+ sumTrendSeries([+ result(0, 0),+ result(1, 20),+ result(0, 5, CompareLabelType.Previous),+ result(1, 10, CompareLabelType.Previous),+ ])+ ).toEqual({ value: 20, previous: 15 })+ expect(sumTrendSeries([result(0, 0)])).toEqual({ value: 0, previous: undefined })+ })++ it.each([+ [0, 5, 2, 4, 0, 0.5],+ [10, 5, 0, 4, 2, 0],+ [10, 5, 2, 0, 2, undefined],+ [10, 0, 2, 4, null, undefined],+ [undefined, 5, 2, 4, null, undefined],+ ])(+ 'distinguishes unavailable ratios from zero (%s/%s)',+ (count, total, priorCount, priorTotal, value, previous) => {+ const items: WebOverviewItem[] = [+ { key: 'count', kind: 'unit', value: count, previous: priorCount },+ { key: 'total', kind: 'unit', value: total, previous: priorTotal },+ ]+ const ratio = ratioItem(items, 'ratio', 'count', 'total')+ expect(+ ratio?.kind === 'metric' ? { value: ratio.item.value, previous: ratio.item.previous } : ratio+ ).toEqual(value === null ? null : { value, previous })+ }+ )+})diff --git a/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.ts b/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.tsnew file mode 100644index 000000000000..b21cf73918b6--- /dev/null+++ b/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.ts@@ -0,0 +1,67 @@+import { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'+import { WebOverviewItem } from '~/queries/schema/schema-general'+import { TrendResult } from '~/types'++import { MetricCardSpec, pctChange } from './cards/metricCardSpec'++/** Sums a BoldNumber trends response, keeping the two compared periods apart. */+export function sumTrendSeries(results: TrendResult[] | undefined): { value: number; previous: number | undefined } {+ if (!results?.length) {+ return { value: 0, previous: undefined }+ }+ let value = 0+ let previous: number | undefined+ for (const result of results) {+ const amount = result.aggregated_value ?? 0+ if (result.compare_label === 'previous') {+ previous = (previous ?? 0) + amount+ continue+ }+ value += amount+ }+ return { value, previous }+}++/** One series of a multi-series trends response, picked by the order the query asked for it in.+ * `value` is undefined when that series returned nothing, which the caller shows as N/A rather+ * than as a zero it cannot stand behind. */+export function seriesTotal(results: TrendResult[] | undefined, order: number): { value?: number; previous?: number } {+ const matching = (results ?? []).filter((result) => (result.order ?? result.action?.order ?? 0) === order)+ if (!matching.length) {+ return {}+ }+ const current = matching.find((result) => result.compare_label !== 'previous')+ const previous = matching.find((result) => result.compare_label === 'previous')+ return {+ value: current?.aggregated_value,+ previous: previous?.aggregated_value,+ }+}++/** One overview scalar divided by another, as a card. Null when the denominator is missing or+ * zero, which the caller shows as a notice rather than as a misleading zero. */+export function ratioItem(+ results: WebOverviewItem[] | undefined,+ key: string,+ numeratorKey: string,+ denominatorKey: string+): MetricCardSpec | null {+ const numerator = results?.find((item) => item.key === numeratorKey)+ const denominator = results?.find((item) => item.key === denominatorKey)+ if (numerator?.value === undefined || !denominator?.value) {+ return null+ }+ const value = numerator.value / denominator.value+ const previous =+ numerator.previous !== undefined && denominator.previous ? numerator.previous / denominator.previous : undefined+ return {+ kind: 'metric',+ item: {+ key,+ kind: 'unit',+ value,+ previous,+ changeFromPreviousPct: pctChange(value, previous),+ } as OverviewMetricCardItem,+ }+}diff --git a/products/marketing_analytics/frontend/retention/RetentionReturnTable.tsx b/products/marketing_analytics/frontend/retention/RetentionReturnTable.tsxindex 07801018186d..b8429ce5c7bd 100644--- a/products/marketing_analytics/frontend/retention/RetentionReturnTable.tsx+++ b/products/marketing_analytics/frontend/retention/RetentionReturnTable.tsx@@ -6,18 +6,12 @@ import { VariationCell } from 'scenes/web-analytics/tiles/WebAnalyticsTile'import { MarketingAnalyticsRetentionSummaryRow } from '~/queries/schema/schema-general'+import { ReturnRow, pairWithPrevious, returnRate } from './retentionSummary'+const CountCell = VariationCell({ reserveTrendSpace: false })const RateCell = VariationCell({ isPercentage: true })const DaysCell = VariationCell({ neutral: true, formatValue: (value) => value.toFixed(1) })-type ReturnRow = MarketingAnalyticsRetentionSummaryRow & { comparison?: MarketingAnalyticsRetentionSummaryRow }--function returnRate(row: MarketingAnalyticsRetentionSummaryRow | undefined, days: 7 | 30): number | null {- const eligible = days === 7 ? row?.eligible7d : row?.eligible30d- const returned = days === 7 ? row?.returned7d : row?.returned30d- return eligible ? (returned ?? 0) / eligible : null-}-export function RetentionReturnTable({rows,dimensionLabel,@@ -31,10 +25,8 @@ export function RetentionReturnTable({compare: booleanonlyNewUsers: boolean}): JSX.Element {- const previous = new Map(rows.filter((row) => row.previous).map((row) => [row.breakdownValue, row]))- const current = rows.filter((row) => !row.previous)- const total = current.reduce((sum, row) => sum + row.acquired, 0)- const data: ReturnRow[] = current.map((row) => ({ ...row, comparison: previous.get(row.breakdownValue) }))+ const data = pairWithPrevious(rows)+ const total = data.reduce((sum, row) => sum + row.acquired, 0)const columns: LemonTableColumn<ReturnRow, keyof ReturnRow | undefined>[] = [{title: dimensionLabel,diff --git a/products/marketing_analytics/frontend/retention/retentionSummary.test.ts b/products/marketing_analytics/frontend/retention/retentionSummary.test.tsnew file mode 100644index 000000000000..7ebee214fb2c--- /dev/null+++ b/products/marketing_analytics/frontend/retention/retentionSummary.test.ts@@ -0,0 +1,33 @@+import { MarketingAnalyticsRetentionSummaryRow } from '~/queries/schema/schema-general'++import { pairWithPrevious, returnRate } from './retentionSummary'++describe('retentionSummary', () => {+ const row = (breakdownValue: string, previous = false): MarketingAnalyticsRetentionSummaryRow => ({+ breakdownValue,+ previous,+ acquired: 10,+ returners: 2,+ eligible7d: 5,+ returned7d: 0,+ eligible30d: 0,+ returned30d: 0,+ medianReturnDays: 4,+ })++ it('pairs interleaved periods by breakdown and keeps new breakdowns', () => {+ const email = row('Email')+ const previousEmail = row('Email', true)+ const direct = row('Direct')+ expect(pairWithPrevious([row('Organic', true), email, previousEmail, direct])).toEqual([+ { ...email, comparison: previousEmail },+ { ...direct, comparison: undefined },+ ])+ })++ it('distinguishes a zero return rate from a cohort with no eligible visitors', () => {+ expect(returnRate(row('Email'), 7)).toBe(0)+ expect(returnRate(row('Email'), 30)).toBeNull()+ expect(returnRate(undefined, 7)).toBeNull()+ })+})diff --git a/products/marketing_analytics/frontend/retention/retentionSummary.ts b/products/marketing_analytics/frontend/retention/retentionSummary.tsnew file mode 100644index 000000000000..5ddf9eba8c2f--- /dev/null+++ b/products/marketing_analytics/frontend/retention/retentionSummary.ts@@ -0,0 +1,18 @@+import { MarketingAnalyticsRetentionSummaryRow } from '~/queries/schema/schema-general'++export type ReturnRow = MarketingAnalyticsRetentionSummaryRow & {+ comparison?: MarketingAnalyticsRetentionSummaryRow+}++/** Null when nobody has had the full window yet, which is not the same as nobody returning. */+export function returnRate(row: MarketingAnalyticsRetentionSummaryRow | undefined, days: 7 | 30): number | null {+ const eligible = days === 7 ? row?.eligible7d : row?.eligible30d+ const returned = days === 7 ? row?.returned7d : row?.returned30d+ return eligible ? (returned ?? 0) / eligible : null+}++/** The response interleaves both periods, tagged by `previous`. */+export function pairWithPrevious(rows: MarketingAnalyticsRetentionSummaryRow[]): ReturnRow[] {+ const previous = new Map(rows.filter((row) => row.previous).map((row) => [row.breakdownValue, row]))+ return rows.filter((row) => !row.previous).map((row) => ({ ...row, comparison: previous.get(row.breakdownValue) }))+}