: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): configure overview metrics by source (#120738)
Javier Bahamondesa87364a25a59
diff --git a/docs/internal/marketing-source-suggestions.md b/docs/internal/marketing-source-suggestions.mdindex 63f6e873f20a..71acfa741018 100644--- a/docs/internal/marketing-source-suggestions.md+++ b/docs/internal/marketing-source-suggestions.md@@ -317,3 +317,11 @@ Advertising metrics appear first, followed by attributed conversion goals and thThe 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.++The Ad performance summary groups metrics by source: Ad platforms contains platform-reported metrics, and PostHog contains configured conversion goals and their costs.+Configure metrics uses the same apply-and-cancel interaction as Configure columns.+It lets users show or hide individual metrics, show or hide an entire group, and reorder metrics within each group with the move buttons.+Each group can also collapse without changing which metrics are selected.+The summary saves visibility, order, and collapsed groups in browser storage per project and view, matching table column preferences.+These preferences survive reloads in the same browser; they do not change table columns or the underlying queries.+New metrics appear by default, and removed goals do not leave empty cards.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 799e106c3b57..7f6f29455b1e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6101,9 +6101,9 @@ snapshots:logs-logsretentionperiodpicker--stored-custom-months-without-paid-retention--light:hash: v1.k794b7964.d8d79824779beb9150246c932e4f2b756133d02aca4ca269271b98d0e9082480.PCD7I0jw8Fis5NRmUgRrjvUpwz5Dap-BO1UKMSJu5Nsmarketing-analytics-ad-performance-metric-trends--with-trends--dark:- hash: v1.k794b7964.9a2823d7597aac44d396018c51abba4545f3079ea859dc75855cb064add75317.2DtYQx5epqWzQwQS5oFiY-QYBMVzZoDVZZbr7SPYrsk+ hash: v1.k794b7964.dfa096290705324753b56f63068257a9875f10125aa777cda272cffaa86b5c4f.eqGAlHkICs4Y5x7wocKsE7IByxstJbRvm4Yb1fJDQmQmarketing-analytics-ad-performance-metric-trends--with-trends--light:- hash: v1.k794b7964.2f4ccaa52f1dac23d7792a6c737b167c3327c76418e35ae15289353f90d3010d.fL2tqTuwK5Zjhq1FOUJkaXAnBHs6qKnexB-SWPfu7rM+ hash: v1.k794b7964.3e0398f0acb61e12fb183a61e6338a49a605c17d42287c9d760ce23458b35d2f.SP6aOetry9kQ6UBRFyUfSucVciwQR6ByWMbmPqsx-AAmarketing-analytics-add-source--dismissed-everywhere--dark:hash: v1.k794b7964.f23fe271dbeafe8d745237090a5a115e167653cdb000e74a3245efd986450ff0.ymRCgme2xTcwSDlK8Mjxj_zM6bDHbYjLGl0ncGYQfuomarketing-analytics-add-source--dismissed-everywhere--light:@@ -13110,6 +13110,34 @@ snapshots:hash: v1.k794b7964.f9b440217e994a034cd41b83c7ce116d3f80c8ffe0a713e478f571d6d3a17523.nVNlflYTiAcXYQ-MYXqFWg3XELCQxOiOIbqp-I6G8pEscenes-app-marketing-analytics-metric-cells--clickable-and-static--light:hash: v1.k794b7964.a35385e9aafb9d78b1b0ef339b1e0979599718ff4678ebab9301a12e68851ac5.ZT4_n2eit5rOyZqjI8giGDt-iTrI3v2ZJSZ8KKQe6A8+ scenes-app-marketing-analytics-overview-metrics--configure-metrics--dark:+ hash: v1.k794b7964.a6e78781d7493784c219218b6db8183ea4f1b50b15b7391ffdcfc15aba8cb439.7LaxkPhlKmMeBZ9k_l_outdUYHuSYfBJX96HHYIPstA+ scenes-app-marketing-analytics-overview-metrics--configure-metrics--light:+ hash: v1.k794b7964.ea4c6b22b24f1b99cfa72598b5bc161e2be9cfb393896890aac0a06a5328c148.6-xO2UKb7W6Bzi5gqN9QOkgAl8PHfZofd1GiEH-MbFc+ scenes-app-marketing-analytics-overview-metrics--configure-metrics-narrow--dark:+ hash: v1.k794b7964.70483d5d7d326ec8cfc64c523f3f91ef23f148fdeda7766b0cb6eeae1b15a395.HojBAGczqULEpl-F0tvuq9n7t1b0uZfqg27rTmHYDP8+ scenes-app-marketing-analytics-overview-metrics--configure-metrics-narrow--light:+ hash: v1.k794b7964.6352b6fb1a31b9ff11e587c958372e79b4b5dc97f8e69b6a97700f1cf0f49817.3q--NBYz1H-Evs4frTCnLVvMOub0DG-5mUGTmN_U8yk+ scenes-app-marketing-analytics-overview-metrics--configure-metrics-with-changes--dark:+ hash: v1.k794b7964.c4ed3c178467cd9895d729f6e3f9dab22e383bcd58bbde2e1e6524bb97b9ad52.hoj-T9GIfK6zBo9aCWyxC8GWaGDYs-CL2QYwY1JBg-0+ scenes-app-marketing-analytics-overview-metrics--configure-metrics-with-changes--light:+ hash: v1.k794b7964.d40d71594f50a072d6dc241ed0e5910a5d96eb46d72d6242f9b1bf0b3b365d97.1NeHWIBODUcgGp4ieGAX34BNb8pNE-WUhdMs5lntXps+ scenes-app-marketing-analytics-overview-metrics--default--dark:+ hash: v1.k794b7964.de5dcad47f39b08ed1e3534154c1e4023d307d61b672f8431d9555741638eb80.2AY2eK7kh_PqqTdMlhQFboVLIh8TJtNNHer9urA9BPM+ scenes-app-marketing-analytics-overview-metrics--default--light:+ hash: v1.k794b7964.dea58d08440358b79037ddb62e38e4a181c0c2e1c12c2aa88c23e417ee784845.2BkdhNxyNP4MtuM89cLyjxY99JAGi6bfxMYyrWww3Z0+ scenes-app-marketing-analytics-overview-metrics--loading--dark:+ hash: v1.k794b7964.56c6f2db7be4e1ad9ca9020f8b4321d2a61eb3fdc1fe61b28d31999ca2e8c86e.JPF_UHfiToTpFgwpzir00n4evZe_oNmwVrPPrAN_TGY+ scenes-app-marketing-analytics-overview-metrics--loading--light:+ hash: v1.k794b7964.a19f03532e741569858d5406d3a4f3d6916a4b0038caa08906094679c356df9a.AXxrzuS9tZJ0gd4RREaa0GQjzoLT-pnGXHKWGSoAAZA+ scenes-app-marketing-analytics-overview-metrics--narrow--dark:+ hash: v1.k794b7964.de5dcad47f39b08ed1e3534154c1e4023d307d61b672f8431d9555741638eb80.5xvHhVsIPCwqzRWOH3afae9SYBKaVLACfPwTOYmzCtg+ scenes-app-marketing-analytics-overview-metrics--narrow--light:+ hash: v1.k794b7964.dea58d08440358b79037ddb62e38e4a181c0c2e1c12c2aa88c23e417ee784845.0idqdkAK6ujddcW1IYlpxtVCl5JzISGzrUSa3MjmFCU+ scenes-app-marketing-analytics-overview-metrics--without-goals--dark:+ hash: v1.k794b7964.a85de6f5dc1e52aa6c67797fffc87ee309c967c19bee78c1eb663627396760e0.x1bR-dxut9QApqtZDM2sBHB72BVtAafzS-r6Y8p-SX4+ scenes-app-marketing-analytics-overview-metrics--without-goals--light:+ hash: v1.k794b7964.f6f339d9349e40b9e5836adb5cd39ef6f8ae83aa8a14ca1bee61e83aa513e4d8.FrbhauwQ8rm3ttqi5SjV7kVz3o_tWF8D_f6msUsOruAscenes-app-marketing-analytics-persisted-conversion-recommendations--consent-required--dark:hash: v1.k794b7964.6b518ef694d9645756f342b734cb8071e6af9fe37119cb2aae995e0e2a5b7bf6.sCvbdJpyNHb_e-zZjs5UpzayGBCoE406ha2RYy-VIw0scenes-app-marketing-analytics-persisted-conversion-recommendations--consent-required--light:@@ -13187,9 +13215,9 @@ snapshots:scenes-app-marketing-analytics-search-performance--landing-pages--light:hash: v1.k794b7964.168de9991a12f9fae2674e4dd8656d7592124e7ccd94d961a02146a8bdb15fb4.t3SCmE8mTnC3UdVi35t_SQgQDxKsNr7uN38XUsOHyYkscenes-app-marketing-analytics-search-performance--legacy-scene--dark:- hash: v1.k794b7964.302d6b9da5ad7665c1cfc1fdb728dc100351f3b6b916cb5b4a8028b91e5d9696.ufd0wIU9RXJKboMt25FPArU6h7e2TxRLng2n6q6c5tk+ hash: v1.k794b7964.7b0c55bef8dfaac42b50b130b297bef3891085c4d66ee1c7ffcb50224a27f8f0._VNoZlIWIOKCQUyki6rytQP5OlHtGQv89uSGGzMxNngscenes-app-marketing-analytics-search-performance--legacy-scene--light:- hash: v1.k794b7964.2b2cbd533ef872f9909f2f541ea04ab314c3b3e92be64b0efd9ec78ef59d6c5b._S37M0wcszlCSINuohn69n_szKX55e2qzDD6RPyx45M+ hash: v1.k794b7964.2b671c96efa294edb6940a97640240820fee25aaec0abfd10b8ce0536491f735.0u14hvowv9SXKzxDPXPYL2nB7-OAcqOAZeY0JnzEdLUscenes-app-marketing-analytics-search-performance--loading--dark:hash: v1.k794b7964.c2efa78ddd96c45aa10bd5e6c4682aa0cafac243622b3ba0c37166506647549e.KixqIty9DjPGkbstbuoo84SKVhjZA3joqVmIayL9Ahcscenes-app-marketing-analytics-search-performance--loading--light:@@ -13207,13 +13235,13 @@ snapshots:scenes-app-marketing-analytics-search-performance--narrow-position-metrics--light:hash: v1.k794b7964.1a5b05437a85b339fe72012a2e8b7ecf9343ad3d58be8f1df756b4874c49f77b.4K1otf3N65qp57kfTlUdWIGPtzS-__ZIjG_GBuqKaBsscenes-app-marketing-analytics-search-performance--new-dashboard-flag-off--dark:- hash: v1.k794b7964.7adfc0ee89093703b8e923935870475615161314419fa409f03a59f9de5ec90b.6AeZyZLr78BXMkf-QvQSLQv7xF5-EpIyAwQSVD55YG4+ hash: v1.k794b7964.b5396b32369d9e930e3db3dcd3f7e87bfbe9e813c815be0819b4a6b3f90ae63e.-n0OMQJZ2BHjrGTarQVkOln7dl6v1tLs81vsnimxTlcscenes-app-marketing-analytics-search-performance--new-dashboard-flag-off--light:- hash: v1.k794b7964.2502d21dc38a51fef502b7ef452df680896462b29284847d1d107a7c0daf8727.nDQD9ooWp2VeSndPJnTKI4DVAZY5WNbdi41Y_vSBqYM+ hash: v1.k794b7964.8fcb2ab7cbfb8600fb7b1e8484440128366c693dccf8acd1b35bc5f41ba84f0f.XFossOxDeskeQzkA-9uZqNp-B3Q49RghdBcMzvlKRE0scenes-app-marketing-analytics-search-performance--new-dashboard-scene--dark:- hash: v1.k794b7964.e99aaa5f1a121f120f1020538a2d3e4c9e59669f372d4ccc9362e10bbff03c39.pZ6M8QnH52HEj3C0p2Qp9nOM4w6z4fNNl2YzO42ikIw+ hash: v1.k794b7964.4da66e231e98d43143ae46e365cd9a6f263cd8c5ce608d3bb6f778d46623401a.GNeBOxV_q7f9apUzeDNxgQ9CEFXnmt2r-IapMDJGAeEscenes-app-marketing-analytics-search-performance--new-dashboard-scene--light:- hash: v1.k794b7964.7476e7f828a2ba455f442c024ce8345505f93dc23cec37856ad496b2bdd90bf1.4D_UJ7cO3gVqgW9w8Ys7bvCOm-qIZsT2fnMlx2ONX40+ hash: v1.k794b7964.d39c6ba1f1bc86ad0d33172b602cc7a0858666418e982d990b7b66e24bf42c1f.aHzF7Z1mI2cphlNtMzG-KbqAGgsNbWjg6S8bs2PtJP4scenes-app-marketing-analytics-search-performance--not-connected--dark:hash: v1.k794b7964.fc45f91fd10720c94e64d84bd64d043e472d35c7be2a2c813f98a627fbbd93be.OvmqVf3mYSyJ_wXsOKvp-LWwhymTTD6MbSikTmLg564scenes-app-marketing-analytics-search-performance--not-connected--light:@@ -13291,9 +13319,9 @@ snapshots:scenes-app-marketing-analytics-search-performance--wrapped-landing-pages-narrow--light:hash: v1.k794b7964.bc7e930ff65d3898a309bf63b7dedafb78c498d14e2ddbce421ce701b4114b19.4vEUxz-8PhpNNO7we_L1k3W-USCIj0sfcsCjdEL3Um4scenes-app-marketing-analytics-source-onboarding--ad-performance-data-available--dark:- hash: v1.k794b7964.8e7b5a5e0a0ea5c4b51e2b2de1ebb19b6ee9762442a2f80d50c5c11af7cb41c0.dmy1asCAzzn280lIIWPJvtDeGwXCTFYU5uwBXm1Qeh8+ hash: v1.k794b7964.52d793e434ed135a17252c76b796cc7f059342600f7ea6c95241ab76669a2441.FveMgmXg9otKomgnoJbhm7TP1HJyln_odWNWqALJEiwscenes-app-marketing-analytics-source-onboarding--ad-performance-data-available--light:- hash: v1.k794b7964.6bef64a6d0e91622b0d11695fec4f71b01da8419f4a3109f71dd3a37258e3e61.ox4QhyCUW4hnC6Vc2tvLKNaV8rXni64SX-zmOdeLiwE+ hash: v1.k794b7964.084136bef3ef1ca7cd84e82e155ea25033ea5d8781c2c621ea0514db76997906._GLmWqtmpM-aIOjRxbQgAga4eBMqP0fz8_fBMmKX47Escenes-app-marketing-analytics-source-onboarding--ad-performance-with-detected-sources--dark:hash: v1.k794b7964.86e93f2243024c677ca7b0a2ba4e18e8bb164e1f172ecbd43f92f2a5359f0b9c.j492cCtgKRxf5KtvFw8hCZ_PSqqJeS_uLhwoq91xpScscenes-app-marketing-analytics-source-onboarding--ad-performance-with-detected-sources--light:@@ -13323,13 +13351,13 @@ snapshots:scenes-app-marketing-analytics-source-onboarding--dashboard-scanning-with-search-console--light:hash: v1.k794b7964.96925f009594f797806c47cbc799946341b4e4800844baacef5f8951ad434cf9.P_bQfBSfYVpIeEPw6WGMqzloDECX40vH57tb3fvuPxMscenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-and-search-console--dark:- hash: v1.k794b7964.47b1850977208b98c470e7f154f58de2abb7e29e7361ac377fa8a97b97aa457f.Xm_oYIE0TxXRbMVnTBal6KpOIpt3sEKKnqC3aaFrczY+ hash: v1.k794b7964.a8368267f7ff5b455100231b3a5770bf6f66cdf8ca5bbe4ec9e1664aebab9210.18-g90ixUzMnIiIvHSKBjwgXT2uq9XHnqbKMS67BvZ8scenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-and-search-console--light:- hash: v1.k794b7964.e9528a39aecc7609eda45c52c082ed365bd0d01b104c53f57dbebf15eefe3a65.fKwEvw-_Vb5DT4Q2Umg6nt8C2-QcaqJFt4-UvzoIn54+ hash: v1.k794b7964.f79a729f6adf2bdabd4f0a62cafff98880723cd7127286d2328e52e66db952c0.MevTv3vBQt56cn3xsroM4l4-DZHPAS7bR38wS_BgdBMscenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-only--dark:- hash: v1.k794b7964.38254c72b3d34460b427657ab1a323d0c126f47481faafd5d3e3c2e754ec0b08.LVei2svqlTFhMY1GTRCUXAHi7VJzjATpvGMDwig7Amk+ hash: v1.k794b7964.93c6207b96686bf692667460595ec4f5f192510ea440bf2ce5dfb7c7e7e96ece.PXzw3mMXCPjgU8UD7rL4O_oU2TLlWoExmq-HMalNPSwscenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-only--light:- hash: v1.k794b7964.14376a3211c2e9d502f090404ee8bb3d8b2f12faa11fd8a74aab63c5a85a40c7.Or5G3_1QBdlt08fORsuLGYWV0C65cBFrZXZh4pZ9b60+ hash: v1.k794b7964.b000e0bdbf58908e885760cbd2193ebf7bc0af5d3c227dbfff89d47e0e37e5d4.6rIxgkPccXr32_WjurrJPlMhoCk0Daq29iTUp4VAL3Uscenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-syncing-without-search-console--dark:hash: v1.k794b7964.bfa13529bdb940ef1cd344b2bf11c58522804280d0e0dd141008411660a53505.ApfEsWw3lxynpDaRYL_pRTblq_-Yucp5d6hwOFDmY9kscenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-syncing-without-search-console--light: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 1865ec87c4e0..d02d3ead88b2 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@@ -6,7 +6,7 @@ import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { InsightErrorState } from 'scenes/insights/EmptyStates'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'-import { OverviewMetricCardGrid, OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'+import { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'import {AnyResponseType,MarketingAnalyticsAggregatedQuery,@@ -17,6 +17,7 @@ import { MarketingAnalyticsNotReady } from '~/scenes/marketing-analytics/Marketiimport { adPerformanceMetricKey } from 'products/marketing_analytics/frontend/adPerformanceMetrics'import { adPerformanceTrendsLogic } from 'products/marketing_analytics/frontend/adPerformanceTrendsLogic'+import { AdPerformanceOverviewMetrics } from 'products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics'import { marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'import { marketingAnalyticsSettingsLogic } from '../../logic/marketingAnalyticsSettingsLogic'@@ -113,28 +114,15 @@ export function MarketingAnalyticsOverview(props: {return (<>{allWarnings.length > 0 && <MarketingAnalyticsValidationWarningBanner warnings={allWarnings} />}- <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>+ <AdPerformanceOverviewMetrics+ viewKey={dataNodeCollectionId ?? MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID}+ items={overviewItems.filter(filterEmptyMetrics)}+ loading={responseLoading}+ numSkeletons={numSkeletons}+ samplingRate={samplingRate}+ sparklineTheme={sparklineTheme}+ labelFromKey={(key) => <span className="[overflow-wrap:anywhere]">{labelFromKey(key)}</span>}+ /></>)}diff --git a/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.stories.tsx b/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.stories.tsxnew file mode 100644index 000000000000..4129c110b54d--- /dev/null+++ b/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.stories.tsx@@ -0,0 +1,126 @@+import type { Meta, StoryObj } from '@storybook/react'+import { waitFor, within } from '@testing-library/dom'++import type { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'++import { expect, userEvent } from 'storybook/test'++import { AdPerformanceOverviewMetrics } from './AdPerformanceOverviewMetrics'++const items: OverviewMetricCardItem[] = [+ { key: 'Cost', value: 1800, previous: 1500, changeFromPreviousPct: 20, kind: 'currency', isIncreaseBad: true },+ { key: 'Clicks', value: 4200, previous: 3500, changeFromPreviousPct: 20, kind: 'unit' },+ { key: 'Impressions', value: 90000, previous: 75000, changeFromPreviousPct: 20, kind: 'unit' },+ { key: 'Reported Conversions', value: 60, previous: 50, changeFromPreviousPct: 20, kind: 'unit' },+ { key: 'Reported Conversion Value', value: 3600, previous: 3000, changeFromPreviousPct: 20, kind: 'currency' },+ { key: 'CPC', value: 0.43, previous: 0.43, changeFromPreviousPct: 0, kind: 'currency', isIncreaseBad: true },+ { key: 'CTR', value: 4.67, previous: 4.67, changeFromPreviousPct: 0, kind: 'percentage' },+ {+ key: 'Cost per Reported Conversions',+ value: 30,+ previous: 30,+ changeFromPreviousPct: 0,+ kind: 'currency',+ isIncreaseBad: true,+ },+ { key: 'Reported ROAS', value: 2, previous: 2, changeFromPreviousPct: 0, kind: 'unit' },+ { key: 'Trial started', value: 80, previous: 64, changeFromPreviousPct: 25, kind: 'unit' },+ {+ key: 'Cost Per Trial started',+ value: 22.5,+ previous: 23.44,+ changeFromPreviousPct: -4,+ kind: 'currency',+ isIncreaseBad: true,+ },+ { key: 'Subscription started', value: 20, previous: 16, changeFromPreviousPct: 25, kind: 'unit' },+ {+ key: 'Cost Per Subscription started',+ value: 90,+ previous: 93.75,+ changeFromPreviousPct: -4,+ kind: 'currency',+ isIncreaseBad: true,+ },+]++const meta: Meta<typeof AdPerformanceOverviewMetrics> = {+ title: 'Scenes-App/Marketing Analytics/Overview metrics',+ component: AdPerformanceOverviewMetrics,+ parameters: { layout: 'padded' },+ args: { items, loading: false, numSkeletons: 13, viewKey: 'overview-metrics-story', labelFromKey: (key) => key },+}+export default meta++type Story = StoryObj<typeof AdPerformanceOverviewMetrics>++export const Default: Story = {}++export const Narrow: Story = {+ args: { viewKey: 'overview-metrics-narrow-story' },+ decorators: [+ (Story) => (+ <div className="max-w-lg">+ <Story />+ </div>+ ),+ ],+}++export const Loading: Story = {+ args: { viewKey: 'overview-metrics-loading-story', items: [], loading: true },+ parameters: { testOptions: { waitForLoadersToDisappear: false } },+}++export const WithoutGoals: Story = {+ args: { viewKey: 'overview-metrics-no-goals-story', items: items.slice(0, 9) },+}++export const ConfigureMetrics: Story = {+ args: { viewKey: 'overview-metrics-configure-story' },+ play: async ({ canvasElement }) => {+ await userEvent.click(await within(canvasElement).findByRole('button', { name: 'Configure metrics' }))+ await waitFor(() => expect(within(canvasElement.ownerDocument.body).getByRole('dialog')).toBeVisible())+ },+ parameters: {+ testOptions: {+ waitForSelector: '.LemonModal.ReactModal__Content--after-open',+ snapshotTargetSelector: '.LemonModal',+ },+ },+}++export const ConfigureMetricsNarrow: Story = {+ ...ConfigureMetrics,+ args: { viewKey: 'overview-metrics-configure-narrow-story' },+ parameters: {+ testOptions: {+ viewport: { width: 520, height: 1024 },+ waitForSelector: '.LemonModal.ReactModal__Content--after-open',+ snapshotTargetSelector: '.LemonModal',+ },+ },+}++export const ConfigureMetricsWithChanges: Story = {+ ...ConfigureMetrics,+ args: { viewKey: 'overview-metrics-configure-changes-story' },+ play: async (context) => {+ await ConfigureMetrics.play!(context)+ const dialog = within(context.canvasElement.ownerDocument.body).getByRole('dialog')+ await userEvent.click(within(dialog).getByRole('button', { name: 'Move Clicks up' }))+ await userEvent.click(within(dialog).getByText('Impressions', { exact: true }))+ await userEvent.click(+ within(within(dialog).getByRole('region', { name: 'PostHog' })).getByRole('button', {+ name: 'Hide all',+ })+ )+ const applyButton = within(dialog).getByRole('button', { name: 'Apply' })+ await expect(applyButton).toBeEnabled()+ const content = dialog.querySelector<HTMLElement>('.LemonModal__content')!+ // The last interaction focuses a control below the fold and scrolls the modal.+ ;(dialog.ownerDocument.activeElement as HTMLElement | null)?.blur()+ content.scrollTo({ top: 0, behavior: 'instant' })+ await waitFor(() => expect(content.scrollTop).toBe(0))+ },+}diff --git a/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.tsx b/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.tsxnew file mode 100644index 000000000000..2936dd0d6d77--- /dev/null+++ b/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.tsx@@ -0,0 +1,112 @@+import { useActions, useValues } from 'kea'++import { IconChevronDown, IconChevronRight, IconGear } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'+import type { ChartTheme } from '@posthog/quill-charts'++import { SamplingNotice, SamplingRate } from '~/queries/nodes/OverviewGrid/OverviewGrid'+import { OverviewMetricCardGrid, OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'++import { OverviewMetricConfigModal } from './OverviewMetricConfigModal'+import { OVERVIEW_METRIC_GROUPS, overviewMetricsForGroup } from './overviewMetricConfiguration'+import { overviewMetricsLogic } from './overviewMetricsLogic'++export interface AdPerformanceOverviewMetricsProps {+ items: OverviewMetricCardItem[]+ loading: boolean+ numSkeletons: number+ samplingRate?: SamplingRate+ sparklineTheme?: ChartTheme+ labelFromKey: (key: string) => React.ReactNode+ viewKey: string+}++export function AdPerformanceOverviewMetrics({+ items,+ loading,+ numSkeletons,+ samplingRate,+ sparklineTheme,+ labelFromKey,+ viewKey,+}: AdPerformanceOverviewMetricsProps): JSX.Element {+ const logic = overviewMetricsLogic({ viewKey })+ const { configuration } = useValues(logic)+ const { configureMetrics, setGroupCollapsed } = useActions(logic)++ return (+ <div className="flex flex-col gap-4">+ <div className="flex justify-end">+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconGear />}+ onClick={() => configureMetrics(configuration)}+ disabledReason={loading ? 'Wait for metrics to load' : undefined}+ data-attr="marketing-configure-metrics"+ >+ Configure metrics+ </LemonButton>+ </div>+ {OVERVIEW_METRIC_GROUPS.map(({ key: group, label, description }) => {+ const metrics = overviewMetricsForGroup(items, group, configuration)+ const visibleMetrics = metrics.filter((item) => !configuration[group].hidden.includes(item.key))+ const collapsed = configuration[group].collapsed+ return (+ <section key={group} aria-label={label}>+ <div className="mb-2 flex flex-wrap items-center gap-x-3 gap-y-1">+ <LemonButton+ size="small"+ icon={collapsed ? <IconChevronRight /> : <IconChevronDown />}+ onClick={() => setGroupCollapsed(group, !collapsed)}+ aria-expanded={!collapsed}+ aria-controls={`${viewKey}-${group}-metrics`}+ data-attr={`marketing-metrics-toggle-${group}`}+ >+ {label}+ </LemonButton>+ <span className="text-xs text-secondary">{description}</span>+ {!loading && (+ <span className="text-xs text-secondary">+ {visibleMetrics.length} / {metrics.length}+ </span>+ )}+ </div>+ <div id={`${viewKey}-${group}-metrics`} hidden={collapsed}>+ {loading || visibleMetrics.length > 0 ? (+ <OverviewMetricCardGrid+ sparklineTheme={sparklineTheme}+ className="grid-cols-[repeat(auto-fit,minmax(12rem,1fr))]"+ items={visibleMetrics}+ loading={loading}+ numSkeletons={+ group === 'platforms'+ ? Math.min(numSkeletons, 9)+ : Math.max(numSkeletons - 9, 2)+ }+ emptyMessage="-"+ labelFromKey={labelFromKey}+ />+ ) : (+ <div className="flex flex-wrap items-center gap-2 py-2 text-sm text-secondary">+ <span>+ {metrics.length+ ? 'All metrics in this group are hidden.'+ : 'No metrics available for this group.'}+ </span>+ {metrics.length > 0 && (+ <LemonButton size="small" onClick={() => configureMetrics(configuration)}>+ Choose metrics+ </LemonButton>+ )}+ </div>+ )}+ </div>+ </section>+ )+ })}+ <SamplingNotice samplingRate={samplingRate} />+ <OverviewMetricConfigModal items={items} viewKey={viewKey} />+ </div>+ )+}diff --git a/products/marketing_analytics/frontend/overview/OverviewMetricConfigModal.tsx b/products/marketing_analytics/frontend/overview/OverviewMetricConfigModal.tsxnew file mode 100644index 000000000000..3acf1287c5d0--- /dev/null+++ b/products/marketing_analytics/frontend/overview/OverviewMetricConfigModal.tsx@@ -0,0 +1,141 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonCheckbox, LemonModal } from '@posthog/lemon-ui'++import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'++import type { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'++import { OVERVIEW_METRIC_GROUPS, overviewMetricsForGroup } from './overviewMetricConfiguration'+import { overviewMetricsLogic } from './overviewMetricsLogic'++export function OverviewMetricConfigModal({+ items,+ viewKey,+}: {+ items: OverviewMetricCardItem[]+ viewKey: string+}): JSX.Element {+ const logic = overviewMetricsLogic({ viewKey })+ const { configuration, draftConfiguration } = useValues(logic)+ const { closeConfiguration, applyConfiguration, updateDraftGroup, resetDraft } = useActions(logic)++ return (+ <LemonModal+ title="Configure metrics"+ isOpen={!!draftConfiguration}+ onClose={closeConfiguration}+ width={600}+ footer={+ <div className="flex w-full flex-wrap items-center justify-between gap-2">+ <LemonButton type="secondary" onClick={resetDraft} data-attr="marketing-metrics-reset">+ Reset to defaults+ </LemonButton>+ <div className="flex gap-2">+ <LemonButton type="secondary" onClick={closeConfiguration}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ onClick={() => draftConfiguration && applyConfiguration(draftConfiguration)}+ disabledReason={+ JSON.stringify(configuration) === JSON.stringify(draftConfiguration)+ ? 'No changes to apply'+ : undefined+ }+ data-attr="marketing-metrics-apply"+ >+ Apply+ </LemonButton>+ </div>+ </div>+ }+ >+ <p className="text-secondary">+ Choose which metrics appear in this summary and change their order. Table columns stay unchanged.+ </p>+ <div className="flex flex-col gap-6">+ {draftConfiguration &&+ OVERVIEW_METRIC_GROUPS.map(({ key: group, label }) => {+ const metrics = overviewMetricsForGroup(items, group, draftConfiguration)+ const { hidden } = draftConfiguration[group]+ return (+ <section key={group} aria-label={label}>+ <div className="mb-2 flex flex-wrap items-center justify-between gap-2">+ <h4 className="m-0">{label}</h4>+ <div className="flex gap-1">+ <LemonButton+ size="small"+ onClick={() => updateDraftGroup(group, { hidden: [] })}+ disabledReason={!hidden.length ? 'All metrics are visible' : undefined}+ >+ Show all+ </LemonButton>+ <LemonButton+ size="small"+ onClick={() =>+ updateDraftGroup(group, {+ hidden: [+ ...new Set([...hidden, ...metrics.map((item) => item.key)]),+ ],+ })+ }+ disabledReason={+ metrics.every((item) => hidden.includes(item.key))+ ? 'All metrics are hidden'+ : undefined+ }+ >+ Hide all+ </LemonButton>+ </div>+ </div>+ {metrics.length === 0 ? (+ <p className="text-secondary">No metrics available for this group.</p>+ ) : (+ metrics.map((item, index) => (+ <div key={item.key} className="flex items-center gap-2 border-b py-2">+ <LemonCheckbox+ className="min-w-0 flex-1"+ checked={!hidden.includes(item.key)}+ label={<span className="break-words">{item.key}</span>}+ onChange={(checked) =>+ updateDraftGroup(group, {+ hidden: checked+ ? hidden.filter((key) => key !== item.key)+ : [...hidden, item.key],+ })+ }+ />+ {([-1, 1] as const).map((direction) => (+ <LemonButton+ key={direction}+ size="small"+ icon={direction === -1 ? <IconArrowUp /> : <IconArrowDown />}+ aria-label={`Move ${item.key} ${direction === -1 ? 'up' : 'down'}`}+ tooltip={direction === -1 ? 'Move up' : 'Move down'}+ disabledReason={+ (direction === -1 ? index === 0 : index === metrics.length - 1)+ ? 'Already at the end'+ : undefined+ }+ onClick={() => {+ const order = metrics.map((metric) => metric.key)+ ;[order[index], order[index + direction]] = [+ order[index + direction],+ order[index],+ ]+ updateDraftGroup(group, { order })+ }}+ />+ ))}+ </div>+ ))+ )}+ </section>+ )+ })}+ </div>+ </LemonModal>+ )+}diff --git a/products/marketing_analytics/frontend/overview/overviewMetricConfiguration.ts b/products/marketing_analytics/frontend/overview/overviewMetricConfiguration.tsnew file mode 100644index 000000000000..1ee1aa53d38a--- /dev/null+++ b/products/marketing_analytics/frontend/overview/overviewMetricConfiguration.ts@@ -0,0 +1,39 @@+import type { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'++import { adPerformanceMetricKey } from '../adPerformanceMetrics'++export type OverviewMetricGroup = 'platforms' | 'posthog'++export interface OverviewMetricGroupConfiguration {+ hidden: string[]+ order: string[]+ collapsed: boolean+}++export type OverviewMetricConfiguration = Record<OverviewMetricGroup, OverviewMetricGroupConfiguration>++export const OVERVIEW_METRIC_GROUPS: { key: OverviewMetricGroup; label: string; description: string }[] = [+ { key: 'platforms', label: 'Ad platforms', description: 'Metrics reported by your connected ad platforms' },+ { key: 'posthog', label: 'PostHog', description: 'Your conversion goals and cost per result' },+]++export function defaultOverviewMetricConfiguration(): OverviewMetricConfiguration {+ return {+ platforms: { hidden: [], order: [], collapsed: false },+ posthog: { hidden: [], order: [], collapsed: false },+ }+}++export function overviewMetricsForGroup(+ items: OverviewMetricCardItem[],+ group: OverviewMetricGroup,+ configuration: OverviewMetricConfiguration+): OverviewMetricCardItem[] {+ const metrics = items.filter((item) => !!adPerformanceMetricKey(item.key) === (group === 'platforms'))+ const byKey = new Map(metrics.map((item) => [item.key, item]))+ const keys = [...new Set([...configuration[group].order, ...metrics.map((item) => item.key)])]+ return keys.flatMap((key) => {+ const item = byKey.get(key)+ return item ? [item] : []+ })+}diff --git a/products/marketing_analytics/frontend/overview/overviewMetricsLogic.test.ts b/products/marketing_analytics/frontend/overview/overviewMetricsLogic.test.tsnew file mode 100644index 000000000000..8b3fc19fc0b7--- /dev/null+++ b/products/marketing_analytics/frontend/overview/overviewMetricsLogic.test.ts@@ -0,0 +1,85 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'++import type { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'+import { initKeaTests } from '~/test/init'++import { defaultOverviewMetricConfiguration, overviewMetricsForGroup } from './overviewMetricConfiguration'+import { overviewMetricsLogic } from './overviewMetricsLogic'++const items: OverviewMetricCardItem[] = [+ { key: 'Cost', value: 100, kind: 'currency' },+ { key: 'Clicks', value: 200, kind: 'unit' },+ { key: 'Trial started', value: 20, kind: 'unit' },+ { key: 'Cost Per Trial started', value: 5, kind: 'currency' },+]++describe('overview metric configuration', () => {+ beforeEach(() => {+ localStorage.clear()+ initKeaTests()+ })++ it('discards canceled edits and persists applied visibility, order, and collapsed groups for the view', () => {+ const logic = overviewMetricsLogic({ viewKey: 'ad-performance' })+ const unmount = logic.mount()+ logic.actions.configureMetrics(logic.values.configuration)+ logic.actions.updateDraftGroup('platforms', { hidden: ['Cost'], order: ['Clicks', 'Cost'] })+ expect(logic.values.configuration.platforms.hidden).toEqual([])+ logic.actions.closeConfiguration()+ expect(logic.values.configuration.platforms.hidden).toEqual([])+ logic.actions.configureMetrics(logic.values.configuration)+ logic.actions.updateDraftGroup('platforms', { hidden: ['Cost'], order: ['Clicks', 'Cost'] })+ logic.actions.applyConfiguration(logic.values.draftConfiguration!)+ logic.actions.setGroupCollapsed('posthog', true)+ const saved = logic.values.configuration+ unmount()+ const restored = overviewMetricsLogic({ viewKey: 'ad-performance' })+ const unmountRestored = restored.mount()+ expect(restored.values.configuration).toEqual(saved)+ expect(restored.values.draftConfiguration).toBeNull()+ expect(+ JSON.parse(+ localStorage.getItem(+ `${MOCK_TEAM_ID}__.products.marketingAnalytics.overviewMetricsLogic.ad-performance.configuration`+ )!+ )+ ).toEqual(saved)+ const anotherView = overviewMetricsLogic({ viewKey: 'another-view' })+ const unmountOther = anotherView.mount()+ expect(anotherView.values.configuration).toEqual(defaultOverviewMetricConfiguration())+ unmountOther()+ unmountRestored()+ })++ it('keeps platform metrics separate, appends new goals, and drops removed metrics from saved ordering', () => {+ const configuration = defaultOverviewMetricConfiguration()+ configuration.platforms.order = ['Clicks', 'Cost']+ configuration.posthog.order = ['Removed goal', 'Cost Per Trial started', 'Trial started']+ expect(overviewMetricsForGroup(items, 'platforms', configuration).map((item) => item.key)).toEqual([+ 'Clicks',+ 'Cost',+ ])+ expect(+ overviewMetricsForGroup(+ [...items, { key: 'New goal', value: 10, kind: 'unit' }],+ 'posthog',+ configuration+ ).map((item) => item.key)+ ).toEqual(['Cost Per Trial started', 'Trial started', 'New goal'])+ })++ it('resets a saved hidden section without changing it until Apply', () => {+ const logic = overviewMetricsLogic({ viewKey: 'ad-performance' })+ const unmount = logic.mount()+ const configuration = defaultOverviewMetricConfiguration()+ configuration.platforms = { hidden: ['Cost', 'Clicks'], order: ['Clicks', 'Cost'], collapsed: true }+ logic.actions.applyConfiguration(configuration)+ logic.actions.configureMetrics(logic.values.configuration)+ logic.actions.resetDraft()+ expect(logic.values.configuration.platforms.collapsed).toBe(true)+ expect(logic.values.draftConfiguration).toEqual(defaultOverviewMetricConfiguration())+ logic.actions.applyConfiguration(logic.values.draftConfiguration!)+ expect(logic.values.configuration).toEqual(defaultOverviewMetricConfiguration())+ unmount()+ })+})diff --git a/products/marketing_analytics/frontend/overview/overviewMetricsLogic.ts b/products/marketing_analytics/frontend/overview/overviewMetricsLogic.tsnew file mode 100644index 000000000000..891f52d12c21--- /dev/null+++ b/products/marketing_analytics/frontend/overview/overviewMetricsLogic.ts@@ -0,0 +1,85 @@+import { LogicWrapper, MakeLogicType, actions, kea, key, path, props, reducers } from 'kea'++import { buildTeamScopedPersistenceConfig } from 'lib/logic/persistence'++import {+ OverviewMetricConfiguration,+ OverviewMetricGroup,+ OverviewMetricGroupConfiguration,+ defaultOverviewMetricConfiguration,+} from './overviewMetricConfiguration'++export interface OverviewMetricsLogicProps {+ viewKey: string+}++export interface overviewMetricsLogicValues {+ configuration: OverviewMetricConfiguration+ draftConfiguration: OverviewMetricConfiguration | null+}++export interface overviewMetricsLogicActions {+ configureMetrics: (configuration: OverviewMetricConfiguration) => { configuration: OverviewMetricConfiguration }+ closeConfiguration: () => void+ applyConfiguration: (configuration: OverviewMetricConfiguration) => { configuration: OverviewMetricConfiguration }+ updateDraftGroup: (+ group: OverviewMetricGroup,+ configuration: Partial<OverviewMetricGroupConfiguration>+ ) => {+ group: OverviewMetricGroup+ configuration: Partial<OverviewMetricGroupConfiguration>+ }+ resetDraft: () => void+ setGroupCollapsed: (+ group: OverviewMetricGroup,+ collapsed: boolean+ ) => { group: OverviewMetricGroup; collapsed: boolean }+}++export type overviewMetricsLogicType = MakeLogicType<+ overviewMetricsLogicValues,+ overviewMetricsLogicActions,+ OverviewMetricsLogicProps+>++export const overviewMetricsLogic: LogicWrapper<overviewMetricsLogicType> = kea<overviewMetricsLogicType>([+ props({} as OverviewMetricsLogicProps),+ key(({ viewKey }) => viewKey),+ // The path is the storage key for saved metric preferences.+ path((key) => ['products', 'marketingAnalytics', 'overviewMetricsLogic', key]),+ actions({+ configureMetrics: (configuration: OverviewMetricConfiguration) => ({ configuration }),+ closeConfiguration: () => ({}),+ applyConfiguration: (configuration: OverviewMetricConfiguration) => ({ configuration }),+ updateDraftGroup: (group: OverviewMetricGroup, configuration: Partial<OverviewMetricGroupConfiguration>) => ({+ group,+ configuration,+ }),+ resetDraft: () => ({}),+ setGroupCollapsed: (group: OverviewMetricGroup, collapsed: boolean) => ({ group, collapsed }),+ }),+ reducers(() => ({+ configuration: [+ defaultOverviewMetricConfiguration(),+ buildTeamScopedPersistenceConfig(),+ {+ applyConfiguration: (_, { configuration }) => configuration,+ setGroupCollapsed: (state, { group, collapsed }) => ({+ ...state,+ [group]: { ...state[group], collapsed },+ }),+ },+ ],+ draftConfiguration: [+ null as OverviewMetricConfiguration | null,+ {+ configureMetrics: (_, { configuration }) => configuration,+ closeConfiguration: () => null,+ applyConfiguration: () => null,+ resetDraft: () => defaultOverviewMetricConfiguration(),+ updateDraftGroup: (state, { group, configuration }) =>+ state ? { ...state, [group]: { ...state[group], ...configuration } } : state,+ },+ ],+ })),+])