: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): add interactive ad performance sparklines (#120441)
Javier Bahamondes653769f607e4
diff --git a/docs/internal/marketing-source-suggestions.md b/docs/internal/marketing-source-suggestions.mdindex 313002bba4d9..4e7055a25e2f 100644--- a/docs/internal/marketing-source-suggestions.md+++ b/docs/internal/marketing-source-suggestions.md@@ -301,3 +301,13 @@ With source onboarding disabled, the existing banner remains available.The Ad performance summary uses the same metric cards as Web analytics.Cards preserve period comparisons, currency formatting, and missing-value labels, and wrap to the available scene width.++Ad performance cards include time-series sparklines for advertising metrics, including platform-reported conversions.+Select an advertising metric card to update the existing trend chart while keeping the date range, interval, and source filters.+CPC, CTR, reported ROAS, and cost per reported conversion use ratios of bucket totals in both sparklines and the main trend, with monetary values converted to the project currency; undefined ratios leave gaps rather than zeroes.+Attributed PostHog conversion goals retain their summary cards without sparklines or selection.++Advertising metrics appear first, followed by attributed conversion goals and their cost per conversion.+The goal cards use a separate grid so cards without sparklines keep a compact height.++The overview loads on demand so other query surfaces do not load marketing-specific validation eagerly.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 538e58dd863d..6dc9393f78f2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6036,6 +6036,10 @@ snapshots:hash: v1.k794b7964.f9059da612f8cb309c1100982a7352bf0c010c585701ed9f703ed1962da1a8b2.4Wbe0lwcRKZju4mbcJDVTwzvT2DtSSqF1VwdFStAA5ologs-logsretentionperiodpicker--stored-custom-months-without-paid-retention--light:hash: v1.k794b7964.d8d79824779beb9150246c932e4f2b756133d02aca4ca269271b98d0e9082480.PCD7I0jw8Fis5NRmUgRrjvUpwz5Dap-BO1UKMSJu5Ns+ marketing-analytics-ad-performance-metric-trends--with-trends--dark:+ hash: v1.k794b7964.9a2823d7597aac44d396018c51abba4545f3079ea859dc75855cb064add75317.2DtYQx5epqWzQwQS5oFiY-QYBMVzZoDVZZbr7SPYrsk+ marketing-analytics-ad-performance-metric-trends--with-trends--light:+ hash: v1.k794b7964.2f4ccaa52f1dac23d7792a6c737b167c3327c76418e35ae15289353f90d3010d.fL2tqTuwK5Zjhq1FOUJkaXAnBHs6qKnexB-SWPfu7rMmarketing-analytics-add-source--dismissed-everywhere--dark:hash: v1.k794b7964.f23fe271dbeafe8d745237090a5a115e167653cdb000e74a3245efd986450ff0.ymRCgme2xTcwSDlK8Mjxj_zM6bDHbYjLGl0ncGYQfuomarketing-analytics-add-source--dismissed-everywhere--light:diff --git a/frontend/src/queries/Query/Query.tsx b/frontend/src/queries/Query/Query.tsxindex 73cc8cf9c1c5..1204363b398f 100644--- a/frontend/src/queries/Query/Query.tsx+++ b/frontend/src/queries/Query/Query.tsx@@ -5,7 +5,6 @@ import { LemonDivider } from 'lib/lemon-ui/LemonDivider'import { Spinner } from 'lib/lemon-ui/Spinner'import { lazyWithRetry } from 'lib/utils/retryImport'import { HogDebug } from 'scenes/debug/HogDebug'-import { MarketingAnalyticsOverview } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview'import { ErrorBoundary } from '~/layout/ErrorBoundary'import { DataNode } from '~/queries/nodes/DataNode/DataNode'@@ -46,6 +45,11 @@ import {isWebVitalsQuery,} from '../utils'+const MarketingAnalyticsOverview = lazyWithRetry(() =>+ import('scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview').then(+ (m) => ({ default: m.MarketingAnalyticsOverview })+ )+)const WebVitals = lazyWithRetry(() =>import('~/queries/nodes/WebVitals/WebVitals').then((m) => ({ default: m.WebVitals })))@@ -236,13 +240,15 @@ export function Query<Q extends Node>(props: QueryProps<Q>): JSX.Element | null)} else if (isMarketingAnalyticsAggregatedQuery(query)) {component = (- <MarketingAnalyticsOverview- attachTo={props.attachTo}- query={query}- cachedResults={props.cachedResults}- context={queryContext}- uniqueKey={uniqueKey}- />+ <Suspense fallback={<Spinner />}>+ <MarketingAnalyticsOverview+ attachTo={props.attachTo}+ query={query}+ cachedResults={props.cachedResults}+ context={queryContext}+ uniqueKey={uniqueKey}+ />+ </Suspense>)} else if (isWebVitalsQuery(query)) {component = (diff --git a/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx b/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsxindex 44babf760123..d713ba9284b4 100644--- a/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx+++ b/frontend/src/queries/nodes/OverviewGrid/OverviewMetricCardGrid.tsx@@ -3,10 +3,11 @@ import type React from 'react'import { IconWarning } from '@posthog/icons'import { Link } from '@posthog/lemon-ui'-import { type MetricChange } from '@posthog/quill-charts'+import { type ChartTheme, type MetricChange } from '@posthog/quill-charts'import { AnalyticsMetricCard } from 'lib/components/AnalyticsMetricCard/AnalyticsMetricCard'import { PreAggregatedBadge } from 'lib/components/PreAggregatedBadge'+import { dayjs } from 'lib/dayjs'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { range } from 'lib/utils/arrays'import { cn } from 'lib/utils/css-classes'@@ -16,7 +17,7 @@ import { WebAnalyticsPreComputeStrategy } from '~/queries/schema/schema-general'import { formatItem, NO_BASELINE_CHANGE_SENTINEL, OverviewItem, SamplingNotice, SamplingRate } from './OverviewGrid'-export type OverviewMetricCardItem = OverviewItem+export type OverviewMetricCardItem = OverviewItem & { sparkline?: { data: number[]; labels: string[] } }interface OverviewMetricCardGridProps {items: OverviewMetricCardItem[]@@ -25,6 +26,7 @@ interface OverviewMetricCardGridProps {numSkeletons: numberemptyMessage?: React.ReactNodeclassName?: string+ sparklineTheme?: ChartThemesamplingRate?: SamplingRatepreComputeStrategy?: WebAnalyticsPreComputeStrategyonDisablePrecompute?: () => void@@ -38,6 +40,7 @@ export function OverviewMetricCardGrid({numSkeletons,emptyMessage,className,+ sparklineTheme,samplingRate,preComputeStrategy,onDisablePrecompute,@@ -57,6 +60,7 @@ export function OverviewMetricCardGrid({<MetricCardCellkey={item.key}item={item}+ sparklineTheme={sparklineTheme}emptyMessage={emptyMessage}stretch={layout === 'contents'}preComputeStrategy={preComputeStrategy}@@ -72,6 +76,7 @@ export function OverviewMetricCardGrid({function MetricCardCell({item,+ sparklineTheme,emptyMessage,stretch,preComputeStrategy,@@ -79,6 +84,7 @@ function MetricCardCell({labelFromKey,}: {item: OverviewMetricCardItem+ sparklineTheme?: ChartThemeemptyMessage?: React.ReactNodestretch?: booleanpreComputeStrategy?: WebAnalyticsPreComputeStrategy@@ -105,7 +111,14 @@ function MetricCardCell({formatValue={(value) =>formatItem(typeof item.value === 'number' ? value : item.value, item.kind, { currency: baseCurrency })}- subtitle={subtitle}+ subtitle={item.sparkline && sparklineTheme ? undefined : subtitle}+ restingSubtitle={subtitle}+ data={sparklineTheme ? item.sparkline?.data : undefined}+ labels={item.sparkline?.labels}+ theme={sparklineTheme}+ formatLabel={(label) => dayjs(label).format('MMM D')}+ sparklineHeight={48}+ sparklineClassName="mt-3"adornment={preComputeStrategy === WebAnalyticsPreComputeStrategy.LazyPrecompute ? (<PreAggregatedBadge variant="precomputed" position="bottom-right" onDisable={onDisablePrecompute} />diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.test.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.test.tsxnew file mode 100644index 000000000000..02965d88f016--- /dev/null+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.test.tsx@@ -0,0 +1,48 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'+import { marketingAnalyticsTilesLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'++import { Query } from '~/queries/Query/Query'+import { InsightVizNode, MarketingAnalyticsAggregatedQueryResponse, NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++const response: MarketingAnalyticsAggregatedQueryResponse = {+ results: {+ Cost: { key: 'Cost', value: 100, kind: 'currency' },+ Clicks: { key: 'Clicks', value: 50, kind: 'unit' },+ CPC: { key: 'CPC', value: 2, kind: 'currency' },+ CTR: { key: 'CTR', value: 5, kind: 'percentage' },+ 'Trial started': { key: 'Trial started', value: 10, kind: 'unit' },+ },+}++describe('Ad performance metric selection', () => {+ beforeEach(() => initKeaTests())+ afterEach(cleanup)++ it.each([+ ['Clicks', 'clicks'],+ ['CPC', 'cpc'],+ ['CTR', 'ctr'],+ ])('selecting %s updates the existing trend without changing the filters', async (label, metric) => {+ render(+ <Query+ query={{ kind: NodeKind.MarketingAnalyticsAggregatedQuery, properties: [] }}+ cachedResults={response}+ context={{}}+ uniqueKey="metric-selection"+ />+ )+ const button = (await screen.findByText(label)).closest('button')!+ const before = (marketingAnalyticsTilesLogic.values.marketingChartTile.query as InsightVizNode).source+ fireEvent.click(button)+ expect(marketingAnalyticsLogic.values.tileColumnSelection).toBe(metric)+ expect(button.getAttribute('aria-pressed')).toBe('true')+ expect(marketingAnalyticsTilesLogic.values.marketingChartTile.title).toBe(`Marketing ${metric}`)+ expect(+ (marketingAnalyticsTilesLogic.values.marketingChartTile.query as InsightVizNode).source.dateRange+ ).toEqual(before.dateRange)+ expect(screen.getByText('Trial Started').closest('button')).toBeNull()+ })+})diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.tsxindex 584cf61d7ada..1865ec87c4e0 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview.tsx@@ -1,6 +1,7 @@-import { BuiltLogic, LogicWrapper, useValues } from 'kea'+import { BuiltLogic, LogicWrapper, useActions, useValues } from 'kea'import { useMemo, useState } from 'react'+import { useChartTheme } from 'lib/charts/hooks'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { InsightErrorState } from 'scenes/insights/EmptyStates'@@ -14,7 +15,15 @@ import {import { QueryContext } from '~/queries/types'import { MarketingAnalyticsNotReady } from '~/scenes/marketing-analytics/MarketingAnalyticsNotReady'+import { adPerformanceMetricKey } from 'products/marketing_analytics/frontend/adPerformanceMetrics'+import { adPerformanceTrendsLogic } from 'products/marketing_analytics/frontend/adPerformanceTrendsLogic'++import { marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'import { marketingAnalyticsSettingsLogic } from '../../logic/marketingAnalyticsSettingsLogic'+import {+ MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID,+ marketingAnalyticsTilesLogic,+} from '../../logic/marketingAnalyticsTilesLogic'import {MarketingAnalyticsValidationWarningBanner,validateConversionGoals,@@ -48,19 +57,36 @@ export function MarketingAnalyticsOverview(props: {const marketingOverviewQueryResponse = response as MarketingAnalyticsAggregatedQueryResponse | undefined+ const { createAdPerformanceSparklineQuery } = useValues(marketingAnalyticsTilesLogic)+ const { tileColumnSelection } = useValues(marketingAnalyticsLogic)+ const { setTileColumnSelection } = useActions(marketingAnalyticsLogic)+ const { sparklines } = useValues(+ adPerformanceTrendsLogic({+ query: createAdPerformanceSparklineQuery(props.query),+ queryKey: `${key}-sparklines`,+ dataNodeCollectionId: dataNodeCollectionId ?? MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID,+ })+ )+ const sparklineTheme = useChartTheme()const samplingRate = marketingOverviewQueryResponse?.samplingRateconst validationWarnings = useMemo(() => validateConversionGoals(conversion_goals), [conversion_goals])const overviewItems: OverviewMetricCardItem[] = marketingOverviewQueryResponse?.results- ? Object.entries(marketingOverviewQueryResponse.results).map(([key, item]) => ({- key,- value: item.value,- previous: item.previous,- changeFromPreviousPct: item.changeFromPreviousPct,- kind: item.kind,- isIncreaseBad: item.isIncreaseBad,- }))+ ? Object.entries(marketingOverviewQueryResponse.results).map(([key, item]) => {+ const metric = adPerformanceMetricKey(key)+ return {+ key,+ value: item.value,+ previous: item.previous,+ changeFromPreviousPct: item.changeFromPreviousPct,+ kind: item.kind,+ isIncreaseBad: item.isIncreaseBad,+ selected: metric ? tileColumnSelection === metric : undefined,+ onClick: metric ? () => setTileColumnSelection(metric) : undefined,+ sparkline: metric && typeof item.value === 'number' ? sparklines[metric] : undefined,+ }+ }): []// Calculate number of skeletons based on expected metrics@@ -87,15 +113,28 @@ export function MarketingAnalyticsOverview(props: {return (<>{allWarnings.length > 0 && <MarketingAnalyticsValidationWarningBanner warnings={allWarnings} />}- <OverviewMetricCardGrid- className="grid-cols-[repeat(auto-fit,minmax(12rem,1fr))]"- items={overviewItems.filter(filterEmptyMetrics)}- loading={responseLoading}- numSkeletons={numSkeletons}- emptyMessage="-"- samplingRate={samplingRate}- labelFromKey={(key) => <span className="[overflow-wrap:anywhere]">{labelFromKey(key)}</span>}- />+ <div className="flex flex-col gap-2">+ {[+ overviewItems.filter((item) => adPerformanceMetricKey(item.key)),+ overviewItems.filter((item) => !adPerformanceMetricKey(item.key)),+ ].map((items, index) =>+ (responseLoading && index === 0) || (!responseLoading && items.length > 0) ? (+ <OverviewMetricCardGrid+ key={index}+ sparklineTheme={sparklineTheme}+ className="grid-cols-[repeat(auto-fit,minmax(12rem,1fr))]"+ items={items.filter(filterEmptyMetrics)}+ loading={responseLoading}+ numSkeletons={numSkeletons}+ emptyMessage="-"+ samplingRate={index === 0 ? samplingRate : undefined}+ labelFromKey={(key) => (+ <span className="[overflow-wrap:anywhere]">{labelFromKey(key)}</span>+ )}+ />+ ) : null+ )}+ </div></>)}diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/__snapshots__/utils.test.ts.snap b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/__snapshots__/utils.test.ts.snapindex 9fca5db009e9..bf7887d26f3b 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/__snapshots__/utils.test.ts.snap+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/__snapshots__/utils.test.ts.snap@@ -398,7 +398,7 @@ exports[`marketing analytics utils createMarketingTile snapshots BingAds - roas"id_field": "campaign_id","kind": "DataWarehouseNode","math": "hogql",- "math_hogql": "SUM(ifNull(toFloat(revenue), 0)) / nullIf(SUM(ifNull(toFloat(spend), 0)), 0)",+ "math_hogql": "SUM(toFloat(convertCurrency(coalesce(currency_code, 'USD'), 'USD', ifNull(toFloat(revenue), 0)))) / nullIf(SUM(toFloat(convertCurrency(coalesce(currency_code, 'USD'), 'USD', ifNull(toFloat(spend), 0)))), 0)","name": "bing","table_name": "prefix.campaign_performance_report","timestamp_field": "time_period",@@ -533,7 +533,7 @@ exports[`marketing analytics utils createMarketingTile snapshots GoogleAds - roa"id_field": "campaign_id","kind": "DataWarehouseNode","math": "hogql",- "math_hogql": "SUM(ifNull(toFloat(metrics_conversions_value), 0)) / nullIf(SUM(ifNull(toFloat(metrics_cost_micros), 0) / 1000000), 0)",+ "math_hogql": "SUM(toFloat(convertCurrency(coalesce(customer_currency_code, 'USD'), 'USD', ifNull(toFloat(metrics_conversions_value), 0)))) / nullIf(SUM(toFloat(convertCurrency(coalesce(customer_currency_code, 'USD'), 'USD', ifNull(toFloat(metrics_cost_micros), 0) / 1000000))), 0)","name": "google","table_name": "prefix.campaign_overview_stats","timestamp_field": "segments_date",@@ -668,7 +668,7 @@ exports[`marketing analytics utils createMarketingTile snapshots LinkedinAds - r"id_field": "campaign_group_id","kind": "DataWarehouseNode","math": "hogql",- "math_hogql": "SUM(ifNull(toFloat(conversion_value_in_local_currency), 0)) / nullIf(SUM(ifNull(toFloat(cost_in_usd), 0)), 0)",+ "math_hogql": "toFloat(convertCurrency('USD', 'USD', SUM(ifNull(toFloat(conversion_value_in_local_currency), 0)))) / nullIf(toFloat(convertCurrency('USD', 'USD', SUM(ifNull(toFloat(cost_in_usd), 0)))), 0)","name": "linkedin","table_name": "prefix.campaign_group_stats","timestamp_field": "date_start",@@ -803,7 +803,7 @@ exports[`marketing analytics utils createMarketingTile snapshots MetaAds - roas"id_field": "campaign_id","kind": "DataWarehouseNode","math": "hogql",- "math_hogql": "SUM(if(arraySum(x -> JSONExtractFloat(x, 'value'), arrayFilter(x -> JSONExtractString(x, 'action_type') IN ('omni_purchase', 'omni_lead', 'omni_complete_registration', 'omni_app_install', 'omni_subscribe'), JSONExtractArrayRaw(coalesce(action_values, '[]')))) > 0, arraySum(x -> JSONExtractFloat(x, 'value'), arrayFilter(x -> JSONExtractString(x, 'action_type') IN ('omni_purchase', 'omni_lead', 'omni_complete_registration', 'omni_app_install', 'omni_subscribe'), JSONExtractArrayRaw(coalesce(action_values, '[]')))), arraySum(x -> JSONExtractFloat(x, 'value'), arrayFilter(x -> JSONExtractString(x, 'action_type') IN ('purchase', 'lead', 'complete_registration', 'app_install', 'subscribe'), JSONExtractArrayRaw(coalesce(action_values, '[]')))))) / nullIf(SUM(ifNull(toFloat(spend), 0)), 0)",+ "math_hogql": "SUM(toFloat(convertCurrency(coalesce(account_currency, 'USD'), 'USD', if(arraySum(x -> JSONExtractFloat(x, 'value'), arrayFilter(x -> JSONExtractString(x, 'action_type') IN ('omni_purchase', 'omni_lead', 'omni_complete_registration', 'omni_app_install', 'omni_subscribe'), JSONExtractArrayRaw(coalesce(action_values, '[]')))) > 0, arraySum(x -> JSONExtractFloat(x, 'value'), arrayFilter(x -> JSONExtractString(x, 'action_type') IN ('omni_purchase', 'omni_lead', 'omni_complete_registration', 'omni_app_install', 'omni_subscribe'), JSONExtractArrayRaw(coalesce(action_values, '[]')))), arraySum(x -> JSONExtractFloat(x, 'value'), arrayFilter(x -> JSONExtractString(x, 'action_type') IN ('purchase', 'lead', 'complete_registration', 'app_install', 'subscribe'), JSONExtractArrayRaw(coalesce(action_values, '[]')))))))) / nullIf(SUM(toFloat(convertCurrency(coalesce(account_currency, 'USD'), 'USD', ifNull(toFloat(spend), 0)))), 0)","name": "meta","table_name": "prefix.campaign_stats","timestamp_field": "date_stop",@@ -1073,7 +1073,7 @@ exports[`marketing analytics utils createMarketingTile snapshots PinterestAds -"id_field": "campaign_id","kind": "DataWarehouseNode","math": "hogql",- "math_hogql": "SUM(ifNull(toFloat(total_checkout_value_in_micro_dollar), 0) / 1000000) / nullIf(SUM(ifNull(toFloat(spend_in_dollar), 0)), 0)",+ "math_hogql": "SUM(toFloat(convertCurrency(coalesce(currency, 'USD'), 'USD', ifNull(toFloat(total_checkout_value_in_micro_dollar), 0) / 1000000))) / nullIf(SUM(toFloat(convertCurrency(coalesce(currency, 'USD'), 'USD', ifNull(toFloat(spend_in_dollar), 0)))), 0)","name": "pinterest","table_name": "prefix.campaign_analytics","timestamp_field": "date",@@ -1208,7 +1208,7 @@ exports[`marketing analytics utils createMarketingTile snapshots RedditAds - roa"id_field": "campaign_id","kind": "DataWarehouseNode","math": "hogql",- "math_hogql": "SUM(ifNull(toFloat(conversion_purchase_total_value), 0) / 100 + ifNull(toFloat(conversion_signup_total_value), 0) / 100) / nullIf(SUM(ifNull(toFloat(spend), 0) / 1000000), 0)",+ "math_hogql": "SUM(toFloat(convertCurrency(coalesce(currency, 'USD'), 'USD', ifNull(toFloat(conversion_purchase_total_value), 0) / 100 + ifNull(toFloat(conversion_signup_total_value), 0) / 100))) / nullIf(SUM(toFloat(convertCurrency(coalesce(currency, 'USD'), 'USD', ifNull(toFloat(spend), 0) / 1000000))), 0)","name": "reddit","table_name": "prefix.campaign_report","timestamp_field": "date",@@ -1478,7 +1478,7 @@ exports[`marketing analytics utils createMarketingTile snapshots SnapchatAds - r"id_field": "id","kind": "DataWarehouseNode","math": "hogql",- "math_hogql": "SUM(ifNull(toFloat(conversion_purchases_value), 0) + ifNull(toFloat(conversion_sign_ups_value), 0) + ifNull(toFloat(conversion_subscribe_value), 0)) / nullIf(SUM(ifNull(toFloat(spend), 0) / 1000000), 0)",+ "math_hogql": "SUM(toFloat(convertCurrency(coalesce(currency, 'USD'), 'USD', ifNull(toFloat(conversion_purchases_value), 0) + ifNull(toFloat(conversion_sign_ups_value), 0) + ifNull(toFloat(conversion_subscribe_value), 0)))) / nullIf(SUM(toFloat(convertCurrency(coalesce(currency, 'USD'), 'USD', ifNull(toFloat(spend), 0) / 1000000))), 0)","name": "snapchat","table_name": "prefix.campaign_stats_daily","timestamp_field": "start_time",@@ -1613,7 +1613,7 @@ exports[`marketing analytics utils createMarketingTile snapshots TikTokAds - roa"id_field": "campaign_id","kind": "DataWarehouseNode","math": "hogql",- "math_hogql": "SUM(ifNull(toFloat(total_complete_payment_value), 0)) / nullIf(SUM(ifNull(toFloat(spend), 0)), 0)",+ "math_hogql": "SUM(toFloat(convertCurrency(coalesce(currency, 'USD'), 'USD', ifNull(toFloat(total_complete_payment_value), 0)))) / nullIf(SUM(toFloat(convertCurrency(coalesce(currency, 'USD'), 'USD', ifNull(toFloat(spend), 0)))), 0)","name": "tiktok","table_name": "prefix.campaign_report","timestamp_field": "stat_time_day",diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.tsindex 4ac16c1e72c7..d65ab6cd7e4a 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts@@ -18,6 +18,8 @@ import {MARKETING_ANALYTICS_DRILL_DOWN_CONFIG,MARKETING_ANALYTICS_SCHEMA,MarketingAnalyticsBaseColumns,+ MarketingAnalyticsAggregatedQuery,+ TrendsQuery,MarketingAnalyticsConstants,MarketingAnalyticsDrillDownLevel,MarketingAnalyticsTableQuery,@@ -35,7 +37,9 @@ import {PropertyOperator,} from '~/types'-import { marketingAnalyticsLogic } from './marketingAnalyticsLogic'+import { buildAdPerformanceTrendsQuery } from 'products/marketing_analytics/frontend/adPerformanceMetrics'++import { marketingAnalyticsLogic, type NativeSource, type ExternalTable } from './marketingAnalyticsLogic'import { marketingAnalyticsTableLogic } from './marketingAnalyticsTableLogic'import {getOrderBy,@@ -49,11 +53,13 @@ import {export const MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID = pageCollectionId('marketing-analytics')const isSchemaBackedMarketingColumn = (column: validColumnsForTiles): column is rawColumnsForTiles =>- column !== 'roas' && column !== 'cost_per_reported_conversion'+ column !== 'roas' && column !== 'cost_per_reported_conversion' && column !== 'cpc' && column !== 'ctr'// Maps a chart column to a HogQL aggregate over the native cost precompute table. Costs are already// converted to the team's base currency at materialization time, so no convertCurrency() is needed.const PRECOMPUTE_METRIC_EXPR: Record<validColumnsForTiles, string> = {+ cpc: 'sum(cost) / nullIf(sum(clicks), 0)',+ ctr: 'sum(clicks) / nullIf(sum(impressions), 0) * 100',cost: 'sum(cost)',clicks: 'sum(clicks)',impressions: 'sum(impressions)',@@ -90,10 +96,13 @@ export interface marketingAnalyticsTilesLogicValues {shouldFilterTestAccounts: boolean // marketingAnalyticsLogicsourcesInitialLoading: boolean // marketingAnalyticsLogictileColumnSelection: validColumnsForTiles // marketingAnalyticsLogic+ validExternalTables: ExternalTable[] // marketingAnalyticsLogic+ validNativeSources: NativeSource[] // marketingAnalyticsLogicdefaultColumns: string[] // marketingAnalyticsTableLogicquery: DataTableNode | null // marketingAnalyticsTableLogiccampaignBreakdownTile: QueryTile | nullcampaignCostsBreakdown: DataTableNode | null+ createAdPerformanceSparklineQuery: (query: MarketingAnalyticsAggregatedQuery) => TrendsQuerymarketingChartTile: QueryTileoverviewTile: QueryTiletiles: QueryTile[]@@ -102,6 +111,17 @@ export interface marketingAnalyticsTilesLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface marketingAnalyticsTilesLogicMeta {__keaTypeGenInternalSelectorTypes: {+ createAdPerformanceSparklineQuery: (+ dateFilter: {+ dateFrom: string | null+ dateTo: string | null+ interval: IntervalType+ },+ validNativeSources: NativeSource[],+ validExternalTables: ExternalTable[],+ baseCurrency: CurrencyCode,+ featureFlags: FeatureFlagsSet+ ) => (query: MarketingAnalyticsAggregatedQuery) => TrendsQueryoverviewTile: (compareFilter: CompareFilter,dateFilter: {@@ -184,6 +204,8 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType'drillDownLevel','baseCurrency','includeConversionGoals',+ 'validNativeSources',+ 'validExternalTables',],marketingAnalyticsTableLogic,['query', 'defaultColumns'],@@ -192,6 +214,25 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType],})),selectors({+ createAdPerformanceSparklineQuery: [+ (s) => [s.dateFilter, s.validNativeSources, s.validExternalTables, s.baseCurrency, s.featureFlags],+ (+ dateFilter: { interval: IntervalType },+ nativeSources: NativeSource[],+ externalTables: ExternalTable[],+ baseCurrency: CurrencyCode,+ featureFlags: FeatureFlagsSet+ ): ((query: MarketingAnalyticsAggregatedQuery) => TrendsQuery) =>+ (query) =>+ buildAdPerformanceTrendsQuery(+ query,+ dateFilter.interval,+ nativeSources,+ externalTables,+ baseCurrency,+ !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_COSTS_PRECOMPUTATION]+ ),+ ],// One selector per tile so an input change only invalidates the tile that uses// it — entries keep identity in `tiles` below, so `dataNodeLogic` doesn't refetch.overviewTile: [@@ -262,9 +303,10 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicTypeconst hasSources = createMarketingDataWarehouseNodes.length > 0const metricExpr = PRECOMPUTE_METRIC_EXPR[tileColumnSelection] ?? 'sum(cost)'const isCurrency =- tileColumnSelection && isSchemaBackedMarketingColumn(tileColumnSelection)+ ['cpc', 'cost_per_reported_conversion'].includes(tileColumnSelection) ||+ (tileColumnSelection && isSchemaBackedMarketingColumn(tileColumnSelection)? MARKETING_ANALYTICS_SCHEMA[tileColumnSelection].isCurrency- : false+ : false)const { symbol: currencySymbol, isPrefix: currencyIsPrefix } = getCurrencySymbol(baseCurrency)// Gated behind the same flag as the backend cost precompute read-side: when off, the tile@@ -348,7 +390,12 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicTypedisplay: chartDisplayType,aggregationAxisFormat: 'numeric',aggregationAxisPrefix: isCurrency && currencyIsPrefix ? currencySymbol : undefined,- aggregationAxisPostfix: isCurrency && !currencyIsPrefix ? ` ${currencySymbol}` : undefined,+ aggregationAxisPostfix:+ tileColumnSelection === 'ctr'+ ? '%'+ : isCurrency && !currencyIsPrefix+ ? ` ${currencySymbol}`+ : undefined,},tags: MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS,},diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingCostTile.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingCostTile.tsindex a77d0ff522da..9cc377e3fb0e 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingCostTile.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingCostTile.ts@@ -1,4 +1,9 @@-import { DataWarehouseNode, MarketingAnalyticsConstants, NodeKind } from '~/queries/schema/schema-general'+import {+ DataWarehouseNode,+ MarketingAnalyticsColumnsSchemaNames,+ MarketingAnalyticsConstants,+ NodeKind,+} from '~/queries/schema/schema-general'import { HogQLMathType } from '~/types'import { ExternalTable } from './marketingAnalyticsLogic'@@ -59,24 +64,31 @@ export const externalAdsCostTile = (let mathHogql: string- if (tileColumnSelection === 'roas') {- const costColumn = sanitizeColumnName(table.source_map.cost)- const conversionValueColumn = table.source_map.reported_conversion_value- ? sanitizeColumnName(table.source_map.reported_conversion_value)- : null- if (!costColumn || !conversionValueColumn) {+ if (+ tileColumnSelection === 'cpc' ||+ tileColumnSelection === 'ctr' ||+ tileColumnSelection === 'roas' ||+ tileColumnSelection === 'cost_per_reported_conversion'+ ) {+ const ratioColumns = {+ cpc: [MarketingAnalyticsColumnsSchemaNames.Cost, MarketingAnalyticsColumnsSchemaNames.Clicks],+ ctr: [MarketingAnalyticsColumnsSchemaNames.Clicks, MarketingAnalyticsColumnsSchemaNames.Impressions],+ roas: [+ MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue,+ MarketingAnalyticsColumnsSchemaNames.Cost,+ ],+ cost_per_reported_conversion: [+ MarketingAnalyticsColumnsSchemaNames.Cost,+ MarketingAnalyticsColumnsSchemaNames.ReportedConversion,+ ],+ } as const+ const [numeratorColumn, denominatorColumn] = ratioColumns[tileColumnSelection]+ const numerator = externalAdsCostTile(table, baseCurrency, numeratorColumn)+ const denominator = externalAdsCostTile(table, baseCurrency, denominatorColumn)+ if (!numerator || !denominator) {return null}- mathHogql = `${sumSafeFloat(conversionValueColumn)} / nullIf(SUM(toFloat(${costColumn})), 0)`- } else if (tileColumnSelection === 'cost_per_reported_conversion') {- const costColumn = sanitizeColumnName(table.source_map.cost)- const conversionColumn = table.source_map.reported_conversion- ? sanitizeColumnName(table.source_map.reported_conversion)- : null- if (!costColumn || !conversionColumn) {- return null- }- mathHogql = `SUM(toFloat(${costColumn})) / nullIf(${sumSafeFloat(conversionColumn)}, 0)`+ mathHogql = `(${numerator.math_hogql}) / nullIf(${denominator.math_hogql}, 0)${tileColumnSelection === 'ctr' ? ' * 100' : ''}`} else {const rawColumn = table.source_map[tileColumnSelection]const column = rawColumn ? sanitizeColumnName(rawColumn) : null@@ -86,7 +98,10 @@ export const externalAdsCostTile = (const currencyExpr = buildCurrencyExpr(table.source_map.currency, baseCurrency)const dateExpr = buildDateExpr(table)const safeCurrency = sanitizeCurrencyCode(baseCurrency) ?? 'USD'- mathHogql = `SUM(convertCurrency(${currencyExpr}, '${safeCurrency}', ${safeFloat(column)}, _toDate(${dateExpr})))`+ mathHogql =+ tileColumnSelection === 'cost' || tileColumnSelection === 'reported_conversion_value'+ ? `SUM(convertCurrency(${currencyExpr}, '${safeCurrency}', ${safeFloat(column)}, _toDate(${dateExpr})))`+ : sumSafeFloat(column)}const dateField = sanitizeColumnName(table.source_map.date)diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.tsindex c2e0b135e17d..8faa1e5c7c3c 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.test.ts@@ -595,6 +595,16 @@ describe('marketing analytics utils', () => {expect(mathHogql).not.toContain(`${costColumn} / 1000000`)})+ it.each(['cpc', 'cost_per_reported_conversion', 'roas'] as const)(+ 'converts Google Ads %s to the project currency',+ (metric) => {+ const source = makeMockSource('GoogleAds', sourceFields.GoogleAds)+ expect(createMarketingTile(source, metric, 'EUR')?.math_hogql).toContain(+ "convertCurrency(coalesce(customer_currency_code, 'EUR'), 'EUR'"+ )+ }+ )+const testCases = VALID_NATIVE_MARKETING_SOURCES.flatMap((sourceType) =>ALL_TILE_COLUMNS.map((column) =>diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.tsindex eee849e815ce..ce05b6cde1ee 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils.ts@@ -420,9 +420,11 @@ export type validColumnsForTiles =>| 'roas'| 'cost_per_reported_conversion'+ | 'cpc'+ | 'ctr'// Raw column types that have actual column mappings (excludes calculated fields like ROAS)-export type rawColumnsForTiles = Exclude<validColumnsForTiles, 'roas' | 'cost_per_reported_conversion'>+export type rawColumnsForTiles = Exclude<validColumnsForTiles, 'roas' | 'cost_per_reported_conversion' | 'cpc' | 'ctr'>interface ColumnConfig {name: string@@ -976,7 +978,8 @@ export function createMarketingTile(tileColumnSelection === MarketingAnalyticsColumnsSchemaNames.Cost ||tileColumnSelection === MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue ||tileColumnSelection === 'roas' ||- tileColumnSelection === 'cost_per_reported_conversion'+ tileColumnSelection === 'cost_per_reported_conversion' ||+ tileColumnSelection === 'cpc'if (monetaryColumn && !('currency_code' in table.fields)) {return null}@@ -994,7 +997,8 @@ export function createMarketingTile(tileColumnSelection === MarketingAnalyticsColumnsSchemaNames.Cost ||tileColumnSelection === MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue ||tileColumnSelection === 'roas' ||- tileColumnSelection === 'cost_per_reported_conversion'+ tileColumnSelection === 'cost_per_reported_conversion' ||+ tileColumnSelection === 'cpc'const currencyColumn = sourceType === 'AmazonAds' ? 'campaign_budget_currency_code' : 'currency'if (monetaryColumn && !(currencyColumn in table.fields)) {return null@@ -1005,7 +1009,10 @@ export function createMarketingTile(if (!['campaign_id', 'start_time', 'impressions', 'clicks', 'spend'].every((field) => field in table.fields)) {return null}- if (tileColumnSelection === MarketingAnalyticsColumnsSchemaNames.Cost && !('currency_code' in table.fields)) {+ if (+ (tileColumnSelection === MarketingAnalyticsColumnsSchemaNames.Cost || tileColumnSelection === 'cpc') &&+ !('currency_code' in table.fields)+ ) {return null}}@@ -1019,6 +1026,15 @@ export function createMarketingTile(}: tileConfig.columnMappings+ if (tileColumnSelection === 'cpc' || tileColumnSelection === 'ctr') {+ const clicks = sumSafeFloat(tileConfig.columnMappings.clicks)+ const expression =+ tileColumnSelection === 'cpc'+ ? `${wrapWithCurrencyConversion(buildNativeCostExpr(tileConfig.columnMappings), tileConfig.columnMappings, table, baseCurrency)} / nullIf(${clicks}, 0)`+ : `${clicks} / nullIf(${sumSafeFloat(tileConfig.columnMappings.impressions)}, 0) * 100`+ return buildNativeTileNode(table, integrationConfig, tileConfig, tileColumnSelection, expression)+ }+// Handle ROAS (Return on Ad Spend) - calculated as conversion_value / costif (tileColumnSelection === 'roas') {const costExpr = buildNativeCostExpr(tileConfig.columnMappings)@@ -1030,7 +1046,7 @@ export function createMarketingTile()let totalValueExpr = conversionValueExprlet totalCostExpr = `SUM(${costExpr})`- if (tileConfig.columnMappings.currencyTimestampColumn && conversionValueExpr !== '0') {+ if (conversionValueExpr !== '0') {const perRowValue =tileConfig.specialConversionLogic?.(table, MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue)?.perRowValueExpr ?? safeFloat(tileConfig.columnMappings.reportedConversionValue)@@ -1050,9 +1066,7 @@ export function createMarketingTile(MarketingAnalyticsColumnsSchemaNames.ReportedConversion,tileConfig.columnMappings.reportedConversion)- const totalCostExpr = tileConfig.columnMappings.currencyTimestampColumn- ? wrapWithCurrencyConversion(costExpr, tileConfig.columnMappings, table, baseCurrency)- : `SUM(${costExpr})`+ const totalCostExpr = wrapWithCurrencyConversion(costExpr, tileConfig.columnMappings, table, baseCurrency)const mathHogql = conversionExpr === '0' ? '0' : `${totalCostExpr} / nullIf(${conversionExpr}, 0)`return buildNativeTileNode(table, integrationConfig, tileConfig, tileColumnSelection, mathHogql)}diff --git a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsxindex 5ec7491160f5..5936f0c56a2c 100644--- a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx+++ b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.tsx@@ -991,6 +991,8 @@ export const MarketingAnalyticsTrendTile = ({value: MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue,label: 'Reported conversion value',},+ { value: 'cpc', label: 'CPC' },+ { value: 'ctr', label: 'CTR' },{ value: 'roas', label: 'Reported ROAS' },{ value: 'cost_per_reported_conversion', label: 'Cost per reported conversion' },]diff --git a/products/marketing_analytics/frontend/AdPerformanceOverview.stories.tsx b/products/marketing_analytics/frontend/AdPerformanceOverview.stories.tsxnew file mode 100644index 000000000000..789d8a3a0903--- /dev/null+++ b/products/marketing_analytics/frontend/AdPerformanceOverview.stories.tsx@@ -0,0 +1,212 @@+import { Meta, StoryObj } from '@storybook/react'+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { FEATURE_FLAGS } from 'lib/constants'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'+import { MarketingAnalyticsOverview } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview'+import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'+import { marketingAnalyticsTilesLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'+import { MarketingAnalyticsTrendTile } from 'scenes/web-analytics/tiles/WebAnalyticsTile'++import { useStorybookMocks } from '~/mocks/browser'+import {+ DatabaseSchemaDataWarehouseTable,+ InsightVizNode,+ MARKETING_INTEGRATION_CONFIGS,+ MarketingAnalyticsAggregatedQueryResponse,+ NodeKind,+ TrendsQuery,+} from '~/queries/schema/schema-general'+import { ExternalDataSource } from '~/types'++const days = ['2026-09-10', '2026-09-11', '2026-09-12', '2026-09-13', '2026-09-14', '2026-09-15', '2026-09-16']+const data: Record<string, number[]> = {+ cost: [2200, 2600, 2100, 3100, 3000, 2400, 2800],+ clicks: [1200, 1400, 1000, 1800, 1500, 1300, 1400],+ impressions: [80000, 90000, 70000, 110000, 100000, 90000, 100000],+ reported_conversion: [40, 50, 30, 70, 60, 45, 55],+ reported_conversion_value: [11000, 13000, 9000, 16000, 15000, 12000, 15000],+}+for (const [metric, numerator, denominator, scale] of [+ ['cpc', 'cost', 'clicks', 1],+ ['ctr', 'clicks', 'impressions', 100],+ ['roas', 'reported_conversion_value', 'cost', 1],+ ['cost_per_reported_conversion', 'cost', 'reported_conversion', 1],+] as const) {+ data[metric] = data[numerator].map((value, index) => (value / data[denominator][index]) * scale)+}++const schemaNames = [+ MARKETING_INTEGRATION_CONFIGS.GoogleAds.campaignTableName,+ MARKETING_INTEGRATION_CONFIGS.GoogleAds.statsTableName,+]+const source = {+ id: 'example-google-ads',+ source_type: 'GoogleAds',+ prefix: 'example',+ status: 'Completed',+ schemas: schemaNames.map((name) => ({ id: `example-${name}`, name, should_sync: true, status: 'Completed' })),+} as ExternalDataSource+const tables = Object.fromEntries(+ schemaNames.map((name) => [+ name,+ {+ id: `table-${name}`,+ name,+ type: 'data_warehouse',+ schema: { id: `example-${name}`, name, should_sync: true, incremental: false },+ fields: Object.fromEntries(+ [+ 'campaign_id',+ 'id',+ 'name',+ 'segments_date',+ 'customer_currency_code',+ 'metrics_cost_micros',+ 'metrics_clicks',+ 'metrics_impressions',+ 'metrics_conversions',+ 'metrics_conversions_value',+ ].map((field) => [field, { name: field, hogql_value: field, type: 'float', schema_valid: true }])+ ),+ } satisfies DatabaseSchemaDataWarehouseTable,+ ])+)++const summary: MarketingAnalyticsAggregatedQueryResponse = {+ results: {+ Cost: {+ key: 'Cost',+ value: 18200,+ previous: 20000,+ changeFromPreviousPct: -9,+ kind: 'currency',+ isIncreaseBad: true,+ },+ Clicks: { key: 'Clicks', value: 9600, previous: 8000, changeFromPreviousPct: 20, kind: 'unit' },+ Impressions: { key: 'Impressions', value: 640000, previous: 600000, changeFromPreviousPct: 7, kind: 'unit' },+ 'Reported Conversions': {+ key: 'Reported Conversions',+ value: 350,+ previous: 300,+ changeFromPreviousPct: 17,+ kind: 'unit',+ },+ 'Reported Conversion Value': {+ key: 'Reported Conversion Value',+ value: 91000,+ previous: 75000,+ changeFromPreviousPct: 21,+ kind: 'currency',+ },+ 'Trial started': { key: 'Trial started', value: 620, previous: 540, changeFromPreviousPct: 15, kind: 'unit' },+ 'Demo booked': { key: 'Demo booked', value: 84, previous: 70, changeFromPreviousPct: 20, kind: 'unit' },+ CPC: {+ key: 'CPC',+ value: 1.9,+ previous: 2.5,+ changeFromPreviousPct: -24,+ kind: 'currency',+ isIncreaseBad: true,+ },+ CTR: { key: 'CTR', value: 1.5, previous: 1.33, changeFromPreviousPct: 13, kind: 'percentage' },+ 'Cost per Reported Conversions': {+ key: 'Cost per Reported Conversions',+ value: 52,+ previous: 66.67,+ changeFromPreviousPct: -22,+ kind: 'currency',+ isIncreaseBad: true,+ },+ 'Reported ROAS': { key: 'Reported ROAS', value: 5, previous: 3.75, changeFromPreviousPct: 33, kind: 'unit' },+ 'Cost per Trial started': { key: 'Cost per Trial started', value: 29.35, kind: 'currency' },+ 'Cost per Demo booked': { key: 'Cost per Demo booked', value: 216.67, kind: 'currency' },+ },+}++const meta: Meta<typeof MarketingAnalyticsOverview> = {+ title: 'Marketing Analytics/Ad performance metric trends',+ component: MarketingAnalyticsOverview,+ parameters: { layout: 'padded', mockDate: '2026-09-16', featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING] },+ args: {+ query: {+ kind: NodeKind.MarketingAnalyticsAggregatedQuery,+ properties: [],+ dateRange: { date_from: '2026-09-10', date_to: '2026-09-16' },+ },+ cachedResults: summary,+ context: {},+ uniqueKey: 'ad-performance-trends-story',+ },+}+export default meta+type Story = StoryObj<typeof MarketingAnalyticsOverview>++export const WithTrends: Story = {+ render: function Render(args) {+ const { loadSourcesSuccess, setDatesAndInterval } = useActions(marketingAnalyticsLogic)+ const { marketingChartTile } = useValues(marketingAnalyticsTilesLogic)+ useStorybookMocks({+ get: {+ '/api/projects/:team_id/external_data_sources/wizard/': {},+ '/api/environments/:team_id/external_data_sources/': {+ count: 1,+ results: [source],+ next: null,+ previous: null,+ },+ '/api/projects/:team_id/marketing_analytics/source_validation/': { errors_by_source: {} },+ },+ post: {+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {+ const { query } = (await request.json()) as { query: TrendsQuery }+ if (query.kind === (NodeKind.DatabaseSchemaQuery as string)) {+ return [200, { tables, joins: [] }]+ }+ return [+ 200,+ {+ results: (query.series ?? []).map((series, index) => {+ const metric =+ series.custom_name && data[series.custom_name]+ ? series.custom_name+ : marketingAnalyticsLogic.values.tileColumnSelection+ return {+ action: { ...series, type: 'data_warehouse', order: index },+ order: index,+ label: series.custom_name ?? metric,+ days,+ dates: days,+ labels: days,+ data: data[metric] ?? data.cost,+ count: (data[metric] ?? data.cost).reduce((total, value) => total + value, 0),+ aggregated_value: (data[metric] ?? data.cost).reduce(+ (total, value) => total + value,+ 0+ ),+ }+ }),+ },+ ]+ },+ },+ })+ useEffect(() => {+ loadSourcesSuccess({ count: 1, results: [source], next: null, previous: null })+ databaseTableListLogic.actions.loadDatabaseSuccess({ tables, joins: [] })+ setDatesAndInterval('2026-09-10', '2026-09-16', 'day')+ }, [loadSourcesSuccess, setDatesAndInterval])+ return (+ <div className="flex flex-col gap-4">+ <MarketingAnalyticsOverview {...args} />+ <MarketingAnalyticsTrendTile+ query={marketingChartTile.query as InsightVizNode}+ insightProps={marketingChartTile.insightProps}+ uniqueKey="ad-performance-main-trend-story"+ showIntervalTile+ />+ </div>+ )+ },+}diff --git a/products/marketing_analytics/frontend/adPerformanceMetrics.test.ts b/products/marketing_analytics/frontend/adPerformanceMetrics.test.tsnew file mode 100644index 000000000000..36b7dd22d547--- /dev/null+++ b/products/marketing_analytics/frontend/adPerformanceMetrics.test.ts@@ -0,0 +1,144 @@+import type { ExternalTable } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'+import { externalAdsCostTile } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingCostTile'++import { MarketingAnalyticsColumnsSchemaNames, NodeKind, SourceMap } from '~/queries/schema/schema-general'+import { DataWarehouseSettingsTab, PropertyFilterType, PropertyOperator, TrendResult } from '~/types'++import { adPerformanceSparklines, buildAdPerformanceTrendsQuery } from './adPerformanceMetrics'++const row = (metric: string, data: number[], days = ['2026-01-01', '2026-01-02']): TrendResult =>+ ({+ action: { custom_name: metric },+ data,+ days,+ labels: days,+ label: metric,+ count: 0,+ aggregated_value: 0,+ }) as TrendResult++const table: ExternalTable = {+ id: 'table-one',+ source_map_id: 'source-one',+ name: 'example_ad_stats',+ source_type: 'manual',+ source_prefix: '',+ columns: [],+ url_pattern: '',+ sourceUrl: '',+ external_type: DataWarehouseSettingsTab.Managed,+ schema_name: 'example_ad_stats',+ dw_source_type: 'manual',+ source_map: {+ ...(Object.fromEntries(+ Object.values(MarketingAnalyticsColumnsSchemaNames).map((key) => [key, undefined])+ ) as SourceMap),+ date: 'day',+ cost: 'spend',+ clicks: 'clicks',+ impressions: 'impressions',+ reported_conversion: 'conversions',+ reported_conversion_value: 'revenue',+ currency: 'const:EUR',+ },+}++describe('Ad performance sparklines', () => {+ it('sums sources by date before calculating ratios and leaves zero denominators as gaps', () => {+ const metrics = adPerformanceSparklines([+ row('cost', [10, 20]),+ row('cost', [90, 30]),+ row('clicks', [5, 0]),+ row('clicks', [15, 0]),+ row('impressions', [200, 100]),+ row('reported_conversion', [2, 0]),+ row('reported_conversion_value', [300, 0]),+ ])+ expect(metrics.cost?.data).toEqual([100, 50])+ expect(metrics.cpc?.data).toEqual([5, NaN])+ expect(metrics.ctr?.data).toEqual([10, 0])+ expect(metrics.roas?.data).toEqual([3, 0])+ expect(metrics.cost_per_reported_conversion?.data).toEqual([50, NaN])+ })++ it('aligns dates, preserves unknown values, and excludes attributed goals and comparison periods', () => {+ const metrics = adPerformanceSparklines([+ row('cost', [20, 10], ['2026-01-02', '2026-01-01']),+ row('clicks', [5, NaN]),+ row('trial started', [100, 200]),+ { ...row('cost', [500, 600]), compare: true },+ ])+ expect(metrics.cost).toEqual({ labels: ['2026-01-01', '2026-01-02'], data: [10, 20] })+ expect(metrics.cpc?.data).toEqual([2, NaN])+ expect(Object.keys(metrics)).not.toContain('trial started')+ })++ it.each([false, true])('keeps request filters and current-period dates with precompute=%s', (precomputed) => {+ const query = buildAdPerformanceTrendsQuery(+ {+ kind: NodeKind.MarketingAnalyticsAggregatedQuery,+ properties: [],+ dateRange: { date_from: '-30d', date_to: null },+ compareFilter: { compare: true },+ integrationFilter: { integrationSourceIds: ['source-one'] },+ },+ 'day',+ [],+ [table, { ...table, source_map_id: 'source-two' }],+ 'USD',+ precomputed+ )+ expect(query.series).toHaveLength(5)+ expect(query.dateRange).toEqual({ date_from: '-30d', date_to: null })+ expect(query.compareFilter).toBeUndefined()+ if (precomputed) {+ expect(query.series[0].properties).toContainEqual({+ type: PropertyFilterType.DataWarehouse,+ key: 'source_id',+ operator: PropertyOperator.Exact,+ value: ['source-one'],+ })+ } else {+ expect(query.series.every((series) => 'table_name' in series && series.table_name === table.name)).toBe(+ true+ )+ expect((query.series[0] as { math_hogql: string }).math_hogql).toContain('convertCurrency')+ expect((query.series[1] as { math_hogql: string }).math_hogql).not.toContain('convertCurrency')+ expect((query.series[3] as { math_hogql: string }).math_hogql).not.toContain('convertCurrency')+ }+ })++ it.each([+ [+ 'cost_per_reported_conversion',+ MarketingAnalyticsColumnsSchemaNames.Cost,+ MarketingAnalyticsColumnsSchemaNames.ReportedConversion,+ ],+ [+ 'roas',+ MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue,+ MarketingAnalyticsColumnsSchemaNames.Cost,+ ],+ ] as const)(+ 'keeps the external %s trend in the same currency as its sparkline',+ (metric, numerator, denominator) => {+ const top = externalAdsCostTile(table, 'USD', numerator)?.math_hogql+ const bottom = externalAdsCostTile(table, 'USD', denominator)?.math_hogql+ expect(externalAdsCostTile(table, 'USD', metric)?.math_hogql).toBe(`(${top}) / nullIf(${bottom}, 0)`)+ expect(externalAdsCostTile(table, 'USD', metric)?.math_hogql).toContain("convertCurrency('EUR', 'USD'")+ }+ )++ it('does not request data when there are no supported sources', () => {+ expect(+ buildAdPerformanceTrendsQuery(+ { kind: NodeKind.MarketingAnalyticsAggregatedQuery, properties: [] },+ 'day',+ [],+ [],+ 'USD',+ false+ ).series+ ).toEqual([])+ })+})diff --git a/products/marketing_analytics/frontend/adPerformanceMetrics.ts b/products/marketing_analytics/frontend/adPerformanceMetrics.tsnew file mode 100644index 000000000000..770e3ee078c4--- /dev/null+++ b/products/marketing_analytics/frontend/adPerformanceMetrics.ts@@ -0,0 +1,187 @@+import type {+ ExternalTable,+ NativeSource,+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'+import { externalAdsCostTile } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingCostTile'+import {+ MarketingDashboardMapper,+ type validColumnsForTiles,+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils'++import {+ DataWarehouseNode,+ MarketingAnalyticsAggregatedQuery,+ MarketingAnalyticsBaseColumns,+ MarketingAnalyticsColumnsSchemaNames,+ NodeKind,+ TrendsQuery,+} from '~/queries/schema/schema-general'+import {+ ChartDisplayType,+ HogQLMathType,+ IntervalType,+ PropertyFilterType,+ PropertyOperator,+ TrendResult,+} from '~/types'++export const AD_PERFORMANCE_METRICS: Record<string, validColumnsForTiles> = {+ [MarketingAnalyticsBaseColumns.Cost]: MarketingAnalyticsColumnsSchemaNames.Cost,+ [MarketingAnalyticsBaseColumns.Clicks]: MarketingAnalyticsColumnsSchemaNames.Clicks,+ [MarketingAnalyticsBaseColumns.Impressions]: MarketingAnalyticsColumnsSchemaNames.Impressions,+ [MarketingAnalyticsBaseColumns.ReportedConversions]: MarketingAnalyticsColumnsSchemaNames.ReportedConversion,+ [MarketingAnalyticsBaseColumns.ReportedConversionValue]:+ MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue,+ [MarketingAnalyticsBaseColumns.CPC]: 'cpc',+ [MarketingAnalyticsBaseColumns.CTR]: 'ctr',+ [MarketingAnalyticsBaseColumns.ReportedROAS]: 'roas',+ [MarketingAnalyticsBaseColumns.CostPerReportedConversions]: 'cost_per_reported_conversion',+}++export function adPerformanceMetricKey(key: string): validColumnsForTiles | undefined {+ return Object.hasOwn(AD_PERFORMANCE_METRICS, key) ? AD_PERFORMANCE_METRICS[key] : undefined+}++const RAW_METRICS = [+ MarketingAnalyticsColumnsSchemaNames.Cost,+ MarketingAnalyticsColumnsSchemaNames.Clicks,+ MarketingAnalyticsColumnsSchemaNames.Impressions,+ MarketingAnalyticsColumnsSchemaNames.ReportedConversion,+ MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue,+] as const+const PRECOMPUTED_FIELDS = [+ 'cost',+ 'clicks',+ 'impressions',+ 'reported_conversions',+ 'reported_conversion_value',+] as const++export interface AdPerformanceSparkline {+ data: number[]+ labels: string[]+}++export function buildAdPerformanceTrendsQuery(+ query: MarketingAnalyticsAggregatedQuery,+ interval: IntervalType,+ nativeSources: NativeSource[],+ externalTables: ExternalTable[],+ baseCurrency: string,+ precomputed: boolean+): TrendsQuery {+ const selectedIds = query.integrationFilter?.integrationSourceIds ?? []+ const native = nativeSources.filter((source) => !selectedIds.length || selectedIds.includes(source.source.id))+ const external = externalTables.filter((table) => !selectedIds.length || selectedIds.includes(table.source_map_id))+ const series: DataWarehouseNode[] = []+ if (native.length || external.length) {+ RAW_METRICS.forEach((metric, index) => {+ const nodes: DataWarehouseNode[] = precomputed+ ? [+ {+ kind: NodeKind.DataWarehouseNode,+ id: 'marketing_costs_precomputed',+ table_name: 'marketing_costs_precomputed',+ id_field: 'campaign_id',+ distinct_id_field: 'campaign_id',+ timestamp_field: 'timestamp',+ math: HogQLMathType.HogQL,+ math_hogql: `sum(${PRECOMPUTED_FIELDS[index]})`,+ properties: [+ { type: PropertyFilterType.HogQL, key: "grain = 'campaign' AND expires_at > today()" },+ ...(selectedIds.length+ ? [+ {+ type: PropertyFilterType.DataWarehouse as const,+ key: 'source_id',+ operator: PropertyOperator.Exact,+ value: selectedIds,+ },+ ]+ : []),+ ],+ },+ ]+ : [+ ...native.map((source) => MarketingDashboardMapper(source, metric, baseCurrency)),+ ...external.map((table) => externalAdsCostTile(table, baseCurrency, metric)),+ ].filter((node): node is DataWarehouseNode => node !== null)+ series.push(...nodes.map((node) => ({ ...node, custom_name: metric })))+ })+ }+ return {+ kind: NodeKind.TrendsQuery,+ series,+ interval,+ dateRange: query.dateRange,+ properties: query.properties,+ filterTestAccounts: query.filterTestAccounts,+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph },+ tags: query.tags,+ }+}++export function adPerformanceSparklines(+ results: TrendResult[]+): Partial<Record<validColumnsForTiles, AdPerformanceSparkline>> {+ const buckets = new Map<string, Map<string, number>>()+ for (const row of results) {+ const metric = row.action?.custom_name+ if (row.compare || !metric || !RAW_METRICS.some((key) => key === metric)) {+ continue+ }+ const values = buckets.get(metric) ?? new Map<string, number>()+ row.days.forEach((day, index) => {+ const value = row.data[index]+ values.set(+ day,+ (values.get(day) ?? 0) + (typeof value === 'number' && Number.isFinite(value) ? value : NaN)+ )+ })+ buckets.set(metric, values)+ }+ const labels = [...new Set([...buckets.values()].flatMap((values) => [...values.keys()]))].sort()+ const output: Partial<Record<validColumnsForTiles, AdPerformanceSparkline>> = {}+ const add = (metric: validColumnsForTiles, data: number[]): void => {+ if (data.some(Number.isFinite)) {+ output[metric] = { data, labels }+ }+ }+ for (const metric of RAW_METRICS) {+ const values = buckets.get(metric)+ if (values) {+ add(+ metric,+ labels.map((label) => values.get(label) ?? NaN)+ )+ }+ }+ const ratio = (+ metric: validColumnsForTiles,+ numerator: (typeof RAW_METRICS)[number],+ denominator: (typeof RAW_METRICS)[number],+ scale = 1+ ): void => {+ const top = output[numerator]?.data+ const bottom = output[denominator]?.data+ if (top && bottom) {+ add(+ metric,+ top.map((value, index) => (bottom[index] ? (value / bottom[index]) * scale : NaN))+ )+ }+ }+ ratio('cpc', MarketingAnalyticsColumnsSchemaNames.Cost, MarketingAnalyticsColumnsSchemaNames.Clicks)+ ratio('ctr', MarketingAnalyticsColumnsSchemaNames.Clicks, MarketingAnalyticsColumnsSchemaNames.Impressions, 100)+ ratio(+ 'roas',+ MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue,+ MarketingAnalyticsColumnsSchemaNames.Cost+ )+ ratio(+ 'cost_per_reported_conversion',+ MarketingAnalyticsColumnsSchemaNames.Cost,+ MarketingAnalyticsColumnsSchemaNames.ReportedConversion+ )+ return output+}diff --git a/products/marketing_analytics/frontend/adPerformanceTrendsLogic.ts b/products/marketing_analytics/frontend/adPerformanceTrendsLogic.tsnew file mode 100644index 000000000000..c6bb4223ec1a--- /dev/null+++ b/products/marketing_analytics/frontend/adPerformanceTrendsLogic.ts@@ -0,0 +1,65 @@+import { LogicWrapper, MakeLogicType, connect, kea, key, path, props, propsChanged, selectors } from 'kea'++import type { validColumnsForTiles } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils'++import { DataNodeLogicProps, dataNodeLogic, dataNodeLogicType } from '~/queries/nodes/DataNode/dataNodeLogic'+import { TrendsQuery, TrendsQueryResponse } from '~/queries/schema/schema-general'+import { TrendResult } from '~/types'++import { AdPerformanceSparkline, adPerformanceSparklines } from './adPerformanceMetrics'++export interface AdPerformanceTrendsLogicProps {+ query: TrendsQuery+ queryKey: string+ dataNodeCollectionId: string+}++function dataProps(props: AdPerformanceTrendsLogicProps): DataNodeLogicProps {+ return {+ key: props.queryKey,+ query: props.query,+ doNotLoad: !props.query.series.length,+ dataNodeCollectionId: props.dataNodeCollectionId,+ }+}++export interface adPerformanceTrendsLogicValues extends Pick<+ dataNodeLogicType['values'],+ 'response' | 'responseLoading' | 'responseError'+> {+ sparklines: Partial<Record<validColumnsForTiles, AdPerformanceSparkline>>+}++export type adPerformanceTrendsLogicType = MakeLogicType<+ adPerformanceTrendsLogicValues,+ {},+ AdPerformanceTrendsLogicProps+>++export const adPerformanceTrendsLogic: LogicWrapper<adPerformanceTrendsLogicType> = kea<adPerformanceTrendsLogicType>([+ props({} as AdPerformanceTrendsLogicProps),+ key(({ queryKey }) => queryKey),+ path((key) => ['products', 'marketingAnalytics', 'adPerformanceTrendsLogic', key]),+ connect((props: AdPerformanceTrendsLogicProps) => ({+ values: [dataNodeLogic(dataProps(props)), ['response', 'responseLoading', 'responseError']],+ })),+ selectors({+ sparklines: [+ (s) => [s.response, s.responseLoading, s.responseError],+ (response, loading, error): Partial<Record<validColumnsForTiles, AdPerformanceSparkline>> =>+ loading || error+ ? {}+ : adPerformanceSparklines(+ ((response as TrendsQueryResponse | null)?.results ?? []) as TrendResult[]+ ),+ ],+ }),+ propsChanged(({ props }, oldProps) => {+ if (JSON.stringify(props.query) !== JSON.stringify(oldProps.query)) {+ const logic = dataNodeLogic.findMounted({ key: props.queryKey })+ logic?.actions.abortAnyRunningQuery()+ logic?.actions.clearResponse()+ dataNodeLogic(dataProps(props))+ }+ }),+])