Skip to content

: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.

feat(marketing): add breakdown value and export helpers (#104627)

Javier Bahamondesaa0d1afb06a7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index fe93df560ba8..5d377d5b1aa0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9556,6 +9556,46 @@ snapshots:
hash: v1.k794b7964.4d75bf1926fdf1fdebad47ad4fd07f4035634bca040c9aeb0fd58e18adaa4fb4.3sBwvXuvVbhUPQY3T9JG4G3LwQL6Tvv_a22YYhQJifo
scenes-app-marketing-analytics-cell-actions--source-cell-action-unmapped--light:
hash: v1.k794b7964.c15b997111d34fb17ad2dd192b97c01d0a7ab3a320c5edf9a3e20b0b63a4ff9b.UHxcXJdZkFGXRnzIMFWO99QMD_gZm0V47g8f1j4OFS0
+ scenes-app-marketing-analytics-dashboard-change-value-cell--bounce-rate--dark:
+ hash: v1.k794b7964.077ba380688f01ece0aa53fbdd827aa0b79a58e6f952315fe51af26bc835b64a.PRdHzGD2h3pbMEhUAGi2JC6w2vr8_XebNg_iPCpM9bg
+ scenes-app-marketing-analytics-dashboard-change-value-cell--bounce-rate--light:
+ hash: v1.k794b7964.fa0025bb6bb96998113541c0a88c07df9a3fb13eb88a5d3db77dc09e2610dbb5.YFARE1wxwsYcYAwnmdeWNx0RMg5aJWZ9p_gGHdhbPGo
+ scenes-app-marketing-analytics-dashboard-change-value-cell--currency--dark:
+ hash: v1.k794b7964.244ae95fb34aeaf551ead9698f7a98eee66e1ab0ae4f71ed2237f96d24143754.VhVCgLRQlP27oGTCKNoe2ODSZ2qAvKLrvmeUsTvCgiw
+ scenes-app-marketing-analytics-dashboard-change-value-cell--currency--light:
+ hash: v1.k794b7964.294e22100120b3ed041f6064f4de7ea64faf37121cf09bfcadef3972e83371e1.eW-jkMPXbVQN1lDgX8YZ6aUgjHtugXy1jrF-yBcgYwU
+ scenes-app-marketing-analytics-dashboard-change-value-cell--duration--dark:
+ hash: v1.k794b7964.dd83f21380350590edec4792347a381e44434d043c9828c34ba539cab8a05672.P_wPZwEUIcD_huuRMLLeoUNyIkyo6pkzAQEhDYrpYxA
+ scenes-app-marketing-analytics-dashboard-change-value-cell--duration--light:
+ hash: v1.k794b7964.3cde4c804c7448d6ece25debff96e7a36377b87890910059d3c535eaaeb7e4d5.VtfsENIxNsgnypzn_sNC9-UeAezicqU8kPyMkl6laW8
+ scenes-app-marketing-analytics-dashboard-change-value-cell--interactive-table--dark:
+ hash: v1.k794b7964.7a40b4f2794c76031620be7e1d88adb6a37b3e7edf5a028d024e1047ab0f59da.D3ciTTiGBwj94sXwRUBDc871D06_OemyQSrHrZ9OQaQ
+ scenes-app-marketing-analytics-dashboard-change-value-cell--interactive-table--light:
+ hash: v1.k794b7964.c40e228c0a0bc236eb2157d68fbbd9ed3b03f1a7930d84a0f46f76a9eb6d7aca.ngcDe0Tt55ZP4B-Nmm7X0lvoZrgQc2oGoei73zMCHg4
+ scenes-app-marketing-analytics-dashboard-change-value-cell--negative-currency--dark:
+ hash: v1.k794b7964.789d1f0afd837adfd0efa09a542e9f2d378288421df5d8d80b673d748daaeeda.WwxuZ22NM2Zz99PbOJRY_P1cnd8BVQ7wbSMjwLEk7xg
+ scenes-app-marketing-analytics-dashboard-change-value-cell--negative-currency--light:
+ hash: v1.k794b7964.2da09c227a1de2666e207ac7ac07917036b8ea30b5bcbd6dd85cd9576d4f558a.GbWVCr885-nT6g5UcTX4j60cF7Ul8BL45AI6FOsUdD0
+ scenes-app-marketing-analytics-dashboard-change-value-cell--no-baseline--dark:
+ hash: v1.k794b7964.f172abbe2b6cff81cbde8c456029d3cdc873fc9090f6980fb8fae5bd94b4312a.sY-BJR13mVtiZx31wFpqAQC5BxW_j3kT9zRXRihr2A8
+ scenes-app-marketing-analytics-dashboard-change-value-cell--no-baseline--light:
+ hash: v1.k794b7964.90a2c50431c5e06a41bb5177312e766f1285ca34a269c60b712f90adef9af5df.QOEjsl37FOwmDdzdZ5azbvkjE-FIJaqwwJCX2TE0M24
+ scenes-app-marketing-analytics-dashboard-change-value-cell--number--dark:
+ hash: v1.k794b7964.f6950f48809a084f056f49a14600ed29560971bb5dd25651634d731533f41e5d.C93vGIQ5HAI7xskzcb645hrkLZrKlAUEHcc2kjvuVWo
+ scenes-app-marketing-analytics-dashboard-change-value-cell--number--light:
+ hash: v1.k794b7964.5f647058804ddb8ae81b40188e1081f68399bb622140c4c63f94c515a37e9181.q_Ntv759JbSmfHBikXMRfCoGiA-gltcRi5q9SBGmi7Q
+ scenes-app-marketing-analytics-dashboard-change-value-cell--rate--dark:
+ hash: v1.k794b7964.2396ec0386b28781ab80372412ec44bf4f37488ef8122491861b32494666c9f9.FHyeBiNeo-m9vAOnLMFeW7jfD6CPSYVgM0hKpwkOWog
+ scenes-app-marketing-analytics-dashboard-change-value-cell--rate--light:
+ hash: v1.k794b7964.5f285adee61b3675b3c0e7044f89991a5a6442ba2876118623763ab2ff0006ad.mnm3oxMC4lfAwxe9-FflSu2p-TwLLzL8xFcE9dLk51Q
+ scenes-app-marketing-analytics-dashboard-change-value-cell--rounded-flat--dark:
+ hash: v1.k794b7964.bee8d683cf64b3c2f8284a8bc4faee4bc714fbde660b04bf50bc02fe75352ef7.wYHeLYpctZsms2TqseLkLTVepIXI4HOKo47oMuWig00
+ scenes-app-marketing-analytics-dashboard-change-value-cell--rounded-flat--light:
+ hash: v1.k794b7964.f20644df1c54b8e71adc7a548f81a616e95b89513d64974137504a7a41c05dac.J78XkCDuTF8XdkIVhcA_grX77xR6AOhWSfGQVL_KYpo
+ scenes-app-marketing-analytics-dashboard-change-value-cell--unavailable--dark:
+ hash: v1.k794b7964.a08eefe3f8b95c0cee0659fb050cd3114778edb6a3755fdfe7b95460e031e425.Sodxn6zMfktliL0TqxWRzmRFMPymrVZSrGH4ryLJKRc
+ scenes-app-marketing-analytics-dashboard-change-value-cell--unavailable--light:
+ hash: v1.k794b7964.077208274eef6634c72fb949f22e3cfc5ce4ee6ed110883744ddc6c598e2997c.8WkzjKlIOrwhI2hYPh3FKHnwWIsSzE39LASNS1SaTo8
scenes-app-max-ai-logs-query-tool--no-matches--dark:
hash: v1.k794b7964.c231a64a00f6dfc8bf5b88c3dab624bad88d347b96be0b2e6b0cc14e1c10e1cc.ScE515QePrAYrJB-UWn5sakLt5cKxQKQQrx_n_uJERI
scenes-app-max-ai-logs-query-tool--no-matches--light:
diff --git a/products/marketing_analytics/frontend/dashboard/tables/ChangeValueCell.stories.tsx b/products/marketing_analytics/frontend/dashboard/tables/ChangeValueCell.stories.tsx
new file mode 100644
index 000000000000..da9d0e0d5f43
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/ChangeValueCell.stories.tsx
@@ -0,0 +1,100 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useState } from 'react'
+
+import { LemonButton, LemonMenu, LemonTable, LemonTextArea } from '@posthog/lemon-ui'
+
+import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
+
+import { CurrencyCode } from '~/queries/schema/schema-general'
+
+import { compareByCurrent } from './breakdownTableColumn'
+import { buildExportMenuItems, buildExportRows } from './breakdownTableExport'
+import { ChangeValueCell } from './ChangeValueCell'
+import { CONVERSION_VALUE_COLUMN, VISITORS_COLUMN } from './webStatsColumns'
+import { WebStatsRow } from './webStatsRows'
+
+const meta: Meta<typeof ChangeValueCell> = {
+ title: 'Scenes-App/Marketing analytics/Dashboard/Change value cell',
+ component: ChangeValueCell,
+ args: { currency: CurrencyCode.USD, compare: true },
+}
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const Number: Story = { args: { value: [150, 100] } }
+export const Rate: Story = { args: { value: [0.1, 0.08], kind: 'percentage' } }
+export const BounceRate: Story = { args: { value: [0.2, 0.3], kind: 'percentage', reverseColors: true } }
+export const Duration: Story = { args: { value: [90, 60], kind: 'duration' } }
+export const Currency: Story = { args: { value: [12.5, 10], kind: 'currency' } }
+export const NegativeCurrency: Story = { args: { value: [-12.5, -10], kind: 'currency' } }
+export const NoBaseline: Story = { args: { value: [0, null] } }
+export const Unavailable: Story = { args: { value: null } }
+export const RoundedFlat: Story = { args: { value: [0.10001, 0.1], kind: 'percentage' } }
+
+const rows: WebStatsRow[] = [
+ { breakdownValue: 'Direct', visitors: [10, 5] },
+ { breakdownValue: 'Paid search', visitors: [20, 10], conversion_value: [125, 100] },
+ { breakdownValue: 'Email', visitors: [5, 10], conversion_value: [-12.5, -10] },
+ { breakdownValue: 'Referral', visitors: [0, null], conversion_value: [0, null] },
+ { breakdownValue: 'Organic search', visitors: [30, 25] },
+]
+const columns = [CONVERSION_VALUE_COLUMN, VISITORS_COLUMN]
+
+export const InteractiveTable: Story = {
+ render: function Render(): JSX.Element {
+ const [sorting, setSorting] = useState<Sorting | null>({ columnKey: 'conversion_value', order: 1 })
+ const [pastedExport, setPastedExport] = useState('')
+
+ return (
+ <div className="flex flex-col gap-4 w-full max-w-[60rem]">
+ <LemonMenu
+ items={buildExportMenuItems(
+ () =>
+ buildExportRows({
+ columns,
+ rows,
+ breakdownLabel: 'Channel',
+ breakdownValue: (row) => row.breakdownValue,
+ compare: true,
+ }),
+ 'marketing-breakdown',
+ true
+ )}
+ >
+ <LemonButton type="secondary">Export</LemonButton>
+ </LemonMenu>
+ <LemonTable
+ rowKey="breakdownValue"
+ dataSource={rows}
+ useURLForSorting={false}
+ sorting={sorting}
+ onSort={setSorting}
+ noSortingCancellation
+ columns={[
+ { title: 'Channel', dataIndex: 'breakdownValue' },
+ ...columns.map((column) => ({
+ key: column.key,
+ title: column.title,
+ align: 'right' as const,
+ sorter: compareByCurrent(column, sorting?.order ?? 1),
+ render: (_: unknown, row: WebStatsRow) => (
+ <ChangeValueCell
+ value={column.value(row)}
+ kind={column.kind}
+ currency={CurrencyCode.USD}
+ compare
+ />
+ ),
+ })),
+ ]}
+ />
+ <LemonTextArea
+ aria-label="Paste exported rows"
+ placeholder="Paste exported rows here"
+ value={pastedExport}
+ onChange={setPastedExport}
+ />
+ </div>
+ )
+ },
+}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/ChangeValueCell.tsx b/products/marketing_analytics/frontend/dashboard/tables/ChangeValueCell.tsx
new file mode 100644
index 000000000000..45381318f95d
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/ChangeValueCell.tsx
@@ -0,0 +1,74 @@
+import { IconTrending } from '@posthog/icons'
+
+import { getColorVar } from 'lib/colors'
+import { IconTrendingDown, IconTrendingFlat } from 'lib/lemon-ui/icons'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+
+import { CurrencyCode } from '~/queries/schema/schema-general'
+
+import type { ComparedValue } from './breakdownTableColumn'
+import { ChangeFormat, formatComparedValue } from './formatComparedValue'
+
+export interface ChangeValueCellProps {
+ value: ComparedValue | null
+ compare: boolean
+ kind?: ChangeFormat
+ /** Up is bad for metrics like bounce rate. */
+ reverseColors?: boolean
+ /** Neither direction is good or bad, so the change stays grey. */
+ neutral?: boolean
+ tooltipContent?: React.ReactNode
+ /** The project's currency, for the `currency` format. */
+ currency: CurrencyCode
+}
+
+/** The value with its change against the previous period spelled out, rather than an arrow whose
+ * size the reader has to take on trust. */
+export function ChangeValueCell({
+ value,
+ compare,
+ kind = 'number',
+ reverseColors,
+ neutral,
+ tooltipContent,
+ currency,
+}: ChangeValueCellProps): JSX.Element {
+ if (!value) {
+ return <span className="text-muted">–</span>
+ }
+
+ const { current, previous, difference, delta } = formatComparedValue(value, compare, kind, currency)
+ const moved = difference !== null && delta !== null
+ const Icon = !moved ? IconTrendingFlat : difference > 0 ? IconTrending : IconTrendingDown
+ const color =
+ neutral || !moved
+ ? getColorVar('muted')
+ : difference > 0 !== !!reverseColors
+ ? getColorVar('success')
+ : getColorVar('danger')
+
+ const body = (
+ <span className="inline-flex items-center justify-end gap-1.5 tabular-nums">
+ <span>{current}</span>
+ {difference !== null && (
+ // eslint-disable-next-line react/forbid-dom-props
+ <span className="inline-flex items-center gap-0.5 text-xs" style={{ color }}>
+ <Icon />
+ <span>{delta}</span>
+ </span>
+ )}
+ </span>
+ )
+
+ const tooltip =
+ previous !== null ? (
+ <div className="flex flex-col gap-1">
+ <div>{`${previous} in the previous period`}</div>
+ {tooltipContent ? <div>{tooltipContent}</div> : null}
+ </div>
+ ) : (
+ tooltipContent
+ )
+
+ return tooltip ? <Tooltip title={tooltip}>{body}</Tooltip> : body
+}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/breakdownTableColumn.test.ts b/products/marketing_analytics/frontend/dashboard/tables/breakdownTableColumn.test.ts
new file mode 100644
index 000000000000..53a53ea433f5
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/breakdownTableColumn.test.ts
@@ -0,0 +1,33 @@
+import { BreakdownTableColumn, ComparedValue, compareByCurrent } from './breakdownTableColumn'
+
+interface Row {
+ name: string
+ value: ComparedValue | null
+}
+
+const rows: Row[] = [
+ { name: 'Missing A', value: null },
+ { name: 'Positive', value: [10, -50] },
+ { name: 'Negative', value: [-5, 100] },
+ { name: 'Missing B', value: null },
+ { name: 'Zero', value: [0, null] },
+]
+
+const column: BreakdownTableColumn<Row> = {
+ key: 'value',
+ title: 'Value',
+ exportLabel: 'Value',
+ value: (row) => row.value,
+}
+
+describe('compareByCurrent', () => {
+ it.each([
+ [1, ['Negative', 'Zero', 'Positive', 'Missing A', 'Missing B']],
+ [-1, ['Positive', 'Zero', 'Negative', 'Missing A', 'Missing B']],
+ ] as const)('keeps missing values last under the LemonTable sort-order contract (%s)', (order, expected) => {
+ const sorter = compareByCurrent(column, order)
+ const sorted = rows.slice().sort((a, b) => order * sorter(a, b))
+
+ expect(sorted.map((row) => row.name)).toEqual(expected)
+ })
+})
diff --git a/products/marketing_analytics/frontend/dashboard/tables/breakdownTableColumn.ts b/products/marketing_analytics/frontend/dashboard/tables/breakdownTableColumn.ts
new file mode 100644
index 000000000000..030a7f20ac4c
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/breakdownTableColumn.ts
@@ -0,0 +1,44 @@
+import type React from 'react'
+
+import type { ChangeFormat } from './formatComparedValue'
+
+/** What every web analytics query returns per metric: this period and the one before it. */
+export type ComparedValue = [number, number | null]
+
+export interface BreakdownTableColumn<Row> {
+ key: string
+ title: string
+ /** Shown instead of `title` once the table is too narrow to spell it out. */
+ shortTitle?: string
+ tooltip?: string
+ value: (row: Row) => ComparedValue | null
+ kind?: ChangeFormat
+ /** Up is bad, as for bounce rate. */
+ reverseColors?: boolean
+ /** Neither direction is good or bad, so the change stays grey. */
+ neutral?: boolean
+ exportLabel: string
+ exportValue?: (value: number) => string
+ tooltipContent?: (row: Row) => React.ReactNode
+}
+
+export function compareByCurrent<Row>(
+ column: BreakdownTableColumn<Row>,
+ sortOrder: 1 | -1
+): (a: Row, b: Row) => number {
+ return (a: Row, b: Row): number => {
+ const aValue = column.value(a)?.[0]
+ const bValue = column.value(b)?.[0]
+ if (aValue === bValue) {
+ return 0
+ }
+ // LemonTable multiplies this result by the sort order, so compensate to keep missing values last.
+ if (aValue === undefined) {
+ return sortOrder
+ }
+ if (bValue === undefined) {
+ return -sortOrder
+ }
+ return aValue - bValue
+ }
+}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.test.ts b/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.test.ts
new file mode 100644
index 000000000000..8ac9950da36a
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.test.ts
@@ -0,0 +1,66 @@
+import { LemonMenuItemLeaf } from 'lib/lemon-ui/LemonMenu'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+
+import { buildExportMenuItems, buildExportRows } from './breakdownTableExport'
+import { SESSIONS_PER_VISITOR_COLUMN, VISITORS_COLUMN } from './webStatsColumns'
+import { WebStatsRow } from './webStatsRows'
+
+jest.mock('lib/utils/copyToClipboard', () => ({ copyToClipboard: jest.fn() }))
+
+describe('buildExportRows', () => {
+ const rows: WebStatsRow[] = [
+ { breakdownValue: 'Email', visitors: [10, 0], sessions: [25, 5] },
+ { breakdownValue: 'Direct', visitors: [0, null] },
+ { breakdownValue: 'Organic' },
+ ]
+
+ it.each([false, true])('exports zeros, unavailable ratios, and previous periods (compare=%s)', (compare) => {
+ expect(
+ buildExportRows({
+ columns: [VISITORS_COLUMN, SESSIONS_PER_VISITOR_COLUMN],
+ rows,
+ breakdownLabel: 'Channel',
+ breakdownValue: (row) => row.breakdownValue,
+ compare,
+ })
+ ).toEqual(
+ compare
+ ? [
+ [
+ 'Channel',
+ 'Visitors (current)',
+ 'Visitors (previous)',
+ 'Sessions per visitor (current)',
+ 'Sessions per visitor (previous)',
+ ],
+ ['Email', '10', '0', '2.50', ''],
+ ['Direct', '0', '', '', ''],
+ ['Organic', '', '', '', ''],
+ ]
+ : [
+ ['Channel', 'Visitors', 'Sessions per visitor'],
+ ['Email', '10', '2.50'],
+ ['Direct', '0', ''],
+ ['Organic', '', ''],
+ ]
+ )
+ })
+
+ it.each([
+ ['Copy as CSV', 'Channel,Visitors\r\nEmail,0'],
+ ['Copy for Excel', 'Channel\tVisitors\r\nEmail\t0'],
+ ])('copies the latest rows through %s', (label, expected) => {
+ let data = [['stale']]
+ const item = buildExportMenuItems(() => data, 'engagement', true).find(
+ (item) => item.label === label
+ ) as LemonMenuItemLeaf
+ data = [
+ ['Channel', 'Visitors'],
+ ['Email', '0'],
+ ]
+
+ item.onClick?.({} as React.MouseEvent)
+
+ expect(copyToClipboard).toHaveBeenLastCalledWith(expected, 'table')
+ })
+})
diff --git a/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.ts b/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.ts
new file mode 100644
index 000000000000..6e5b77db490c
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.ts
@@ -0,0 +1,76 @@
+import { LemonMenuItem } from '@posthog/lemon-ui'
+
+import { downloadTableDataAsCsv } from 'scenes/web-analytics/webAnalyticsExportUtils'
+
+import { copyTableData } from '~/queries/nodes/InsightViz/exportAdapters'
+import { ExporterFormat } from '~/types'
+
+import type { BreakdownTableColumn } from './breakdownTableColumn'
+
+export interface ExportRowsOptions<Row> {
+ columns: BreakdownTableColumn<Row>[]
+ rows: Row[]
+ breakdownLabel: string
+ breakdownValue: (row: Row) => string
+ compare: boolean
+}
+
+/** Rows as `string[][]` with the header first, which is the shape the shared export helpers take. */
+export function buildExportRows<Row>({
+ columns,
+ rows,
+ breakdownLabel,
+ breakdownValue,
+ compare,
+}: ExportRowsOptions<Row>): string[][] {
+ if (!rows.length) {
+ return []
+ }
+
+ const format = (column: BreakdownTableColumn<Row>, value: number): string =>
+ column.exportValue ? column.exportValue(value) : String(value)
+
+ const header = [
+ breakdownLabel,
+ ...columns.flatMap((column) =>
+ compare ? [`${column.exportLabel} (current)`, `${column.exportLabel} (previous)`] : [column.exportLabel]
+ ),
+ ]
+
+ const body = rows.map((row) => [
+ breakdownValue(row),
+ ...columns.flatMap((column) => {
+ const value = column.value(row)
+ const current = value ? format(column, value[0]) : ''
+ if (!compare) {
+ return [current]
+ }
+ return [current, value && value[1] !== null ? format(column, value[1]) : '']
+ }),
+ ])
+
+ return [header, ...body]
+}
+
+export function buildExportMenuItems(getRows: () => string[][], filename: string, hasRows: boolean): LemonMenuItem[] {
+ const disabledReason = hasRows ? undefined : 'No data to export yet'
+ return [
+ {
+ label: 'Download CSV',
+ disabledReason,
+ onClick: () => downloadTableDataAsCsv(getRows(), `${filename}.csv`),
+ },
+ {
+ label: 'Copy as CSV',
+ disabledReason,
+ onClick: () => copyTableData(getRows(), ExporterFormat.CSV),
+ },
+ {
+ // A real .xlsx needs the server exporter, which cannot re-run an in-memory table.
+ // Tab-separated text pastes into Excel as columns, which is what people want here.
+ label: 'Copy for Excel',
+ disabledReason,
+ onClick: () => copyTableData(getRows(), ExporterFormat.XLSX),
+ },
+ ]
+}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.test.ts b/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.test.ts
new file mode 100644
index 000000000000..e93ac20a4b64
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.test.ts
@@ -0,0 +1,58 @@
+import { BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'
+
+import { TrendResult } from '~/types'
+
+import { conversionValueRows } from './conversionValueRows'
+
+const result = (
+ order: number,
+ breakdownValue: string,
+ aggregatedValue: number,
+ compareLabel?: 'current' | 'previous'
+): TrendResult =>
+ ({
+ action: { order },
+ breakdown_value: breakdownValue,
+ aggregated_value: aggregatedValue,
+ compare_label: compareLabel ?? 'current',
+ }) as unknown as TrendResult
+
+describe('conversionValueRows', () => {
+ it('pairs each breakdown with its previous period, by series order', () => {
+ const rows = conversionValueRows([
+ result(0, 'Paid Search', 4000),
+ result(0, 'Paid Search', 3000, 'previous'),
+ result(1, 'Paid Search', 80),
+ result(1, 'Paid Search', 75, 'previous'),
+ ])
+
+ expect(rows.get('Paid Search')).toEqual({ total: [4000, 3000], average: [80, 75] })
+ })
+
+ it('leaves the previous period null when the breakdown is new', () => {
+ const rows = conversionValueRows([result(0, 'Email', 900), result(1, 'Email', 45)])
+
+ expect(rows.get('Email')).toEqual({ total: [900, null], average: [45, null] })
+ })
+
+ // The stats table reports an untagged visit as SQL NULL, which webStatsRows reads as ''. If
+ // these two did not agree, that row's value cells would silently stay empty.
+ it('keys the trends null sentinel the way the stats table keys an untagged row', () => {
+ const rows = conversionValueRows([result(0, BREAKDOWN_NULL_STRING_LABEL, 120)])
+
+ expect(rows.has(BREAKDOWN_NULL_STRING_LABEL)).toBe(false)
+ expect(rows.get('')).toEqual({ total: [120, null] })
+ })
+
+ // The fold is a total over values the stats table lists one by one, so merging it would
+ // attribute the whole tail to whichever row happened to carry that name.
+ it('drops the folded "other" row', () => {
+ const rows = conversionValueRows([result(0, BREAKDOWN_OTHER_STRING_LABEL, 5000), result(0, 'Direct', 100)])
+
+ expect([...rows.keys()]).toEqual(['Direct'])
+ })
+
+ it('returns nothing for an absent response', () => {
+ expect(conversionValueRows(undefined).size).toBe(0)
+ })
+})
diff --git a/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.ts b/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.ts
new file mode 100644
index 000000000000..eb12066ad931
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.ts
@@ -0,0 +1,56 @@
+import { BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'
+
+import { TrendResult } from '~/types'
+
+import type { ComparedValue } from './breakdownTableColumn'
+
+export interface ConversionValueByBreakdown {
+ total?: ComparedValue
+ average?: ComparedValue
+}
+
+/** Series order in `conversionValueSeries`. */
+const TOTAL_ORDER = 0
+const AVERAGE_ORDER = 1
+
+const seriesOrder = (result: TrendResult): number => result.order ?? result.action?.order ?? 0
+
+/** Trends reports an untagged visit as its own sentinel, while the stats table reports SQL NULL,
+ * which `webStatsRows` reads as an empty string. Both have to land on the same key or the two
+ * halves of a row never meet. */
+const joinKey = (breakdownValue: TrendResult['breakdown_value']): string => {
+ const value = String(breakdownValue ?? '')
+ return value === BREAKDOWN_NULL_STRING_LABEL ? '' : value
+}
+
+const pair = (current: number | undefined, previous: number | undefined): ComparedValue | undefined =>
+ current === undefined ? undefined : [current, previous ?? null]
+
+/** Keyed by the raw breakdown value, not its display label. */
+export function conversionValueRows(results: TrendResult[] | undefined): Map<string, ConversionValueByBreakdown> {
+ const byKey = new Map<string, ConversionValueByBreakdown>()
+
+ for (const order of [TOTAL_ORDER, AVERAGE_ORDER]) {
+ const rows = (results ?? []).filter(
+ // The fold row is an aggregate over values the stats table lists individually, so
+ // merging it would attribute the whole tail to one row.
+ (result) => seriesOrder(result) === order && result.breakdown_value !== BREAKDOWN_OTHER_STRING_LABEL
+ )
+ const current = rows.filter((result) => result.compare_label !== 'previous')
+ const previous = new Map(
+ rows.filter((result) => result.compare_label === 'previous').map((r) => [joinKey(r.breakdown_value), r])
+ )
+
+ for (const row of current) {
+ const key = joinKey(row.breakdown_value)
+ const value = pair(row.aggregated_value, previous.get(key)?.aggregated_value)
+ if (value === undefined) {
+ continue
+ }
+ const existing = byKey.get(key) ?? {}
+ byKey.set(key, order === TOTAL_ORDER ? { ...existing, total: value } : { ...existing, average: value })
+ }
+ }
+
+ return byKey
+}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/formatComparedValue.test.ts b/products/marketing_analytics/frontend/dashboard/tables/formatComparedValue.test.ts
new file mode 100644
index 000000000000..41458eca723e
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/formatComparedValue.test.ts
@@ -0,0 +1,36 @@
+import { CurrencyCode } from '~/queries/schema/schema-general'
+
+import { formatComparedValue } from './formatComparedValue'
+
+describe('formatComparedValue', () => {
+ it.each([
+ [CurrencyCode.USD, -12.5, -10, '-$12.50', '-$10.00', '-$2.50'],
+ [CurrencyCode.EUR, -1250, -1200, '-€1,250', '-€1,200', '-€50.00'],
+ ] as const)(
+ 'places the sign before %s for negative values and changes',
+ (currency, current, previous, formattedCurrent, formattedPrevious, delta) => {
+ expect(formatComparedValue([current, previous], true, 'currency', currency)).toEqual({
+ current: formattedCurrent,
+ previous: formattedPrevious,
+ difference: current - previous,
+ delta,
+ })
+ }
+ )
+
+ it.each([
+ [0, true, '$0.00', 12.5, '+$12.50'],
+ [null, true, null, null, null],
+ [0, false, null, null, null],
+ ] as const)(
+ 'distinguishes a zero baseline from an unavailable comparison (previous=%s, compare=%s)',
+ (previous, compare, formattedPrevious, difference, delta) => {
+ expect(formatComparedValue([12.5, previous], compare, 'currency', CurrencyCode.USD)).toEqual({
+ current: '$12.50',
+ previous: formattedPrevious,
+ difference,
+ delta,
+ })
+ }
+ )
+})
diff --git a/products/marketing_analytics/frontend/dashboard/tables/formatComparedValue.ts b/products/marketing_analytics/frontend/dashboard/tables/formatComparedValue.ts
new file mode 100644
index 000000000000..b233d51e6911
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/formatComparedValue.ts
@@ -0,0 +1,86 @@
+import { getCurrencySymbol } from 'lib/utils/currency'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+
+import { CurrencyCode } from '~/queries/schema/schema-general'
+
+import type { ComparedValue } from './breakdownTableColumn'
+
+export type ChangeFormat = 'number' | 'percentage' | 'duration' | 'decimal' | 'currency'
+
+/** Cents matter on an average conversion value and are noise on a five-figure total, so the
+ * precision follows the size rather than being fixed as `formatCurrency` fixes it. */
+const money = (value: number, currency: CurrencyCode): string => {
+ const { symbol, isPrefix } = getCurrencySymbol(currency)
+ const decimals = Math.abs(value) >= 1000 ? 0 : 2
+ const sign = value < 0 ? '-' : ''
+ const amount = humanFriendlyNumber(Math.abs(value), decimals, decimals)
+ return isPrefix ? `${sign}${symbol}${amount}` : `${sign}${amount} ${symbol}`
+}
+
+const format = (value: number, kind: ChangeFormat, currency: CurrencyCode): string => {
+ switch (kind) {
+ case 'percentage':
+ return `${(value * 100).toFixed(1)}%`
+ case 'duration':
+ return humanFriendlyDuration(value) ?? String(value)
+ case 'decimal':
+ return value.toFixed(1)
+ case 'currency':
+ return money(value, currency)
+ default:
+ return humanFriendlyNumber(value)
+ }
+}
+
+/** A rate moves in percentage points, not percent: 8% to 10% is +2pp, and calling that +25% invites
+ * the reader to mix the two up.
+ *
+ * Returns null when the change rounds away at the precision shown, so the cell renders a flat
+ * marker rather than a signed zero. */
+const formatDelta = (difference: number, kind: ChangeFormat, currency: CurrencyCode): string | null => {
+ const size = Math.abs(difference)
+ const sign = difference > 0 ? '+' : '-'
+ switch (kind) {
+ case 'percentage': {
+ const points = (size * 100).toFixed(1)
+ return Number(points) === 0 ? null : `${sign}${points}pp`
+ }
+ case 'duration': {
+ const seconds = Math.round(size)
+ return seconds === 0 ? null : `${sign}${humanFriendlyDuration(seconds) ?? seconds}`
+ }
+ case 'decimal': {
+ const decimals = size.toFixed(1)
+ return Number(decimals) === 0 ? null : `${sign}${decimals}`
+ }
+ case 'currency':
+ return size < 0.01 ? null : `${sign}${money(size, currency)}`
+ default:
+ return size < 1 ? null : `${sign}${humanFriendlyNumber(size)}`
+ }
+}
+
+interface FormattedComparedValue {
+ current: string
+ previous: string | null
+ difference: number | null
+ delta: string | null
+}
+
+export function formatComparedValue(
+ value: ComparedValue,
+ compare: boolean,
+ kind: ChangeFormat,
+ currency: CurrencyCode
+): FormattedComparedValue {
+ const [current, previous] = value
+ const hasComparison = previous !== null && compare
+ const difference = hasComparison ? current - previous : null
+ return {
+ current: format(current, kind, currency),
+ previous: hasComparison ? format(previous, kind, currency) : null,
+ difference,
+ delta: difference === null ? null : formatDelta(difference, kind, currency),
+ }
+}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/webStatsColumns.tsx b/products/marketing_analytics/frontend/dashboard/tables/webStatsColumns.tsx
new file mode 100644
index 000000000000..bf36b9f395ce
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/webStatsColumns.tsx
@@ -0,0 +1,135 @@
+import { humanFriendlyDuration } from 'lib/utils/durations'
+
+import type { BreakdownTableColumn, ComparedValue } from './breakdownTableColumn'
+import type { WebStatsRow } from './webStatsRows'
+
+/** Divides two compared values, keeping the previous period only when both sides have one. */
+export const ratio = (
+ numerator: ComparedValue | undefined,
+ denominator: ComparedValue | undefined
+): ComparedValue | null => {
+ if (!numerator || !denominator || !denominator[0]) {
+ return null
+ }
+ const previous =
+ numerator[1] !== null && denominator[1] !== null && denominator[1] !== 0 ? numerator[1] / denominator[1] : null
+ return [numerator[0] / denominator[0], previous]
+}
+
+export const VISITORS_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'visitors',
+ title: 'Visitors',
+ tooltip: 'People with a pageview or screenview in the selected date range.',
+ value: (row) => row.visitors ?? null,
+ exportLabel: 'Visitors',
+}
+
+export const VIEWS_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'views',
+ title: 'Pageviews',
+ shortTitle: 'Views',
+ value: (row) => row.views ?? null,
+ exportLabel: 'Pageviews',
+}
+
+export const SESSIONS_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'sessions',
+ title: 'Sessions',
+ value: (row) => row.sessions ?? null,
+ exportLabel: 'Sessions',
+}
+
+export const SESSIONS_PER_VISITOR_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'sessions_per_visitor',
+ title: 'Sessions per visitor',
+ shortTitle: 'Sessions/visitor',
+ tooltip: 'Sessions divided by visitors.',
+ value: (row) => ratio(row.sessions, row.visitors),
+ kind: 'decimal',
+ exportLabel: 'Sessions per visitor',
+ exportValue: (value) => value.toFixed(2),
+}
+
+export const SESSION_DURATION_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'session_duration',
+ title: 'Avg. session duration',
+ shortTitle: 'Duration',
+ tooltip: 'The average length of sessions that started here.',
+ value: (row) => row.session_duration ?? null,
+ kind: 'duration',
+ exportLabel: 'Avg. session duration',
+ exportValue: (value) => humanFriendlyDuration(value) ?? String(value),
+}
+
+export const PAGES_PER_SESSION_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'pages_per_session',
+ title: 'Pages per session',
+ shortTitle: 'Pages/session',
+ tooltip: 'Pageviews divided by sessions.',
+ value: (row) => ratio(row.views, row.sessions),
+ kind: 'decimal',
+ exportLabel: 'Pages per session',
+ exportValue: (value) => value.toFixed(2),
+}
+
+export const PAGES_PER_VISITOR_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'pages_per_visitor',
+ title: 'Pageviews per visitor',
+ shortTitle: 'Views/visitor',
+ tooltip: 'Pageviews divided by visitors.',
+ value: (row) => ratio(row.views, row.visitors),
+ kind: 'decimal',
+ exportLabel: 'Pageviews per visitor',
+ exportValue: (value) => value.toFixed(2),
+}
+
+export const BOUNCE_RATE_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'bounce_rate',
+ title: 'Bounce rate',
+ shortTitle: 'Bounce',
+ tooltip: 'Sessions that left without a second pageview or any meaningful interaction.',
+ value: (row) => row.bounce_rate ?? null,
+ kind: 'percentage',
+ reverseColors: true,
+ exportLabel: 'Bounce rate',
+}
+
+export const CONVERSIONS_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'total_conversions',
+ title: 'Conversions',
+ value: (row) => row.total_conversions ?? null,
+ exportLabel: 'Conversions',
+}
+
+export const CONVERSION_RATE_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'conversion_rate',
+ title: 'Conversion rate',
+ shortTitle: 'Conv. rate',
+ tooltip: 'People who completed the goal, divided by visitors.',
+ value: (row) => row.conversion_rate ?? null,
+ kind: 'percentage',
+ exportLabel: 'Conversion rate',
+}
+
+export const CONVERSION_VALUE_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'conversion_value',
+ title: 'Conversion value',
+ shortTitle: 'Value',
+ tooltip: "The goal's value property, summed over the conversions of sessions that started here.",
+ value: (row) => row.conversion_value ?? null,
+ kind: 'currency',
+ exportLabel: 'Conversion value',
+ // A plain number, so a spreadsheet reads the export as money rather than as text.
+ exportValue: (value) => value.toFixed(2),
+}
+
+export const AVG_CONVERSION_VALUE_COLUMN: BreakdownTableColumn<WebStatsRow> = {
+ key: 'avg_conversion_value',
+ title: 'Avg. conversion value',
+ shortTitle: 'Avg. value',
+ tooltip: "The goal's value property, averaged over the conversions of sessions that started here.",
+ value: (row) => row.avg_conversion_value ?? null,
+ kind: 'currency',
+ exportLabel: 'Avg. conversion value',
+ exportValue: (value) => value.toFixed(2),
+}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.test.ts b/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.test.ts
new file mode 100644
index 000000000000..6e681a734888
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.test.ts
@@ -0,0 +1,36 @@
+import { WebStatsTableQueryResponse } from '~/queries/schema/schema-general'
+
+import { webStatsRows } from './webStatsRows'
+
+describe('webStatsRows', () => {
+ it('pairs metrics by column name while preserving zero and missing comparisons', () => {
+ const response = {
+ columns: [
+ 'context.columns.sessions',
+ 'context.columns.breakdown_value',
+ 'context.columns.visitors',
+ 'context.columns.ui_fill_fraction',
+ 'context.columns.cross_sell',
+ ],
+ results: [
+ [[0, 10], null, 0, 0.5, 'ignored'],
+ [[12, null], 'Email', [7, 0], 1, 'ignored'],
+ ],
+ } as WebStatsTableQueryResponse
+
+ expect(webStatsRows(response)).toEqual([
+ { breakdownValue: '', sessions: [0, 10], visitors: [0, null] },
+ { breakdownValue: 'Email', sessions: [12, null], visitors: [7, 0] },
+ ])
+ })
+
+ it('leaves unavailable metrics absent instead of reporting zero', () => {
+ expect(
+ webStatsRows({
+ columns: ['breakdown_value', 'visitors', 'sessions'],
+ results: [['Direct', [null, 4], null]],
+ } as WebStatsTableQueryResponse)
+ ).toEqual([{ breakdownValue: 'Direct' }])
+ expect(webStatsRows(undefined)).toEqual([])
+ })
+})
diff --git a/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.ts b/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.ts
new file mode 100644
index 000000000000..d064d89e6be7
--- /dev/null
+++ b/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.ts
@@ -0,0 +1,56 @@
+import { WebStatsTableQueryResponse } from '~/queries/schema/schema-general'
+
+import type { ComparedValue } from './breakdownTableColumn'
+
+export interface WebStatsRow {
+ breakdownValue: string
+ visitors?: ComparedValue
+ sessions?: ComparedValue
+ views?: ComparedValue
+ bounce_rate?: ComparedValue
+ session_duration?: ComparedValue
+ total_conversions?: ComparedValue
+ unique_conversions?: ComparedValue
+ conversion_rate?: ComparedValue
+ /** Merged in from the conversion value query, not returned by WebStatsTableQuery. */
+ conversion_value?: ComparedValue
+ avg_conversion_value?: ComparedValue
+}
+
+const COLUMN_PREFIX = 'context.columns.'
+
+/** Presentation columns the backend appends for the query table's own chrome. */
+const IGNORED_COLUMNS = new Set(['ui_fill_fraction', 'cross_sell'])
+
+const toCompared = (value: unknown): ComparedValue | undefined => {
+ if (Array.isArray(value)) {
+ const [current, previous] = value
+ return typeof current === 'number' ? [current, typeof previous === 'number' ? previous : null] : undefined
+ }
+ return typeof value === 'number' ? [value, null] : undefined
+}
+
+/** Zips the response's parallel columns and rows into one object per breakdown value. */
+export function webStatsRows(response: WebStatsTableQueryResponse | undefined): WebStatsRow[] {
+ const columns = (response?.columns ?? []) as string[]
+ const results = (response?.results ?? []) as unknown[][]
+
+ return results.map((row) => {
+ const parsed: WebStatsRow = { breakdownValue: '' }
+ columns.forEach((column, index) => {
+ const name = column.startsWith(COLUMN_PREFIX) ? column.slice(COLUMN_PREFIX.length) : column
+ if (IGNORED_COLUMNS.has(name)) {
+ return
+ }
+ if (name === 'breakdown_value') {
+ parsed.breakdownValue = String(row[index] ?? '')
+ return
+ }
+ const compared = toCompared(row[index])
+ if (compared) {
+ ;(parsed as unknown as Record<string, ComparedValue>)[name] = compared
+ }
+ })
+ return parsed
+ })
+}