: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): cap top-line metrics at five with source badges (#128214)
Javier Bahamondes100b50865f08
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7462d0dc4830..bdb63e520624 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6155,9 +6155,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.24d5eb856d9b9745bad4059a4269c01b16e25239c6033be37663252800a97918.psaN8cG1tB4lVMdwGoBhVKDgp_p3PzGkApLFtuESfkw+ hash: v1.k794b7964.fae4e1477c3fd7707a76a3cb9488b821b24bde09abd2113553e6a27a2d572e6a.0KdYNfIK6_UrhSZOhBS3Qz_KX4NglEqsw-IgIg-2I5gmarketing-analytics-ad-performance-metric-trends--with-trends--light:- hash: v1.k794b7964.a53ff384171adc6d44f96b69ebd55ace371408737ad3f5ebf89333dc54e34949.wDGCx3ifSu1gRtq0QbzNnZFo7kpHZCDB-0huQA94Ew4+ hash: v1.k794b7964.e5183e736f9c1a38ecc805ede1f96ed2aaa9a2cf84f79391be94204e152f3b2d.GDMpBOQq0M5-aZyePb_2GO4kx70rRUITFM2O7XwmykMmarketing-analytics-add-source--dismissed-everywhere--dark:hash: v1.k794b7964.f23fe271dbeafe8d745237090a5a115e167653cdb000e74a3245efd986450ff0.ymRCgme2xTcwSDlK8Mjxj_zM6bDHbYjLGl0ncGYQfuomarketing-analytics-add-source--dismissed-everywhere--light:@@ -13711,33 +13711,37 @@ snapshots:scenes-app-marketing-analytics-metric-cells--clickable-and-static--light:hash: v1.k794b7964.a35385e9aafb9d78b1b0ef339b1e0979599718ff4678ebab9301a12e68851ac5.ZT4_n2eit5rOyZqjI8giGDt-iTrI3v2ZJSZ8KKQe6A8scenes-app-marketing-analytics-overview-metrics--configure-metrics--dark:- hash: v1.k794b7964.a6e78781d7493784c219218b6db8183ea4f1b50b15b7391ffdcfc15aba8cb439.7LaxkPhlKmMeBZ9k_l_outdUYHuSYfBJX96HHYIPstA+ hash: v1.k794b7964.71003b92fe4ea01176b5781076f0fde3ba0dd3a8b9d6d00d8c34eb528339588d.8HSF71VDglawGPezfF01xhyzUwG4-JUTcksA7yu3nKkscenes-app-marketing-analytics-overview-metrics--configure-metrics--light:- hash: v1.k794b7964.ea4c6b22b24f1b99cfa72598b5bc161e2be9cfb393896890aac0a06a5328c148.6-xO2UKb7W6Bzi5gqN9QOkgAl8PHfZofd1GiEH-MbFc+ hash: v1.k794b7964.2c7fdb693e8e812ceaf4b20cb624eecc662ea632420c96746e2b44b4c70fbbde.QZZjQx1tL2jwWv--RUK-1aNXLnupmL9OH7Zhf5jXs_wscenes-app-marketing-analytics-overview-metrics--configure-metrics-narrow--dark:- hash: v1.k794b7964.70483d5d7d326ec8cfc64c523f3f91ef23f148fdeda7766b0cb6eeae1b15a395.HojBAGczqULEpl-F0tvuq9n7t1b0uZfqg27rTmHYDP8+ hash: v1.k794b7964.e23d1b3a2a3edf2472bb1bfa6796325eeaaf092cb447768d1264fdcee7d47ed7.9VVXv4JBtMjkX6U8F0r8uz0VWuo6RBzWfLrwBkZROB0scenes-app-marketing-analytics-overview-metrics--configure-metrics-narrow--light:- hash: v1.k794b7964.6352b6fb1a31b9ff11e587c958372e79b4b5dc97f8e69b6a97700f1cf0f49817.3q--NBYz1H-Evs4frTCnLVvMOub0DG-5mUGTmN_U8yk+ hash: v1.k794b7964.cf335222aaae00b8cb1a3c4d6a1c22442ba718e17231971eab2a766e20d6ab55.kGT0OpbCGERNQjUm9iTXQaL16CrMDSdCcYFS1lkh7eUscenes-app-marketing-analytics-overview-metrics--configure-metrics-with-changes--dark:- hash: v1.k794b7964.c4ed3c178467cd9895d729f6e3f9dab22e383bcd58bbde2e1e6524bb97b9ad52.hoj-T9GIfK6zBo9aCWyxC8GWaGDYs-CL2QYwY1JBg-0+ hash: v1.k794b7964.11157882382d2aba7a539f55143c3a1201df92ac36b8e0b3850fad9a73c15f16.oGyc1RLkmzR_IQ0djkWb2hBr_V0eUHHr9OR8Ygd_Dxkscenes-app-marketing-analytics-overview-metrics--configure-metrics-with-changes--light:- hash: v1.k794b7964.d40d71594f50a072d6dc241ed0e5910a5d96eb46d72d6242f9b1bf0b3b365d97.1NeHWIBODUcgGp4ieGAX34BNb8pNE-WUhdMs5lntXps+ hash: v1.k794b7964.941a341065082992f359d889102a7fea2a4597e5ffa7745f5998c207de38bb08.Deye8XZ-_dM4rB6CvzqwsukOwq_FPgjV1aeGAHHQNHgscenes-app-marketing-analytics-overview-metrics--default--dark:- hash: v1.k794b7964.4c16198c9c0968153edc7929b07856ead0f03886fb144e5b9faf1c7ccb678b13.8WvH2v3hMOQcNRp8gpaqckqix7LuzpWivVheyThE630+ hash: v1.k794b7964.6f1510349fae3da5fe01d492ff9e5e1f8cd843e13bfad2ab7227fee1b76379da.Bz5BwPJL3l0BhWJMn6aZmqaSCx-5PbhKDqcccrzCR4sscenes-app-marketing-analytics-overview-metrics--default--light:- hash: v1.k794b7964.9abdd5cfb2f2ea6b2cc5bb39019bb2ce807554f4224daaba140b0a5df54e3ba9.r0G8PiDerZJheSS-yZriGCoVwUga9lUFL_a1DFYXMjY+ hash: v1.k794b7964.e6c136adea8f9043bd3472ead9eae1f86084f6e706ef318f1f6f4136d1a3115f.heeF_lpSIYVFBKyk9Fmd9wQAzX8B84GqfeQFl1bsbYEscenes-app-marketing-analytics-overview-metrics--loading--dark:- hash: v1.k794b7964.56c6f2db7be4e1ad9ca9020f8b4321d2a61eb3fdc1fe61b28d31999ca2e8c86e.JPF_UHfiToTpFgwpzir00n4evZe_oNmwVrPPrAN_TGY+ hash: v1.k794b7964.c0fc195faac9abea62b8022427fa685a815429888a1a843ca6f52510c7a4c76f.W3L3h_xh4VlLSCjAI1Q8KyVJPv6VlEmFlYb4SAGZJnwscenes-app-marketing-analytics-overview-metrics--loading--light:- hash: v1.k794b7964.a19f03532e741569858d5406d3a4f3d6916a4b0038caa08906094679c356df9a.AXxrzuS9tZJ0gd4RREaa0GQjzoLT-pnGXHKWGSoAAZA+ hash: v1.k794b7964.2e4e40f55047c539fbc5ea60deb21e29ac97d4291c3549197377d4459fdd8317.o7s6SCE4LnlawnskXwQ3vzcIS82tup17MdGNf9pwnWQ+ scenes-app-marketing-analytics-overview-metrics--medium-width--dark:+ hash: v1.k794b7964.25ae28efc292f7aa92c5cd271cafd38d21884cbc77b0fcbb66cdb8cd3c5ba8c1.YDYgAiaG0Vmrp3u69N7Xi1EAnS92fKjCVVB8bXWzb5A+ scenes-app-marketing-analytics-overview-metrics--medium-width--light:+ hash: v1.k794b7964.a07b602458cffe1283c630ee6f9abaab1ae2ed6536fde6a4417add9c99310b0c._W6Jpfvg412tOOpDwbblvWuQgN301Y-hJY9bxXn4C7Qscenes-app-marketing-analytics-overview-metrics--narrow--dark:- hash: v1.k794b7964.4c16198c9c0968153edc7929b07856ead0f03886fb144e5b9faf1c7ccb678b13.VPHKXOPEObQYPwguk9So2fDchIDi0XhBq_4Unv5DRCo+ hash: v1.k794b7964.b47d6dceeaa780811bca9774f6f45c6b06ea758a6051a832f211ed642355c2e2.mJifOKNNHd_n2ouXQg9l4xXvrP_nDHST9CLc1w8S1P0scenes-app-marketing-analytics-overview-metrics--narrow--light:- hash: v1.k794b7964.9abdd5cfb2f2ea6b2cc5bb39019bb2ce807554f4224daaba140b0a5df54e3ba9.MFKp65pfg2LvHJU8r0-UUryW9PTyZmTbZx64u2SDX3w+ hash: v1.k794b7964.bb8ce2d01cc71dc809d6af386b64ec9f0a44dc8a1f0a37e3e60af07e2a564243.rG3SLxJIgKk-qz-JPgtWchUwNvvcsrIhDXdq1nkJOnQscenes-app-marketing-analytics-overview-metrics--without-goals--dark:- hash: v1.k794b7964.9fb859ee1df8911c4f86bb97a03112fb5bc4eaedd8001f6de6c6094e13e3b82e.FbxkcTtnMxYSLDrsHlQ1K4G7Yp0CgsfslUv_i5WwUtU+ hash: v1.k794b7964.f998357db651ee7ec1598236cce06a2722b246c58f22da42c95f409c85edabba.WB7ezdkr0-ncnImfuEd7DS2UpjEC9vVFDbrVyTR2a8cscenes-app-marketing-analytics-overview-metrics--without-goals--light:- hash: v1.k794b7964.2bfe3293ff8ac319265afbac74449c4f6b00cab2e19063c7226fd873dd025d7b.e6SZseiGgJQcJqtm8Ezj3AFDatXo3kU63mOjItQ14-0+ hash: v1.k794b7964.a9743fd9c314ff9e880f7cd44c5c8fc15129a1fae3cb18d702fcfe314f72af05.6d6oEVqXu_LvETe9-n_Zwt2NAzazuAG_qAZsNSsNmwgscenes-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:@@ -13839,9 +13843,9 @@ snapshots:scenes-app-marketing-analytics-search-performance--landing-pages--light:hash: v1.k794b7964.dd554a599a0d095f78868c92fdfe331a84c6f6f138d4127cb0a5f8493730facc.vhQ-u2B_9Bejcm2aM7XDeekBubcBaRNMixO_gByXXFoscenes-app-marketing-analytics-search-performance--legacy-scene--dark:- hash: v1.k794b7964.80cd943f01878bd1bc4b8b837afe442d9e597f23b1f8530fe39cead6fd94fd71.pNSDj3S724YzAye0L44C6pqFSA1NzKvT_zKLgGxykaQ+ hash: v1.k794b7964.02a8531fb005382f65d6ababe17b6902925cf1e85dc6e7a4f985bccd1b19e958.euygfkesoJLgv-DxHnmRl7KFhkH5i_CgoOAt5I7-yR8scenes-app-marketing-analytics-search-performance--legacy-scene--light:- hash: v1.k794b7964.7f021d9b4b29c3e996634b92b1d4fa9116a0a8e494083d50be7b55a51a689fee.Opspu4oCDBN0wSXbkd8VflRNlm52B1LwLYzr7lLNxc0+ hash: v1.k794b7964.a11a911355e14774a6fb661339a173e564a2b23619aa79c8517006653e4a4c9a.OlaR7z6OsgLryr7PTWgCKzZEk1A-B2D00K2vSCF-LBIscenes-app-marketing-analytics-search-performance--loading--dark:hash: v1.k794b7964.7a36603ac510eb87c198b5f58af1e63790df5dba69b68ec4e029d31b8e039df8.5KMiknCw40jRDabVuNEY3-_UY6CcDHD8_4QomprfYZoscenes-app-marketing-analytics-search-performance--loading--light:@@ -13955,9 +13959,9 @@ snapshots:scenes-app-marketing-analytics-search-performance--wrapped-landing-pages-narrow--light:hash: v1.k794b7964.e3ea090216c589966b1dc39ef4c0a08ed49cbbc9566fe6b744b58ddc02a6edf6.PvzNyXoo1I8VeIMUoFlnxQxzK4o-C8nuB6amiE6VzeYscenes-app-marketing-analytics-source-onboarding--ad-performance-data-available--dark:- hash: v1.k794b7964.52d793e434ed135a17252c76b796cc7f059342600f7ea6c95241ab76669a2441.FveMgmXg9otKomgnoJbhm7TP1HJyln_odWNWqALJEiw+ hash: v1.k794b7964.7e2732cfd14a4b45bb6e172476572133cd1735d51b8a82665bd9d165132e77b6.BXqnOvcE4bMVXyLzPNQdxTzBABVJaDAzgo5HnlkkxMoscenes-app-marketing-analytics-source-onboarding--ad-performance-data-available--light:- hash: v1.k794b7964.084136bef3ef1ca7cd84e82e155ea25033ea5d8781c2c621ea0514db76997906._GLmWqtmpM-aIOjRxbQgAga4eBMqP0fz8_fBMmKX47E+ hash: v1.k794b7964.a2c55ff9a54d2ca168edab15a272ed0bed828fdf2349144e5d48dce6a0230f9f.kZZGmy7VAh8jODbriJgvxJukfSGq5udkKlUcXGLFqmYscenes-app-marketing-analytics-source-onboarding--ad-performance-with-detected-sources--dark:hash: v1.k794b7964.cbcd359205f8e84f3f6b9b2662b68156ff2df3a61e298bce8a8f887ba6b29d07.Jj320C_XAIzsjfsq1lZlhAX_EXt4BvaiItoKbCn7cj0scenes-app-marketing-analytics-source-onboarding--ad-performance-with-detected-sources--light:@@ -13987,13 +13991,13 @@ snapshots:scenes-app-marketing-analytics-source-onboarding--dashboard-scanning-with-search-console--light:hash: v1.k794b7964.7e510f054d50679dd5536707b38b2ec9fbc7e210e597a7164a940aabbf055c43.EDI_yFckDdIdgoFKJmHgiJjZUMyEjTAL3ZCQ28KNCmYscenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-and-search-console--dark:- hash: v1.k794b7964.7b1b68e4399d14540614720b08e372ccdadedb98caafb485d20cd14522fbb562.Iwp9fKWl4EJfCK15ZseoPmx8XmzfUvQuQM95ihjCrgs+ hash: v1.k794b7964.037c1c821b567f43d2bddd28e34941f1eb26d7f091bbf6e76227e7a99257387e.yoR9_RgYkdoqNHIpG94c4ri_jGvuWloYLQj1I5SrEDEscenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-and-search-console--light:- hash: v1.k794b7964.380c0b0648df0923b92eaa1848b8e52d10a338684f83d6adafc74feaff3c0dd8.uhTHmTv4cj-BNMGHcGJMSL_13sqjKsi290waRiPnXa0+ hash: v1.k794b7964.b2377ce7d2d858307363306e6eaf82cb5af2a56ae6ad2e4a78b458b8ad5301dc.BiIWytnSx8WGxPSMcatoz6MrlT0QdD474R3Z1Na5jvsscenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-only--dark:- hash: v1.k794b7964.c9f881299b4f4debedb56148fd313d15844dcb3b7eb6e0cfa5198b0442650c01.ZBX0OHHHtUcFTvyD9j33622EcgBifGLqOT4ab6PgRYQ+ hash: v1.k794b7964.34ef9c06793036aa43663de6aa38ed292ce1c95edadc8c23b6e144cf71412d1d.r0J2cmCLjzA7lO5nf9ROXyIqqNbd76lVg98FxPP4RHgscenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-only--light:- hash: v1.k794b7964.2537d1eed8e6b104da335ece2f8ffc5ce767c95d4055b3653def391ce9b82a32.XYeRX0Gw9eCFROdBPlc5zuNQrhuGNc76S9A3ikkjX8Q+ hash: v1.k794b7964.17e53dfe290b4630c3e785dbcbae92a5bc7c06dac325f34e6ddf54b3f13648cd.SYeU0pTHDGov688RCeNs7yukpE2NcSYjfpinFjdc5_oscenes-app-marketing-analytics-source-onboarding--dashboard-with-ads-syncing-without-search-console--dark:hash: v1.k794b7964.a79aa6d1604ee97084a9633d628883ea285fedda534a1c37f6c92e95986d0fa0.7koctv5az8HjySQmDNPCivF-9bpbguwb_UXKfWapYEoscenes-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/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsxindex 925dbb106c60..937c52150068 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsFilters/MarketingAnalyticsFilters.tsx@@ -1,7 +1,7 @@import { BindLogic } from 'kea'import { useActions, useValues } from 'kea'-import { IconGear } from '@posthog/icons'+import { IconGear, IconPencil } from '@posthog/icons'import { LemonButton, LemonDivider, Popover } from '@posthog/lemon-ui'import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'@@ -20,8 +20,9 @@ import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollecimport { ReloadAll } from '~/queries/nodes/DataNode/Reload'import { AddIntegrationButton } from 'products/marketing_analytics/frontend/components/AddIntegrationButton'+import { overviewMetricsLogic } from 'products/marketing_analytics/frontend/overview/overviewMetricsLogic'-import { marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'+import { MarketingAnalyticsTab, marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from '../../logic/marketingAnalyticsTilesLogic'import { ConversionGoalFilterButton } from './ConversionGoalFilterButton'import { ConversionGoalModal } from './ConversionGoalModal'@@ -35,8 +36,10 @@ export const MarketingAnalyticsFilters = ({searchOnly?: boolean}): JSX.Element => {const { featureFlags } = useValues(featureFlagLogic)- const { compareFilter, dateFilter, shouldFilterTestAccounts, optionsOpen, isAdPerformance } =+ const { compareFilter, dateFilter, shouldFilterTestAccounts, optionsOpen, isAdPerformance, activeTab } =useValues(marketingAnalyticsLogic)+ const { openEditor } = useActions(overviewMetricsLogic({ viewKey: MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID }))+ const showMetricEditor = !searchOnly && activeTab !== MarketingAnalyticsTab.SEARCH_PERFORMANCEconst showSearch = isAdPerformance && !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]const { currentTeamLoading } = useValues(teamLogic)const { setCompareFilter, setDates, updateFilterTestAccounts, setOptionsOpen } = useActions(marketingAnalyticsLogic)@@ -91,6 +94,21 @@ export const MarketingAnalyticsFilters = ({// Ordered by how often they get touched, so the rarely-changed// project setting sits last.<div className="flex w-80 max-w-[90vw] flex-col gap-4 p-3">+ {showMetricEditor && (+ <LemonButton+ type="secondary"+ size="small"+ fullWidth+ icon={<IconPencil />}+ onClick={() => {+ setOptionsOpen(false)+ openEditor()+ }}+ data-attr="marketing-configure-metrics"+ >+ Edit top-line metrics+ </LemonButton>+ )}<div><div className="text-muted mb-2 text-xs font-semibold uppercase">Comparisondiff --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.tsxindex 02965d88f016..76d529fa8062 100644--- 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.tsx@@ -18,7 +18,10 @@ const response: MarketingAnalyticsAggregatedQueryResponse = {}describe('Ad performance metric selection', () => {- beforeEach(() => initKeaTests())+ beforeEach(() => {+ initKeaTests()+ marketingAnalyticsTilesLogic.mount()+ })afterEach(cleanup)it.each([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 d02d3ead88b2..fc91e51b6974 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,7 +1,6 @@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'@@ -16,22 +15,16 @@ 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 { AdPerformanceOverviewMetrics } from 'products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics'import { marketingAnalyticsLogic } from '../../logic/marketingAnalyticsLogic'import { marketingAnalyticsSettingsLogic } from '../../logic/marketingAnalyticsSettingsLogic'-import {- MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID,- marketingAnalyticsTilesLogic,-} from '../../logic/marketingAnalyticsTilesLogic'+import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from '../../logic/marketingAnalyticsTilesLogic'import {MarketingAnalyticsValidationWarningBanner,validateConversionGoals,} from '../MarketingAnalyticsValidationWarningBanner'-const BASE_METRICS_COUNT = 6 // Total Cost, Total Clicks, CPC, CTR, Total Impressions, Reported Conversion-let uniqueNode = 0export function MarketingAnalyticsOverview(props: {@@ -58,17 +51,8 @@ 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])@@ -85,15 +69,10 @@ export function MarketingAnalyticsOverview(props: {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- const conversionGoalMetrics = conversion_goals.length * 2 // Each conversion goal adds 2 metrics: goal + cost per conversion- const numSkeletons = BASE_METRICS_COUNT + conversionGoalMetrics-const hasResults = overviewItems.length > 0if (responseError && !responseLoading && !hasResults) {return <InsightErrorState title={responseError} queryId={responseErrorObject?.queryId ?? queryId} />@@ -118,9 +97,7 @@ export function MarketingAnalyticsOverview(props: {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/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 d65ab6cd7e4a..6c87fc7a779a 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,8 +18,6 @@ import {MARKETING_ANALYTICS_DRILL_DOWN_CONFIG,MARKETING_ANALYTICS_SCHEMA,MarketingAnalyticsBaseColumns,- MarketingAnalyticsAggregatedQuery,- TrendsQuery,MarketingAnalyticsConstants,MarketingAnalyticsDrillDownLevel,MarketingAnalyticsTableQuery,@@ -37,9 +35,7 @@ import {PropertyOperator,} from '~/types'-import { buildAdPerformanceTrendsQuery } from 'products/marketing_analytics/frontend/adPerformanceMetrics'--import { marketingAnalyticsLogic, type NativeSource, type ExternalTable } from './marketingAnalyticsLogic'+import { marketingAnalyticsLogic } from './marketingAnalyticsLogic'import { marketingAnalyticsTableLogic } from './marketingAnalyticsTableLogic'import {getOrderBy,@@ -96,13 +92,10 @@ 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[]@@ -111,17 +104,6 @@ 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: {@@ -204,8 +186,6 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType'drillDownLevel','baseCurrency','includeConversionGoals',- 'validNativeSources',- 'validExternalTables',],marketingAnalyticsTableLogic,['query', 'defaultColumns'],@@ -214,25 +194,6 @@ 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: [diff --git a/products/marketing_analytics/frontend/adPerformanceMetrics.test.ts b/products/marketing_analytics/frontend/adPerformanceMetrics.test.tsindex d90e825e05d5..cd36cd8882c5 100644--- a/products/marketing_analytics/frontend/adPerformanceMetrics.test.ts+++ b/products/marketing_analytics/frontend/adPerformanceMetrics.test.ts@@ -1,43 +1,8 @@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, TrendsQuery } from '~/queries/schema/schema-general'-import { DataWarehouseSettingsTab, PropertyFilterType, PropertyOperator, TrendResult } from '~/types'--import { adPerformanceSparklines, buildAdPerformanceTrendsQuery } from './adPerformanceMetrics'--const SERIES_METRICS = [- 'cost',- 'clicks',- 'impressions',- 'reported_conversion',- 'reported_conversion_value',- 'trial started',-]--const sparklineQuery: TrendsQuery = {- kind: NodeKind.TrendsQuery,- series: SERIES_METRICS.map((metric) => ({- kind: NodeKind.DataWarehouseNode,- id: 'example_ad_stats',- table_name: 'example_ad_stats',- id_field: 'id',- distinct_id_field: 'id',- timestamp_field: 'day',- custom_name: metric,- })),-}--// The runner labels a warehouse series with its table, so only the series at `order` names the metric-const row = (metric: string, data: number[], days = ['2026-01-01', '2026-01-02']): TrendResult => ({- order: SERIES_METRICS.indexOf(metric),- data,- days,- labels: days,- label: 'example_ad_stats',- count: 0,- aggregated_value: 0,-})+import { MarketingAnalyticsColumnsSchemaNames, SourceMap } from '~/queries/schema/schema-general'+import { DataWarehouseSettingsTab } from '~/types'const table: ExternalTable = {id: 'table-one',@@ -65,84 +30,7 @@ const table: ExternalTable = {},}-describe('Ad performance sparklines', () => {- it('sums sources by date before calculating ratios and leaves zero denominators as gaps', () => {- const metrics = adPerformanceSparklines(sparklineQuery, [- 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(sparklineQuery, [- 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 source filters, drops event filters, and uses current-period dates with precompute=%s',- (precomputed) => {- const query = buildAdPerformanceTrendsQuery(- {- kind: NodeKind.MarketingAnalyticsAggregatedQuery,- properties: [- {- type: PropertyFilterType.Event,- key: 'browser',- operator: PropertyOperator.Exact,- value: 'Chrome',- },- ],- filterTestAccounts: true,- 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()- expect(query.properties).toBeUndefined()- expect(query.filterTestAccounts).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')- }- }- )-+describe('External ad cost tiles', () => {it.each([['cost_per_reported_conversion',@@ -154,26 +42,10 @@ describe('Ad performance sparklines', () => {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([])+ ] as const)('keeps the external %s trend in the base currency', (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'")})})diff --git a/products/marketing_analytics/frontend/adPerformanceMetrics.ts b/products/marketing_analytics/frontend/adPerformanceMetrics.tsindex 8afda8b94809..48d3e4c184b9 100644--- a/products/marketing_analytics/frontend/adPerformanceMetrics.ts+++ b/products/marketing_analytics/frontend/adPerformanceMetrics.ts@@ -1,30 +1,6 @@-import { getResultSeries } from 'scenes/insights/utils/resultSeries'-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 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'+import { MarketingAnalyticsBaseColumns, MarketingAnalyticsColumnsSchemaNames } from '~/queries/schema/schema-general'export const AD_PERFORMANCE_METRICS: Record<string, validColumnsForTiles> = {[MarketingAnalyticsBaseColumns.Cost]: MarketingAnalyticsColumnsSchemaNames.Cost,@@ -42,147 +18,3 @@ export const AD_PERFORMANCE_METRICS: Record<string, validColumnsForTiles> = {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,- trendsFilter: { display: ChartDisplayType.ActionsLineGraph },- tags: query.tags,- }-}--export function adPerformanceSparklines(- query: TrendsQuery,- results: TrendResult[]-): Partial<Record<validColumnsForTiles, AdPerformanceSparkline>> {- const buckets = new Map<string, Map<string, number>>()- for (const row of results) {- // `buildAdPerformanceTrendsQuery` names each series after the metric it reads- const metric = getResultSeries(query, row).node?.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.tsdeleted file mode 100644index 047895237011..000000000000--- a/products/marketing_analytics/frontend/adPerformanceTrendsLogic.ts+++ /dev/null@@ -1,71 +0,0 @@-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, p) => [s.response, s.responseLoading, s.responseError, p.query],- (- response,- loading,- error,- query: TrendsQuery- ): Partial<Record<validColumnsForTiles, AdPerformanceSparkline>> =>- loading || error- ? {}- : adPerformanceSparklines(- query,- ((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))- }- }),-])diff --git a/products/marketing_analytics/frontend/components/MetricSourceBadge.tsx b/products/marketing_analytics/frontend/components/MetricSourceBadge.tsxindex 9c98d5629b8f..1eb10f13446b 100644--- a/products/marketing_analytics/frontend/components/MetricSourceBadge.tsx+++ b/products/marketing_analytics/frontend/components/MetricSourceBadge.tsx@@ -3,7 +3,7 @@ import { Tooltip } from '@posthog/lemon-ui'import posthogIcon from 'public/posthog-icon.svg'-import type { OverviewMetricGroup as OverviewMetricSource } from '../overview/overviewMetricConfiguration'+import type { OverviewMetricSource } from '../overview/overviewMetricConfiguration'const SOURCE_DESCRIPTIONS: Record<OverviewMetricSource, string> = {platforms: 'Reported directly by your ad platforms and added together',diff --git a/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.stories.tsx b/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.stories.tsxindex 4129c110b54d..5f42ac106df1 100644--- a/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.stories.tsx+++ b/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.stories.tsx@@ -6,6 +6,7 @@ import type { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/Overviimport { expect, userEvent } from 'storybook/test'import { AdPerformanceOverviewMetrics } from './AdPerformanceOverviewMetrics'+import { overviewMetricsLogic } from './overviewMetricsLogic'const items: OverviewMetricCardItem[] = [{ key: 'Cost', value: 1800, previous: 1500, changeFromPreviousPct: 20, kind: 'currency', isIncreaseBad: true },@@ -48,7 +49,20 @@ 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 },+ // The grid breaks on its container's width, and the padded root takes its width from its content.+ decorators: [+ (Story) => (+ <div className="w-[72rem]">+ <Story />+ </div>+ ),+ ],+ args: {+ items,+ loading: false,+ viewKey: 'overview-metrics-story',+ labelFromKey: (key) => key,+ },}export default meta@@ -60,7 +74,18 @@ export const Narrow: Story = {args: { viewKey: 'overview-metrics-narrow-story' },decorators: [(Story) => (- <div className="max-w-lg">+ <div className="w-lg">+ <Story />+ </div>+ ),+ ],+}++export const MediumWidth: Story = {+ args: { viewKey: 'overview-metrics-medium-story' },+ decorators: [+ (Story) => (+ <div className="w-[38rem]"><Story /></div>),@@ -78,9 +103,20 @@ export const WithoutGoals: Story = {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())+ play: async ({ canvasElement, args }) => {+ // The modal reads the logic the component mounts, so opening it before the mount is lost.+ const logic = await waitFor(+ () => {+ const mounted = overviewMetricsLogic.findMounted({ viewKey: args.viewKey! })+ expect(mounted).toBeTruthy()+ return mounted!+ },+ { timeout: 5000 }+ )+ logic.actions.openEditor()+ await waitFor(() => expect(within(canvasElement.ownerDocument.body).getByRole('dialog')).toBeVisible(), {+ timeout: 5000,+ })},parameters: {testOptions: {@@ -109,10 +145,12 @@ export const ConfigureMetricsWithChanges: Story = {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 }))+ const platforms = within(within(dialog).getByRole('region', { name: 'Ad platforms' }))+ await userEvent.click(platforms.getByText('Impressions', { exact: true }))+ await userEvent.click(platforms.getByText('CTR', { exact: true }))await userEvent.click(- within(within(dialog).getByRole('region', { name: 'PostHog' })).getByRole('button', {- name: 'Hide all',+ within(within(dialog).getByRole('region', { name: 'PostHog' })).getByText('Trial started', {+ exact: true,}))const applyButton = within(dialog).getByRole('button', { name: 'Apply' })diff --git a/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.tsx b/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.tsxindex 2936dd0d6d77..6eb1b4563219 100644--- a/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.tsx+++ b/products/marketing_analytics/frontend/overview/AdPerformanceOverviewMetrics.tsx@@ -1,22 +1,17 @@-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 { useValues } from 'kea'import { SamplingNotice, SamplingRate } from '~/queries/nodes/OverviewGrid/OverviewGrid'import { OverviewMetricCardGrid, OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'+import { MetricSourceBadge } from '../components/MetricSourceBadge'import { OverviewMetricConfigModal } from './OverviewMetricConfigModal'-import { OVERVIEW_METRIC_GROUPS, overviewMetricsForGroup } from './overviewMetricConfiguration'+import { MAX_OVERVIEW_METRICS, overviewMetricSource, shownOverviewMetrics } from './overviewMetricConfiguration'import { overviewMetricsLogic } from './overviewMetricsLogic'export interface AdPerformanceOverviewMetricsProps {items: OverviewMetricCardItem[]loading: boolean- numSkeletons: numbersamplingRate?: SamplingRate- sparklineTheme?: ChartThemelabelFromKey: (key: string) => React.ReactNodeviewKey: string}@@ -24,87 +19,34 @@ export interface AdPerformanceOverviewMetricsProps {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)+ const { selection } = useValues(logic)+ const shown = shownOverviewMetrics(items, selection)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>- )- })}+ <div className="@container/overview-metrics flex flex-col gap-2">+ {!loading && shown.length === 0 && (+ <p className="m-0 text-secondary text-sm" data-attr="marketing-overview-metrics-empty">+ No metrics for this date range. Try a longer range, or check that your ad sources have synced.+ </p>+ )}+ <OverviewMetricCardGrid+ className="grid-cols-2 @min-[36rem]/overview-metrics:grid-cols-3 @min-[56rem]/overview-metrics:grid-cols-5"+ items={shown}+ loading={loading}+ numSkeletons={MAX_OVERVIEW_METRICS}+ emptyMessage="-"+ labelFromKey={(key) => (+ <span className="flex items-start justify-between gap-1">+ {labelFromKey(key)}+ <MetricSourceBadge source={overviewMetricSource(key)} />+ </span>+ )}+ /><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.tsxindex 3acf1287c5d0..d0161ff54e9e 100644--- a/products/marketing_analytics/frontend/overview/OverviewMetricConfigModal.tsx+++ b/products/marketing_analytics/frontend/overview/OverviewMetricConfigModal.tsx@@ -6,7 +6,16 @@ import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'import type { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'-import { OVERVIEW_METRIC_GROUPS, overviewMetricsForGroup } from './overviewMetricConfiguration'+import { MetricSourceBadge } from '../components/MetricSourceBadge'+import {+ MAX_OVERVIEW_METRICS,+ OVERVIEW_METRIC_SOURCES,+ defaultOverviewMetricSelection,+ moveOverviewMetric,+ overviewMetricSource,+ shownOverviewMetrics,+ toggleOverviewMetric,+} from './overviewMetricConfiguration'import { overviewMetricsLogic } from './overviewMetricsLogic'export function OverviewMetricConfigModal({@@ -17,32 +26,34 @@ export function OverviewMetricConfigModal({viewKey: string}): JSX.Element {const logic = overviewMetricsLogic({ viewKey })- const { configuration, draftConfiguration } = useValues(logic)- const { closeConfiguration, applyConfiguration, updateDraftGroup, resetDraft } = useActions(logic)+ const { selection, editorOpen, draftSelection } = useValues(logic)+ const { closeEditor, applySelection, setDraftSelection } = useActions(logic)+ const draft = draftSelection ?? shownOverviewMetrics(items, selection).map((item) => item.key)+ const full = draft.length >= MAX_OVERVIEW_METRICSreturn (<LemonModal- title="Configure metrics"- isOpen={!!draftConfiguration}- onClose={closeConfiguration}+ title="Edit top-line metrics"+ isOpen={editorOpen}+ onClose={closeEditor}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">+ <LemonButton+ type="secondary"+ onClick={() => setDraftSelection(defaultOverviewMetricSelection(items))}+ data-attr="marketing-metrics-reset"+ >Reset to defaults</LemonButton><div className="flex gap-2">- <LemonButton type="secondary" onClick={closeConfiguration}>+ <LemonButton type="secondary" onClick={closeEditor}>Cancel</LemonButton><LemonButtontype="primary"- onClick={() => draftConfiguration && applyConfiguration(draftConfiguration)}- disabledReason={- JSON.stringify(configuration) === JSON.stringify(draftConfiguration)- ? 'No changes to apply'- : undefined- }+ onClick={() => applySelection(draft)}+ disabledReason={draft.length === 0 ? 'Choose at least one metric' : undefined}data-attr="marketing-metrics-apply">Apply@@ -52,89 +63,73 @@ export function OverviewMetricConfigModal({}><p className="text-secondary">- Choose which metrics appear in this summary and change their order. Table columns stay unchanged.+ Choose up to {MAX_OVERVIEW_METRICS} metrics to show above the chart. Table columns stay unchanged.</p>+ <section aria-label="Shown metrics" className="mb-6">+ <h4 className="mb-2">+ Shown ({draft.length} of {MAX_OVERVIEW_METRICS})+ </h4>+ {draft.length === 0 ? (+ <p className="text-secondary">No metrics chosen. Pick at least one below.</p>+ ) : (+ draft.map((key, index) => (+ <div key={key} className="flex items-center gap-2 border-b py-2">+ <MetricSourceBadge source={overviewMetricSource(key)} />+ <span className="min-w-0 flex-1 break-words">{key}</span>+ {([-1, 1] as const).map((direction) => (+ <LemonButton+ key={direction}+ size="small"+ icon={direction === -1 ? <IconArrowUp /> : <IconArrowDown />}+ aria-label={`Move ${key} ${direction === -1 ? 'up' : 'down'}`}+ tooltip={direction === -1 ? 'Move up' : 'Move down'}+ disabledReason={+ (direction === -1 ? index === 0 : index === draft.length - 1)+ ? 'Already at the end'+ : undefined+ }+ onClick={() => setDraftSelection(moveOverviewMetric(draft, key, direction))}+ />+ ))}+ </div>+ ))+ )}+ </section><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">+ {OVERVIEW_METRIC_SOURCES.map(({ key: source, label }) => {+ const metrics = items.filter((item) => overviewMetricSource(item.key) === source)+ return (+ <section key={source} aria-label={label}>+ <h4 className="mb-2 flex items-center gap-2">+ <MetricSourceBadge source={source} />+ {label}+ </h4>+ {metrics.length === 0 ? (+ <p className="text-secondary">No metrics available from this source.</p>+ ) : (+ metrics.map((item) => {+ const checked = draft.includes(item.key)+ return (+ <div key={item.key} className="border-b py-2"><LemonCheckbox- className="min-w-0 flex-1"- checked={!hidden.includes(item.key)}+ checked={checked}label={<span className="break-words">{item.key}</span>}- onChange={(checked) =>- updateDraftGroup(group, {- hidden: checked- ? hidden.filter((key) => key !== item.key)- : [...hidden, item.key],- })+ onChange={() =>+ setDraftSelection(toggleOverviewMetric(draft, item.key))+ }+ disabledReason={+ !checked && full+ ? `You can show up to ${MAX_OVERVIEW_METRICS} metrics. Remove one to add another.`+ : undefined}/>- {([-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>- )- })}+ )+ })+ )}+ </section>+ )+ })}</div></LemonModal>)diff --git a/products/marketing_analytics/frontend/overview/overviewMetricConfiguration.ts b/products/marketing_analytics/frontend/overview/overviewMetricConfiguration.tsindex 959aa510cf68..06ed1b95043f 100644--- a/products/marketing_analytics/frontend/overview/overviewMetricConfiguration.ts+++ b/products/marketing_analytics/frontend/overview/overviewMetricConfiguration.ts@@ -2,49 +2,68 @@ import type { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/Overviimport { adPerformanceMetricKey } from '../adPerformanceMetrics'-export type OverviewMetricGroup = 'platforms' | 'posthog'+export type OverviewMetricSource = 'platforms' | 'posthog'-export interface OverviewMetricGroupConfiguration {- hidden: string[]- order: string[]- collapsed: boolean-}+export const MAX_OVERVIEW_METRICS = 5-export type OverviewMetricConfiguration = Record<OverviewMetricGroup, OverviewMetricGroupConfiguration>+const DEFAULT_POSTHOG_METRICS = 2-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 const OVERVIEW_METRIC_SOURCES: { key: OverviewMetricSource; label: string }[] = [+ { key: 'platforms', label: 'Ad platforms' },+ { key: 'posthog', label: 'PostHog' },]-export function defaultOverviewMetricConfiguration(): OverviewMetricConfiguration {- return {- platforms: { hidden: [], order: [], collapsed: false },- posthog: { hidden: [], order: [], collapsed: false },+export function overviewMetricSource(key: string): OverviewMetricSource {+ return adPerformanceMetricKey(key) ? 'platforms' : 'posthog'+}++export function defaultOverviewMetricSelection(items: OverviewMetricCardItem[]): string[] {+ const platforms = items.filter((item) => overviewMetricSource(item.key) === 'platforms').map((item) => item.key)+ const posthog = items+ .filter((item) => overviewMetricSource(item.key) === 'posthog')+ .slice(0, DEFAULT_POSTHOG_METRICS)+ .map((item) => item.key)+ return [...platforms.slice(0, MAX_OVERVIEW_METRICS - posthog.length), ...posthog]+}++export function shownOverviewMetrics(+ items: OverviewMetricCardItem[],+ selection: string[] | null+): OverviewMetricCardItem[] {+ const byKey = new Map(items.map((item) => [item.key, item]))+ const saved = (selection ?? []).flatMap((key) => byKey.get(key) ?? [])+ if (saved.length > 0) {+ return saved.slice(0, MAX_OVERVIEW_METRICS)}+ return defaultOverviewMetricSelection(items).flatMap((key) => byKey.get(key) ?? [])}-export type OverviewHiddenGroups = 'none' | OverviewMetricGroup | 'both'+export function toggleOverviewMetric(selection: string[], key: string): string[] {+ if (selection.includes(key)) {+ return selection.filter((selected) => selected !== key)+ }+ return selection.length < MAX_OVERVIEW_METRICS ? [...selection, key] : selection+}-export function hiddenOverviewMetricGroups(configuration: OverviewMetricConfiguration): OverviewHiddenGroups {- const platforms = configuration.platforms.hidden.length > 0- const posthog = configuration.posthog.hidden.length > 0+export function moveOverviewMetric(selection: string[], key: string, direction: -1 | 1): string[] {+ const index = selection.indexOf(key)+ const target = index + direction+ if (index < 0 || target < 0 || target >= selection.length) {+ return selection+ }+ const next = [...selection]+ ;[next[index], next[target]] = [next[target], next[index]]+ return next+}++export type OverviewHiddenSources = 'none' | OverviewMetricSource | 'both'++export function hiddenOverviewMetricSources(selection: string[]): OverviewHiddenSources {+ const shown = new Set(selection.map(overviewMetricSource))+ const platforms = !shown.has('platforms')+ const posthog = !shown.has('posthog')if (platforms && posthog) {return 'both'}return platforms ? 'platforms' : posthog ? 'posthog' : 'none'}--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.tsindex 4fa4c71bf1e5..ad93af1e3338 100644--- a/products/marketing_analytics/frontend/overview/overviewMetricsLogic.test.ts+++ b/products/marketing_analytics/frontend/overview/overviewMetricsLogic.test.ts@@ -7,15 +7,16 @@ import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-anaimport type { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'import { initKeaTests } from '~/test/init'-import { defaultOverviewMetricConfiguration, overviewMetricsForGroup } from './overviewMetricConfiguration'+import { moveOverviewMetric, shownOverviewMetrics, toggleOverviewMetric } 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' },-]+const platformItems: OverviewMetricCardItem[] = ['Cost', 'Clicks', 'Impressions', 'CPC', 'CTR', 'Reported ROAS'].map(+ (key) => ({ key, value: 1, kind: 'unit' })+)+const posthogItems: OverviewMetricCardItem[] = ['Trial started', 'Cost Per Trial started', 'Demo booked'].map(+ (key) => ({ key, value: 1, kind: 'unit' })+)+const items = [...platformItems, ...posthogItems]describe('overview metric configuration', () => {beforeEach(() => {@@ -23,99 +24,99 @@ describe('overview metric configuration', () => {initKeaTests()})- it('discards canceled edits and persists applied visibility, order, and collapsed groups for the view', () => {+ it('discards canceled edits and persists the applied selection for the view only', () => {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+ logic.actions.openEditor()+ logic.actions.setDraftSelection(['Cost'])+ logic.actions.closeEditor()+ expect(logic.values.selection).toBeNull()+ logic.actions.openEditor()+ expect(logic.values.draftSelection).toBeNull()+ logic.actions.setDraftSelection(['Clicks', 'Cost', 'Trial started'])+ logic.actions.applySelection(logic.values.draftSelection!)+ expect(logic.values.editorOpen).toBe(false)unmount()const restored = overviewMetricsLogic({ viewKey: 'ad-performance' })const unmountRestored = restored.mount()- expect(restored.values.configuration).toEqual(saved)- expect(restored.values.draftConfiguration).toBeNull()+ expect(restored.values.selection).toEqual(['Clicks', 'Cost', 'Trial started'])+ expect(restored.values.draftSelection).toBeNull()expect(JSON.parse(localStorage.getItem(- `${MOCK_TEAM_ID}__.products.marketingAnalytics.overviewMetricsLogic.ad-performance.configuration`+ `${MOCK_TEAM_ID}__.products.marketingAnalytics.overviewMetricsLogic.ad-performance.selection`)!)- ).toEqual(saved)+ ).toEqual(['Clicks', 'Cost', 'Trial started'])const anotherView = overviewMetricsLogic({ viewKey: 'another-view' })const unmountOther = anotherView.mount()- expect(anotherView.values.configuration).toEqual(defaultOverviewMetricConfiguration())+ expect(anotherView.values.selection).toBeNull()unmountOther()unmountRestored()})- it.each([- ['none', [], []],- ['platforms', ['Cost'], []],- ['posthog', [], ['Trial started']],- ['both', ['Cost'], ['Trial started']],- ])(- 'reports %s when applying with those groups hidden, and nothing on cancel',- async (value, platforms, posthogHidden) => {- const logic = overviewMetricsLogic({ viewKey: 'ad-performance' })- const unmount = logic.mount()- logic.actions.configureMetrics(logic.values.configuration)- logic.actions.updateDraftGroup('platforms', { hidden: platforms })- logic.actions.updateDraftGroup('posthog', { hidden: posthogHidden })- await expectLogic(logic, () => logic.actions.closeConfiguration()).toNotHaveDispatchedActions([- 'reportDashboardControlUsed',- ])- logic.actions.configureMetrics(logic.values.configuration)- logic.actions.updateDraftGroup('platforms', { hidden: platforms })- logic.actions.updateDraftGroup('posthog', { hidden: posthogHidden })- await expectLogic(logic, () =>- logic.actions.applyConfiguration(logic.values.draftConfiguration!)- ).toDispatchActions([- marketingAnalyticsLogic.actionCreators.reportDashboardControlUsed(- 'overview',- 'metric_configuration_applied',- value- ),- ])- unmount()- }- )-- 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',+ it('toggles and moves metrics, ignoring additions past five', () => {+ const five = ['Cost', 'Clicks', 'Impressions', 'CPC', 'CTR']+ expect(toggleOverviewMetric(five, 'Trial started')).toEqual(five)+ expect(toggleOverviewMetric(toggleOverviewMetric(five, 'CTR'), 'Trial started')).toEqual(['Cost',+ 'Clicks',+ 'Impressions',+ 'CPC',+ 'Trial started',])- 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'])+ expect(moveOverviewMetric(five, 'Clicks', -1).slice(0, 2)).toEqual(['Clicks', 'Cost'])+ expect(moveOverviewMetric(five, 'Cost', -1)).toEqual(five)})- it('resets a saved hidden section without changing it until Apply', () => {+ it.each([+ ['none', ['Cost', 'Trial started']],+ ['posthog', ['Cost', 'Clicks']],+ ['platforms', ['Trial started']],+ ])('reports %s hidden when applying that selection, and nothing on cancel', async (value, selection) => {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())+ logic.actions.openEditor()+ logic.actions.setDraftSelection(selection)+ await expectLogic(logic, () => logic.actions.closeEditor()).toNotHaveDispatchedActions([+ 'reportDashboardControlUsed',+ ])+ await expectLogic(logic, () => logic.actions.applySelection(selection)).toDispatchActions([+ marketingAnalyticsLogic.actionCreators.reportDashboardControlUsed(+ 'overview',+ 'metric_configuration_applied',+ value+ ),+ ])unmount()})++ it.each([+ [+ 'defaults to three platform and two PostHog metrics',+ items,+ null,+ ['Cost', 'Clicks', 'Impressions', 'Trial started', 'Cost Per Trial started'],+ ],+ [+ 'defaults to five platform metrics without goals',+ platformItems,+ null,+ ['Cost', 'Clicks', 'Impressions', 'CPC', 'CTR'],+ ],+ [+ 'keeps the saved order and drops removed goals',+ items,+ ['Removed goal', 'Demo booked', 'Cost'],+ ['Demo booked', 'Cost'],+ ],+ [+ 'falls back to the default when no saved metric remains',+ platformItems,+ ['Removed goal'],+ ['Cost', 'Clicks', 'Impressions', 'CPC', 'CTR'],+ ],+ ])('%s', (_, available, selection, expected) => {+ expect(shownOverviewMetrics(available, selection).map((item) => item.key)).toEqual(expected)+ })})diff --git a/products/marketing_analytics/frontend/overview/overviewMetricsLogic.ts b/products/marketing_analytics/frontend/overview/overviewMetricsLogic.tsindex 2538a4a2e9c6..ab98419e52fb 100644--- a/products/marketing_analytics/frontend/overview/overviewMetricsLogic.ts+++ b/products/marketing_analytics/frontend/overview/overviewMetricsLogic.ts@@ -3,40 +3,25 @@ import { LogicWrapper, MakeLogicType, actions, connect, kea, key, listeners, patimport { buildTeamScopedPersistenceConfig } from 'lib/logic/persistence'import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'-import {- OverviewMetricConfiguration,- OverviewMetricGroup,- OverviewMetricGroupConfiguration,- defaultOverviewMetricConfiguration,- hiddenOverviewMetricGroups,-} from './overviewMetricConfiguration'+import { hiddenOverviewMetricSources } from './overviewMetricConfiguration'export interface OverviewMetricsLogicProps {viewKey: string}export interface overviewMetricsLogicValues {- configuration: OverviewMetricConfiguration- draftConfiguration: OverviewMetricConfiguration | null+ /** Saved metric keys in display order, or null to use the default selection. */+ selection: string[] | null+ editorOpen: boolean+ draftSelection: string[] | 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+ openEditor: () => void+ closeEditor: () => void+ setDraftSelection: (selection: string[]) => { selection: string[] }+ applySelection: (selection: string[]) => { selection: string[] }reportDashboardControlUsed: (section: string, control: string, value?: boolean | string) => void- setGroupCollapsed: (- group: OverviewMetricGroup,- collapsed: boolean- ) => { group: OverviewMetricGroup; collapsed: boolean }}export type overviewMetricsLogicType = MakeLogicType<@@ -52,46 +37,43 @@ export const overviewMetricsLogic: LogicWrapper<overviewMetricsLogicType> = kea<path((key) => ['products', 'marketingAnalytics', 'overviewMetricsLogic', key]),connect(() => ({ actions: [marketingAnalyticsLogic, ['reportDashboardControlUsed']] })),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 }),+ openEditor: () => ({}),+ closeEditor: () => ({}),+ setDraftSelection: (selection: string[]) => ({ selection }),+ applySelection: (selection: string[]) => ({ selection }),}),reducers(() => ({- configuration: [- defaultOverviewMetricConfiguration(),+ selection: [+ null as string[] | null,buildTeamScopedPersistenceConfig(),{- applyConfiguration: (_, { configuration }) => configuration,- setGroupCollapsed: (state, { group, collapsed }) => ({- ...state,- [group]: { ...state[group], collapsed },- }),+ applySelection: (_, { selection }) => selection,},],- draftConfiguration: [- null as OverviewMetricConfiguration | null,+ editorOpen: [+ false,{- configureMetrics: (_, { configuration }) => configuration,- closeConfiguration: () => null,- applyConfiguration: () => null,- resetDraft: () => defaultOverviewMetricConfiguration(),- updateDraftGroup: (state, { group, configuration }) =>- state ? { ...state, [group]: { ...state[group], ...configuration } } : state,+ openEditor: () => true,+ closeEditor: () => false,+ applySelection: () => false,+ },+ ],+ draftSelection: [+ null as string[] | null,+ {+ setDraftSelection: (_, { selection }) => selection,+ openEditor: () => null,+ closeEditor: () => null,+ applySelection: () => null,},],})),listeners(({ actions }) => ({- applyConfiguration: ({ configuration }) => {+ applySelection: ({ selection }) => {actions.reportDashboardControlUsed('overview','metric_configuration_applied',- hiddenOverviewMetricGroups(configuration)+ hiddenOverviewMetricSources(selection))},})),