: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(marketing-analytics): retention explorer tab (#86909)
Javier Bahamondes043738b812c0
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 0810700ae6f5..e7c5aba6f0c2 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -394,6 +394,7 @@ export const FEATURE_FLAGS = {MARKETING_ANALYTICS_MCP: 'marketing-analytics-mcp', // owner: @jabahamondes #team-web-analytics — gates MCP tool exposure (read-only marketing-analytics tools)MARKETING_ANALYTICS_MULTI_TOUCH_ATTRIBUTION: 'marketing-analytics-multi-touch-attribution', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_NEW_DASHBOARD: 'new-marketing-analytics-dashboard', // owner: @jabahamondes #team-web-analytics — gates the WIP redesigned dashboard tab+ MARKETING_ANALYTICS_RETENTION: 'marketing-analytics-retention', // owner: @jabahamondes #team-web-analytics — gates the Retention explorer tabMARKETING_ANALYTICS_RETURN_METRICS: 'marketing-analytics-return-metrics', // owner: @jabahamondes #team-web-analytics — gates the ROAS columnMARKETING_ANALYTICS_SETUP: 'marketing-analytics-setup', // owner: @jabahamondes #team-web-analytics — gates the Setup tab and its setup_plan / apply_setup_ops endpointsMARKETING_ANALYTICS_UTM_AUDIT: 'marketing-analytics-utm-audit', // owner: @jabahamondes #team-web-analyticsdiff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsxindex 32bbb2afd4fe..7b5e5cd04c6c 100644--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx@@ -15,6 +15,7 @@ import { urls } from 'scenes/urls'import { QueryTile } from 'scenes/web-analytics/common'import { AttributionTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab'import { NonIntegratedConversionsTable } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/NonIntegratedConversionsTable/NonIntegratedConversionsTable'+import { RetentionTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab'import { UtmAuditTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/UtmAuditTab/UtmAuditTab'import { WebQuery } from 'scenes/web-analytics/tiles/WebAnalyticsTile'@@ -255,6 +256,15 @@ const MarketingAnalyticsContent = (): JSX.Element => {},]: []),+ ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_RETENTION]+ ? [+ {+ key: MarketingAnalyticsTab.RETENTION,+ label: 'Retention explorer',+ content: <RetentionTab />,+ },+ ]+ : []),...(setupEnabled? [{ key: MarketingAnalyticsTab.SETUP, label: 'Setup', content: <SetupTab /> }]: featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_UTM_AUDIT]@@ -296,6 +306,8 @@ const TAB_DESCRIPTIONS: Record<string, string> = {'Analyze your marketing performance across integrations: spend, impressions, conversions, ROAS, and more metrics.',[MarketingAnalyticsTab.ATTRIBUTION]:'Compare how each attribution model credits your conversions, to see which marketing you might be over or under valuing.',+ [MarketingAnalyticsTab.RETENTION]:+ 'See how well the users each channel brings you stick around, grouped by the channel that first brought them in.',[MarketingAnalyticsTab.INTEGRATION_HEALTH]:'Check that your ad platform campaigns are properly linked to UTM tracking in PostHog.',[MarketingAnalyticsTab.SETUP]:diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab.tsxindex 8d5bde7cefa4..83d54e436bd1 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab.tsx@@ -14,11 +14,11 @@ import { MarketingAnalyticsAttributionBreakdown } from '~/queries/schema/schema-import { marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'import { marketingAnalyticsSettingsLogic } from '../../logic/marketingAnalyticsSettingsLogic'import {- BREAKDOWN_LABELS,MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID,marketingAttributionLogic,unattributedTooltip,} from '../../logic/marketingAttributionLogic'+import { BREAKDOWN_LABELS } from '../../logic/marketingBreakdown'import { AttributionTable } from './AttributionTable'import { ConversionPaths } from './ConversionPaths'diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.tsxindex bd0c44b986bd..9ed41d9dae54 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable.tsx@@ -22,11 +22,11 @@ import {import {ATTRIBUTION_ROW_LIMIT,- BREAKDOWN_LABELS,MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID,MODEL_LABELS,marketingAttributionLogic,} from '../../logic/marketingAttributionLogic'+import { BREAKDOWN_LABELS } from '../../logic/marketingBreakdown'import { AttributionChart } from './AttributionChart'const modelTooltip = (model: AttributionMode, windowDays: number): string => {diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPaths.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPaths.tsxindex ba2aeb8ff060..bef10d30e427 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPaths.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/ConversionPaths.tsx@@ -20,12 +20,12 @@ import {} from '~/queries/schema/schema-general'import {- BREAKDOWN_LABELS,MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID,PATHS_ROW_LIMIT,PathTouchpointFilter,marketingAttributionLogic,} from '../../logic/marketingAttributionLogic'+import { BREAKDOWN_LABELS } from '../../logic/marketingBreakdown'import { ConversionPathChips } from './ConversionPathChips'// The segmented control offers exact lengths up to this, then an open-ended "N+" bucket.diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionCohortTable.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionCohortTable.tsxnew file mode 100644index 000000000000..af6f7a4fb294--- /dev/null+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionCohortTable.tsx@@ -0,0 +1,234 @@+import { BuiltLogic, LogicWrapper, useActions, useValues } from 'kea'++import { LemonCollapse, LemonTable, LemonTableColumn, Tooltip } from '@posthog/lemon-ui'++import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'+import { gradateColor } from 'lib/utils/colors'+import { parseDateInTimezone } from 'lib/utils/datetime'+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'+import { InsightErrorState } from 'scenes/insights/EmptyStates'+import { teamLogic } from 'scenes/teamLogic'++import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import {+ MarketingAnalyticsRetentionInterval,+ MarketingAnalyticsRetentionQuery,+ MarketingAnalyticsRetentionQueryResponse,+ MarketingAnalyticsRetentionRow,+} from '~/queries/schema/schema-general'++import { BREAKDOWN_LABELS, displayBreakdownValue, isFoldedBreakdownValue } from '../../logic/marketingBreakdown'+import {+ MARKETING_ANALYTICS_RETENTION_COLLECTION_ID,+ marketingRetentionLogic,+} from '../../logic/marketingRetentionLogic'++const EXPANDED_BY_DEFAULT = 3++/** Same values as PostHog's retention table, so a rate reads as the same shade on both. */+const CELL_COLOR = '#1d4aff'+const CELL_COLOR_FLOOR = 0.1+/** Past this the background is dark enough that the theme's text fails WCAG AA. */+const CELL_TEXT_LIGHT_THRESHOLD = 0.4++/** In the team's timezone: a UTC cohort read from New York would be labelled with the previous day. */+const cohortLabel = (isoDate: string, interval: MarketingAnalyticsRetentionInterval, timezone: string): string => {+ const date = parseDateInTimezone(isoDate, timezone)+ switch (interval) {+ case MarketingAnalyticsRetentionInterval.Month:+ return date.format('MMM YYYY')+ case MarketingAnalyticsRetentionInterval.Week:+ return `${date.format('MMM D')} to ${date.add(6, 'day').format('MMM D')}`+ default:+ return date.format('ddd, MMM D')+ }+}++// Stable, because `useAttachedLogic` only detaches when the scene unmounts. An incrementing key leaves+// a fresh dataNodeLogic attached on every visit to the tab, and the filter bar's ReloadAll then re-runs+// each earlier visit's stale query on top of the live one.+const RETENTION_DATA_NODE_KEY = 'MarketingRetention'++export function RetentionCohortTable({+ query,+ attachTo,+}: {+ query: MarketingAnalyticsRetentionQuery+ attachTo?: LogicWrapper | BuiltLogic+}): JSX.Element {+ const logic = dataNodeLogic({+ query,+ key: RETENTION_DATA_NODE_KEY,+ dataNodeCollectionId: MARKETING_ANALYTICS_RETENTION_COLLECTION_ID,+ })+ const { response, responseLoading, responseError } = useValues(logic)+ const { loadData } = useActions(logic)+ const { breakdownBy } = useValues(marketingRetentionLogic)+ const { timezone } = useValues(teamLogic)+ useAttachedLogic(logic, attachTo)++ const retentionResponse = response as MarketingAnalyticsRetentionQueryResponse | undefined+ const rows = retentionResponse?.results ?? []+ const labels = retentionResponse?.labels ?? []+ const interval = retentionResponse?.interval ?? MarketingAnalyticsRetentionInterval.Week+ const dimensionLabel = BREAKDOWN_LABELS[breakdownBy]++ const caveats: string[] = []+ if (retentionResponse?.truncatedCohorts) {+ caveats.push(+ `The ${humanFriendlyNumber(retentionResponse.truncatedCohorts)} earliest periods in your date range aren't included. Narrow the range, or group by a longer period, to see them.`+ )+ }+ if (retentionResponse?.otherBreakdownCount) {+ caveats.push(+ `"Other" groups the smallest ${humanFriendlyNumber(retentionResponse.otherBreakdownCount)} values.`+ )+ }++ if (responseError) {+ return <InsightErrorState query={query} onRetry={loadData} />+ }++ const columns: LemonTableColumn<MarketingAnalyticsRetentionRow, any>[] = [+ {+ title: 'Cohort',+ dataIndex: 'cohortDate',+ render: (_, row) => cohortLabel(row.cohortDate, interval, timezone),+ },+ {+ title: 'Acquired',+ dataIndex: 'cohortSize',+ align: 'right',+ render: (_, row) => humanFriendlyNumber(row.cohortSize),+ },+ ...labels.map((label, index) => ({+ title: label,+ key: label,+ align: 'center' as const,+ render: (_: any, row: MarketingAnalyticsRetentionRow) => {+ const cell = row.values[index]+ if (!cell) {+ return null+ }+ if (!cell.complete) {+ return (+ <Tooltip title="This period hasn't finished yet, so there's nothing to measure.">+ <span className="text-muted">–</span>+ </Tooltip>+ )+ }+ return (+ <Tooltip title={`${humanFriendlyNumber(cell.count)} of ${humanFriendlyNumber(row.cohortSize)}`}>+ <div+ className="rounded px-2 py-1"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ backgroundColor: gradateColor(CELL_COLOR, cell.rate ?? 0, CELL_COLOR_FLOOR),+ color: (cell.rate ?? 0) > CELL_TEXT_LIGHT_THRESHOLD ? '#fff' : 'var(--text-3000)',+ }}+ >+ {cell.rate === null ? '–' : percentage(cell.rate, 1)}+ </div>+ </Tooltip>+ )+ },+ })),+ ]++ const byBreakdown = new Map<string, MarketingAnalyticsRetentionRow[]>()+ for (const row of rows) {+ byBreakdown.set(row.breakdownValue, [...(byBreakdown.get(row.breakdownValue) ?? []), row])+ }+ // "Other" is a sum of the tail, so ranking it by size floats it above real channels.+ const breakdownValues = [...byBreakdown.keys()].sort((a, b) => {+ if (isFoldedBreakdownValue(a) !== isFoldedBreakdownValue(b)) {+ return isFoldedBreakdownValue(a) ? 1 : -1+ }+ return totalAcquired(byBreakdown.get(b)) - totalAcquired(byBreakdown.get(a))+ })++ if (responseLoading || !breakdownValues.length) {+ return (+ <LemonTable+ columns={columns}+ dataSource={[]}+ loading={responseLoading}+ emptyState='No new users arrived in this period. Widen the date range, or turn off "Only new users" to include people who were already here.'+ />+ )+ }++ return (+ <div className="flex flex-col gap-4">+ {caveats.length > 0 && <div className="text-secondary text-xs">{caveats.join(' ')}</div>}+ <div>+ <div className="text-muted mb-1 text-xs font-semibold uppercase">+ All {dimensionLabel.toLowerCase()}s+ </div>+ <LemonTable columns={columns} dataSource={baselineRows(rows)} size="small" firstColumnSticky />+ </div>+ <LemonCollapse+ multiple+ defaultActiveKeys={breakdownValues.slice(0, EXPANDED_BY_DEFAULT)}+ panels={breakdownValues.map((value) => ({+ key: value,+ header: (+ <div className="flex items-center gap-2">+ <span className="font-semibold">{displayBreakdownValue(value, dimensionLabel)}</span>+ <span className="text-secondary text-xs">+ {humanFriendlyNumber(totalAcquired(byBreakdown.get(value)))} acquired+ </span>+ </div>+ ),+ content: (+ <LemonTable+ columns={columns}+ dataSource={byBreakdown.get(value) ?? []}+ loading={responseLoading}+ size="small"+ firstColumnSticky+ />+ ),+ }))}+ />+ </div>+ )+}++const totalAcquired = (rows: MarketingAnalyticsRetentionRow[] | undefined): number =>+ (rows ?? []).reduce((total, row) => total + row.cohortSize, 0)++/**+ * Rates are recomputed from the summed counts, because averaging per-channel rates would weight a+ * channel with ten people the same as one with ten thousand.+ */+export function baselineRows(rows: MarketingAnalyticsRetentionRow[]): MarketingAnalyticsRetentionRow[] {+ const byCohort = new Map<number, MarketingAnalyticsRetentionRow>()+ for (const row of rows) {+ const merged = byCohort.get(row.cohortIndex)+ if (!merged) {+ byCohort.set(row.cohortIndex, {+ ...row,+ breakdownValue: '',+ values: row.values.map((cell) => ({ ...cell })),+ })+ continue+ }+ merged.cohortSize += row.cohortSize+ row.values.forEach((cell, index) => {+ const into = merged.values[index]+ if (into) {+ into.count += cell.count+ }+ })+ }+ return [...byCohort.values()]+ .sort((a, b) => a.cohortIndex - b.cohortIndex)+ .map((row) => ({+ ...row,+ values: row.values.map((cell) => ({+ ...cell,+ rate: row.cohortSize ? cell.count / row.cohortSize : null,+ })),+ }))+}diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab.tsxnew file mode 100644index 000000000000..f05d5ab9e293--- /dev/null+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab.tsx@@ -0,0 +1,160 @@+import { BindLogic, useActions, useValues } from 'kea'++import { IconGear } from '@posthog/icons'+import { LemonButton, LemonDivider, LemonSelect, LemonSwitch, Popover } from '@posthog/lemon-ui'++import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { FilterBar } from 'lib/components/FilterBar'++import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'+import { ReloadAll } from '~/queries/nodes/DataNode/Reload'+import {+ MarketingAnalyticsAttributionBreakdown,+ MarketingAnalyticsRetentionInterval,+} from '~/queries/schema/schema-general'++import { marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'+import { BREAKDOWN_LABELS } from '../../logic/marketingBreakdown'+import {+ MARKETING_ANALYTICS_RETENTION_COLLECTION_ID,+ RETENTION_INTERVAL_LABELS,+ marketingRetentionLogic,+} from '../../logic/marketingRetentionLogic'+import { RetentionCohortTable } from './RetentionCohortTable'++const COLUMN_COUNT_OPTIONS = [4, 6, 8, 12, 16, 24]++export function RetentionTab(): JSX.Element {+ const {+ breakdownBy,+ retentionInterval,+ totalIntervals,+ excludeDirectTraffic,+ excludeUnattributed,+ onlyNewUsers,+ optionsOpen,+ query,+ } = useValues(marketingRetentionLogic)+ const {+ setBreakdownBy,+ setRetentionInterval,+ setTotalIntervals,+ setExcludeDirectTraffic,+ setExcludeUnattributed,+ setOnlyNewUsers,+ setOptionsOpen,+ } = useActions(marketingRetentionLogic)+ const { dateFilter } = useValues(marketingAnalyticsLogic)+ const { setDates } = useActions(marketingAnalyticsLogic)++ const optionsContent = (+ <div className="flex w-80 max-w-[90vw] flex-col gap-4 p-3">+ <div>+ <div className="text-muted mb-2 text-xs font-semibold uppercase">Acquisition period</div>+ <DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />+ <div className="text-muted mt-1 text-xs">+ People who arrived in this period become the cohorts. Each cohort is then followed forward.+ </div>+ </div>+ <div>+ <div className="text-muted mb-2 text-xs font-semibold uppercase">Period length</div>+ <LemonSelect+ fullWidth+ value={retentionInterval}+ onChange={(value) => value && setRetentionInterval(value)}+ options={Object.values(MarketingAnalyticsRetentionInterval).map((value) => ({+ value,+ label: RETENTION_INTERVAL_LABELS[value],+ }))}+ />+ </div>+ <div>+ <div className="text-muted mb-2 text-xs font-semibold uppercase">Periods to follow</div>+ <LemonSelect+ fullWidth+ value={totalIntervals}+ onChange={(value) => value && setTotalIntervals(value)}+ options={COLUMN_COUNT_OPTIONS.map((count) => ({ value: count, label: `${count} periods` }))}+ />+ </div>+ <LemonDivider className="my-0" />+ <LemonSwitch+ fullWidth+ checked={onlyNewUsers}+ onChange={setOnlyNewUsers}+ label="Only new users"+ tooltip="Skip people who had already visited before this period started. Leave it on unless you want a channel's own returning traffic counted as newly acquired."+ data-attr="marketing-retention-only-new-users"+ />+ <LemonSwitch+ fullWidth+ checked={excludeDirectTraffic}+ onChange={setExcludeDirectTraffic}+ label="Exclude direct traffic"+ tooltip="Direct sessions stop counting when working out where someone came from, so a person's first non-direct session decides their cohort."+ data-attr="marketing-retention-exclude-direct"+ />+ <LemonSwitch+ fullWidth+ checked={excludeUnattributed}+ onChange={setExcludeUnattributed}+ label="Exclude unattributed traffic"+ tooltip={`People whose first session has no ${BREAKDOWN_LABELS[+ breakdownBy+ ].toLowerCase()} are left out of the table entirely.`}+ data-attr="marketing-retention-exclude-unattributed"+ />+ </div>+ )++ return (+ // Shadows the scene-level binding on purpose. See MARKETING_ANALYTICS_RETENTION_COLLECTION_ID.+ <BindLogic logic={dataNodeCollectionLogic} props={{ key: MARKETING_ANALYTICS_RETENTION_COLLECTION_ID }}>+ <div className="flex flex-col">+ <FilterBar+ showBorderBottom+ left={+ <div className="flex flex-wrap items-center gap-4">+ <div className="flex items-center gap-2">+ <span className="text-secondary">Acquired by</span>+ <LemonSelect+ size="small"+ value={breakdownBy}+ onChange={(value) => value && setBreakdownBy(value)}+ options={Object.values(MarketingAnalyticsAttributionBreakdown).map((level) => ({+ value: level,+ label: BREAKDOWN_LABELS[level],+ }))}+ />+ </div>+ </div>+ }+ right={+ <div className="flex items-center gap-2">+ <ReloadAll iconOnly />+ <Popover+ visible={optionsOpen}+ onClickOutside={() => setOptionsOpen(false)}+ placement="bottom-end"+ overlay={optionsContent}+ >+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconGear />}+ onClick={() => setOptionsOpen(!optionsOpen)}+ data-attr="marketing-retention-options"+ >+ Options+ </LemonButton>+ </Popover>+ </div>+ }+ />+ <div className="mt-4 flex flex-col gap-4 pb-8">+ <RetentionCohortTable query={query} attachTo={marketingAnalyticsLogic} />+ </div>+ </div>+ </BindLogic>+ )+}diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/baselineRows.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/baselineRows.test.tsnew file mode 100644index 000000000000..9af60e3179ce--- /dev/null+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/baselineRows.test.ts@@ -0,0 +1,54 @@+import { MarketingAnalyticsRetentionRow } from '~/queries/schema/schema-general'++import { baselineRows } from './RetentionCohortTable'++const row = (+ breakdownValue: string,+ cohortIndex: number,+ cohortSize: number,+ counts: number[]+): MarketingAnalyticsRetentionRow => ({+ breakdownValue,+ cohortDate: '2023-01-04T00:00:00Z',+ cohortIndex,+ cohortSize,+ values: counts.map((count) => ({ count, rate: count / cohortSize, complete: true })),+})++describe('baselineRows', () => {+ it('weights the combined rate by cohort size instead of averaging the channels', () => {+ // A channel with 10 people retaining 100% and one with 1000 retaining 10% is a 10.9% baseline,+ // not the 55% an average of the two rates would report.+ const combined = baselineRows([row('small', 0, 10, [10]), row('big', 0, 1000, [100])])++ expect(combined).toHaveLength(1)+ expect(combined[0].cohortSize).toBe(1010)+ expect(combined[0].values[0].count).toBe(110)+ expect(combined[0].values[0].rate).toBeCloseTo(110 / 1010)+ })++ it('keeps cohorts apart while merging the channels within each one', () => {+ const combined = baselineRows([+ row('google', 0, 5, [5, 2]),+ row('bing', 0, 5, [5, 4]),+ row('google', 1, 8, [8, 1]),+ ])++ expect(combined.map((r) => [r.cohortIndex, r.cohortSize])).toEqual([+ [0, 10],+ [1, 8],+ ])+ expect(combined[0].values[1].count).toBe(6)+ })++ it('does not mutate the rows it was handed', () => {+ // The same array backs the per-channel tables rendered next to the baseline, so merging in+ // place would silently double the counts they show.+ const source = [row('google', 0, 5, [5, 2]), row('bing', 0, 5, [5, 4])]++ baselineRows(source)++ expect(source[0].cohortSize).toBe(5)+ expect(source[0].values[1].count).toBe(2)+ })+})diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.tsindex 6c697353e616..bd4f2b1bd6c7 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts@@ -69,6 +69,7 @@ export type NativeSourceHierarchyStatus = {export enum MarketingAnalyticsTab {DASHBOARD = 'dashboard',ATTRIBUTION = 'attribution',+ RETENTION = 'retention',// Still the tab key when Setup's flag is off, which is everywhere until it rolls// out. Removing it would change the URL and the header copy for every user of the// audit — which is fully rolled out — for no gain.diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.tsindex 98c253a01f09..e2c948159d0d 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic.ts@@ -12,6 +12,7 @@ import { BaseMathType, IntervalType } from '~/types'import { marketingAnalyticsLogic } from './marketingAnalyticsLogic'import { marketingAnalyticsSettingsLogic } from './marketingAnalyticsSettingsLogic'+import { BREAKDOWN_LABELS, attributableConversionGoals } from './marketingBreakdown'/** Rows the table asks for. Sorting happens client side over this page, so it's also the sort scope. */export const ATTRIBUTION_ROW_LIMIT = 100@@ -28,17 +29,6 @@ export const MARKETING_ANALYTICS_ATTRIBUTION_COLLECTION_ID = 'marketing-analytic/** The conversion paths length filter: an exact touchpoint count, "4 or more", or null for any. */export type PathTouchpointFilter = number | 'four_plus' | null-export const BREAKDOWN_LABELS: Record<MarketingAnalyticsAttributionBreakdown, string> = {- [MarketingAnalyticsAttributionBreakdown.Channel]: 'Channel',- [MarketingAnalyticsAttributionBreakdown.Source]: 'Source',- [MarketingAnalyticsAttributionBreakdown.Campaign]: 'Campaign',- [MarketingAnalyticsAttributionBreakdown.Medium]: 'Medium',- [MarketingAnalyticsAttributionBreakdown.Content]: 'Content',- [MarketingAnalyticsAttributionBreakdown.Term]: 'Term',- [MarketingAnalyticsAttributionBreakdown.ReferringDomain]: 'Referring domain',- [MarketingAnalyticsAttributionBreakdown.LandingPage]: 'Landing page',-}-/*** How the row that "Exclude unattributed traffic" removes is labelled — only where that label is* knowable from here. Most breakdowns leave the value empty and render as "(none)"; channel and@@ -236,10 +226,11 @@ export const marketingAttributionLogic = kea<marketingAttributionLogicType>([selectors({attributableGoals: [(s) => [s.conversion_goals],- // Data warehouse goals are excluded: their conversions live in a warehouse table keyed by- // distinct id, so the events-based touchpoint query has nothing to join them on.+ // Annotated rather than passing `attributableConversionGoals` straight through: typegen+ // cannot infer a bare imported function's return, and silently drops the selector from the+ // generated values when it can't.(conversion_goals: ConversionGoalFilter[]): ConversionGoalFilter[] =>- (conversion_goals || []).filter((goal) => goal.kind !== NodeKind.DataWarehouseNode),+ attributableConversionGoals(conversion_goals),],selectedGoalId: [(s) => [s.conversionGoalId, s.attributableGoals],diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.test.tsnew file mode 100644index 000000000000..098b06177f25--- /dev/null+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.test.ts@@ -0,0 +1,19 @@+import { BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'++import { displayBreakdownValue } from './marketingBreakdown'++describe('marketingBreakdown', () => {+ it('names the folded row instead of printing the sentinel the backend folds into', () => {+ // The backend rolls the long tail into a sentinel string. Rendering it raw puts+ // "$$_posthog_breakdown_other_$$" in the table while the caveat text below talks about "Other".+ expect(displayBreakdownValue(BREAKDOWN_OTHER_STRING_LABEL, 'Channel')).toBe('Other')+ })++ it('names the dimension when a session carried no value for it', () => {+ expect(displayBreakdownValue('', 'Referring domain')).toBe('(no referring domain)')+ })++ it('passes a real value through untouched', () => {+ expect(displayBreakdownValue('google', 'Source')).toBe('google')+ })+})diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.tsnew file mode 100644index 000000000000..97e3e9e1fd07--- /dev/null+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.ts@@ -0,0 +1,29 @@+import { BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'++import { ConversionGoalFilter, MarketingAnalyticsAttributionBreakdown, NodeKind } from '~/queries/schema/schema-general'++export const BREAKDOWN_LABELS: Record<MarketingAnalyticsAttributionBreakdown, string> = {+ [MarketingAnalyticsAttributionBreakdown.Channel]: 'Channel',+ [MarketingAnalyticsAttributionBreakdown.Source]: 'Source',+ [MarketingAnalyticsAttributionBreakdown.Campaign]: 'Campaign',+ [MarketingAnalyticsAttributionBreakdown.Medium]: 'Medium',+ [MarketingAnalyticsAttributionBreakdown.Content]: 'Content',+ [MarketingAnalyticsAttributionBreakdown.Term]: 'Term',+ [MarketingAnalyticsAttributionBreakdown.ReferringDomain]: 'Referring domain',+ [MarketingAnalyticsAttributionBreakdown.LandingPage]: 'Landing page',+}++/** True for the row the backend folds the long tail of breakdown values into. */+export const isFoldedBreakdownValue = (value: string): boolean => value === BREAKDOWN_OTHER_STRING_LABEL++/** Neither the folded sentinel nor an empty value is something to show a marketer raw. */+export const displayBreakdownValue = (value: string, dimensionLabel: string): string => {+ if (isFoldedBreakdownValue(value)) {+ return 'Other'+ }+ return value || `(no ${dimensionLabel.toLowerCase()})`+}++/** Warehouse goals are keyed by distinct id, so the events-based session queries can't join them. */+export const attributableConversionGoals = (conversionGoals: ConversionGoalFilter[]): ConversionGoalFilter[] =>+ (conversionGoals || []).filter((goal) => goal.kind !== NodeKind.DataWarehouseNode)diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingRetentionLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingRetentionLogic.tsnew file mode 100644index 000000000000..3bdb0cd97f51--- /dev/null+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingRetentionLogic.ts@@ -0,0 +1,163 @@+import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'++import {+ MarketingAnalyticsAttributionBreakdown,+ MarketingAnalyticsRetentionInterval,+ MarketingAnalyticsRetentionQuery,+ NodeKind,+} from '~/queries/schema/schema-general'+import { IntervalType } from '~/types'++import { marketingAnalyticsLogic } from './marketingAnalyticsLogic'++/** Keeps the tab's refresh button off the dashboard tiles, which sit in the scene-level collection. */+export const MARKETING_ANALYTICS_RETENTION_COLLECTION_ID = 'marketing-analytics-retention'++export const DEFAULT_TOTAL_INTERVALS: number = 8++export const RETENTION_INTERVAL_LABELS: Record<MarketingAnalyticsRetentionInterval, string> = {+ [MarketingAnalyticsRetentionInterval.Day]: 'Daily',+ [MarketingAnalyticsRetentionInterval.Week]: 'Weekly',+ [MarketingAnalyticsRetentionInterval.Month]: 'Monthly',+}++interface DateFilter {+ dateFrom: string | null+ dateTo: string | null+ interval: IntervalType+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface marketingRetentionLogicValues {+ dateFilter: {+ dateFrom: string | null+ dateTo: string | null+ interval: IntervalType+ } // marketingAnalyticsLogic+ breakdownBy: MarketingAnalyticsAttributionBreakdown+ excludeDirectTraffic: boolean+ excludeUnattributed: boolean+ onlyNewUsers: boolean+ optionsOpen: boolean+ query: MarketingAnalyticsRetentionQuery+ retentionInterval: MarketingAnalyticsRetentionInterval+ totalIntervals: number+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface marketingRetentionLogicActions {+ setBreakdownBy: (breakdownBy: MarketingAnalyticsAttributionBreakdown) => {+ breakdownBy: MarketingAnalyticsAttributionBreakdown+ }+ setExcludeDirectTraffic: (excludeDirectTraffic: boolean) => {+ excludeDirectTraffic: boolean+ }+ setExcludeUnattributed: (excludeUnattributed: boolean) => {+ excludeUnattributed: boolean+ }+ setOnlyNewUsers: (onlyNewUsers: boolean) => {+ onlyNewUsers: boolean+ }+ setOptionsOpen: (optionsOpen: boolean) => {+ optionsOpen: boolean+ }+ setRetentionInterval: (retentionInterval: MarketingAnalyticsRetentionInterval) => {+ retentionInterval: MarketingAnalyticsRetentionInterval+ }+ setTotalIntervals: (totalIntervals: number) => {+ totalIntervals: number+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface marketingRetentionLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ query: (+ breakdownBy: MarketingAnalyticsAttributionBreakdown,+ retentionInterval: MarketingAnalyticsRetentionInterval,+ totalIntervals: number,+ excludeDirectTraffic: boolean,+ excludeUnattributed: boolean,+ onlyNewUsers: boolean,+ dateFilter: {+ dateFrom: string | null+ dateTo: string | null+ interval: IntervalType+ }+ ) => MarketingAnalyticsRetentionQuery+ }+}++export type marketingRetentionLogicType = MakeLogicType<+ marketingRetentionLogicValues,+ marketingRetentionLogicActions,+ Record<string, any>,+ marketingRetentionLogicMeta+>++export const marketingRetentionLogic = kea<marketingRetentionLogicType>([+ path(['scenes', 'webAnalytics', 'marketingRetentionLogic']),+ connect(() => ({+ values: [marketingAnalyticsLogic, ['dateFilter']],+ })),+ actions({+ setBreakdownBy: (breakdownBy: MarketingAnalyticsAttributionBreakdown) => ({ breakdownBy }),+ setRetentionInterval: (retentionInterval: MarketingAnalyticsRetentionInterval) => ({ retentionInterval }),+ setTotalIntervals: (totalIntervals: number) => ({ totalIntervals }),+ setExcludeDirectTraffic: (excludeDirectTraffic: boolean) => ({ excludeDirectTraffic }),+ setExcludeUnattributed: (excludeUnattributed: boolean) => ({ excludeUnattributed }),+ setOnlyNewUsers: (onlyNewUsers: boolean) => ({ onlyNewUsers }),+ setOptionsOpen: (optionsOpen: boolean) => ({ optionsOpen }),+ }),+ reducers({+ breakdownBy: [+ MarketingAnalyticsAttributionBreakdown.Channel as MarketingAnalyticsAttributionBreakdown,+ { setBreakdownBy: (_, { breakdownBy }) => breakdownBy },+ ],+ retentionInterval: [+ MarketingAnalyticsRetentionInterval.Week as MarketingAnalyticsRetentionInterval,+ { setRetentionInterval: (_, { retentionInterval }) => retentionInterval },+ ],+ totalIntervals: [DEFAULT_TOTAL_INTERVALS, { setTotalIntervals: (_, { totalIntervals }) => totalIntervals }],+ excludeDirectTraffic: [+ false,+ { setExcludeDirectTraffic: (_, { excludeDirectTraffic }) => excludeDirectTraffic },+ ],+ excludeUnattributed: [false, { setExcludeUnattributed: (_, { excludeUnattributed }) => excludeUnattributed }],+ // Defaults on: without it a channel's cohorts are inflated by the users it acquired long ago.+ onlyNewUsers: [true, { setOnlyNewUsers: (_, { onlyNewUsers }) => onlyNewUsers }],+ optionsOpen: [false, { setOptionsOpen: (_, { optionsOpen }) => optionsOpen }],+ }),+ selectors({+ query: [+ (s) => [+ s.breakdownBy,+ s.retentionInterval,+ s.totalIntervals,+ s.excludeDirectTraffic,+ s.excludeUnattributed,+ s.onlyNewUsers,+ s.dateFilter,+ ],+ (+ breakdownBy: MarketingAnalyticsAttributionBreakdown,+ retentionInterval: MarketingAnalyticsRetentionInterval,+ totalIntervals: number,+ excludeDirectTraffic: boolean,+ excludeUnattributed: boolean,+ onlyNewUsers: boolean,+ dateFilter: DateFilter+ ): MarketingAnalyticsRetentionQuery => ({+ kind: NodeKind.MarketingAnalyticsRetentionQuery,+ dateRange: { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo },+ breakdownBy,+ retentionInterval,+ totalIntervals,+ excludeDirectTraffic,+ excludeUnattributed,+ onlyNewUsers,+ properties: [],+ }),+ ],+ }),+])