Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(marketing): remove the new marketing analytics dashboard flag (#124478)

Javier Bahamondes02a8423213e5
diff --git a/docs/internal/marketing-source-suggestions.md b/docs/internal/marketing-source-suggestions.md
index a00bb0ae07d8..8ce77b9f0e0a 100644
--- a/docs/internal/marketing-source-suggestions.md
+++ b/docs/internal/marketing-source-suggestions.md
@@ -193,7 +193,7 @@ The source scan, enhanced catalog, dashboard section changes, and header feedbac
Google Search Console onboarding stays behind its independent `marketing-analytics-organic-keywords` flag.
Mounting source setup state does not start the UTM audit; Integration health loads the audit when opened.
Search onboarding stays independent under `marketing-analytics-organic-keywords`.
-The read-only setup plan is available with `marketing-analytics-source-onboarding`, `marketing-analytics-setup`, or `new-marketing-analytics-dashboard`; other setup operations keep their existing flag requirements.
+The read-only setup plan is available with `marketing-analytics-source-onboarding` or `marketing-analytics-setup`; other setup operations keep their existing flag requirements.
Source setup uses a consistent panel for connection checks, event scanning, suggestions, empty results, and recoverable errors.
Detected platforms show concise evidence with expandable details.
@@ -242,8 +242,8 @@ Integration buttons show the external-link icon because their connection panels
The native integration catalog uses a consistent display order: Google Ads, Meta Ads, Bing Ads, LinkedIn Ads, TikTok Ads, Reddit Ads, Pinterest Ads, Snapchat Ads, OpenAI Ads, Apple Ads, Amazon Ads, Rokt Ads, and X Ads. Google Search Console stays in the search section.
-The separate Ad performance tab is available only with `new-marketing-analytics-dashboard` enabled.
-Enabling Search performance alone keeps paid and organic reporting inside the current Dashboard tab.
+The separate Ad performance tab appears when `marketing-analytics-organic-keywords` is on and `marketing-analytics-source-onboarding` is off.
+Otherwise paid and organic reporting stay inside the Dashboard tab.
Detected-source suggestions keep the money hedgehog in the header, matching the empty state and manual catalog.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 59d51a23025c..ce45530470d2 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6150,142 +6150,6 @@ snapshots:
hash: v1.k794b7964.e4ba9a5b539d8d5793cd006a4216d0fb269bfdf6aadb73fc2a0000bbc134a628.538OiZKa7nx5_GM1n-96_LPIFUtjFVrMfe0eZyoh1TE
marketing-analytics-conversion-recordings--with-recordings--light:
hash: v1.k794b7964.2bd23ebf34db8691d2635efd1d0e69e72c62a5bf316b0eb5d111f31c5adbd599.-EMHfqpoNfdDI8FC2Puf8apQ3FIgYPXYrpearRoPrIk
- marketing-analytics-customer-acquisition-cards--configuration-loading--dark:
- hash: v1.k794b7964.4e3295796230b8ccc9ce5cb239d9ffe000af9d00324d31584d3fa6fde8550fe9.04jR2iHz7Mn5n3Z6KmK4yt-R520UGYL9im_4Icykhxk
- marketing-analytics-customer-acquisition-cards--configuration-loading--light:
- hash: v1.k794b7964.e0621c392648364dcfd76d6aa207ef3cf5990d9509dd05641e0280e83dbe7f9c.bicYg7JvUWNQ92J9Gge8euSuSBODkAA4EuzwfBFJ1Uk
- marketing-analytics-customer-acquisition-cards--configured--dark:
- hash: v1.k794b7964.cd290a64934279b1a7e0e23a3442283a9e44630b8aa963aa8554c03e8499f5e3.QGxL2MsCjol09uXF1P14nUszoc98dZpxUnK880_Vf8Q
- marketing-analytics-customer-acquisition-cards--configured--light:
- hash: v1.k794b7964.553471dfede5b1c1450f705e01c340442bfecff66e01efcb206c502ada534e36.aPzAwumsGjGtQqMYWtnFUDA3jhkIrMuf5EJ1fG1snUM
- marketing-analytics-customer-acquisition-cards--error--dark:
- hash: v1.k794b7964.dc409831738ce2b25d5a5fa4b7b31d3310108e0335670f5e93de50b80b9e4d02.aRmpYSiDd_AMCnBTDyRzKgt4Hn1kcX5u-C7wSKMzZYY
- marketing-analytics-customer-acquisition-cards--error--light:
- hash: v1.k794b7964.e80f2eb9c01b27aa8297e6f8644941db5f5dd9665044c4f562418988ebde43a0.-bjEtmLDqxX0XU_k8CZDaZ02knZpPTrijQ44mDhEKEE
- marketing-analytics-customer-acquisition-cards--loading--dark:
- hash: v1.k794b7964.9c7937c5eeebaab82299b1eab7c64e567045df1d8342efabb006f55234f853e7.t1KXV9kOCbgn8aYOuJ0eEJFrAF-bs1Z3VYyADYdHDwM
- marketing-analytics-customer-acquisition-cards--loading--light:
- hash: v1.k794b7964.885cc20f71571a703d9d91afeabf622ca654b97908e4cc3adfd4a9d7d3809185.tXMt6YqMYkUigQXZZyKan4j_hEeb7YL8UDaO4H09u2A
- marketing-analytics-customer-acquisition-cards--no-customers--dark:
- hash: v1.k794b7964.d373fc20fdafc0d07ec36de7a05ae9a67503dea118d04cad304647c25fd3a404.HiqYRZCwBEdtfwWgfgiv5KS5G9Q8fDgue9xC5gxxP_c
- marketing-analytics-customer-acquisition-cards--no-customers--light:
- hash: v1.k794b7964.2c6caa70fd61247a739d507f8d9b57f67e0262165c0fa5ed42ceb1213f2484ad.qshFf-kF2oLF5w2RLB29ntSYfArxj0CvRo8cd0uRqrA
- marketing-analytics-customer-acquisition-cards--unconfigured--dark:
- hash: v1.k794b7964.fda088b86665fa1e7f42ac158d9c5acf12b2afc030a90ad385d3d0fe16170d46.WqmQ9-wSSHQj0J-kUbJKkFI8DhDljOP6queW3e6jxDQ
- marketing-analytics-customer-acquisition-cards--unconfigured--light:
- hash: v1.k794b7964.40240d162f715f3da0d8363e08797fb8a9c131852a5d6356c892424e25dfa35c.yeHaH7ecKHVh7IOwmerxuVPzSGclQrUDBwWnoPV0rmw
- marketing-analytics-dashboard-ask-posthog-ai--acquisition--dark:
- hash: v1.k794b7964.bf802fa137c78dcb6d3ca94c02e903e9464e92aabb02a3dc92391e0d60c64f8a.tCxe-gi3h9CTPQnEcqATxDNa8DtXQaoYz5QuvYVhOjY
- marketing-analytics-dashboard-ask-posthog-ai--acquisition--light:
- hash: v1.k794b7964.c2b261cbc4ae91d1326fd5e6bb3ef4bf135d4dbe1bd08d0692caf7dcb936d639.3Fc6a9f_crPuHJCfuqHBad4X8flG5C3N6SMGSg4nxKM
- marketing-analytics-dashboard-ask-posthog-ai--ai-data-processing-not-approved--dark:
- hash: v1.k794b7964.92b3949d77ad5cd056fbea060a61917358f03c1ef68419470d8ff0901ac0792b.6sQEKQbE4m3ua9QrQJdos5mZ30G2AI9-EWBeJTo0TWk
- marketing-analytics-dashboard-ask-posthog-ai--ai-data-processing-not-approved--light:
- hash: v1.k794b7964.64cb096bcb631102e0581e9b52b038b34ca611f6bdb23057eb5774d5bdf3e773.twzGE8BSXYdX5BtCMV76UoLLssbsgYCVHMvWu5xxhnQ
- marketing-analytics-dashboard-ask-posthog-ai--conversion--dark:
- hash: v1.k794b7964.6a71d4510e44a0a9c20d357c912f00af7976c48a984e77157a456c05ea9742e7.8uwssiuWJenX4i5x-OIMZxEr2Fi4Wg0C6xfMx7Xzu_4
- marketing-analytics-dashboard-ask-posthog-ai--conversion--light:
- hash: v1.k794b7964.191d111022982f97a17e13419e72f9c5da73becb6c5c34f3b7e5e5a7256f5348.5X6pfOyc_whtc_kMHLz9ftl5Y7U-UZLFnQPmH0TNUqk
- marketing-analytics-dashboard-ask-posthog-ai--engagement--dark:
- hash: v1.k794b7964.8e9f49c14f469f2f9b38ab3f50d7e758c2c271238be6dfc24221bc1acc865ff3.OULQj22Y6PJNphdoG8_fdtsBiGCUrmiFX0DZ-hG_HzY
- marketing-analytics-dashboard-ask-posthog-ai--engagement--light:
- hash: v1.k794b7964.105cd44e9e677e2842a4bed1329b29e9be2ee939dd61bc021f7eccabdb0b1e39.niH90yoFtA8ulu6vt1Nx39mGoES2dPck28gCCV8axNo
- marketing-analytics-dashboard-ask-posthog-ai--narrow--dark:
- hash: v1.k794b7964.39f19e95e4f467f0f5b562fda90630e1e1b2eb69413a3ab1d89ea2ee79ca66f0.Xjv3Qzby0wjmS5u9XddnUBQ0Fglx_om6lvsZoAfqtGA
- marketing-analytics-dashboard-ask-posthog-ai--narrow--light:
- hash: v1.k794b7964.39bca8ed804102275c50f24f654e61973cfd5788f5c29febf5b63e1a9aff393c.EYkjYvOxP5dbWZTuHUwSO9xXcU68eBd3KCeAS3vkF3k
- marketing-analytics-dashboard-ask-posthog-ai--overview--dark:
- hash: v1.k794b7964.92b3949d77ad5cd056fbea060a61917358f03c1ef68419470d8ff0901ac0792b.3D-2_ljkj3N7vXcBu1k1F0KR-1psjK36YPjjPLlUrZg
- marketing-analytics-dashboard-ask-posthog-ai--overview--light:
- hash: v1.k794b7964.64cb096bcb631102e0581e9b52b038b34ca611f6bdb23057eb5774d5bdf3e773.F_49bxAIbWEShaBxeQr22JHS5ZQCzQ4cLQj_0zhZhOo
- marketing-analytics-dashboard-ask-posthog-ai--retention--dark:
- hash: v1.k794b7964.897494ae1bb8d405601e93e9d3b746716f68aec81d761c94b953dadc04097a96.rOFMLNnCszQIL0uG_O4mFIIGdUaTNrP2Z4ATcHewwlo
- marketing-analytics-dashboard-ask-posthog-ai--retention--light:
- hash: v1.k794b7964.74e7aa3b07c74c5e6f6e40bec5a4e32bfb498525e5e4278b3cb80ea5035f1113.7rrdBr-XRoEB3mQi_C0Nqr62IcxhDmg5wmrnYRTtz_w
- marketing-analytics-dashboard-breakdown-table--empty--dark:
- hash: v1.k794b7964.595e55eba52af8b27ddecd40dd1b59d636bcbae1ee0dc5d78be62dd3b892d981.IyZb58wgD9xEUOLcWOt5PP2o4wps9Oh7Sb6S1SfQKvE
- marketing-analytics-dashboard-breakdown-table--empty--light:
- hash: v1.k794b7964.60b8c75933454013c8d7539b3007c7caa6f0441f1dc23e3c334f7a5872187557.dxJ3aGIlzFEUyl7-pqdaOYuXFUdOXkNZTClmZbEJmaQ
- marketing-analytics-dashboard-breakdown-table--error--dark:
- hash: v1.k794b7964.eebc6e004f1842c2083110bc236d68d1bd02922262ecdd4616b834253c196c34.4CgdirQZGwGdbeZVm-0x2AV5qAMzKN6JzihBkSvcm3g
- marketing-analytics-dashboard-breakdown-table--error--light:
- hash: v1.k794b7964.be182f1ad0321aca7ecad66bf6542b1cb293dbb1feac6846e1a6d1cbec2c43bc.psYi72UaaE2V8n2EEl_eLM5trQb558iM-K9KiO_W6cY
- marketing-analytics-dashboard-breakdown-table--interactive--dark:
- hash: v1.k794b7964.26101b571687a3e276320f8614905e37e974878b8c97394bbcab3529071ed94b.g9JC1Dl369GaW2Smmnfhs0lE_r7QNMa-kQyhDtUyXpA
- marketing-analytics-dashboard-breakdown-table--interactive--light:
- hash: v1.k794b7964.48a01e6ed781d8cb4a8304fde452a48881a684635940aff184f4d368373991bc.MdNlqtUcdUAzW3cJznYE1DhoGbkhpYo9eBQFciZaNuc
- marketing-analytics-dashboard-breakdown-table--loading--dark:
- hash: v1.k794b7964.3ed4d155c3d1dc42a922ca9245738dd964be8ea64de45e8277098f8b8a72d6fb.LQIl_ubh4uCgp4CNTSJqZW7eLRntIFpgDPuQgIuJ6Pg
- marketing-analytics-dashboard-breakdown-table--loading--light:
- hash: v1.k794b7964.0452833de0d3a8ced6b8b1f792998f7f352c15398053ad67a9643459b62fae0f.8key9ACTC3rCKFjmq2LRfZKSDBh1q_TwwZU70LP_VX8
- marketing-analytics-dashboard-breakdown-table--narrow--dark:
- hash: v1.k794b7964.3146e200a27a61ff64e9e1ea91f195d5d1aae75bc431d368f4ff0c575db062bd.NwGD71k9q_I_ai9lpQUbnUTYOdX4-4-M7r1N_6zWc3o
- marketing-analytics-dashboard-breakdown-table--narrow--light:
- hash: v1.k794b7964.1b4e76ab2e17352db7d12e0437368b7991143c5ce31fd14c329d5ef07a2f27f7.Rw-g3rHkdH6cYXDCkLOpCgVXOwCuzZc6W1Lp670paaQ
- marketing-analytics-dashboard-breakdown-table--narrow-comparison--dark:
- hash: v1.k794b7964.31e41069d269db8708235ebe4532f1d192bbaa665684020f6fdb4027aa8acd46.ZUY6P6E0RJdx4a7g6MNz26VSupyhqYn89k6oTj8xmEM
- marketing-analytics-dashboard-breakdown-table--narrow-comparison--light:
- hash: v1.k794b7964.aeb0d17c3166922193e00df2ff2b294a46046f5f0dafb448eb378b03f45de07a.6g_f5vb1BIZzlbnBa0ii0axbN9XzPruR7CZfbKiDGK4
- marketing-analytics-dashboard-metric-cards--interactive--dark:
- hash: v1.k794b7964.13e3b45ffbaa12c7b347602d6bfef551a73d5165cedd187c4c7352e7e3eafbf4.nQbGKqkKb0KjlOsfANfGLHH0I3mWN1lo1fPI6X-I-CY
- marketing-analytics-dashboard-metric-cards--interactive--light:
- hash: v1.k794b7964.9ffa94d7ec26e13ecee2265fe527a5079c932caeb2ff15c9b095e6b322567c2a.mj4xFPDPAYtga6QwCmgK23kGo1FNDRdR80MssUI6lCs
- marketing-analytics-dashboard-metric-cards--loading--dark:
- hash: v1.k794b7964.51ad00cd8818358b38d57bdd5d694ea98446dbdef7727db1e6f89320dacb1ff9.XLLDF_4xHonffqOBzexuguHLaGw8rSq4xMKSN5cSZmU
- marketing-analytics-dashboard-metric-cards--loading--light:
- hash: v1.k794b7964.cc0559f266eccc72b9b5f443568c3b7c056073ef51c798f024afce930115d993.dtMKcpd7lEz3_eTuPButOD5iWcsQPvNuRxc4G7Oh_fY
- marketing-analytics-dashboard-metric-cards--missing-spec--dark:
- hash: v1.k794b7964.9f3ab79ae9f0a76b9ab9f11ccbf7c8b6dfd95b0746b3b8ed9d2d88c0ab1fea7d.KbY111eISEcuj4UdV7mgp3qp9Alh0pu9Q0IRKTRd6H8
- marketing-analytics-dashboard-metric-cards--missing-spec--light:
- hash: v1.k794b7964.12b8b666752c7d711a63902cdb85be26560f338128078e1dc9569b9033fd00b9.xSyR6WQ4h5L_Vu6L03qlODjEG5XGN_EaCgS2kU6pllU
- marketing-analytics-dashboard-metric-cards--narrow--dark:
- hash: v1.k794b7964.73675491c0d46d77c0897ec40b46a93c911f20a3f43b1ed7010b393819b03358.0rCIfrsLbFrzr-0eKAq3OqxXizh5SYOv4DOb5RmJd2c
- marketing-analytics-dashboard-metric-cards--narrow--light:
- hash: v1.k794b7964.67da4b12571f3093a54e8d5afddff2fde5da8cecfd61ba132d0b4fb181ab205a.71jVgbw9JdnG8bUSuydyjqGgKDA9-ntDJgzLgCIHgOY
- marketing-analytics-dashboard-metric-chart--empty--dark:
- hash: v1.k794b7964.7b6020b3d1d18ce093240b91f693ea2c2c26fbf3c013ebffaa4e3f2166da25e5.TjRc-gGEpBCZP3Ite7qHlDW6JcZce1gJIHH1BGuWieI
- marketing-analytics-dashboard-metric-chart--empty--light:
- hash: v1.k794b7964.689218e3c187ef67f2cac86867da5df5c74c49c4448f0b530c949d9005499c23.egxucJAOTaVMEwYkNmtJQJJrA6ci-2H_qHVsMCndcT4
- marketing-analytics-dashboard-metric-chart--error--dark:
- hash: v1.k794b7964.e809ea038ca7c8a676941744aa8b828d583bcec82c8e4c13d8c9aa2e617fe81b.JPk5U6T9QqNAsvpIipO0tmNX73qRqlEe2uVr4ac41nI
- marketing-analytics-dashboard-metric-chart--error--light:
- hash: v1.k794b7964.62715b403c1f9cf81295fffcfc17f428f4f8a5f67b2a650f5f01098f28500b52.qbBoEKB7pcYmr-n4M7-zMhwTBAk9l4Xnc6TMU8hIbvY
- marketing-analytics-dashboard-metric-chart--interactive--dark:
- hash: v1.k794b7964.1171481aac8e380c23b35ed7201df782d2e6c8320c37dcef046a344c3607bed9._SCYVG0_Yn3FeknY8CUBX45M9_lkkWMXSWAEDuMlz94
- marketing-analytics-dashboard-metric-chart--interactive--light:
- hash: v1.k794b7964.052a39648417d77f897ef2ba52c53dbe07e44e07dd0ba83f7fea3b4a36dcb70d.FEcw-a3jVZx-DwrFh5_XvytVpWJYTxi_5nj5w1CxITo
- marketing-analytics-dashboard-metric-chart--loading--dark:
- hash: v1.k794b7964.82a9b4e0a2f369d89ee7161b4537b3e97e5c461a157fc1803a5f5c2dcb063dce.PxIAHr4mRzPTF-iVmryTjLtm_00h7CGmOm5za0rmy4E
- marketing-analytics-dashboard-metric-chart--loading--light:
- hash: v1.k794b7964.9372cf54ba7c2309858e4e2f649c4fc589ceda9bb6118629a0ad4f5ea2c71d40.xZvN9hfVD7NxhecYQqOfjKgTPEFhYb9hBFu8nVntduw
- marketing-analytics-dashboard-metric-chart--narrow--dark:
- hash: v1.k794b7964.ca8dd72bb4556f2452c8d88b6fdd878f153a1a228f0f2d24f5d2cc7cb383448a.mCPDTBOzBKsDDRGXVRc0LMdGJ7smRTNBls8nqCjNX60
- marketing-analytics-dashboard-metric-chart--narrow--light:
- hash: v1.k794b7964.4892e85e55ec70c9406fcc562761b8a6496ae857af380bc2709958e7e82b4f67.QxiuaCdQdagzXPNXwmNsdBL19e286pDHiZpUyOBuXD0
- marketing-analytics-dashboard-metric-chart--narrow-error--dark:
- hash: v1.k794b7964.a56a21ce4c7d5c492b9cb7c8b6291a1347a99ed7e8e14f2adca9c1a2613d499b.rSLMTKIeWVoinQ_Pvf5hpM6vcHQzXI8hh_zwZ7JYgfk
- marketing-analytics-dashboard-metric-chart--narrow-error--light:
- hash: v1.k794b7964.476d3187f9bcf929140f6b5169584bee7985c5a9fd692d152ce711ef2711f932.TL33eGlCu1UyWiYc8UQuopK4F91ttLIWlWUplEQfJy8
- marketing-analytics-dashboard-metric-chart--percentage--dark:
- hash: v1.k794b7964.6fb50145654e53e748fe132435c760a8624d512d455daffb4fac1beee43b9f26.W9IYyo2xYX7QTa4Lxi2S2Mch4jtOAFeaXx4CzHf9C1U
- marketing-analytics-dashboard-metric-chart--percentage--light:
- hash: v1.k794b7964.7f355743c54a5d245b96469658060692079f2bba19a4dafc9e56bd4cf772e5b6.sQTvJVJVPV-1VZSJiBpjlOzHUkpHh2D9CG77rUblwTY
- marketing-analytics-dashboard-metric-chart--refreshing--dark:
- hash: v1.k794b7964.10de1f1ee3cabcd375230e26384b61ef01e0587ce6927c68fd5db1ff76aee496.i1r8fbZwXkwZ-fvg7bW1YelQKnskxIw7WhQvvMkTLEg
- marketing-analytics-dashboard-metric-chart--refreshing--light:
- hash: v1.k794b7964.38afa435aa16e9a38e6513446d2d2876f8fbba5fa9bf5bc6178135598d9f1a8b.-pUeEvoZxSPMjlsReWUE-IDYliHwcGXilv_CbN-S0LY
- marketing-analytics-dashboard-metric-chart--total--dark:
- hash: v1.k794b7964.b534f4ca547e10b9fae117c7ad42100972cb5863d76592c5a2db74351020b4bb.K5pm_IZiAgcMUETOyn4mPrPPscHPLJtvj-UX97XC_ic
- marketing-analytics-dashboard-metric-chart--total--light:
- hash: v1.k794b7964.b2249c43b08031cff84d2333c09b1dfafda2bbb321249afc6cfce04af1966028.C7JFm6S2QcyHxJZu1Pebh7Idaevdqlbn0gFdukxHGVI
- marketing-analytics-dashboard-section-switcher--interactive-navigation--dark:
- hash: v1.k794b7964.2fe3cc126cedcb557e16085f3ded5054e98c699e5f0ba98435273de51ddcf248.fDtABuH6P0Lp-EO3fMPs5xxxtU7g6kzS_eWIAlr4Yrw
- marketing-analytics-dashboard-section-switcher--interactive-navigation--light:
- hash: v1.k794b7964.39bc0a8e67496a7645071d8acebab20a6e52b70a8e111d087c57deac5e6804da.BxJIbgasGkapMR2rHPihKjiTEyYy77Y35tedIfazYvE
- marketing-analytics-dashboard-section-switcher--narrow--dark:
- hash: v1.k794b7964.7f9cf9b30f89933e7d0650da0414ee7001f9856d8717bd69af2f2880873b3c16.MX2GsV1y9zfHzEIAY20aKtFbaHkvUzKobcpjYb25bqI
- marketing-analytics-dashboard-section-switcher--narrow--light:
- hash: v1.k794b7964.c0d4b116a5afbe3e5b6b6159d519b54c08071f14cb9824596b1ce10304af6b69.7J099ANtsc1tVP_psTgnMCCvHgRV-YihqS_-YxpXs1o
marketing-analytics-failed-queries--attribution-query-failure--dark:
hash: v1.k794b7964.e745bb4ecdbfbb70a20bb493bd6a3b7b8f2a35c88c808de2d7aa3bccfc2d8be9.-EDk7fcim63V2V0oO4KOcJ0xSF_w-VR4BA8ETQYZnKA
marketing-analytics-failed-queries--attribution-query-failure--light:
@@ -13516,46 +13380,6 @@ snapshots:
hash: v1.k794b7964.536225a6a2ac6f9f09cf4e65461f4784d0fcdc45d7028ccf8f9b2fe16b85abbe.XhoJ5_pnyhKCmDxmVqedDLLGmUrmByirzm-OGykFTuM
scenes-app-marketing-analytics-conversion-recommendation-card--narrow--light:
hash: v1.k794b7964.cbeb4ae795b45495275107103f6e0c37f9ed7ab01298f23c58f5d8a730a980c1.p0qJ9cJxt-eEUId_imrS6W6kiDOiBB0NpjA1yZB0Qws
- scenes-app-marketing-analytics-dashboard-change-value-cell--bounce-rate--dark:
- hash: v1.k794b7964.077ba380688f01ece0aa53fbdd827aa0b79a58e6f952315fe51af26bc835b64a.PRdHzGD2h3pbMEhUAGi2JC6w2vr8_XebNg_iPCpM9bg
- scenes-app-marketing-analytics-dashboard-change-value-cell--bounce-rate--light:
- hash: v1.k794b7964.fa0025bb6bb96998113541c0a88c07df9a3fb13eb88a5d3db77dc09e2610dbb5.YFARE1wxwsYcYAwnmdeWNx0RMg5aJWZ9p_gGHdhbPGo
- scenes-app-marketing-analytics-dashboard-change-value-cell--currency--dark:
- hash: v1.k794b7964.244ae95fb34aeaf551ead9698f7a98eee66e1ab0ae4f71ed2237f96d24143754.VhVCgLRQlP27oGTCKNoe2ODSZ2qAvKLrvmeUsTvCgiw
- scenes-app-marketing-analytics-dashboard-change-value-cell--currency--light:
- hash: v1.k794b7964.294e22100120b3ed041f6064f4de7ea64faf37121cf09bfcadef3972e83371e1.eW-jkMPXbVQN1lDgX8YZ6aUgjHtugXy1jrF-yBcgYwU
- scenes-app-marketing-analytics-dashboard-change-value-cell--duration--dark:
- hash: v1.k794b7964.dd83f21380350590edec4792347a381e44434d043c9828c34ba539cab8a05672.P_wPZwEUIcD_huuRMLLeoUNyIkyo6pkzAQEhDYrpYxA
- scenes-app-marketing-analytics-dashboard-change-value-cell--duration--light:
- hash: v1.k794b7964.3cde4c804c7448d6ece25debff96e7a36377b87890910059d3c535eaaeb7e4d5.VtfsENIxNsgnypzn_sNC9-UeAezicqU8kPyMkl6laW8
- scenes-app-marketing-analytics-dashboard-change-value-cell--interactive-table--dark:
- hash: v1.k794b7964.74c6c7f6b82b0efb2a7308fcae655afc904ef15e368dffaf8771c8250a359461.fbPrR4nWxGldigT8pO2rQi8rLpWbsztppew2sAKKhEU
- scenes-app-marketing-analytics-dashboard-change-value-cell--interactive-table--light:
- hash: v1.k794b7964.b4ed878c5b2b0c63d34a87f57cdbb8f64b5fe31079282d700c0b70720ee3717b.okYTr19qNMuYE_03SNBeIgKv6Nc0MU_T6wpcVSty2i4
- scenes-app-marketing-analytics-dashboard-change-value-cell--negative-currency--dark:
- hash: v1.k794b7964.789d1f0afd837adfd0efa09a542e9f2d378288421df5d8d80b673d748daaeeda.WwxuZ22NM2Zz99PbOJRY_P1cnd8BVQ7wbSMjwLEk7xg
- scenes-app-marketing-analytics-dashboard-change-value-cell--negative-currency--light:
- hash: v1.k794b7964.2da09c227a1de2666e207ac7ac07917036b8ea30b5bcbd6dd85cd9576d4f558a.GbWVCr885-nT6g5UcTX4j60cF7Ul8BL45AI6FOsUdD0
- scenes-app-marketing-analytics-dashboard-change-value-cell--no-baseline--dark:
- hash: v1.k794b7964.f172abbe2b6cff81cbde8c456029d3cdc873fc9090f6980fb8fae5bd94b4312a.sY-BJR13mVtiZx31wFpqAQC5BxW_j3kT9zRXRihr2A8
- scenes-app-marketing-analytics-dashboard-change-value-cell--no-baseline--light:
- hash: v1.k794b7964.90a2c50431c5e06a41bb5177312e766f1285ca34a269c60b712f90adef9af5df.QOEjsl37FOwmDdzdZ5azbvkjE-FIJaqwwJCX2TE0M24
- scenes-app-marketing-analytics-dashboard-change-value-cell--number--dark:
- hash: v1.k794b7964.f6950f48809a084f056f49a14600ed29560971bb5dd25651634d731533f41e5d.C93vGIQ5HAI7xskzcb645hrkLZrKlAUEHcc2kjvuVWo
- scenes-app-marketing-analytics-dashboard-change-value-cell--number--light:
- hash: v1.k794b7964.5f647058804ddb8ae81b40188e1081f68399bb622140c4c63f94c515a37e9181.q_Ntv759JbSmfHBikXMRfCoGiA-gltcRi5q9SBGmi7Q
- scenes-app-marketing-analytics-dashboard-change-value-cell--rate--dark:
- hash: v1.k794b7964.2396ec0386b28781ab80372412ec44bf4f37488ef8122491861b32494666c9f9.FHyeBiNeo-m9vAOnLMFeW7jfD6CPSYVgM0hKpwkOWog
- scenes-app-marketing-analytics-dashboard-change-value-cell--rate--light:
- hash: v1.k794b7964.5f285adee61b3675b3c0e7044f89991a5a6442ba2876118623763ab2ff0006ad.mnm3oxMC4lfAwxe9-FflSu2p-TwLLzL8xFcE9dLk51Q
- scenes-app-marketing-analytics-dashboard-change-value-cell--rounded-flat--dark:
- hash: v1.k794b7964.bee8d683cf64b3c2f8284a8bc4faee4bc714fbde660b04bf50bc02fe75352ef7.wYHeLYpctZsms2TqseLkLTVepIXI4HOKo47oMuWig00
- scenes-app-marketing-analytics-dashboard-change-value-cell--rounded-flat--light:
- hash: v1.k794b7964.f20644df1c54b8e71adc7a548f81a616e95b89513d64974137504a7a41c05dac.J78XkCDuTF8XdkIVhcA_grX77xR6AOhWSfGQVL_KYpo
- scenes-app-marketing-analytics-dashboard-change-value-cell--unavailable--dark:
- hash: v1.k794b7964.a08eefe3f8b95c0cee0659fb050cd3114778edb6a3755fdfe7b95460e031e425.Sodxn6zMfktliL0TqxWRzmRFMPymrVZSrGH4ryLJKRc
- scenes-app-marketing-analytics-dashboard-change-value-cell--unavailable--light:
- hash: v1.k794b7964.077208274eef6634c72fb949f22e3cfc5ce4ee6ed110883744ddc6c598e2997c.8WkzjKlIOrwhI2hYPh3FKHnwWIsSzE39LASNS1SaTo8
scenes-app-marketing-analytics-dismissible-setup-prompts--failed--dark:
hash: v1.k794b7964.51438fd0e71ce7105750a911714f2f25cf70720e99b61348abf6ab932afde6a1.MHYM9cydAa10EVK3eByQMJVNFVS6p9xhnYGXqIKwa8M
scenes-app-marketing-analytics-dismissible-setup-prompts--failed--light:
@@ -13708,14 +13532,6 @@ snapshots:
hash: v1.k794b7964.a10e363be836b1bacfbea847357f80b987323caf54d45e7a85d3a4758ac44671.DbFPlLNt06dWI5V2w2-0luic5oaqJCAgfUS4EBlnvJ8
scenes-app-marketing-analytics-search-performance--narrow-position-metrics--light:
hash: v1.k794b7964.0b7811f39d52b8d297f1b7f75c837bfd43df60b464024804de78ab21e18c1010.kuyz3alS3WRQreQO2U0ylB1c5BZEsaaGbkra06QdSSs
- scenes-app-marketing-analytics-search-performance--new-dashboard-flag-off--dark:
- hash: v1.k794b7964.b5396b32369d9e930e3db3dcd3f7e87bfbe9e813c815be0819b4a6b3f90ae63e.-n0OMQJZ2BHjrGTarQVkOln7dl6v1tLs81vsnimxTlc
- scenes-app-marketing-analytics-search-performance--new-dashboard-flag-off--light:
- hash: v1.k794b7964.8fcb2ab7cbfb8600fb7b1e8484440128366c693dccf8acd1b35bc5f41ba84f0f.XFossOxDeskeQzkA-9uZqNp-B3Q49RghdBcMzvlKRE0
- scenes-app-marketing-analytics-search-performance--new-dashboard-scene--dark:
- hash: v1.k794b7964.4da66e231e98d43143ae46e365cd9a6f263cd8c5ce608d3bb6f778d46623401a.GNeBOxV_q7f9apUzeDNxgQ9CEFXnmt2r-IapMDJGAeE
- scenes-app-marketing-analytics-search-performance--new-dashboard-scene--light:
- hash: v1.k794b7964.d39c6ba1f1bc86ad0d33172b602cc7a0858666418e982d990b7b66e24bf42c1f.aHzF7Z1mI2cphlNtMzG-KbqAGgsNbWjg6S8bs2PtJP4
scenes-app-marketing-analytics-search-performance--not-connected--dark:
hash: v1.k794b7964.fc45f91fd10720c94e64d84bd64d043e472d35c7be2a2c813f98a627fbbd93be.OvmqVf3mYSyJ_wXsOKvp-LWwhymTTD6MbSikTmLg564
scenes-app-marketing-analytics-search-performance--not-connected--light:
@@ -16136,10 +15952,6 @@ snapshots:
hash: v1.k794b7964.55240799900ad880b8e40b2f0a00936830f0547a88613cd476610d2e2e72947b.ihwaSOiLbve6MI_IKzxYoEn3CJjSC1-HkkNxAcZBGDU
scenes-app-web-analytics-pageperformancemetriccard--without-sparkline--light:
hash: v1.k794b7964.e7ebd4a413d617f5c6e38419027f3affa40cd1da68af95d686ccc152860dbb5b.Fq3Sz8vrvMYKZQk1yKdN-t5SvImO0L7rvFjFf0ZyfFc
- scenes-app-web-analytics-search-ai--marketing-page-visibility--dark:
- hash: v1.k794b7964.9d2a4328a633d99cd36f372075097876ee63442f26f6bd99989154fbead648a4.eDi62-RfC2Klyg6ka9LB3FWEqnWuV7_5eSdQ5sSlaPs
- scenes-app-web-analytics-search-ai--marketing-page-visibility--light:
- hash: v1.k794b7964.49d2b18381388fc172ec35ead6730dc7df25977f5e0d62ca61a56cc7090f9e60.0uC7NjwGA9p2v_ZB9ECxxxbiLvjZLaOFmNNWWbWhnC4
scenes-app-web-analytics-search-ai--web-analytics-page-performance--dark:
hash: v1.k794b7964.a1d227732d38e137de94f3d3ecd4bff68a157354afe9699d3fd6ae02f7e8c64c.2NMYhx_jnA8WQO_YQxseSzP8hHOKY8I-NOXbqjF_lKw
scenes-app-web-analytics-search-ai--web-analytics-page-performance--light:
diff --git a/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.test.tsx b/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.test.tsx
index c9237b8aac2a..8fe514e494f7 100644
--- a/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.test.tsx
+++ b/frontend/src/lib/components/ProductEmptyState/ProductEmptyStateGate.test.tsx
@@ -84,10 +84,10 @@ describe('ProductEmptyStateGate', () => {
const setup = productSetupStatusLogic({ productKey: ProductKey.EXPERIMENTS })
setup.actions.setDetectedStatus('loading')
setup.actions.setDetectedStatus(status)
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true })
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: true })
const { rerender } = render(
<ProductEmptyStateGate
- emptyState={{ ...emptyState, bypassFeatureFlag: FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD }}
+ emptyState={{ ...emptyState, bypassFeatureFlag: FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP }}
>
<div>the real scene</div>
</ProductEmptyStateGate>
@@ -102,7 +102,7 @@ describe('ProductEmptyStateGate', () => {
expect(setup.values.skipped).toBe(false)
act(() =>
featureFlagLogic.actions.setFeatureFlags([], {
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: true,
})
)
rerender(
@@ -118,7 +118,7 @@ describe('ProductEmptyStateGate', () => {
productSetupStatusLogic({ productKey: ProductKey.EXPERIMENTS }).actions.setDetectedStatus('needs-setup')
render(
<ProductEmptyStateGate
- emptyState={{ ...emptyState, bypassFeatureFlag: FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD }}
+ emptyState={{ ...emptyState, bypassFeatureFlag: FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP }}
>
<div>the real scene</div>
</ProductEmptyStateGate>
@@ -126,9 +126,7 @@ describe('ProductEmptyStateGate', () => {
expect(noopStatusLogic.findMounted()).toBeNull()
expect(screen.queryByText('Set up experiments')).toBeNull()
expect(screen.queryByText('the real scene')).toBeNull()
- act(() =>
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true })
- )
+ act(() => featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: true }))
expect(screen.getByText('the real scene')).not.toBeNull()
expect(noopStatusLogic.findMounted()).toBeNull()
})
@@ -143,12 +141,12 @@ describe('ProductEmptyStateGate', () => {
['?empty_state=0', false],
['', false],
])('renders the setup screen for %s: %s', (search, expectedForced) => {
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true })
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: true })
router.actions.push(`/experiments${search}`)
render(
<ProductEmptyStateGate
- emptyState={{ ...emptyState, bypassFeatureFlag: FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD }}
+ emptyState={{ ...emptyState, bypassFeatureFlag: FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP }}
>
<div>the real scene</div>
</ProductEmptyStateGate>
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 6d72818128ec..7d8a5c6b763c 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -405,7 +405,6 @@ export const FEATURE_FLAGS = {
MARKETING_ANALYTICS_EXTENDED_DRILL_DOWN: 'marketing-analytics-extended-drill-down', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_MCP: 'marketing-analytics-mcp', // owner: @jabahamondes #team-web-analytics — gates MCP tool exposure (read-only marketing-analytics tools)
MARKETING_ANALYTICS_MULTI_TOUCH_ATTRIBUTION: 'marketing-analytics-multi-touch-attribution', // owner: @jabahamondes #team-web-analytics
- MARKETING_ANALYTICS_NEW_DASHBOARD: 'new-marketing-analytics-dashboard', // owner: @jabahamondes #team-web-analytics — gates the redesigned dashboard and all of its sections
MARKETING_ANALYTICS_OPENAI_ADS: 'marketing-analytics-openai-ads', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_ORGANIC_KEYWORDS: 'marketing-analytics-organic-keywords', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_RETENTION: 'marketing-analytics-retention', // owner: @jabahamondes #team-web-analytics — gates the legacy Retention explorer tab; the new dashboard ignores it
diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
index 07cd57f84faf..61851535d263 100644
--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
@@ -17,15 +17,10 @@ import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { QueryTile } from 'scenes/web-analytics/common'
-import { PagePerformance } from 'scenes/web-analytics/PagePerformance'
-import { PagePerformanceFilters } from 'scenes/web-analytics/PagePerformanceFilters'
-import { pagePerformanceLogic } from 'scenes/web-analytics/pagePerformanceLogic'
import { AttributionTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab'
import { RetentionTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab'
import { UtmAuditTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/UtmAuditTab/UtmAuditTab'
import { WebQuery } from 'scenes/web-analytics/tiles/WebAnalyticsTile'
-import { webAnalyticsFilterLogic } from 'scenes/web-analytics/webAnalyticsFilterLogic'
-import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
@@ -34,7 +29,6 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics/sourcesDataLogic'
import { DetectedSources } from 'products/marketing_analytics/frontend/dashboard/DetectedSources'
-import { NewMarketingAnalyticsDashboard } from 'products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard'
import { SearchConsoleSource } from 'products/marketing_analytics/frontend/dashboard/SearchConsoleSource'
import { SourceSetupPanel } from 'products/marketing_analytics/frontend/dashboard/SourceSetupPanel'
import { marketingAnalyticsEmptyState } from 'products/marketing_analytics/frontend/emptyState/marketingAnalyticsEmptyState'
@@ -102,16 +96,12 @@ const QueryTileItem = ({ tile }: { tile: QueryTile }): JSX.Element => {
}
const LegacySearchConnectionCard = (): JSX.Element | null => {
- const { dataWarehouseSources, isAdPerformance } = useValues(marketingAnalyticsLogic)
+ const { isAdPerformance } = useValues(marketingAnalyticsLogic)
const { showOnboarding } = useValues(marketingOnboardingLogic)
if (showOnboarding && !isAdPerformance) {
return null
}
- return dataWarehouseSources?.results.some((source) =>
- ['GoogleAds', 'BingAds', 'GoogleSearchConsole'].includes(source.source_type)
- ) ? null : (
- <SearchConsoleSource />
- )
+ return <SearchConsoleSource />
}
const MarketingAnalyticsDashboard = (): JSX.Element => {
@@ -404,37 +394,28 @@ const MarketingAnalyticsContent = (): JSX.Element => {
['GoogleAds', 'BingAds', 'GoogleSearchConsole'].includes(source.source_type)
)
- // The redesigned dashboard replaces the current one under the same "Dashboard" tab when its flag is
- // on, so the eventual cutover is just flipping the flag — no tab rename, no extra tab key to strand.
const dashboard = (
<>
- {featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD] ? (
- <NewMarketingAnalyticsDashboard />
- ) : (
- <>
- {(!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] ||
- hasSyncedMarketingSources ||
- hasConnectedSearchSource) && (
- <MarketingAnalyticsFilters
- tabs={<></>}
- searchOnly={
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] &&
- !hasSyncedMarketingSources &&
- hasConnectedSearchSource
- }
- />
- )}
- <MarketingAnalyticsDashboard />
- {hasConnectedSearchSource && (
- <div className="mt-8">
- <SearchPerformanceTab />
- </div>
- )}
- </>
+ {(!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] ||
+ hasSyncedMarketingSources ||
+ hasConnectedSearchSource) && (
+ <MarketingAnalyticsFilters
+ tabs={<></>}
+ searchOnly={
+ !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] &&
+ !hasSyncedMarketingSources &&
+ hasConnectedSearchSource
+ }
+ />
+ )}
+ <MarketingAnalyticsDashboard />
+ {hasConnectedSearchSource && (
+ <div className="mt-8">
+ <SearchPerformanceTab />
+ </div>
)}
- {/* Both dashboards carry the campaign breakdown, whose mapping menus open this modal, so it
- is mounted beside them rather than inside one. It sits in the tab content, because Setup
- and Integration health mount their own copy off the same shared state. */}
+ {/* The campaign breakdown's mapping menus open this modal. It sits in the tab content, because
+ Setup and Integration health mount their own copy off the same shared state. */}
{integrationSettingsModal.integration && (
<IntegrationSettingsModal
integrationName={integrationSettingsModal.integration}
@@ -463,9 +444,8 @@ const MarketingAnalyticsContent = (): JSX.Element => {
const tabs = [
{ key: MarketingAnalyticsTab.DASHBOARD, label: 'Dashboard', content: dashboard },
- ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD] ||
- (!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] &&
- featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS])
+ ...(!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] &&
+ featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]
? [
{
key: MarketingAnalyticsTab.AD_PERFORMANCE,
@@ -504,26 +484,7 @@ const MarketingAnalyticsContent = (): JSX.Element => {
},
]
: []),
- ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]
- ? [
- {
- key: MarketingAnalyticsTab.PAGE_VISIBILITY,
- label: 'Page visibility',
- content: (
- <BindLogic logic={webAnalyticsLogic} props={{ context: 'page-visibility' }}>
- <BindLogic logic={webAnalyticsFilterLogic} props={{ context: 'page-visibility' }}>
- <BindLogic logic={pagePerformanceLogic} props={{ context: 'page-visibility' }}>
- <PagePerformanceFilters tabs={<></>} />
- <PagePerformance />
- </BindLogic>
- </BindLogic>
- </BindLogic>
- ),
- },
- ]
- : []),
- ...(!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD] &&
- featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ATTRIBUTION]
+ ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ATTRIBUTION]
? [
{
key: MarketingAnalyticsTab.ATTRIBUTION,
@@ -532,8 +493,7 @@ const MarketingAnalyticsContent = (): JSX.Element => {
},
]
: []),
- ...(!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD] &&
- featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_RETENTION]
+ ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_RETENTION]
? [
{
key: MarketingAnalyticsTab.RETENTION,
@@ -563,15 +523,9 @@ const MarketingAnalyticsContent = (): JSX.Element => {
const tabIsRendered = tabs.some((tab) => tab.key === activeTab)
useEffect(() => {
if (!tabIsRendered && !absorbed) {
- setActiveTab(
- activeTab === MarketingAnalyticsTab.SEARCH_PERFORMANCE &&
- featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD] &&
- featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]
- ? MarketingAnalyticsTab.AD_PERFORMANCE
- : MarketingAnalyticsTab.DASHBOARD
- )
+ setActiveTab(MarketingAnalyticsTab.DASHBOARD)
}
- }, [tabIsRendered, absorbed, setActiveTab, activeTab, featureFlags])
+ }, [tabIsRendered, absorbed, setActiveTab])
const selectedTab = tabIsRendered ? activeTab : MarketingAnalyticsTab.DASHBOARD
// Only surface the tab bar once a secondary tab is enabled; otherwise show the dashboard directly.
@@ -587,8 +541,6 @@ const MarketingAnalyticsContent = (): JSX.Element => {
const TAB_DESCRIPTIONS: Record<string, string> = {
[MarketingAnalyticsTab.SEARCH_PERFORMANCE]:
'Explore paid and organic search performance across keywords, queries and landing pages.',
- [MarketingAnalyticsTab.PAGE_VISIBILITY]:
- 'Explore page traffic, Google search visibility, AI referrals, crawler activity, and conversions.',
[MarketingAnalyticsTab.AD_PERFORMANCE]: 'Compare ad spend, clicks and impressions across your connected platforms.',
[MarketingAnalyticsTab.DASHBOARD]:
'Analyze your marketing performance across integrations: spend, impressions, conversions, ROAS, and more metrics.',
@@ -603,11 +555,10 @@ const TAB_DESCRIPTIONS: Record<string, string> = {
}
const MarketingAnalyticsAIToolWrapper = ({ children }: { children: React.ReactNode }): JSX.Element => {
- const { activeTab, dateFilter, integrationFilter, compareFilter } = useValues(marketingAnalyticsLogic)
+ const { dateFilter, integrationFilter, compareFilter } = useValues(marketingAnalyticsLogic)
const { conversion_goals, marketingAnalyticsConfig } = useValues(marketingAnalyticsSettingsLogic)
const { featureFlags } = useValues(featureFlagLogic)
- const aiEnabled =
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_AI] && activeTab !== MarketingAnalyticsTab.PAGE_VISIBILITY
+ const aiEnabled = !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_AI]
// Shared context for every Marketing analytics Max tool — consumed by
// MARKETING_CONTEXT_PROMPT in products/marketing_analytics/backend/max_tools.py.
@@ -682,9 +633,7 @@ const MarketingAnalyticsAIToolWrapper = ({ children }: { children: React.ReactNo
export function MarketingAnalyticsScene(): JSX.Element {
const { openSupportForm } = useActions(supportLogic)
const { featureFlags } = useValues(featureFlagLogic)
- const setupEnabled =
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] ||
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]
+ const setupEnabled = !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING]
useEffect(() => (setupEnabled ? setupPlanLogic.mount() : undefined), [setupEnabled])
const { activeTab } = useValues(marketingAnalyticsLogic)
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsx
deleted file mode 100644
index 1517238930d6..000000000000
--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.goals.test.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { marketingOnboardingLogic } from 'scenes/marketing-analytics/Onboarding/marketingOnboardingLogic'
-import {
- marketingAnalyticsLogic,
- MarketingAnalyticsTab,
- SetupSection,
-} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
-import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
-
-import { useMocks } from '~/mocks/jest'
-import { initKeaTests } from '~/test/init'
-
-import { NewMarketingAnalyticsDashboard } from 'products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard'
-
-jest.mock('scenes/web-analytics/tiles/WebAnalyticsTile', () => ({
- VariationCell: () => () => null,
- webAnalyticsDataTableQueryContext: {},
-}))
-jest.mock('~/queries/Query/Query', () => ({ Query: () => null }))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable', () => ({
- AttributionTable: () => null,
-}))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab', () => ({
- AttributionTab: () => null,
-}))
-
-describe('Dashboard goal suggestions', () => {
- it('reuses goal suggestions, remembers collapse and opens their review in Setup', async () => {
- useMocks({
- get: {
- '/api/projects/:team_id/marketing_analytics/setup_plan': () => [
- 200,
- {
- suggestions: [
- {
- id: 'mark_goal_as_revenue:purchase',
- kind: 'mark_goal_as_revenue',
- also_recommended: [],
- title: 'Mark a revenue goal',
- evidence: 'Choose which goal measures revenue.',
- source: 'deterministic',
- severity: 'info',
- unlocks: [],
- apply: {
- op: 'update_conversion_goal',
- conversion_goal_id: 'purchase',
- patch: { counts_as_revenue: true },
- },
- },
- ],
- readiness: [],
- degraded: [],
- truncated: false,
- summary: '',
- },
- ],
- },
- })
- initKeaTests()
- const unmountFeatureFlags = featureFlagLogic.mount()
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING]: true })
- const unmountOnboarding = marketingOnboardingLogic.mount()
- marketingOnboardingLogic.actions.completeOnboarding()
- localStorage.removeItem('marketing-goal-suggestions-expanded')
- const unmountMarketing = marketingAnalyticsLogic.mount()
- const unmountSetup = setupPlanLogic.mount()
- const view = render(<NewMarketingAnalyticsDashboard />)
- try {
- await screen.findByText('Suggested conversion goals (1)')
- expect(
- screen
- .getByText('Suggested conversion goals (1)')
- .closest('[aria-expanded]')
- ?.getAttribute('aria-expanded')
- ).toBe('false')
- fireEvent.click(screen.getByText('Suggested conversion goals (1)'))
- await screen.findByText('Mark a revenue goal')
- fireEvent.click(screen.getByText('Suggested conversion goals (1)'))
- expect(localStorage.getItem('marketing-goal-suggestions-expanded')).toBe('false')
- view.unmount()
- render(<NewMarketingAnalyticsDashboard />)
- expect(
- screen
- .getByText('Suggested conversion goals (1)')
- .closest('[aria-expanded]')
- ?.getAttribute('aria-expanded')
- ).toBe('false')
- fireEvent.click(screen.getByText('Suggested conversion goals (1)'))
- fireEvent.click(screen.getByText('Review change', { exact: true }))
- await waitFor(() => expect(marketingAnalyticsLogic.values.activeTab).toBe(MarketingAnalyticsTab.SETUP))
- expect(marketingAnalyticsLogic.values.setupSection).toBe(SetupSection.CONVERSION_GOALS)
- expect(setupPlanLogic.values.reviewingSuggestion?.id).toBe('mark_goal_as_revenue:purchase')
- fireEvent.click(screen.getByText('Dismiss'))
- await waitFor(() => expect(screen.queryByText('Suggested conversion goals (1)')).toBeNull())
- } finally {
- cleanup()
- unmountFeatureFlags()
- setupPlanLogic.actions.restoreAllDismissed()
- localStorage.removeItem('marketing-goal-suggestions-expanded')
- unmountOnboarding()
- localStorage.removeItem('marketing-analytics-onboarding-completed')
- unmountSetup()
- unmountMarketing()
- }
- })
-})
diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.sources.test.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.sources.test.tsx
deleted file mode 100644
index c8b1744c7200..000000000000
--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.sources.test.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
-
-import { supportLogic } from 'lib/components/Support/supportLogic'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { MarketingAnalyticsScene } from 'scenes/marketing-analytics/MarketingAnalyticsScene'
-import { marketingOnboardingLogic } from 'scenes/marketing-analytics/Onboarding/marketingOnboardingLogic'
-import {
- marketingAnalyticsLogic,
- MarketingAnalyticsTab,
-} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
-import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
-
-import { useMocks } from '~/mocks/jest'
-import { initKeaTests } from '~/test/init'
-
-import { DetectedSources } from 'products/marketing_analytics/frontend/dashboard/DetectedSources'
-import { NewMarketingAnalyticsDashboard } from 'products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard'
-
-jest.mock('products/data_warehouse/frontend/shared/components/SourceIcon', () => ({ SourceIcon: () => null }))
-
-jest.mock('~/queries/Query/Query', () => ({ Query: () => null }))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable', () => ({
- AttributionTable: () => null,
-}))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab', () => ({
- AttributionTab: () => null,
-}))
-
-it.each([false, true])('keeps suggestions actionable with synced data %s', async (hasSyncedData) => {
- useMocks({
- get: {
- '/api/projects/:team_id/marketing_analytics/setup_plan': () => [
- 200,
- {
- suggestions: [
- {
- id: 'connect_source:GoogleAds',
- kind: 'connect_source',
- also_recommended: [],
- title: 'Connect Google Ads',
- evidence: 'Traffic contains Google Ads tags.',
- integration: 'GoogleAds',
- source: 'deterministic',
- severity: 'info',
- unlocks: [],
- apply: { op: 'open_source_wizard', kind: 'GoogleAds' },
- },
- ],
- readiness: [],
- degraded: [],
- truncated: false,
- summary: '',
- },
- ],
- },
- })
- initKeaTests()
- const unmountFeatureFlags = featureFlagLogic.mount()
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING]: true })
- const unmountOnboarding = marketingOnboardingLogic.mount()
- marketingOnboardingLogic.actions.completeOnboarding()
- localStorage.removeItem('marketing-source-suggestions-expanded')
- const unmountMarketing = marketingAnalyticsLogic.mount()
- const readiness = jest
- .spyOn(marketingAnalyticsLogic.selectors, 'hasSyncedMarketingSources')
- .mockReturnValue(hasSyncedData)
- const unmountSetup = setupPlanLogic.mount()
- const view = render(<NewMarketingAnalyticsDashboard />)
- try {
- await screen.findByText('Connect your ad platforms')
- expect(screen.queryByText('Your connections are getting ready')).toBeNull()
- expect(screen.queryByText('You can leave this page. Your import will continue in the background.')).toBeNull()
- expect(screen.queryByText('Your marketing data in one place') !== null).toBe(!hasSyncedData)
- expect(screen.getByText('Google Ads')).not.toBeNull()
- view.unmount()
- render(<NewMarketingAnalyticsDashboard />)
- expect(screen.getByText('Google Ads')).not.toBeNull()
- fireEvent.click(screen.getByText('Browse integrations'))
- await screen.findByText('Connect your marketing sources')
- expect(screen.queryByText('Google Search Console')).toBeNull()
- expect(marketingAnalyticsLogic.values.activeTab).toBe(MarketingAnalyticsTab.DASHBOARD)
- fireEvent.click(screen.getByText('Back to suggestions'))
- expect(screen.getByText('Google Ads')).not.toBeNull()
- expect(screen.queryByText('Review in setup')).toBeNull()
- fireEvent.click(screen.getByText('Dismiss'))
- await waitFor(() => expect(screen.queryByText('Google Ads')).toBeNull())
- } finally {
- cleanup()
- readiness.mockRestore()
- unmountFeatureFlags()
- setupPlanLogic.actions.restoreAllDismissed()
- localStorage.removeItem('marketing-source-suggestions-expanded')
- unmountOnboarding()
- localStorage.removeItem('marketing-analytics-onboarding-completed')
- unmountSetup()
- unmountMarketing()
- }
-})
-
-it.each([
- [false, false, 'Finding your ad platforms'],
- [true, false, 'Finding your ad platforms'],
- [false, true, 'Could not check your events'],
-])('distinguishes scan loading %s and failure %s', (loading, failed, heading) => {
- initKeaTests()
- const unmountFlags = featureFlagLogic.mount()
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING]: true })
- const unmountSetup = setupPlanLogic.mount()
- const plan = jest.spyOn(setupPlanLogic.selectors, 'setupPlan').mockReturnValue(null)
- const planLoading = jest.spyOn(setupPlanLogic.selectors, 'setupPlanLoading').mockReturnValue(loading)
- const planFailed = jest.spyOn(setupPlanLogic.selectors, 'setupPlanFailed').mockReturnValue(failed)
- try {
- render(<DetectedSources />)
- expect(screen.getByText(heading)).not.toBeNull()
- } finally {
- cleanup()
- plan.mockRestore()
- planLoading.mockRestore()
- planFailed.mockRestore()
- unmountSetup()
- unmountFlags()
- }
-})
-
-it('opens the feedback form from the source onboarding header', async () => {
- initKeaTests()
- const unmountFlags = featureFlagLogic.mount()
- featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING]: true })
- try {
- render(<MarketingAnalyticsScene />)
- fireEvent.click(screen.getByText('Send feedback'))
- await waitFor(() => {
- expect(supportLogic.values.sendSupportRequest.kind).toBe('feedback')
- expect(supportLogic.values.isEmailFormOpen).toBe(true)
- })
- } finally {
- cleanup()
- unmountFlags()
- }
-})
diff --git a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx b/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx
deleted file mode 100644
index 1b01446cbd99..000000000000
--- a/frontend/src/scenes/marketing-analytics/NewMarketingAnalyticsDashboard.test.tsx
+++ /dev/null
@@ -1,229 +0,0 @@
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
-import { useValues } from 'kea'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-
-import { NewMarketingAnalyticsDashboard } from 'products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard'
-
-jest.mock('scenes/marketing-analytics/Setup/sectionRouting', () => ({ suggestionsForSection: () => [] }))
-
-jest.mock('scenes/marketing-analytics/Setup/SuggestionRow', () => ({ SuggestionRow: () => null }))
-
-jest.mock('kea', () => ({
- ...jest.requireActual('kea'),
- useValues: jest.fn(),
- useActions: () => new Proxy({}, { get: () => jest.fn() }),
-}))
-jest.mock('@posthog/lemon-ui', () => ({
- LemonBanner: ({ children }: { children: React.ReactNode }) => <div role="alert">{children}</div>,
- LemonCard: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- LemonSelect: ({
- value,
- onChange,
- options,
- 'aria-label': label,
- }: {
- value: string
- onChange: (value: string) => void
- options: { value: string; label: string }[]
- 'aria-label': string
- }) => (
- <select aria-label={label} value={value} onChange={(event) => onChange(event.target.value)}>
- {options.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- ),
- LemonButton: ({
- children,
- onClick,
- 'aria-pressed': pressed,
- }: {
- children: React.ReactNode
- onClick: () => void
- 'aria-pressed'?: boolean
- }) => (
- <button onClick={onClick} aria-pressed={pressed}>
- {children}
- </button>
- ),
- LemonSkeleton: () => null,
-}))
-jest.mock('lib/components/CompareFilter/CompareFilter', () => ({ CompareFilter: () => <div>Compare periods</div> }))
-jest.mock('lib/components/DateFilter/DateFilter', () => ({ DateFilter: () => null }))
-jest.mock('lib/logic/featureFlagLogic', () => ({ featureFlagLogic: {} }))
-jest.mock('scenes/web-analytics/common', () => ({ MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS: {} }))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic', () => ({
- marketingAnalyticsLogic: {},
- SetupSection: { CONVERSION_GOALS: 'conversion-goals' },
-}))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/shared', () => ({
- MarketingAnalyticsCell: () => null,
-}))
-jest.mock('scenes/web-analytics/tiles/WebAnalyticsTile', () => ({
- VariationCell: () => () => null,
- webAnalyticsDataTableQueryContext: {},
-}))
-jest.mock('~/queries/nodes/DataNode/dataNodeLogic', () => ({ dataNodeLogic: (props: { key: string }) => ({ props }) }))
-jest.mock('~/queries/nodes/OverviewGrid/OverviewMetricCardGrid', () => ({ OverviewMetricCardGrid: () => null }))
-jest.mock('~/queries/nodes/WebOverview/WebOverview', () => ({ labelFromKey: () => '' }))
-jest.mock('~/queries/Query/Query', () => ({
- Query: ({ query }: { query: { kind: string } }) => (
- <div data-attr={query.kind === 'DataTableNode' ? 'traffic-query' : 'trend-query'}>{JSON.stringify(query)}</div>
- ),
-}))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab', () => ({
- AttributionTab: () => <div>Attribution explorer</div>,
-}))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic', () => ({ setupPlanLogic: {} }))
-
-jest.mock('scenes/teamLogic', () => ({ teamLogic: {} }))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic', () => ({
- marketingAttributionLogic: {},
-}))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable', () => ({
- AttributionTable: () => null,
-}))
-jest.mock('scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab', () => ({
- RetentionTab: () => <div>Retention explorer</div>,
-}))
-
-jest.mock('scenes/marketing-analytics/Onboarding/Onboarding', () => ({
- Onboarding: () => <div>Marketing onboarding</div>,
-}))
-
-jest.mock('products/marketing_analytics/frontend/dashboard/DetectedSources', () => ({ DetectedSources: () => null }))
-
-describe('NewMarketingAnalyticsDashboard', () => {
- afterEach(cleanup)
-
- it.each([
- ['marketing-acquisition-overview', 'failed-traffic-query', 'current-traffic-query', 'failed-traffic-query'],
- ['marketing-acquisition-overview', undefined, 'current-traffic-query', 'current-traffic-query'],
- ['marketing-acquisition-customers', 'failed-customer-query', 'current-customer-query', 'failed-customer-query'],
- ['marketing-acquisition-customers', undefined, 'current-customer-query', 'current-customer-query'],
- ['marketing-acquisition-overview', undefined, null, null],
- ])('identifies the failed %s request with error ID %s and request ID %s', (key, errorId, requestId, expected) => {
- jest.mocked(useValues).mockImplementation((logic) => ({
- dateFilter: { dateFrom: '-30d', dateTo: null },
- compareFilter: { compare: false },
- shouldFilterTestAccounts: false,
- responseLoading: false,
- setupPlan: {},
- visibleSuggestions: [],
- featureFlags: {},
- nativeSources: [{ id: 'connected-source', source_type: 'GoogleAds' }],
- validExternalTables: [],
- showOnboarding: false,
- allAvailableSourcesWithStatus: [],
- hasSyncedMarketingSources: true,
- sourceValidationError: null,
- trafficOrderBy: {},
- trafficChartMetric: 'visitors',
- trafficChartSeries: { kind: 'EventsNode', event: null, math: 'dau', custom_name: 'Visitors' },
- customerConversionGoal: { kind: 'EventsNode', event: 'purchase' },
- customerGoals: [],
- ...(typeof logic !== 'function' && (logic as { props?: { key?: string } }).props?.key === key
- ? {
- responseError: 'Query failed',
- responseErrorObject: { queryId: errorId },
- queryId: requestId,
- response: { query_status: { id: 'previous-successful-query' } },
- }
- : {}),
- }))
-
- render(<NewMarketingAnalyticsDashboard />)
-
- const error = screen.getByRole('alert')
- expect(error.textContent?.match(/Query ID: (.+)/)?.[1] ?? null).toBe(expected)
- expect(error.textContent).not.toContain('previous-successful-query')
- })
-
- it.each(['ads', 'gsc', 'gsc-without-flag', 'none', 'onboarding-disabled'] as const)(
- 'handles source onboarding for %s',
- (sourceState) => {
- const searchConsoleOnly = sourceState.startsWith('gsc')
- jest.mocked(useValues).mockReturnValue({
- dateFilter: { dateFrom: '-30d', dateTo: null },
- compareFilter: { compare: false },
- shouldFilterTestAccounts: false,
- responseLoading: false,
- setupPlan: {},
- visibleSuggestions: [],
- featureFlags: {
- [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]: sourceState === 'gsc',
- [FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING]: sourceState !== 'onboarding-disabled',
- },
- nativeSources: sourceState === 'ads' ? [{ id: 'connected-source', source_type: 'GoogleAds' }] : [],
- dataWarehouseSources: { results: searchConsoleOnly ? [{ source_type: 'GoogleSearchConsole' }] : [] },
- validExternalTables: [],
- showOnboarding: sourceState !== 'ads',
- allAvailableSourcesWithStatus: [],
- hasSyncedMarketingSources: true,
- sourceValidationError: null,
- trafficOrderBy: {},
- trafficChartMetric: 'visitors',
- trafficChartSeries: { kind: 'EventsNode', event: null, math: 'dau', custom_name: 'Visitors' },
- })
-
- render(<NewMarketingAnalyticsDashboard />)
-
- if (sourceState === 'gsc-without-flag' || sourceState === 'none') {
- expect(screen.getByText('Marketing onboarding')).not.toBeNull()
- return
- }
- expect(screen.queryByText('Marketing onboarding')).toBeNull()
- expect(screen.getByLabelText('Acquisition')).not.toBeNull()
- expect(screen.queryByText('Compare periods')).not.toBeNull()
- expect(screen.queryByText('Reload summary')).not.toBeNull()
- expect(screen.getByText('Engagement')).not.toBeNull()
- expect(screen.queryByText('Attribution explorer')).toBeNull()
- expect(screen.queryByText('Retention explorer')).toBeNull()
- expect(screen.getByText('Visitors over time')).not.toBeNull()
- expect(screen.getByLabelText('Chart metric')).not.toBeNull()
- const trendBeforeBreakdown = screen.getByTestId('trend-query').textContent
- expect(JSON.parse(trendBeforeBreakdown || '{}').source.series).toEqual([
- { kind: 'EventsNode', event: null, math: 'dau', custom_name: 'Visitors' },
- ])
- fireEvent.change(screen.getByLabelText('Traffic breakdown'), { target: { value: 'InitialUTMCampaign' } })
- expect(JSON.parse(screen.getByTestId('traffic-query').textContent || '{}').source).toMatchObject({
- kind: 'WebStatsTableQuery',
- breakdownBy: 'InitialUTMCampaign',
- includeBounceRate: false,
- dateRange: { date_from: '-30d', date_to: null },
- compareFilter: { compare: false },
- })
- expect(screen.getByTestId('trend-query').textContent).toBe(trendBeforeBreakdown)
- fireEvent.click(screen.getByText('Engagement'))
- expect(JSON.parse(screen.getByTestId('traffic-query').textContent || '{}')).toMatchObject({
- hiddenColumns: ['context.columns.views'],
- source: {
- breakdownBy: 'InitialUTMCampaign',
- includeBounceRate: true,
- dateRange: { date_from: '-30d', date_to: null },
- compareFilter: { compare: false },
- },
- })
- expect(screen.queryByLabelText('Acquisition')).toBeNull()
- expect(screen.getByLabelText('Engagement')).not.toBeNull()
- fireEvent.click(screen.getByText('Conversion'))
- expect(screen.getByText('Attribution explorer')).not.toBeNull()
- expect(screen.queryByLabelText('Engagement')).toBeNull()
- fireEvent.click(screen.getByText('Revenue'))
- expect(screen.queryByText('Attribution explorer')).toBeNull()
- expect(screen.getByLabelText('Revenue')).not.toBeNull()
- fireEvent.click(screen.getByText('Retention'))
- expect(screen.getByText('Retention explorer')).not.toBeNull()
- expect(screen.queryByText('Compare periods')).toBeNull()
- expect(screen.queryByText('Reload summary')).toBeNull()
- fireEvent.click(screen.getByText('Acquisition'))
- expect(screen.getByLabelText('Acquisition')).not.toBeNull()
- expect(screen.queryByText('Compare periods')).not.toBeNull()
- expect(screen.queryByText('Reload summary')).not.toBeNull()
- expect(screen.queryByText('Retention explorer')).toBeNull()
- }
- )
-})
diff --git a/frontend/src/scenes/marketing-analytics/marketingAcquisitionLogic.test.ts b/frontend/src/scenes/marketing-analytics/marketingAcquisitionLogic.test.ts
deleted file mode 100644
index 311a714916bf..000000000000
--- a/frontend/src/scenes/marketing-analytics/marketingAcquisitionLogic.test.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
-
-import { expectLogic } from 'kea-test-utils'
-
-import { teamLogic } from 'scenes/teamLogic'
-
-import { ConversionGoalFilter, NodeKind, WebAnalyticsOrderByFields } from '~/queries/schema/schema-general'
-import { initKeaTests } from '~/test/init'
-import { PropertyFilterType, PropertyOperator } from '~/types'
-
-import { marketingAcquisitionLogic } from 'products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic'
-
-describe('marketingAcquisitionLogic', () => {
- it('keeps customer goal filters and falls back when a selected goal is removed or unmarked', async () => {
- initKeaTests()
- const logic = marketingAcquisitionLogic()
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- const goal: ConversionGoalFilter = {
- kind: NodeKind.EventsNode,
- event: 'customer_created',
- conversion_goal_id: 'customer',
- conversion_goal_name: 'New customer',
- schema_map: {},
- counts_as_customer: true,
- properties: [
- { type: PropertyFilterType.Event, key: 'plan', value: 'paid', operator: PropertyOperator.Exact },
- ],
- }
- const loadGoals = async (goals: ConversionGoalFilter[]): Promise<void> => {
- await expectLogic(logic, () =>
- teamLogic.actions.loadCurrentTeamSuccess({
- ...MOCK_DEFAULT_TEAM,
- marketing_analytics_config: { conversion_goals: goals },
- })
- ).toFinishAllListeners()
- }
- await loadGoals([goal, { ...goal, kind: NodeKind.ActionsNode, id: 42, conversion_goal_id: 'action' }])
- expect(logic.values.customerConversionGoal).toEqual({
- customEventName: 'customer_created',
- properties: goal.properties,
- })
- logic.actions.setCustomerGoalId('action')
- expect(logic.values.customerConversionGoal).toEqual({ actionId: 42, properties: goal.properties })
- await loadGoals([goal])
- expect(logic.values.selectedCustomerGoal?.conversion_goal_id).toBe('customer')
- await loadGoals([{ ...goal, counts_as_customer: false }])
- expect(logic.values.customerConversionGoal).toBeNull()
- logic.unmount()
- })
-
- it('toggles metric sorting independently for acquisition and engagement', () => {
- initKeaTests()
- const logic = marketingAcquisitionLogic()
- logic.mount()
- try {
- logic.actions.toggleTrafficSort('acquisition', WebAnalyticsOrderByFields.Views)
- expect(logic.values.trafficOrderBy.acquisition).toEqual([WebAnalyticsOrderByFields.Views, 'DESC'])
- logic.actions.toggleTrafficSort('acquisition', WebAnalyticsOrderByFields.Views)
- expect(logic.values.trafficOrderBy.acquisition).toEqual([WebAnalyticsOrderByFields.Views, 'ASC'])
- logic.actions.toggleTrafficSort('engagement', WebAnalyticsOrderByFields.BounceRate)
- expect(logic.values.trafficOrderBy.engagement).toEqual([WebAnalyticsOrderByFields.BounceRate, 'DESC'])
- expect(logic.values.trafficOrderBy.acquisition).toEqual([WebAnalyticsOrderByFields.Views, 'ASC'])
- logic.actions.toggleTrafficSort('acquisition', WebAnalyticsOrderByFields.UniqueConversions)
- expect(logic.values.trafficOrderBy.acquisition).toEqual([
- WebAnalyticsOrderByFields.UniqueConversions,
- 'DESC',
- ])
- } finally {
- logic.unmount()
- }
- })
-})
diff --git a/frontend/src/scenes/web-analytics/PagePerformance.stories.tsx b/frontend/src/scenes/web-analytics/PagePerformance.stories.tsx
index 393a2ae7a3ab..d473408de46d 100644
--- a/frontend/src/scenes/web-analytics/PagePerformance.stories.tsx
+++ b/frontend/src/scenes/web-analytics/PagePerformance.stories.tsx
@@ -208,11 +208,3 @@ export function WebAnalyticsPagePerformance(): JSX.Element {
return <App />
}
-
-MarketingPageVisibility.parameters = {
- pageUrl: `${urls.marketingAnalyticsApp()}?tab=page-visibility`,
- featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING, FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
-}
-export function MarketingPageVisibility(): JSX.Element {
- return <App />
-}
diff --git a/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts b/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
index a2ce7caf95ab..6e72495c0446 100644
--- a/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
+++ b/frontend/src/scenes/web-analytics/pagePerformanceLogic.ts
@@ -661,7 +661,7 @@ export type pagePerformanceLogicType = MakeLogicType<
export const pagePerformanceLogic: LogicWrapper<pagePerformanceLogicType> = kea<pagePerformanceLogicType>([
props({} as WebAnalyticsLogicProps),
key((props) => props.context ?? 'web-analytics'),
- path((key) => ['scenes', key === 'page-visibility' ? 'pageVisibility' : 'webAnalytics', 'pagePerformanceLogic']),
+ path(['scenes', 'webAnalytics', 'pagePerformanceLogic']),
connect((props: WebAnalyticsLogicProps) => ({
actions: [dataNodeCollectionLogic({ key: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID }), ['reloadAll']],
values: [
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
index df7f3190b1f3..fa4354b87313 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
@@ -23,7 +23,6 @@ import {
TrendsQuery,
DataTableNode,
MarketingAnalyticsAggregatedQuery,
- MarketingAnalyticsAttributionBreakdown,
MarketingAnalyticsTableQuery,
MarketingAnalyticsSearchRow,
MarketingAnalyticsOrderBy,
@@ -31,7 +30,6 @@ import {
MarketingAnalyticsColumnsSchemaNames,
NodeKind,
SourceMap,
- WebAnalyticsPropertyFilters,
} from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import {
@@ -40,8 +38,6 @@ import {
ExternalDataSchemaStatus,
ExternalDataSource,
ExternalDataSourceSchema,
- PropertyFilterType,
- PropertyOperator,
} from '~/types'
import { SEARCH_PERFORMANCE_QUERY_KEY } from 'products/marketing_analytics/frontend/search/searchPerformance'
@@ -50,7 +46,6 @@ import { searchPerformanceLogic } from 'products/marketing_analytics/frontend/se
import {
MarketingAnalyticsTab,
MarketingSourceStatus,
- MarketingDashboardView,
SetupSection,
marketingAnalyticsLogic,
} from './marketingAnalyticsLogic'
@@ -393,7 +388,7 @@ describe('marketingAnalyticsLogic', () => {
).toFinishAllListeners()
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.MARKETING_ANALYTICS_SEARCH_CONVERSIONS]: true,
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]: true,
})
logic.actions.setActiveTab(MarketingAnalyticsTab.AD_PERFORMANCE)
expect(logic.values.includeConversionGoals).toBe(true)
@@ -440,13 +435,13 @@ describe('marketingAnalyticsLogic', () => {
).toFinishAllListeners()
expect(search.values.query.includePostHogConversions).toBe(true)
featureFlagLogic.actions.setFeatureFlags([], {
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]: true,
[FEATURE_FLAGS.MARKETING_ANALYTICS_SEARCH_CONVERSIONS]: false,
})
expect(search.values.query.includePostHogConversions).toBe(false)
expect(search.values.displayMetrics).toBe('conversions')
featureFlagLogic.actions.setFeatureFlags([], {
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]: true,
[FEATURE_FLAGS.MARKETING_ANALYTICS_SEARCH_CONVERSIONS]: true,
})
expect(search.values.query.includePostHogConversions).toBe(true)
@@ -457,14 +452,14 @@ describe('marketingAnalyticsLogic', () => {
search.actions.setBreakdown('page')
expect(search.values.query.includePostHogConversions).toBe(true)
featureFlagLogic.actions.setFeatureFlags([], {
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]: true,
[FEATURE_FLAGS.MARKETING_ANALYTICS_SEARCH_CONVERSIONS]: false,
})
expect(logic.values.includeConversionGoals).toBe(true)
expect(search.values.query.includePostHogConversions).toBe(false)
expect(search.values.displayMetrics).toBe('traffic')
featureFlagLogic.actions.setFeatureFlags([], {
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]: true,
[FEATURE_FLAGS.MARKETING_ANALYTICS_SEARCH_CONVERSIONS]: true,
})
expect(search.values.query.includePostHogConversions).toBe(true)
@@ -567,7 +562,7 @@ describe('marketingAnalyticsLogic', () => {
for (const precomputed of [false, true]) {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.MARKETING_ANALYTICS_SEARCH_CONVERSIONS]: true,
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]: true,
[FEATURE_FLAGS.MARKETING_ANALYTICS_COSTS_PRECOMPUTATION]: precomputed,
})
logic.actions.setAdPerformanceConversionGoals(true)
@@ -631,7 +626,7 @@ describe('marketingAnalyticsLogic', () => {
)
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.MARKETING_ANALYTICS_SEARCH_CONVERSIONS]: true,
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: legacyState !== 'flag-off',
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]: legacyState !== 'flag-off',
})
expect(logic.values.includeConversionGoals).toBe(true)
expect((tiles.values.overviewTile.query as MarketingAnalyticsAggregatedQuery).select).toBeUndefined()
@@ -652,7 +647,7 @@ describe('marketingAnalyticsLogic', () => {
await expectLogic(logic).toFinishAllListeners()
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.MARKETING_ANALYTICS_SEARCH_CONVERSIONS]: true,
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]: true,
})
logic.actions.setActiveTab(MarketingAnalyticsTab.AD_PERFORMANCE)
expect(logic.values.includeConversionGoals).toBe(false)
@@ -1125,112 +1120,6 @@ describe('marketingAnalyticsLogic', () => {
unmountSettings()
}
)
- it('carries dashboard view, breakdown and filters in the URL', async () => {
- featureFlagLogic.mount()
- featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD], {
- [FEATURE_FLAGS.MARKETING_ANALYTICS_SEARCH_CONVERSIONS]: true,
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
- })
- logic = marketingAnalyticsLogic()
- logic.mount()
-
- await expectLogic(logic, () => logic.actions.setDates('-30d', null)).toFinishAllListeners()
- expect(router.values.searchParams).not.toHaveProperty('view')
- expect(router.values.searchParams).not.toHaveProperty('breakdown')
- expect(new URLSearchParams(router.values.location.search).get('date_to')).toBe('')
-
- const filters: WebAnalyticsPropertyFilters = [
- {
- type: PropertyFilterType.Session,
- key: '$channel_type',
- operator: PropertyOperator.Exact,
- value: 'Direct',
- },
- ]
- logic.actions.setDashboardView(MarketingDashboardView.ENGAGEMENT)
- logic.actions.setDashboardBreakdown(MarketingAnalyticsAttributionBreakdown.Campaign)
- logic.actions.setDashboardProperties(filters)
- await expectLogic(logic).toFinishAllListeners()
-
- expect(router.values.searchParams).toMatchObject({
- view: 'engagement',
- breakdown: 'campaign',
- filters,
- })
-
- await expectLogic(logic, () => logic.actions.setDates('-7d', null)).toFinishAllListeners()
- expect(router.values.searchParams).toMatchObject({ view: 'engagement', breakdown: 'campaign', filters })
-
- logic.actions.setDashboardView(MarketingDashboardView.OVERVIEW)
- logic.actions.setDashboardBreakdown(MarketingAnalyticsAttributionBreakdown.Channel)
- await expectLogic(logic).toFinishAllListeners()
- expect(router.values.searchParams).toMatchObject({ view: 'overview', breakdown: 'channel' })
- expect(new URLSearchParams(router.values.location.search).get('date_to')).toBe('')
-
- await expectLogic(logic, () =>
- router.actions.push(urls.marketingAnalyticsApp(), { view: 'retention', breakdown: 'source' })
- ).toMatchValues({
- dashboardView: MarketingDashboardView.RETENTION,
- dashboardBreakdown: MarketingAnalyticsAttributionBreakdown.Source,
- dashboardProperties: [],
- })
-
- await expectLogic(logic, () => router.actions.push(urls.marketingAnalyticsApp())).toMatchValues({
- dashboardView: MarketingDashboardView.OVERVIEW,
- dashboardBreakdown: MarketingAnalyticsAttributionBreakdown.Channel,
- dashboardProperties: [],
- })
- })
-
- it.each([
- {
- search: { view: 'retention' },
- savedBreakdown: 'campaign',
- expectedView: MarketingDashboardView.RETENTION,
- expectedBreakdown: MarketingAnalyticsAttributionBreakdown.Channel,
- },
- {
- search: { breakdown: 'source' },
- savedBreakdown: 'campaign',
- expectedView: MarketingDashboardView.OVERVIEW,
- expectedBreakdown: MarketingAnalyticsAttributionBreakdown.Source,
- },
- {
- search: {},
- savedBreakdown: 'campaign',
- expectedView: MarketingDashboardView.ENGAGEMENT,
- expectedBreakdown: MarketingAnalyticsAttributionBreakdown.Campaign,
- },
- {
- search: { view: 'retention' },
- savedBreakdown: 'retired_dimension',
- expectedView: MarketingDashboardView.RETENTION,
- expectedBreakdown: MarketingAnalyticsAttributionBreakdown.Channel,
- },
- ])(
- 'hydrates $search with persisted breakdown $savedBreakdown',
- async ({ search, savedBreakdown, expectedView, expectedBreakdown }) => {
- localStorage.setItem(
- `${MOCK_TEAM_ID}__.scenes.webAnalytics.marketingAnalyticsLogic._dashboardView`,
- JSON.stringify(MarketingDashboardView.ENGAGEMENT)
- )
- localStorage.setItem(
- `${MOCK_TEAM_ID}__.scenes.webAnalytics.marketingAnalyticsLogic._dashboardBreakdown`,
- JSON.stringify(savedBreakdown)
- )
- router.actions.push(urls.marketingAnalyticsApp(), search)
-
- logic = marketingAnalyticsLogic()
- logic.mount()
-
- await expectLogic(logic).toMatchValues({
- dashboardView: expectedView,
- dashboardBreakdown: expectedBreakdown,
- dashboardProperties: [],
- })
- }
- )
-
it.each([
['?date_from=-7d&date_to=', { dateFrom: '-7d', dateTo: null }],
['?date_from=-7d&date_to=&tab=setup&section=sources', { dateFrom: '-7d', dateTo: null }],
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
index 6ab72b85e8b7..a9f50973bc75 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
@@ -11,7 +11,7 @@ import {
selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
-import { actionToUrl, router, urlToAction } from 'kea-router'
+import { actionToUrl, router } from 'kea-router'
import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -24,7 +24,6 @@ import { urls } from 'scenes/urls'
import { MARKETING_ANALYTICS_DATA_COLLECTION_NODE_ID } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
-import { isWebAnalyticsPropertyFilters } from '~/queries/schema-guards'
import {
CompareFilter,
ConversionGoalFilter,
@@ -34,7 +33,6 @@ import {
DateRange,
IntegrationFilter,
MarketingAnalyticsAggregatedQuery,
- MarketingAnalyticsAttributionBreakdown,
MarketingAnalyticsColumnsSchemaNames,
MarketingAnalyticsDrillDownLevel,
NativeMarketingSource,
@@ -43,7 +41,6 @@ import {
ProductKey,
SourceMap,
VALID_NATIVE_MARKETING_SOURCES,
- WebAnalyticsPropertyFilters,
} from '~/queries/schema/schema-general'
import { MARKETING_ANALYTICS_SCHEMA } from '~/queries/schema/schema-general'
import { DataWarehouseSettingsTab, ExternalDataSchemaStatus, ExternalDataSource, IntervalType } from '~/types'
@@ -59,7 +56,6 @@ import type { FeatureFlagsSet } from '../../../../../../lib/logic/featureFlagLog
import type { ProductIntentProperties } from '../../../../../../lib/utils/product-intents'
import { defaultConversionGoalFilter } from '../components/settings/constants'
import { SetupEntryPoint, marketingAnalyticsSettingsLogic } from './marketingAnalyticsSettingsLogic'
-import { DASHBOARD_BREAKDOWNS, DEFAULT_DASHBOARD_BREAKDOWN } from './marketingBreakdown'
import { externalAdsCostTile } from './marketingCostTile'
import {
MarketingDashboardMapper,
@@ -91,7 +87,6 @@ export enum MarketingAnalyticsTab {
DASHBOARD = 'dashboard',
AD_PERFORMANCE = 'ad-performance',
SEARCH_PERFORMANCE = 'search-performance',
- PAGE_VISIBILITY = 'page-visibility',
ATTRIBUTION = 'attribution',
RETENTION = 'retention',
// Still the tab key when Setup's flag is off, which is everywhere until it rolls
@@ -121,52 +116,6 @@ export interface DashboardGoalsConfigured {
revenueGoal: boolean
}
-/** Sections of the redesigned dashboard. Declared here rather than in the scene so the logic that
- * owns the URL doesn't have to import the component tree. */
-export enum MarketingDashboardView {
- OVERVIEW = 'overview',
- ACQUISITION = 'acquisition',
- ENGAGEMENT = 'engagement',
- RETENTION = 'retention',
- CONVERSION = 'conversion',
-}
-
-export const DEFAULT_DASHBOARD_VIEW = MarketingDashboardView.OVERVIEW
-
-function hasDashboardParams(searchParams: URLSearchParams): boolean {
- return ['view', 'breakdown', 'filters'].some((key) => searchParams.has(key))
-}
-
-function dashboardParamsFromSearch(searchParams: URLSearchParams): {
- view?: MarketingDashboardView
- breakdown?: MarketingAnalyticsAttributionBreakdown
- properties?: WebAnalyticsPropertyFilters
-} {
- const params: ReturnType<typeof dashboardParamsFromSearch> = hasDashboardParams(searchParams)
- ? { view: DEFAULT_DASHBOARD_VIEW, breakdown: DEFAULT_DASHBOARD_BREAKDOWN, properties: [] }
- : {}
- const view = searchParams.get('view') as MarketingDashboardView | null
- if (view && Object.values(MarketingDashboardView).includes(view)) {
- params.view = view
- }
- const breakdown = searchParams.get('breakdown') as MarketingAnalyticsAttributionBreakdown | null
- if (breakdown && DASHBOARD_BREAKDOWNS.includes(breakdown)) {
- params.breakdown = breakdown
- }
- const filters = searchParams.get('filters')
- if (filters) {
- try {
- const parsed = JSON.parse(filters)
- if (isWebAnalyticsPropertyFilters(parsed)) {
- params.properties = parsed
- }
- } catch {
- // A hand-edited or truncated URL should load the dashboard unfiltered, not break it.
- }
- }
- return params
-}
-
/** Where a tab key lands once Setup absorbs it. Applied by the scene, which is what
* knows whether Setup is rendering — with its flag off `integration-health` is still a
* real tab and resolves on its own. */
@@ -344,8 +293,6 @@ export interface marketingAnalyticsLogicValues {
dataWarehouseSourcesLoading: boolean // sourceManagementLogic
dataWarehouseTables: DatabaseSchemaDataWarehouseTable[] // sourceManagementLogic
baseCurrency: CurrencyCode // teamLogic
- _dashboardBreakdown: MarketingAnalyticsAttributionBreakdown
- _dashboardView: MarketingDashboardView
_drillDownLevel: MarketingAnalyticsDrillDownLevel
_integrationFilter: IntegrationFilter
activeTab: MarketingAnalyticsTab
@@ -392,9 +339,6 @@ export interface marketingAnalyticsLogicValues {
conversionGoalInput: ConversionGoalFilter
conversionGoalModalVisible: boolean
createMarketingDataWarehouseNodes: DataWarehouseNode[]
- dashboardBreakdown: MarketingAnalyticsAttributionBreakdown
- dashboardProperties: WebAnalyticsPropertyFilters
- dashboardView: MarketingDashboardView
dateFilter: {
dateFrom: string | null
dateTo: string | null
@@ -570,15 +514,6 @@ export interface marketingAnalyticsLogicActions {
setConversionGoalInput: (goal: ConversionGoalFilter) => {
goal: ConversionGoalFilter
}
- setDashboardBreakdown: (breakdown: MarketingAnalyticsAttributionBreakdown) => {
- breakdown: MarketingAnalyticsAttributionBreakdown
- }
- setDashboardProperties: (properties: WebAnalyticsPropertyFilters) => {
- properties: WebAnalyticsPropertyFilters
- }
- setDashboardView: (view: MarketingDashboardView) => {
- view: MarketingDashboardView
- }
setDateInterval: (interval: IntervalType) => {
interval: IntervalType
}
@@ -626,7 +561,6 @@ export interface marketingAnalyticsLogicActions {
value: true
}
syncFromUrl: (params: {
- breakdown?: MarketingAnalyticsAttributionBreakdown
chartDisplayType?: ChartDisplayType
compare?: boolean
compare_to?: string
@@ -636,12 +570,9 @@ export interface marketingAnalyticsLogicActions {
includeNonIntegrated?: boolean
integrationSourceIds?: string[]
interval?: IntervalType
- properties?: WebAnalyticsPropertyFilters
tileColumnSelection?: string
- view?: MarketingDashboardView
}) => {
params: {
- breakdown?: MarketingAnalyticsAttributionBreakdown | undefined
chartDisplayType?: ChartDisplayType | undefined
compare?: boolean | undefined
compare_to?: string | undefined
@@ -651,9 +582,7 @@ export interface marketingAnalyticsLogicActions {
includeNonIntegrated?: boolean | undefined
integrationSourceIds?: string[] | undefined
interval?: IntervalType | undefined
- properties?: WebAnalyticsPropertyFilters | undefined
tileColumnSelection?: string | undefined
- view?: MarketingDashboardView | undefined
}
}
}
@@ -673,10 +602,6 @@ export interface marketingAnalyticsLogicMeta {
_drillDownLevel: MarketingAnalyticsDrillDownLevel,
featureFlags: FeatureFlagsSet
) => MarketingAnalyticsDrillDownLevel
- dashboardView: (_dashboardView: MarketingDashboardView) => MarketingDashboardView
- dashboardBreakdown: (
- _dashboardBreakdown: MarketingAnalyticsAttributionBreakdown
- ) => MarketingAnalyticsAttributionBreakdown
validSourcesMap: (sources_map: Record<string, SourceMap>) => {
[x: string]: SourceMap
} | null
@@ -916,9 +841,6 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
chartDisplayType?: ChartDisplayType
tileColumnSelection?: string
drillDownLevel?: MarketingAnalyticsDrillDownLevel
- view?: MarketingDashboardView
- breakdown?: MarketingAnalyticsAttributionBreakdown
- properties?: WebAnalyticsPropertyFilters
}) => ({ params }),
showColumnConfigModal: true,
hideColumnConfigModal: true,
@@ -927,9 +849,6 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
setChartDisplayType: (chartDisplayType: ChartDisplayType) => ({ chartDisplayType }),
setTileColumnSelection: (column: validColumnsForTiles) => ({ column }),
setDrillDownLevel: (level: MarketingAnalyticsDrillDownLevel) => ({ level }),
- setDashboardView: (view: MarketingDashboardView) => ({ view }),
- setDashboardBreakdown: (breakdown: MarketingAnalyticsAttributionBreakdown) => ({ breakdown }),
- setDashboardProperties: (properties: WebAnalyticsPropertyFilters) => ({ properties }),
setInitialized: true,
}),
reducers(() => {
@@ -1119,46 +1038,18 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
params.drillDownLevel !== undefined ? params.drillDownLevel : state,
},
],
- _dashboardView: [
- DEFAULT_DASHBOARD_VIEW as MarketingDashboardView,
- persistConfig,
- {
- setDashboardView: (_, { view }) => view,
- syncFromUrl: (state, { params }) => (params.view !== undefined ? params.view : state),
- },
- ],
- _dashboardBreakdown: [
- DEFAULT_DASHBOARD_BREAKDOWN as MarketingAnalyticsAttributionBreakdown,
- persistConfig,
- {
- setDashboardBreakdown: (_, { breakdown }) => breakdown,
- syncFromUrl: (state, { params }) => (params.breakdown !== undefined ? params.breakdown : state),
- },
- ],
- // Not persisted: a filter is a per-visit refinement, so it travels in the URL for
- // sharing but does not follow someone back to the dashboard tomorrow.
- dashboardProperties: [
- [] as WebAnalyticsPropertyFilters,
- {
- setDashboardProperties: (_, { properties }) => properties,
- syncFromUrl: (state, { params }) => (params.properties !== undefined ? params.properties : state),
- },
- ],
}
}),
selectors({
setupEnabled: [
(s) => [s.featureFlags],
- (featureFlags: FeatureFlagsSet): boolean =>
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP] ||
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP],
],
isAdPerformance: [
(s) => [s.activeTab, s.featureFlags],
(activeTab: MarketingAnalyticsTab, featureFlags: FeatureFlagsSet): boolean =>
activeTab === MarketingAnalyticsTab.AD_PERFORMANCE &&
- (!!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD] ||
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS]),
+ !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS],
],
includeConversionGoals: [
(s) => [s.isAdPerformance, s.adPerformanceConversionGoals, s.conversion_goals],
@@ -1181,16 +1072,6 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
return level
},
],
- dashboardView: [
- (s) => [s._dashboardView],
- (view: MarketingDashboardView): MarketingDashboardView =>
- Object.values(MarketingDashboardView).includes(view) ? view : DEFAULT_DASHBOARD_VIEW,
- ],
- dashboardBreakdown: [
- (s) => [s._dashboardBreakdown],
- (breakdown: MarketingAnalyticsAttributionBreakdown): MarketingAnalyticsAttributionBreakdown =>
- DASHBOARD_BREAKDOWNS.includes(breakdown) ? breakdown : DEFAULT_DASHBOARD_BREAKDOWN,
- ],
validSourcesMap: [
(s) => [s.sources_map],
(sources_map: Record<string, SourceMap>) => {
@@ -1634,13 +1515,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
],
}),
actionToUrl(({ values }) => {
- const buildUrl = (includeDashboardState: boolean): [string, string] => {
- if (values.activeTab === MarketingAnalyticsTab.PAGE_VISIBILITY) {
- const searchParams = new URLSearchParams(router.values.location.search)
- searchParams.set('tab', MarketingAnalyticsTab.PAGE_VISIBILITY)
- searchParams.delete('section')
- return [router.values.location.pathname, searchParams.toString()]
- }
+ const buildCurrentUrl = (): [string, string] => {
const searchParams = new URLSearchParams()
const currentSearchParams = new URLSearchParams(router.values.location.search)
for (const key of ['select', 'order_column', 'order_direction', 'pinned_columns']) {
@@ -1686,20 +1561,6 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
searchParams.set('include_non_integrated', 'false')
}
- // The current dashboard uses local section state. Only the new controls or an
- // existing dashboard URL opt into shared navigation state.
- if (
- values.activeTab === MarketingAnalyticsTab.DASHBOARD &&
- values.featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD] &&
- (includeDashboardState || hasDashboardParams(new URLSearchParams(router.values.location.search)))
- ) {
- searchParams.set('view', values.dashboardView)
- searchParams.set('breakdown', values.dashboardBreakdown)
- if (values.dashboardProperties.length > 0) {
- searchParams.set('filters', JSON.stringify(values.dashboardProperties))
- }
- }
-
// Chart display type
if (values.chartDisplayType) {
searchParams.set('chart_display_type', values.chartDisplayType)
@@ -1718,9 +1579,6 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
return [router.values.location.pathname, searchParams.toString()]
}
- const buildCurrentUrl = (): [string, string] => buildUrl(false)
- const buildDashboardUrl = (): [string, string] => buildUrl(true)
-
return {
setActiveTab: buildCurrentUrl,
setSetupSection: buildCurrentUrl,
@@ -1732,25 +1590,9 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
setChartDisplayType: buildCurrentUrl,
setTileColumnSelection: buildCurrentUrl,
setDrillDownLevel: buildCurrentUrl,
- setDashboardView: buildDashboardUrl,
- setDashboardBreakdown: buildDashboardUrl,
- setDashboardProperties: buildDashboardUrl,
// Note: syncFromUrl is NOT mapped here - it's only for receiving URL changes
}
}),
- urlToAction(({ actions }) => ({
- [urls.marketingAnalyticsApp()]: (_, searchParams, __, { initial, search }) => {
- if (initial || (searchParams.tab && searchParams.tab !== MarketingAnalyticsTab.DASHBOARD)) {
- return
- }
- actions.syncFromUrl({
- view: DEFAULT_DASHBOARD_VIEW,
- breakdown: DEFAULT_DASHBOARD_BREAKDOWN,
- properties: [],
- ...dashboardParamsFromSearch(new URLSearchParams(search)),
- })
- },
- })),
listeners(({ actions, values, cache }) => {
const trackDashboardInteraction = (): void => {
// Only track after initialization to avoid tracking initial render/setup
@@ -1957,8 +1799,6 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
params.drillDownLevel = drillDownLevel
}
- Object.assign(params, dashboardParamsFromSearch(searchParams))
-
// Apply URL params if any were found
if (Object.keys(params).length > 0) {
actions.syncFromUrl(params)
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.ts
index c763d0ae9e1f..421605003a06 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown.ts
@@ -18,19 +18,6 @@ export const BREAKDOWN_LABELS: Record<MarketingAnalyticsAttributionBreakdown, st
[MarketingAnalyticsAttributionBreakdown.LandingPage]: 'Landing page',
}
-/** The dimensions the dashboard offers. Content and term are left out because a marketer rarely
- * breaks a whole dashboard down by them, and every extra option costs a row in the picker. */
-export const DASHBOARD_BREAKDOWNS: readonly MarketingAnalyticsAttributionBreakdown[] = [
- MarketingAnalyticsAttributionBreakdown.Channel,
- MarketingAnalyticsAttributionBreakdown.Source,
- MarketingAnalyticsAttributionBreakdown.Campaign,
- MarketingAnalyticsAttributionBreakdown.Medium,
- MarketingAnalyticsAttributionBreakdown.ReferringDomain,
- MarketingAnalyticsAttributionBreakdown.LandingPage,
-]
-
-export const DEFAULT_DASHBOARD_BREAKDOWN = MarketingAnalyticsAttributionBreakdown.Channel
-
/** One page-level breakdown drives both the retention query, which takes this enum, and the web
* stats tables, which take their own. Declared total so a new member fails to compile here rather
* than silently dropping a table. */
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts b/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts
index cdae8712dfc1..304ad947600d 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsFilterLogic.ts
@@ -30,10 +30,7 @@ import { DeviceType, INITIAL_WEB_ANALYTICS_FILTER } from './common'
import { WebAnalyticsLogicProps } from './webAnalyticsLogicProps'
const teamId = window.POSTHOG_APP_CONTEXT?.current_team?.id
-const persistConfig = (props: WebAnalyticsLogicProps): { persist: true; prefix: string } => ({
- persist: true as const,
- prefix: `${teamId}__${props.context === 'page-visibility' ? 'page_visibility__' : ''}`,
-})
+const persistConfig = { persist: true as const, prefix: `${teamId}__` }
const eventFilter = (key: string, value: string | string[]): WebAnalyticsPropertyFilter => ({
type: PropertyFilterType.Event,
@@ -148,7 +145,7 @@ export interface webAnalyticsFilterLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface webAnalyticsFilterLogicMeta {
- key: 'page-visibility' | 'web-analytics'
+ key: 'web-analytics'
__keaTypeGenInternalSelectorTypes: {
hasHostFilter: (rawWebAnalyticsFilters: WebAnalyticsPropertyFilters) => boolean
authorizedDomains: (rawAuthorizedUrls: string[]) => string[]
@@ -174,7 +171,7 @@ export type webAnalyticsFilterLogicType = MakeLogicType<
export const webAnalyticsFilterLogic: LogicWrapper<webAnalyticsFilterLogicType> = kea<webAnalyticsFilterLogicType>([
props({} as WebAnalyticsLogicProps),
key((props) => props.context ?? 'web-analytics'),
- path((key) => ['scenes', key === 'page-visibility' ? 'pageVisibility' : 'webAnalytics', 'webAnalyticsFilterLogic']),
+ path(['scenes', 'webAnalytics', 'webAnalyticsFilterLogic']),
connect(() => ({
values: [
authorizedUrlListLogic({
@@ -216,10 +213,10 @@ export const webAnalyticsFilterLogic: LogicWrapper<webAnalyticsFilterLogicType>
}),
clearFilters: true,
}),
- reducers(({ props }) => ({
+ reducers(() => ({
rawWebAnalyticsFilters: [
INITIAL_WEB_ANALYTICS_FILTER,
- persistConfig(props),
+ persistConfig,
{
setWebAnalyticsFilters: (_, { webAnalyticsFilters }) => webAnalyticsFilters,
clearFilters: () => INITIAL_WEB_ANALYTICS_FILTER,
@@ -300,7 +297,7 @@ export const webAnalyticsFilterLogic: LogicWrapper<webAnalyticsFilterLogicType>
],
domainFilter: [
null as string | null,
- persistConfig(props),
+ persistConfig,
{
setDomainFilter: (_: string | null, payload: { domain: string | null }) => {
const { domain } = payload
@@ -323,7 +320,7 @@ export const webAnalyticsFilterLogic: LogicWrapper<webAnalyticsFilterLogicType>
],
deviceTypeFilter: [
null as DeviceType | null,
- persistConfig(props),
+ persistConfig,
{
setDeviceTypeFilter: (_: DeviceType | null, { deviceType }: { deviceType: DeviceType | null }) =>
deviceType,
@@ -333,7 +330,7 @@ export const webAnalyticsFilterLogic: LogicWrapper<webAnalyticsFilterLogicType>
],
countryFilter: [
null as string | null,
- persistConfig(props),
+ persistConfig,
{
setCountryFilter: (_: string | null, { countryCode }: { countryCode: string | null }) => countryCode,
clearFilters: () => null,
@@ -342,7 +339,7 @@ export const webAnalyticsFilterLogic: LogicWrapper<webAnalyticsFilterLogicType>
],
referrerFilter: [
null as string | null,
- persistConfig(props),
+ persistConfig,
{
setReferrerFilter: (_: string | null, { referrer }: { referrer: string | null }) => referrer,
clearFilters: () => null,
@@ -351,7 +348,7 @@ export const webAnalyticsFilterLogic: LogicWrapper<webAnalyticsFilterLogicType>
],
compareFilter: [
{ compare: true } as CompareFilter,
- persistConfig(props),
+ persistConfig,
{
setCompareFilter: (_, { compareFilter }) => compareFilter,
clearFilters: () => ({ compare: true }),
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
index 2128a7796d22..4b899f7b83be 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
@@ -16,11 +16,6 @@ import { botAnalyticsLogic } from './botAnalyticsLogic'
import { GraphsTab, ProductTab, TileId } from './common'
import { FOCUS_MODE_TILE_IDS } from './focus-mode/focusModeMapping'
import { WebAnalyticsConcern, getFocusModeOnboardingSeenKey } from './focus-mode/types'
-import { pagePerformanceLogic } from './pagePerformanceLogic'
-import {
- MarketingAnalyticsTab,
- marketingAnalyticsLogic,
-} from './tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
import { webAnalyticsFilterLogic } from './webAnalyticsFilterLogic'
import { webAnalyticsLogic } from './webAnalyticsLogic'
@@ -634,17 +629,11 @@ describe('webAnalyticsLogic URL restoration', () => {
value: ['cpc'],
}
- it.each([
- ['/web/page-performance', {}, FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE],
- ['/marketing', { tab: 'page-visibility' }, FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
- ])('keeps all page performance controls in the shareable URL at %s', async (pathname, searchParams, flag) => {
- if (pathname === '/marketing') {
- logic.unmount()
- logic = webAnalyticsLogic({ context: 'page-visibility' })
- logic.mount()
- }
- featureFlagLogic.actions.setFeatureFlags([flag], { [flag]: true })
- router.actions.push(pathname, searchParams)
+ it('keeps all page performance controls in the shareable URL', async () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE], {
+ [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE]: true,
+ })
+ router.actions.push('/web/page-performance')
await expectLogic(logic).toFinishAllListeners()
logic.actions.setDates('-30d', '2026-08-05')
logic.actions.setConversionGoal({ actionId: 42 })
@@ -660,8 +649,7 @@ describe('webAnalyticsLogic URL restoration', () => {
logic.actions.setReferrerFilter('google.com')
await expectLogic(logic).toFinishAllListeners()
- expect(router.values.location.pathname.endsWith(pathname)).toBe(true)
- expect(router.values.searchParams).toMatchObject(searchParams)
+ expect(router.values.location.pathname.endsWith('/web/page-performance')).toBe(true)
expect(router.values.searchParams).toMatchObject({
date_from: '-30d',
date_to: '2026-08-05',
@@ -741,107 +729,15 @@ describe('webAnalyticsLogic URL restoration', () => {
}
})
- it.each([
- ['/web/page-performance', {}, FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE],
- ['/marketing', { tab: 'page-visibility' }, FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
- ])('applies property filters from a shared page performance URL at %s', async (pathname, searchParams, flag) => {
- if (pathname === '/marketing') {
- logic.unmount()
- logic = webAnalyticsLogic({ context: 'page-visibility' })
- logic.mount()
- }
- featureFlagLogic.actions.setFeatureFlags([flag], { [flag]: true })
- router.actions.push(pathname, { ...searchParams, filters: [FILTER_A] })
+ it('applies property filters from a shared page performance URL', async () => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE], {
+ [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE]: true,
+ })
+ router.actions.push('/web/page-performance', { filters: [FILTER_A] })
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.productTab).toBe(ProductTab.PAGE_PERFORMANCE)
expect(logic.values.rawWebAnalyticsFilters).toEqual([FILTER_A])
- if (pathname === '/marketing') {
- const marketingLogic = marketingAnalyticsLogic()
- marketingLogic.mount()
- try {
- expect(marketingLogic.values.activeTab).toBe(MarketingAnalyticsTab.PAGE_VISIBILITY)
- expect(router.values.location.pathname.endsWith('/marketing')).toBe(true)
- expect(router.values.searchParams.filters).toEqual([FILTER_A])
- } finally {
- marketingLogic.unmount()
- }
- }
- })
-
- it('isolates page visibility state, URLs and persistence from Web Analytics in both directions', async () => {
- featureFlagLogic.actions.setFeatureFlags(
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD, FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE],
- {
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: true,
- [FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE]: true,
- }
- )
- const marketing = webAnalyticsLogic({ context: 'page-visibility' })
- let unmountMarketing = marketing.mount()
- try {
- router.actions.push('/web/page-performance')
- logic.actions.setDates('-30d', null)
- logic.actions.setWebAnalyticsFilters([FILTER_A])
- logic.actions.setCountryFilter('US')
- logic.actions.setConversionGoal({ actionId: 42 })
- logic.actions.setCompareFilter({ compare: false })
- await expectLogic(logic).toFinishAllListeners()
-
- router.actions.push('/marketing', {
- tab: 'page-visibility',
- date_from: '-14d',
- interval: 'week',
- filters: [FILTER_B],
- country: 'CL',
- 'conversionGoal.actionId': 43,
- compare_filter: { compare: true },
- })
- await expectLogic(marketing).toFinishAllListeners()
- expect(marketing.values.dateFilter).toMatchObject({ dateFrom: '-14d', interval: 'week' })
- expect(marketing.values.rawWebAnalyticsFilters).toEqual([FILTER_B])
- expect(logic.values.dateFilter.dateFrom).toBe('-30d')
- expect(logic.values.rawWebAnalyticsFilters).toEqual([FILTER_A])
- expect(logic.values.countryFilter).toBe('US')
- expect(logic.values.conversionGoal).toEqual({ actionId: 42 })
- expect(logic.values.rawCompareFilter).toEqual({ compare: false })
-
- const report = pagePerformanceLogic.build({ context: 'page-visibility' })
- expect(report.values.pageCandidateQuery.dateRange?.date_from).toBe('-14d')
- expect(report.values.pageCandidateQuery.properties).toEqual(marketing.values.webAnalyticsFilters)
- expect(report.values.conversionGoal).toEqual({ actionId: 43 })
-
- marketing.actions.setCountryFilter(null)
- marketing.actions.setDates('-7d', null)
- await expectLogic(marketing).toFinishAllListeners()
- expect(router.values.location.pathname.endsWith('/marketing')).toBe(true)
- expect(router.values.searchParams.country).toBeUndefined()
- expect(logic.values.countryFilter).toBe('US')
-
- unmountMarketing()
- unmountMarketing = marketing.mount()
- expect(marketing.values.dateFilter.dateFrom).toBe('-7d')
- expect(marketing.values.countryFilter).toBeNull()
-
- router.actions.push('/web/page-performance', { date_from: '-90d', filters: [FILTER_A] })
- logic.actions.setCountryFilter('CA')
- logic.actions.setWebAnalyticsFilters([FILTER_A, FILTER_B])
- await expectLogic(logic).toFinishAllListeners()
- expect(marketing.values.dateFilter.dateFrom).toBe('-7d')
- expect(marketing.values.rawWebAnalyticsFilters).toEqual([FILTER_B])
- expect(marketing.values.countryFilter).toBeNull()
- expect(marketing.values.conversionGoal).toEqual({ actionId: 43 })
- expect(marketing.values.rawCompareFilter).toEqual({ compare: true })
- expect(router.values.location.pathname.endsWith('/web/page-performance')).toBe(true)
-
- logic.unmount()
- logic = webAnalyticsLogic()
- logic.mount()
- expect(logic.values.dateFilter.dateFrom).toBe('-90d')
- expect(logic.values.countryFilter).toBe('CA')
- } finally {
- unmountMarketing()
- }
})
it('leaves a drilled-in filter in place on back-navigation', async () => {
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index a29030160970..3f5c443762ae 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -550,7 +550,7 @@ export interface webAnalyticsLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface webAnalyticsLogicMeta {
- key: 'page-visibility' | 'web-analytics'
+ key: 'web-analytics'
__keaTypeGenInternalSelectorTypes: {
compareFilter: (rawCompareFilter: CompareFilter, dateFilter: DateFilterState) => CompareFilter
restrictedUiEnabled: (featureFlags: FeatureFlagsSet, currentTeam: TeamPublicType | TeamType | null) => boolean
@@ -733,7 +733,7 @@ export type webAnalyticsLogicType = MakeLogicType<
export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAnalyticsLogicType>([
props({} as WebAnalyticsLogicProps),
key((props) => props.context ?? 'web-analytics'),
- path((key) => ['scenes', key === 'page-visibility' ? 'pageVisibility' : 'webAnalytics', 'webAnalyticsSceneLogic']),
+ path(['scenes', 'webAnalytics', 'webAnalyticsSceneLogic']),
connect((props: WebAnalyticsLogicProps) => ({
values: [
featureFlagLogic,
@@ -904,10 +904,8 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
},
},
})),
- reducers(({ props }) => {
- const persistConfig = buildTeamScopedPersistenceConfig(
- props.context === 'page-visibility' ? 'page_visibility__' : ''
- )
+ reducers(() => {
+ const persistConfig = buildTeamScopedPersistenceConfig('')
// The precompute toggle changed from opt-in (default `false`) to a tri-state where
// `null` means "use the team default". Legacy users persisted the old `false`, which
// would now read as an explicit opt-out. A versioned prefix orphans that stale value so
@@ -3211,7 +3209,7 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
actions.loadShouldShowGeoIPQueries()
}),
- trackedActionToUrl(({ values, cache, props }) => {
+ trackedActionToUrl(({ values, cache }) => {
const buildStateUrl = (): string => {
const urlParams = new URLSearchParams(router.values.location.search)
@@ -3317,10 +3315,7 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
} else {
urlParams.delete('referrer')
}
- const basePath =
- props.context === 'page-visibility'
- ? urls.marketingAnalyticsApp()
- : urls.webAnalyticsPagePerformance()
+ const basePath = urls.webAnalyticsPagePerformance()
return `${basePath}${urlParams.toString() ? '?' + urlParams.toString() : ''}`
} else if (productTab === ProductTab.AGENTS) {
urlParams.delete('filters')
@@ -3436,13 +3431,7 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
// tells kea-router to skip the write, breaking the actionToUrl <-> urlToAction cascade that
// otherwise fires a burst of redundant evaluations and trips the rapid-URL-change detector.
// A single corrective write is emitted afterwards by `reconcileUrlAfterRestore`.
- const isMarketingRoute = router.values.location.pathname.endsWith('/marketing')
- if (
- (props.context === 'page-visibility'
- ? !isMarketingRoute || router.values.searchParams.tab !== 'page-visibility'
- : isMarketingRoute) ||
- cache.applyUrlStateDepth > 0
- ) {
+ if (router.values.location.pathname.endsWith('/marketing') || cache.applyUrlStateDepth > 0) {
return undefined
}
return buildStateUrl()
@@ -3474,7 +3463,7 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
}
}),
- urlToAction(({ actions, values, cache, props }): UrlToActionPayload<webAnalyticsLogicType> => {
+ urlToAction(({ actions, values, cache }): UrlToActionPayload<webAnalyticsLogicType> => {
const applyUrlState = (
{ productTab = ProductTab.ANALYTICS }: { productTab?: ProductTab },
{
@@ -3529,11 +3518,7 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
if (
productTab === ProductTab.PAGE_PERFORMANCE &&
- !values.featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE] &&
- !(
- props.context === 'page-visibility' &&
- values.featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]
- )
+ !values.featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PAGE_PERFORMANCE]
) {
router.actions.replace(urls.webAnalytics())
return
@@ -3710,16 +3695,6 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna
}
}
- if (props.context === 'page-visibility') {
- return {
- '/marketing': (_, searchParams) => {
- if (searchParams.tab === 'page-visibility') {
- toAction({ productTab: ProductTab.PAGE_PERFORMANCE }, searchParams)
- }
- },
- }
- }
-
return {
'/web': toAction,
'/web/bots': (_, searchParams) => {
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogicProps.ts b/frontend/src/scenes/web-analytics/webAnalyticsLogicProps.ts
index 0e6e8828c1f1..ce6138940662 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogicProps.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogicProps.ts
@@ -1,3 +1,3 @@
export interface WebAnalyticsLogicProps {
- context?: 'web-analytics' | 'page-visibility'
+ context?: 'web-analytics'
}
diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.py
index b0ac82a65a51..3b5f18f76fbd 100644
--- a/products/marketing_analytics/backend/api.py
+++ b/products/marketing_analytics/backend/api.py
@@ -150,7 +150,6 @@ def _setup_enabled(request: Request, team: Team, *, include_read_only: bool = Fa
)
for flag in (
"marketing-analytics-setup",
- "new-marketing-analytics-dashboard",
*(
("marketing-analytics-source-onboarding", "marketing-analytics-setup-plan-mcp")
if include_read_only
diff --git a/products/marketing_analytics/backend/test_api_apply_setup_ops.py b/products/marketing_analytics/backend/test_api_apply_setup_ops.py
index 33962bc9f285..66bb23cf391b 100644
--- a/products/marketing_analytics/backend/test_api_apply_setup_ops.py
+++ b/products/marketing_analytics/backend/test_api_apply_setup_ops.py
@@ -419,15 +419,12 @@ class TestApplySetupOpsFeatureFlag(APIBaseTest):
get_or_create_team_extension(self.team, TeamMarketingAnalyticsConfig)
cache.clear()
- @parameterized.expand(
- [(False, False, False), (False, False, True), (False, True, False), (True, False, False), (True, True, True)]
- )
- def test_setup_availability(self, setup: bool, dashboard: bool, mcp: bool) -> None:
+ @parameterized.expand([(False, False), (False, True), (True, False), (True, True)])
+ def test_setup_availability(self, setup: bool, mcp: bool) -> None:
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
flags = {
"marketing-analytics-setup": setup,
- "new-marketing-analytics-dashboard": dashboard,
"marketing-analytics-setup-plan-mcp": mcp,
}
with patch(_FLAG_TARGET, side_effect=lambda flag, *args, **kwargs: flags[flag]):
@@ -437,9 +434,9 @@ class TestApplySetupOpsFeatureFlag(APIBaseTest):
format="json",
)
- assert response.status_code == (200 if setup or dashboard else 404)
+ assert response.status_code == (200 if setup else 404)
assert TeamMarketingAnalyticsConfig.objects.get(team=self.team).custom_source_mappings == (
- {"MetaAds": ["fb-ads"]} if setup or dashboard else {}
+ {"MetaAds": ["fb-ads"]} if setup else {}
)
diff --git a/products/marketing_analytics/backend/test_api_setup_plan.py b/products/marketing_analytics/backend/test_api_setup_plan.py
index e49ddb641458..5218e59074eb 100644
--- a/products/marketing_analytics/backend/test_api_setup_plan.py
+++ b/products/marketing_analytics/backend/test_api_setup_plan.py
@@ -170,18 +170,16 @@ class TestSetupPlanFeatureFlag(APIBaseTest):
@parameterized.expand(
[
- (False, False, False, False),
- (False, False, False, True),
- (False, False, True, False),
- (False, True, False, False),
- (True, False, False, False),
- (True, True, True, True),
+ (False, False, False),
+ (False, False, True),
+ (False, True, False),
+ (True, False, False),
+ (True, True, True),
]
)
- def test_setup_availability(self, setup: bool, dashboard: bool, onboarding: bool, mcp: bool) -> None:
+ def test_setup_availability(self, setup: bool, onboarding: bool, mcp: bool) -> None:
flags = {
"marketing-analytics-setup": setup,
- "new-marketing-analytics-dashboard": dashboard,
"marketing-analytics-source-onboarding": onboarding,
"marketing-analytics-setup-plan-mcp": mcp,
}
@@ -191,8 +189,8 @@ class TestSetupPlanFeatureFlag(APIBaseTest):
):
response = self.client.get(self.url)
- assert response.status_code == (200 if setup or dashboard or onboarding or mcp else 404)
- assert build.call_count == int(setup or dashboard or onboarding or mcp)
+ assert response.status_code == (200 if setup or onboarding or mcp else 404)
+ assert build.call_count == int(setup or onboarding or mcp)
def test_marketing_access_does_not_enable_source_onboarding(self) -> None:
with (
diff --git a/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.stories.tsx b/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.stories.tsx
deleted file mode 100644
index e0ccff115a6f..000000000000
--- a/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.stories.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { Meta, StoryObj } from '@storybook/react'
-
-import { CustomerAcquisitionCards } from './CustomerAcquisitionCards'
-
-const meta: Meta<typeof CustomerAcquisitionCards> = {
- title: 'Marketing Analytics/Customer acquisition cards',
- component: CustomerAcquisitionCards,
- decorators: [
- (Story) => (
- <div className="grid w-160 max-w-full grid-cols-2 gap-2">
- <Story />
- </div>
- ),
- ],
- args: {
- configurationLoading: false,
- configured: true,
- loading: false,
- error: false,
- customerResults: [{ key: 'unique conversions', kind: 'unit', value: 20, previous: 10 }],
- trafficResults: [{ key: 'visitors', kind: 'unit', value: 100, previous: 100 }],
- onConfigure: () => {},
- onRetry: () => {},
- },
-}
-
-export default meta
-type Story = StoryObj<typeof CustomerAcquisitionCards>
-
-export const Configured: Story = {}
-export const Unconfigured: Story = { args: { configured: false } }
-export const Loading: Story = {
- args: { loading: true },
- parameters: { testOptions: { waitForLoadersToDisappear: false } },
-}
-export const ConfigurationLoading: Story = {
- args: { configurationLoading: true, configured: false },
- parameters: { testOptions: { waitForLoadersToDisappear: false } },
-}
-export const Error: Story = { args: { error: true } }
-export const NoCustomers: Story = {
- args: { customerResults: [{ key: 'unique conversions', kind: 'unit', value: 0, previous: 0 }] },
-}
diff --git a/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.tsx b/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.tsx
deleted file mode 100644
index 2f0586e807b2..000000000000
--- a/products/marketing_analytics/frontend/dashboard/CustomerAcquisitionCards.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { IconInfo } from '@posthog/icons'
-import { LemonButton, LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
-
-import { SamplingRate } from '~/queries/nodes/OverviewGrid/OverviewGrid'
-import { OverviewMetricCardGrid } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'
-import { WebOverviewItem } from '~/queries/schema/schema-general'
-
-import { customerAcquisitionMetrics } from './customerAcquisitionMetrics'
-import { MarketingQueryError } from './MarketingQueryError'
-
-interface CustomerAcquisitionCardsProps {
- configurationLoading: boolean
- configured: boolean
- loading: boolean
- error: boolean
- queryId?: string | null
- customerResults?: WebOverviewItem[]
- trafficResults?: WebOverviewItem[]
- samplingRate?: SamplingRate
- onConfigure: () => void
- onRetry: () => void
-}
-
-export function CustomerAcquisitionCards({
- configurationLoading,
- configured,
- loading,
- error,
- queryId,
- customerResults,
- trafficResults,
- samplingRate,
- onConfigure,
- onRetry,
-}: CustomerAcquisitionCardsProps): JSX.Element {
- return (
- <div className="contents">
- {configurationLoading ? (
- <>
- <LemonSkeleton className="h-36" />
- <LemonSkeleton className="h-36" />
- </>
- ) : !configured ? (
- <LemonCard hoverEffect={false} className="h-full !p-3 flex flex-col justify-between gap-2">
- <span className="font-semibold">New customers</span>
- <span className="text-secondary">Mark an event or action goal as a new customer goal.</span>
- <LemonButton
- size="small"
- type="secondary"
- onClick={onConfigure}
- data-attr="marketing-configure-customer-goal"
- >
- Configure in Setup
- </LemonButton>
- </LemonCard>
- ) : error ? (
- <MarketingQueryError
- message="Could not load new customers."
- queryId={queryId}
- onRetry={onRetry}
- loading={loading}
- />
- ) : (
- <OverviewMetricCardGrid
- layout="contents"
- items={customerAcquisitionMetrics(customerResults, trafficResults).map((item) => ({
- ...item,
- value: item.value,
- }))}
- loading={loading}
- numSkeletons={2}
- samplingRate={samplingRate}
- labelFromKey={(key) =>
- key === 'unique conversions' ? (
- 'New customers'
- ) : (
- <span className="inline-flex items-center gap-1">
- Customer-to-visitor ratio
- <Tooltip title="Unique people completing the selected customer goal divided by visitors with a pageview or screenview, multiplied by 100. Each row uses its own channel or campaign. This can exceed 100% when goals complete without pageviews or screenviews.">
- <IconInfo
- className="shrink-0 text-secondary"
- aria-label="How customer-to-visitor ratio is calculated"
- />
- </Tooltip>
- </span>
- )
- }
- />
- )}
- </div>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsx b/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsx
deleted file mode 100644
index 85c32416ed72..000000000000
--- a/products/marketing_analytics/frontend/dashboard/NewMarketingAnalyticsDashboard.tsx
+++ /dev/null
@@ -1,592 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { useEffect, useRef, useState } from 'react'
-
-import { IconCursor, IconPeople, IconRetention, IconTarget, IconTrends } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonCard, LemonCollapse, LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'
-
-import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'
-import { DateFilter } from 'lib/components/DateFilter/DateFilter'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { useLocalStorage } from 'lib/hooks/useLocalStorage'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { marketingOnboardingLogic } from 'scenes/marketing-analytics/Onboarding/marketingOnboardingLogic'
-import { Onboarding } from 'scenes/marketing-analytics/Onboarding/Onboarding'
-import { suggestionsForSection } from 'scenes/marketing-analytics/Setup/sectionRouting'
-import { SuggestionRow } from 'scenes/marketing-analytics/Setup/SuggestionRow'
-import { teamLogic } from 'scenes/teamLogic'
-import { MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS } from 'scenes/web-analytics/common'
-import { AttributionTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTab'
-import { AttributionTable } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/AttributionTab/AttributionTable'
-import { MarketingAnalyticsSourceStatusBanner } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsSourceStatusBanner'
-import { RetentionTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/RetentionTab/RetentionTab'
-import {
- SetupSection,
- marketingAnalyticsLogic,
-} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
-import { marketingAttributionLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAttributionLogic'
-import { BREAKDOWN_LABELS } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown'
-import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
-
-import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
-import { OverviewMetricCardGrid } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'
-import { labelFromKey } from '~/queries/nodes/WebOverview/WebOverview'
-import { Query } from '~/queries/Query/Query'
-import {
- MarketingAnalyticsAttributionBreakdown,
- NodeKind,
- WebOverviewQuery,
- WebOverviewQueryResponse,
- WebStatsBreakdown,
-} from '~/queries/schema/schema-general'
-import { ChartDisplayType } from '~/types'
-
-import { CustomerAcquisitionCards } from './CustomerAcquisitionCards'
-import { DetectedSources } from './DetectedSources'
-import { marketingAcquisitionLogic } from './marketingAcquisitionLogic'
-import { MarketingQueryError } from './MarketingQueryError'
-import { marketingTrafficQueryContext } from './marketingTrafficQueryContext'
-import { TRAFFIC_CHART_METRICS } from './trafficChartSeries'
-
-const TRAFFIC_BREAKDOWNS = [
- { value: WebStatsBreakdown.InitialChannelType, label: 'Channel' },
- { value: WebStatsBreakdown.InitialUTMSource, label: 'UTM source' },
- { value: WebStatsBreakdown.InitialUTMCampaign, label: 'Campaign' },
- { value: WebStatsBreakdown.InitialUTMMedium, label: 'Medium' },
- { value: WebStatsBreakdown.InitialReferringDomain, label: 'Referring domain' },
- { value: WebStatsBreakdown.InitialPage, label: 'Landing page' },
-]
-
-const SECTIONS = [
- {
- key: 'acquisition',
- title: 'Acquisition',
- description: 'Visitors, sessions and pageviews',
- icon: <IconPeople />,
- },
- {
- key: 'engagement',
- title: 'Engagement',
- description: 'Session duration and bounce rate',
- icon: <IconCursor />,
- },
- {
- key: 'retention',
- title: 'Retention',
- description: 'Returning visitors by cohort',
- icon: <IconRetention />,
- },
- {
- key: 'conversion',
- title: 'Conversion',
- description: 'Goals and conversion paths',
- icon: <IconTarget />,
- },
- {
- key: 'revenue',
- title: 'Revenue',
- description: 'Revenue by attribution model',
- icon: <IconTrends />,
- },
-]
-
-// Scaffold for the redesigned marketing analytics dashboard, gated behind the
-// `new-marketing-analytics-dashboard` feature flag.
-export function NewMarketingAnalyticsDashboard(): JSX.Element {
- const { nativeSources, validExternalTables, loading, dataWarehouseSources } = useValues(marketingAnalyticsLogic)
- const { showOnboarding } = useValues(marketingOnboardingLogic)
- const { completeOnboarding } = useActions(marketingOnboardingLogic)
- const [selectedSection, setSelectedSection] = useState('acquisition')
- const [trafficBreakdown, setTrafficBreakdown] = useState(WebStatsBreakdown.InitialChannelType)
- const { currentTeam, currentTeamLoading } = useValues(teamLogic)
- const activeSection = SECTIONS.some(({ key }) => key === selectedSection) ? selectedSection : 'acquisition'
- const isTraffic = activeSection === 'acquisition' || activeSection === 'engagement'
- const { revenueGoals, selectedRevenueGoalId, revenueQuery, breakdownBy } = useValues(marketingAttributionLogic)
- const { setRevenueGoalId, setBreakdownBy } = useActions(marketingAttributionLogic)
- const {
- customerGoals,
- selectedCustomerGoal,
- customerConversionGoal,
- trafficOrderBy,
- trafficChartMetric,
- trafficChartSeries,
- } = useValues(marketingAcquisitionLogic)
- const { setCustomerGoalId, toggleTrafficSort, setTrafficChartMetric } = useActions(marketingAcquisitionLogic)
- const { dateFilter, compareFilter, shouldFilterTestAccounts } = useValues(marketingAnalyticsLogic)
- const { setDates, setCompareFilter, openSetup, reportDashboardSectionViewed, reportDashboardControlUsed } =
- useActions(marketingAnalyticsLogic)
- const { setupPlan, setupPlanLoading, visibleSuggestions } = useValues(setupPlanLogic)
- const { featureFlags } = useValues(featureFlagLogic)
- const { loadSetupPlan, reviewSuggestion } = useActions(setupPlanLogic)
- const [sourcesExpanded, setSourcesExpanded] = useLocalStorage('marketing-source-suggestions-expanded', false)
- const sourceSuggestions = visibleSuggestions.filter((suggestion) => suggestion.kind === 'connect_source')
- const reviewSources = (): void => openSetup(SetupSection.SOURCES, 'dashboard_source_suggestions')
-
- const [goalsExpanded, setGoalsExpanded] = useLocalStorage('marketing-goal-suggestions-expanded', false)
- const goalSuggestions = suggestionsForSection(visibleSuggestions, SetupSection.CONVERSION_GOALS)
- const reviewGoals = (): void => openSetup(SetupSection.CONVERSION_GOALS, 'dashboard_goal_suggestions')
-
- const requestedSetupPlan = useRef(false)
- useEffect(() => {
- if (!setupPlan && !setupPlanLoading && !requestedSetupPlan.current) {
- requestedSetupPlan.current = true
- loadSetupPlan()
- }
- }, [setupPlan, setupPlanLoading, loadSetupPlan])
-
- const reportedSection = useRef<string | null>(null)
- useEffect(() => {
- if (currentTeamLoading || reportedSection.current === activeSection) {
- return
- }
- reportedSection.current = activeSection
- reportDashboardSectionViewed(activeSection, {
- customerGoal: !!customerConversionGoal,
- revenueGoal: !!revenueQuery,
- })
- }, [activeSection, currentTeamLoading, customerConversionGoal, revenueQuery, reportDashboardSectionViewed])
- const reportControl = (control: string, value?: string | boolean): void =>
- reportDashboardControlUsed(activeSection, control, value)
-
- const dateRange = { date_from: dateFilter.dateFrom, date_to: dateFilter.dateTo }
- const query: WebOverviewQuery = {
- kind: NodeKind.WebOverviewQuery,
- dateRange,
- compareFilter,
- filterTestAccounts: shouldFilterTestAccounts,
- properties: [],
- tags: MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS,
- }
- const overviewLogic = dataNodeLogic({ query, key: 'marketing-acquisition-overview' })
- const { response, responseLoading, responseError, responseErrorObject, queryId } = useValues(overviewLogic)
- const { loadData } = useActions(overviewLogic)
- const overview = response as WebOverviewQueryResponse | undefined
- const customerOverviewLogic = dataNodeLogic({
- query: { ...query, conversionGoal: activeSection === 'acquisition' ? customerConversionGoal : null },
- key: 'marketing-acquisition-customers',
- autoLoad: !!customerConversionGoal && activeSection === 'acquisition',
- })
- const {
- response: customerResponse,
- responseLoading: customersLoading,
- responseError: customersError,
- responseErrorObject: customersErrorObject,
- queryId: customersQueryId,
- } = useValues(customerOverviewLogic)
- const { loadData: loadCustomers } = useActions(customerOverviewLogic)
- const customerOverview = customerResponse as WebOverviewQueryResponse | undefined
- const reviewCustomerGoals = (): void => openSetup(SetupSection.CONVERSION_GOALS, 'dashboard_customer_cards')
-
- const hasSearchConsole =
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS] &&
- !!dataWarehouseSources?.results.some((source) => source.source_type === 'GoogleSearchConsole')
- if (
- featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] &&
- !loading &&
- !hasSearchConsole &&
- nativeSources.length === 0 &&
- validExternalTables.length === 0 &&
- showOnboarding
- ) {
- return <Onboarding completeOnboarding={completeOnboarding} />
- }
-
- return (
- <div className="mt-4 flex flex-col gap-4">
- <div className="flex flex-wrap items-center gap-2">
- <DateFilter dateFrom={dateFilter.dateFrom} dateTo={dateFilter.dateTo} onChange={setDates} />
- {isTraffic && (
- <>
- <CompareFilter compareFilter={compareFilter} updateCompareFilter={setCompareFilter} />
- <LemonButton
- size="small"
- loading={
- responseLoading ||
- (activeSection === 'acquisition' && !!customerConversionGoal && customersLoading)
- }
- onClick={() => {
- reportControl('reload_summary')
- loadData('force_async')
- if (activeSection === 'acquisition' && customerConversionGoal) {
- loadCustomers('force_async')
- }
- }}
- >
- Reload summary
- </LemonButton>
- </>
- )}
- </div>
- {!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] && (
- <MarketingAnalyticsSourceStatusBanner />
- )}
- <DetectedSources />
- <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,24rem),1fr))] items-start gap-2 empty:hidden">
- {!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING] && sourceSuggestions.length > 0 && (
- <div className="border rounded relative">
- <LemonButton className="absolute right-2 top-0 z-10" size="small" onClick={reviewSources}>
- Review in Setup
- </LemonButton>
- <LemonCollapse
- embedded
- size="small"
- activeKey={sourcesExpanded ? 'sources' : null}
- onChange={(key) => {
- reportControl('source_suggestions', key !== null)
- setSourcesExpanded(key !== null)
- }}
- panels={[
- {
- key: 'sources',
- header: {
- children: `Suggested ad sources (${sourceSuggestions.length})`,
- className: 'pr-36',
- },
- content: sourceSuggestions.map((suggestion) => (
- <SuggestionRow
- key={suggestion.id}
- suggestion={suggestion}
- currentSection={SetupSection.SOURCES}
- onReview={(item) => {
- reviewSources()
- reviewSuggestion(item)
- }}
- />
- )),
- },
- ]}
- />
- </div>
- )}
- {goalSuggestions.length > 0 && (
- <div className="border rounded relative">
- <LemonButton className="absolute right-2 top-0 z-10" size="small" onClick={reviewGoals}>
- Review in Setup
- </LemonButton>
- <LemonCollapse
- embedded
- size="small"
- activeKey={goalsExpanded ? 'goals' : null}
- onChange={(key) => {
- reportControl('goal_suggestions', key !== null)
- setGoalsExpanded(key !== null)
- }}
- panels={[
- {
- key: 'goals',
- header: {
- children: `Suggested conversion goals (${goalSuggestions.length})`,
- className: 'pr-36',
- },
- content: goalSuggestions.map((suggestion) => (
- <SuggestionRow
- key={suggestion.id}
- suggestion={suggestion}
- currentSection={SetupSection.CONVERSION_GOALS}
- onReview={(item) => {
- reviewGoals()
- reviewSuggestion(item)
- }}
- />
- )),
- },
- ]}
- />
- </div>
- )}
- </div>
- <nav aria-label="Dashboard sections" className="flex flex-wrap gap-1 rounded border p-1 w-fit max-w-full">
- {SECTIONS.map(({ key, title, icon }) => (
- <LemonButton
- key={key}
- type="tertiary"
- active={activeSection === key}
- className={activeSection === key ? '!bg-accent-highlight !text-accent' : undefined}
- icon={icon}
- size="small"
- data-attr={`marketing-dashboard-section-${key}`}
- onClick={() => setSelectedSection(key)}
- aria-pressed={activeSection === key}
- aria-controls="marketing-dashboard-section"
- >
- {title}
- </LemonButton>
- ))}
- </nav>
- <div id="marketing-dashboard-section" className="flex flex-col gap-4">
- {isTraffic &&
- (responseError ? (
- <MarketingQueryError
- message="Could not load traffic metrics. Try again."
- queryId={responseErrorObject?.queryId ?? queryId}
- onRetry={() => loadData('force_async')}
- loading={responseLoading}
- />
- ) : (
- [
- { key: 'acquisition', title: 'Acquisition', keys: ['visitors', 'sessions', 'views'] },
- { key: 'engagement', title: 'Engagement', keys: ['session duration', 'bounce rate'] },
- ]
- .filter(({ key }) => key === activeSection)
- .map(({ title, keys }) => (
- <section key={title} className="flex flex-col gap-2" aria-label={title}>
- <h2 className="mb-0">{title}</h2>
- <p className="text-secondary mb-2">
- {SECTIONS.find(({ key }) => key === activeSection)?.description}
- </p>
- <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))] auto-rows-fr gap-2">
- <div className="contents">
- <OverviewMetricCardGrid
- layout="contents"
- items={keys.flatMap((key) =>
- (overview?.results?.filter((item) => item.key === key) ?? []).map(
- (item) => ({
- ...item,
- value: item.value,
- })
- )
- )}
- loading={responseLoading}
- numSkeletons={keys.length}
- samplingRate={overview?.samplingRate}
- preComputeStrategy={overview?.preComputeStrategy}
- labelFromKey={labelFromKey}
- />
- </div>
- {activeSection === 'acquisition' && (
- <CustomerAcquisitionCards
- configurationLoading={currentTeamLoading}
- configured={!!customerConversionGoal}
- loading={customersLoading || responseLoading}
- error={!!customersError}
- queryId={customersErrorObject?.queryId ?? customersQueryId}
- customerResults={customerOverview?.results}
- trafficResults={overview?.results}
- samplingRate={customerOverview?.samplingRate}
- onConfigure={reviewCustomerGoals}
- onRetry={() => loadCustomers('force_async')}
- />
- )}
- </div>
- {activeSection === 'acquisition' && customerConversionGoal && (
- <div className="flex flex-wrap items-center gap-2">
- <span>New customer goal</span>
- <LemonSelect
- aria-label="Customer goal"
- value={selectedCustomerGoal?.conversion_goal_id}
- onChange={(value) => {
- reportControl('customer_goal')
- setCustomerGoalId(value)
- }}
- options={customerGoals.map((goal) => ({
- value: goal.conversion_goal_id,
- label: goal.conversion_goal_name,
- }))}
- />
- <span className="text-secondary text-xs">
- Unique visitors completing this goal in the period. Use a
- once-per-customer goal to measure new customers.
- </span>
- </div>
- )}
- </section>
- ))
- ))}
- {activeSection === 'conversion' && (
- <section aria-label="Conversion" className="flex flex-col gap-2">
- <h2 className="mb-0">Conversion</h2>
- <p className="text-secondary mb-2">
- {SECTIONS.find(({ key }) => key === activeSection)?.description}
- </p>
- <AttributionTab />
- </section>
- )}
- {activeSection === 'retention' && (
- <section aria-label="Retention" className="flex flex-col gap-2">
- <h2 className="mb-0">Retention</h2>
- <p className="text-secondary mb-0">
- Follow visitors acquired in the selected date range across subsequent periods.
- </p>
- <RetentionTab />
- </section>
- )}
- {activeSection === 'revenue' && (
- <section aria-label="Revenue" className="flex flex-col gap-4">
- <h2 className="mb-0">Revenue</h2>
- {currentTeamLoading || !currentTeam ? (
- <LemonSkeleton className="h-40" />
- ) : revenueQuery ? (
- <>
- <div className="flex flex-wrap items-center gap-2">
- <DateFilter
- dateFrom={dateFilter.dateFrom}
- dateTo={dateFilter.dateTo}
- onChange={setDates}
- />
- <LemonSelect
- value={selectedRevenueGoalId}
- onChange={(value) => {
- if (value) {
- reportControl('revenue_goal')
- setRevenueGoalId(value)
- }
- }}
- options={revenueGoals.map((goal) => ({
- value: goal.conversion_goal_id,
- label: goal.conversion_goal_name,
- }))}
- data-attr="marketing-revenue-goal"
- />
- <LemonSelect
- value={breakdownBy}
- onChange={(value) => {
- reportControl('revenue_breakdown', value)
- setBreakdownBy(value)
- }}
- options={Object.values(MarketingAnalyticsAttributionBreakdown).map((value) => ({
- value,
- label: BREAKDOWN_LABELS[value],
- }))}
- data-attr="marketing-revenue-breakdown"
- />
- </div>
- <p className="text-secondary mb-0">
- Compare attributed value across models for one revenue goal at a time.
- </p>
- <AttributionTable
- metric="revenue"
- query={revenueQuery}
- attachTo={marketingAnalyticsLogic}
- />
- </>
- ) : (
- <LemonBanner
- type="info"
- action={{
- children: 'Review in Setup',
- onClick: () => openSetup(SetupSection.CONVERSION_GOALS, 'dashboard_revenue_banner'),
- }}
- >
- Choose an event or action goal that sums an amount and mark it as Revenue in Setup.
- </LemonBanner>
- )}
- </section>
- )}
- {isTraffic && (
- <>
- {activeSection === 'acquisition' && (
- <LemonCard hoverEffect={false}>
- <div className="flex flex-wrap justify-between items-center gap-2">
- <h3 className="mb-0">
- {`${TRAFFIC_CHART_METRICS.find(({ value }) => value === trafficChartMetric)?.label} over time`}
- </h3>
- <LemonSelect
- size="small"
- value={trafficChartMetric}
- onChange={(value) => {
- if (value) {
- reportControl('chart_metric', value)
- setTrafficChartMetric(value)
- }
- }}
- options={TRAFFIC_CHART_METRICS.map(({ value, label }) => ({
- value,
- label,
- disabledReason:
- value === 'new_customers' && !customerConversionGoal
- ? 'Mark a conversion goal as a new customer goal in Setup first.'
- : undefined,
- }))}
- aria-label="Chart metric"
- data-attr="marketing-traffic-chart-metric"
- />
- </div>
- <p className="text-secondary text-sm">All traffic in the selected period.</p>
- <div className="flex flex-col h-80">
- <Query
- key={`${activeSection}-${trafficChartMetric}`}
- query={{
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.TrendsQuery,
- dateRange,
- compareFilter,
- filterTestAccounts: shouldFilterTestAccounts,
- interval: 'day',
- tags: MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS,
- series: [trafficChartSeries],
- trendsFilter: { display: ChartDisplayType.ActionsLineGraph },
- },
- embedded: true,
- showTable: false,
- hidePersonsModal: true,
- }}
- readOnly
- />
- </div>
- </LemonCard>
- )}
- <LemonCard hoverEffect={false}>
- <div className="flex flex-wrap justify-between items-center gap-2 mb-3">
- <h3 className="mb-0">
- {`${activeSection === 'acquisition' ? 'Acquisition' : 'Engagement'} by ${TRAFFIC_BREAKDOWNS.find(({ value }) => value === trafficBreakdown)?.label.toLowerCase()}`}
- </h3>
- <div className="flex items-center gap-2">
- <span>Breakdown by</span>
- <LemonSelect
- value={trafficBreakdown}
- onChange={(value) => {
- reportControl('traffic_breakdown', value)
- setTrafficBreakdown(value)
- }}
- options={TRAFFIC_BREAKDOWNS}
- aria-label="Traffic breakdown"
- />
- </div>
- </div>
- <p className="text-secondary text-sm">
- Grouped by session entry. UTM source and referring domain are separate breakdowns.
- Visitors can appear in more than one row.
- </p>
- <Query
- query={{
- kind: NodeKind.DataTableNode,
- source: {
- kind: NodeKind.WebStatsTableQuery,
- breakdownBy: trafficBreakdown,
- orderBy: trafficOrderBy[activeSection],
- dateRange,
- compareFilter,
- filterTestAccounts: shouldFilterTestAccounts,
- includeBounceRate: activeSection === 'engagement',
- includeTrafficMetrics: activeSection === 'acquisition',
- conversionGoal: activeSection === 'acquisition' ? customerConversionGoal : null,
- properties: [],
- limit: 25,
- tags: MARKETING_ANALYTICS_DEFAULT_QUERY_TAGS,
- },
- hiddenColumns:
- activeSection === 'engagement'
- ? ['context.columns.views']
- : [
- 'context.columns.total_conversions',
- ...(customerConversionGoal ? ['context.columns.cross_sell'] : []),
- ],
- full: true,
- embedded: false,
- showOpenEditorButton: false,
- }}
- context={{
- ...marketingTrafficQueryContext(trafficOrderBy[activeSection], (field) =>
- toggleTrafficSort(activeSection, field)
- ),
- compareFilter,
- }}
- readOnly
- />
- </LemonCard>
- </>
- )}
- </div>
- </div>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsx b/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsx
index f565d097b3e2..86d8a1e2008f 100644
--- a/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsx
+++ b/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import type { ReactNode } from 'react'
import * as magnifyingGlass from '@posthog/brand/hoggies/png/magnifying-glass'
-import { LemonBanner, LemonButton, LemonCard, LemonTag, Spinner } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonCard, Spinner } from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
@@ -16,6 +16,13 @@ import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics
const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlass)
+const SEARCH_SOURCES = [
+ { type: 'GoogleAds', name: 'Google Ads' },
+ { type: 'BingAds', name: 'Bing Ads' },
+ { type: 'GoogleSearchConsole', name: 'Google Search Console' },
+]
+const SEARCH_SOURCE_TYPES = SEARCH_SOURCES.map((source) => source.type)
+
export function SearchConsoleSource({ headerAction }: { headerAction?: ReactNode }): JSX.Element | null {
const { featureFlags } = useValues(featureFlagLogic)
const { dataWarehouseSources } = useValues(marketingAnalyticsLogic)
@@ -56,14 +63,10 @@ export function SearchConsoleSource({ headerAction }: { headerAction?: ReactNode
</section>
)
}
- const sources = [
- { type: 'GoogleAds', name: 'Google Ads' },
- { type: 'BingAds', name: 'Bing Ads' },
- { type: 'GoogleSearchConsole', name: 'Google Search Console' },
- ].map((source) => ({
- ...source,
- connected: dataWarehouseSources?.results.some((connection) => connection.source_type === source.type),
- }))
+ // Once any search source is connected, the scene renders search performance, which suggests the missing ones.
+ if (dataWarehouseSources.results.some((connection) => SEARCH_SOURCE_TYPES.includes(connection.source_type))) {
+ return null
+ }
return (
<section className="max-w-3xl w-full mx-auto mt-8 mb-6">
<h2 className="mb-4">Search performance</h2>
@@ -81,28 +84,25 @@ export function SearchConsoleSource({ headerAction }: { headerAction?: ReactNode
{headerAction}
</div>
<div className="divide-y">
- {sources.map((source) => (
+ {SEARCH_SOURCES.map((source) => (
<div key={source.type} className="flex flex-wrap items-center justify-between gap-3 py-2">
<div className="min-w-0 flex items-center gap-3">
<SourceIcon type={source.type} size="small" disableTooltip />
<strong>{source.name}</strong>
- {source.connected && <LemonTag type="info">Connected</LemonTag>}
</div>
- {!source.connected && (
- <LemonButton
- type="secondary"
- size="small"
- disabledReason={restrictedReason}
- to={urls.dataWarehouseSourceNew(
- source.type,
- urls.marketingAnalyticsApp(),
- 'Marketing analytics'
- )}
- targetBlank
- >
- Connect
- </LemonButton>
- )}
+ <LemonButton
+ type="secondary"
+ size="small"
+ disabledReason={restrictedReason}
+ to={urls.dataWarehouseSourceNew(
+ source.type,
+ urls.marketingAnalyticsApp(),
+ 'Marketing analytics'
+ )}
+ targetBlank
+ >
+ Connect
+ </LemonButton>
</div>
))}
</div>
diff --git a/products/marketing_analytics/frontend/dashboard/SourceOnboarding.stories.tsx b/products/marketing_analytics/frontend/dashboard/SourceOnboarding.stories.tsx
index 9a4b012c8546..59f0181e70a9 100644
--- a/products/marketing_analytics/frontend/dashboard/SourceOnboarding.stories.tsx
+++ b/products/marketing_analytics/frontend/dashboard/SourceOnboarding.stories.tsx
@@ -53,11 +53,7 @@ const meta: Meta = {
component: SourceOnboardingScan,
parameters: {
layout: 'padded',
- featureFlags: [
- FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING,
- FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD,
- FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP,
- ],
+ featureFlags: [FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING, FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP],
},
decorators: [
mswDecorator({
diff --git a/products/marketing_analytics/frontend/dashboard/askAi/AskPostHogAi.stories.tsx b/products/marketing_analytics/frontend/dashboard/askAi/AskPostHogAi.stories.tsx
deleted file mode 100644
index 6ab826941071..000000000000
--- a/products/marketing_analytics/frontend/dashboard/askAi/AskPostHogAi.stories.tsx
+++ /dev/null
@@ -1,145 +0,0 @@
-import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
-
-import type { Meta, StoryObj } from '@storybook/react'
-import { useActions } from 'kea'
-import { useState } from 'react'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
-import { organizationLogic } from 'scenes/organizationLogic'
-import { urls } from 'scenes/urls'
-import { defaultConversionGoalFilter } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/constants'
-import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
-
-import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
-import { PropertyFilterType, PropertyOperator, SidePanelTab } from '~/types'
-
-import { AskPostHogAi } from './AskPostHogAi'
-
-function AskPostHogAiStory({ approved = true }: { approved?: boolean }): JSX.Element {
- const [ready, setReady] = useState(false)
- const { loadCurrentOrganizationSuccess } = useActions(organizationLogic)
- const { setDashboardProperties, setDates, setDraftConversionGoal } = useActions(marketingAnalyticsLogic)
-
- useOnMountEffect(() => {
- loadCurrentOrganizationSuccess({
- ...MOCK_DEFAULT_ORGANIZATION,
- is_ai_data_processing_approved: approved,
- })
- setDates('-30d', '2026-09-24')
- setDraftConversionGoal({
- ...defaultConversionGoalFilter,
- conversion_goal_id: 'storybook-purchase',
- conversion_goal_name: 'Purchase',
- })
- setDashboardProperties([
- {
- type: PropertyFilterType.Session,
- key: '$channel_type',
- operator: PropertyOperator.Exact,
- value: 'URL-controlled filter value',
- },
- ])
- setReady(true)
- })
-
- return ready ? <AskPostHogAi /> : <></>
-}
-
-const meta: Meta<typeof AskPostHogAi> = {
- title: 'Marketing Analytics/Dashboard/Ask PostHog AI',
- component: AskPostHogAi,
- tags: ['marketing-ask-ai'],
- render: () => <AskPostHogAiStory />,
- parameters: {
- featureFlags: [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
- pageUrl: `${urls.marketingAnalyticsApp()}?view=overview`,
- },
-}
-export default meta
-type Story = StoryObj<typeof meta>
-
-export const Overview: Story = {
- play: async ({ canvasElement }) => {
- const question = 'Which channels contributed most to growth?'
- let firstQuestion: HTMLButtonElement | undefined
-
- for (let frame = 0; frame < 120 && !firstQuestion; frame++) {
- firstQuestion = Array.from(canvasElement.querySelectorAll('button')).find(
- (button) => button.textContent?.trim() === question
- )
- if (!firstQuestion) {
- await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
- }
- }
-
- if (!firstQuestion) {
- throw new Error(`Could not find the question: ${question}`)
- }
-
- for (let frame = 0; frame < 120 && firstQuestion.getAttribute('aria-disabled') === 'true'; frame++) {
- await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
- }
-
- if (firstQuestion.getAttribute('aria-disabled') === 'true') {
- throw new Error('The question is disabled')
- }
-
- firstQuestion.click()
-
- const expectedPrompt =
- '!Which channels contributed most to growth?\n\n' +
- 'Use this Marketing Analytics dashboard context:\n' +
- 'Dashboard section: overview\n' +
- 'Date range: -30d to 2026-09-24\n' +
- 'Breakdown: channel\n' +
- 'Conversion goal: Purchase'
-
- for (
- let frame = 0;
- frame < 120 &&
- (sidePanelStateLogic.values.selectedTab !== SidePanelTab.Max ||
- !sidePanelStateLogic.values.sidePanelOpen ||
- sidePanelStateLogic.values.selectedTabOptions !== expectedPrompt);
- frame++
- ) {
- await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
- }
-
- if (
- sidePanelStateLogic.values.selectedTab !== SidePanelTab.Max ||
- !sidePanelStateLogic.values.sidePanelOpen ||
- sidePanelStateLogic.values.selectedTabOptions !== expectedPrompt
- ) {
- throw new Error('PostHog AI did not receive the question with the dashboard context')
- }
- },
-}
-
-export const Acquisition: Story = {
- parameters: { pageUrl: `${urls.marketingAnalyticsApp()}?view=acquisition` },
-}
-
-export const Engagement: Story = {
- parameters: { pageUrl: `${urls.marketingAnalyticsApp()}?view=engagement` },
-}
-
-export const Retention: Story = {
- parameters: { pageUrl: `${urls.marketingAnalyticsApp()}?view=retention` },
-}
-
-export const Conversion: Story = {
- parameters: { pageUrl: `${urls.marketingAnalyticsApp()}?view=conversion` },
-}
-
-export const AiDataProcessingNotApproved: Story = {
- render: () => <AskPostHogAiStory approved={false} />,
-}
-
-export const Narrow: Story = {
- render: () => (
- <div className="w-[32.5rem] max-w-full">
- <AskPostHogAiStory />
- </div>
- ),
-}
diff --git a/products/marketing_analytics/frontend/dashboard/askAi/AskPostHogAi.tsx b/products/marketing_analytics/frontend/dashboard/askAi/AskPostHogAi.tsx
deleted file mode 100644
index e11eb774d15f..000000000000
--- a/products/marketing_analytics/frontend/dashboard/askAi/AskPostHogAi.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { IconSparkles } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
-
-import { cn } from 'lib/utils/css-classes'
-import { inStorybook } from 'lib/utils/dom'
-import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
-import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
-
-import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
-import { SidePanelTab } from '~/types'
-
-import { MARKETING_AI_QUESTIONS } from './marketingAiQuestions'
-
-export function AskPostHogAi(): JSX.Element {
- const { dashboardBreakdown, dashboardView, dateFilter, draftConversionGoal } = useValues(marketingAnalyticsLogic)
- const { openSidePanel } = useActions(sidePanelStateLogic)
- const { dataProcessingAccepted, dataProcessingApprovalDisabledReason } = useValues(maxGlobalLogic)
-
- const disabledReason = dataProcessingAccepted
- ? undefined
- : (dataProcessingApprovalDisabledReason ?? 'Approve AI data processing to use PostHog AI')
-
- const ask = (question: string): void => {
- const context = [
- `Dashboard section: ${dashboardView}`,
- `Date range: ${dateFilter.dateFrom ?? 'all time'} to ${dateFilter.dateTo ?? 'today'}`,
- `Breakdown: ${dashboardBreakdown}`,
- draftConversionGoal ? `Conversion goal: ${draftConversionGoal.conversion_goal_name}` : null,
- ].filter(Boolean)
-
- openSidePanel(
- SidePanelTab.Max,
- `!${question}\n\nUse this Marketing Analytics dashboard context:\n${context.join('\n')}`
- )
- }
-
- return (
- <div className="rounded-lg border border-dashed border-primary bg-surface-secondary p-4 flex flex-col gap-3">
- <div className="flex items-center gap-2">
- <IconSparkles className="size-4 shrink-0 text-ai" />
- <h4 className="m-0 text-sm font-semibold">
- Need another view of this data?{' '}
- <span className={cn('rainbow-text', !inStorybook() && 'rainbow-text-animating')}>
- Ask PostHog AI.
- </span>
- </h4>
- </div>
- <div className="flex flex-wrap gap-2">
- {MARKETING_AI_QUESTIONS[dashboardView].map((question) => (
- <LemonButton
- key={question}
- type="secondary"
- size="small"
- onClick={() => ask(question)}
- disabledReason={disabledReason}
- data-attr="marketing-dashboard-ask-ai"
- >
- {question}
- </LemonButton>
- ))}
- </div>
- </div>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/askAi/marketingAiQuestions.ts b/products/marketing_analytics/frontend/dashboard/askAi/marketingAiQuestions.ts
deleted file mode 100644
index 51ec6a1bafbb..000000000000
--- a/products/marketing_analytics/frontend/dashboard/askAi/marketingAiQuestions.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { MarketingDashboardView } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
-
-export const MARKETING_AI_QUESTIONS: Record<MarketingDashboardView, string[]> = {
- [MarketingDashboardView.OVERVIEW]: [
- 'Which channels contributed most to growth?',
- 'Compare this quarter with the previous quarter.',
- 'What changed most in this date range?',
- ],
- [MarketingDashboardView.ACQUISITION]: [
- 'Which channels are growing or declining?',
- 'Show new visitors by campaign for the past 12 months.',
- 'Compare the traffic mix with last year.',
- ],
- [MarketingDashboardView.ENGAGEMENT]: [
- 'Compare engagement from social and search.',
- 'Which landing pages have the highest bounce rate?',
- 'How does engagement change by day of week?',
- ],
- [MarketingDashboardView.RETENTION]: [
- 'Show monthly active users for the past 12 months.',
- 'Which channels have the highest three-month retention?',
- 'What do visitors who did not return have in common?',
- ],
- [MarketingDashboardView.CONVERSION]: [
- 'Compare visitors who converted with visitors who did not.',
- 'Show the conversion rate by week for this year.',
- 'Which landing pages lead to the most conversions?',
- ],
-}
diff --git a/products/marketing_analytics/frontend/dashboard/cards/CardsPreview.tsx b/products/marketing_analytics/frontend/dashboard/cards/CardsPreview.tsx
deleted file mode 100644
index ec6d3dc26710..000000000000
--- a/products/marketing_analytics/frontend/dashboard/cards/CardsPreview.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import { useState } from 'react'
-
-import { LemonButton } from '@posthog/lemon-ui'
-
-import { MarketingMetricCard } from './MarketingMetricCard'
-import { MarketingMetricCardGrid } from './MarketingMetricCardGrid'
-import type { MetricCardSpec } from './metricCardSpec'
-
-const LABELS: Record<string, string> = {
- sessions: 'Sessions',
- revenue: 'Revenue',
- bounce_rate: 'Bounce rate',
-}
-
-interface CardsPreviewProps {
- loading: boolean
- setupSelected: boolean
- missingSpec: boolean
-}
-
-export function CardsPreview({
- loading: initialLoading,
- setupSelected: initialSetupSelected,
- missingSpec,
-}: CardsPreviewProps): JSX.Element {
- const [loading, setLoading] = useState(initialLoading)
- const [setupSelected, setSetupSelected] = useState(initialSetupSelected)
- const specs: MetricCardSpec[] = [
- {
- kind: 'metric',
- item: { key: 'sessions', kind: 'unit', value: 1240, previous: 1000, changeFromPreviousPct: 24 },
- },
- {
- kind: 'notice',
- key: 'conversion_value',
- title: 'Conversion value',
- value: 'N/A',
- message: 'Choose a conversion goal with a value to see this metric.',
- action: {
- label: 'Choose a goal',
- onClick: () => setSetupSelected(true),
- dataAttr: 'marketing-story-configure-goal',
- },
- },
- {
- kind: 'metric',
- item: { key: 'revenue', kind: 'currency', value: 0, previous: 100, changeFromPreviousPct: -100 },
- },
- {
- kind: 'metric',
- item: {
- key: 'bounce_rate',
- kind: 'percentage',
- value: 30,
- previous: 40,
- changeFromPreviousPct: -25,
- isIncreaseBad: true,
- },
- },
- ]
-
- // A 960 px scene prevents component snapshots from shrinking the container-query grid to its controls.
- return (
- <div className="flex w-[60rem] max-w-full flex-col gap-4">
- <MarketingMetricCardGrid>
- {specs.map((spec) => (
- <MarketingMetricCard
- key={spec.kind === 'metric' ? spec.item.key : spec.key}
- spec={missingSpec && spec.kind === 'metric' && spec.item.key === 'sessions' ? undefined : spec}
- loading={loading}
- labelFromKey={(key) => LABELS[key] ?? key}
- />
- ))}
- </MarketingMetricCardGrid>
- <div className="flex flex-wrap items-center gap-2">
- <LemonButton data-attr="marketing-story-toggle-loading" onClick={() => setLoading(!loading)}>
- {loading ? 'Show metrics' : 'Show loading'}
- </LemonButton>
- {setupSelected && <span>Goal setup selected</span>}
- </div>
- </div>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCard.stories.tsx b/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCard.stories.tsx
deleted file mode 100644
index ad514b3fcde1..000000000000
--- a/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCard.stories.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { Meta, StoryObj } from '@storybook/react'
-
-import { CardsPreview } from './CardsPreview'
-
-const meta: Meta<typeof CardsPreview> = {
- title: 'Marketing Analytics/Dashboard/Metric cards',
- component: CardsPreview,
- args: { loading: false, setupSelected: false, missingSpec: false },
- // CardsPreview reads these args into state on mount only, so the key remounts it when a Storybook control changes one.
- render: (args) => <CardsPreview key={`${args.loading}-${args.setupSelected}`} {...args} />,
-}
-export default meta
-type Story = StoryObj<typeof meta>
-
-export const Interactive: Story = {}
-export const Loading: Story = {
- args: { loading: true },
- parameters: { testOptions: { waitForLoadersToDisappear: false } },
-}
-export const MissingSpec: Story = { args: { missingSpec: true } }
-export const Narrow: Story = {
- decorators: [
- (Story) => (
- <div className="w-[32.5rem] max-w-full">
- {/* A 520 px scene models the space beside an open side panel. */}
- <Story />
- </div>
- ),
- ],
-}
diff --git a/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCard.test.tsx b/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCard.test.tsx
deleted file mode 100644
index d3e0b4431873..000000000000
--- a/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCard.test.tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-import { renderToStaticMarkup } from 'react-dom/server'
-
-import { MarketingMetricCard } from './MarketingMetricCard'
-
-describe('MarketingMetricCard', () => {
- it.each([
- { loading: true, expected: /Loading…/ },
- { loading: false, expected: /^$/ },
- ])('renders a missing specification with loading=$loading', ({ loading, expected }) => {
- const markup = renderToStaticMarkup(<MarketingMetricCard loading={loading} labelFromKey={(key) => key} />)
-
- expect(markup).toMatch(expected)
- })
-})
diff --git a/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCard.tsx b/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCard.tsx
deleted file mode 100644
index c753b15d9315..000000000000
--- a/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCard.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { OverviewMetricCardGrid } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'
-
-import type { MetricCardSpec } from './metricCardSpec'
-import { MetricNoticeCard } from './MetricNoticeCard'
-
-export interface MarketingMetricCardProps {
- spec?: MetricCardSpec
- loading: boolean
- labelFromKey: (key: string) => React.ReactNode
-}
-
-/** One card per grid instance, so a notice keeps its place in the configured order instead of
- * being pushed past every metric. */
-export function MarketingMetricCard({ spec, loading, labelFromKey }: MarketingMetricCardProps): JSX.Element | null {
- if (loading) {
- return (
- <OverviewMetricCardGrid layout="contents" items={[]} loading numSkeletons={1} labelFromKey={labelFromKey} />
- )
- }
- if (!spec) {
- return null
- }
- if (spec.kind === 'notice') {
- return <MetricNoticeCard title={spec.title} message={spec.message} value={spec.value} action={spec.action} />
- }
- return (
- <OverviewMetricCardGrid
- layout="contents"
- items={[spec.item]}
- loading={false}
- numSkeletons={1}
- labelFromKey={labelFromKey}
- />
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCardGrid.tsx b/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCardGrid.tsx
deleted file mode 100644
index 5dc5fc26e54b..000000000000
--- a/products/marketing_analytics/frontend/dashboard/cards/MarketingMetricCardGrid.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-/** Breaks on its own width, because the scene loses ~520px to the nav and an open side panel.
- * auto-fit rather than a fixed column count so a row of cards always spans the full width. */
-export function MarketingMetricCardGrid({ children }: { children: React.ReactNode }): JSX.Element {
- return (
- <div className="@container">
- <div className="grid gap-2 grid-cols-[repeat(auto-fit,minmax(min(100%,11rem),1fr))]">{children}</div>
- </div>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/cards/MetricNoticeCard.tsx b/products/marketing_analytics/frontend/dashboard/cards/MetricNoticeCard.tsx
deleted file mode 100644
index 90f23730c08f..000000000000
--- a/products/marketing_analytics/frontend/dashboard/cards/MetricNoticeCard.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import { LemonButton, LemonCard } from '@posthog/lemon-ui'
-
-import type { MetricNotice } from './metricCardSpec'
-
-export type MetricNoticeCardProps = Omit<MetricNotice, 'kind' | 'key'>
-
-/** Stands in for a metric card whenever there is no number to show, so the grid never renders an
- * empty bordered box. Matches the metric card's own shell. */
-export function MetricNoticeCard({ title, message, action, value }: MetricNoticeCardProps): JSX.Element {
- return (
- <LemonCard hoverEffect={false} className="flex h-full flex-col gap-1 p-3">
- <span className="text-xs font-medium text-secondary truncate">{title}</span>
- {value && <span className="text-2xl font-semibold text-muted tabular-nums">{value}</span>}
- <span className="text-secondary text-xs">{message}</span>
- {action && (
- <div className="mt-auto pt-1">
- <LemonButton size="small" type="secondary" onClick={action.onClick} data-attr={action.dataAttr}>
- {action.label}
- </LemonButton>
- </div>
- )}
- </LemonCard>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/cards/metricCardSpec.ts b/products/marketing_analytics/frontend/dashboard/cards/metricCardSpec.ts
deleted file mode 100644
index d778f88d0fb9..000000000000
--- a/products/marketing_analytics/frontend/dashboard/cards/metricCardSpec.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'
-import { WebOverviewItem } from '~/queries/schema/schema-general'
-
-export interface MetricNotice {
- kind: 'notice'
- key: string
- title: string
- message: string
- /** Stands in the value's place for a metric that exists but cannot be computed here. */
- value?: string
- action?: { label: string; onClick: () => void; dataAttr: string }
-}
-
-export type MetricCardSpec = { kind: 'metric'; item: OverviewMetricCardItem } | MetricNotice
-
-/** Percent change the way the cards want it: whole percent, and undefined when there is no
- * baseline to divide by. The backend sends a sentinel for that case, which the grid already hides. */
-export function pctChange(value: number | undefined, previous: number | undefined): number | undefined {
- if (value === undefined || previous === undefined || previous === 0) {
- return undefined
- }
- return Math.round(((value - previous) / previous) * 100)
-}
-
-/** Picks named keys out of a WebOverviewQuery response, keeping the requested order. */
-export function pickOverviewItems(results: WebOverviewItem[] | undefined, keys: string[]): MetricCardSpec[] {
- return keys.flatMap((key) => {
- const item = results?.find((result) => result.key === key)
- return item ? [{ kind: 'metric' as const, item: item as OverviewMetricCardItem }] : []
- })
-}
diff --git a/products/marketing_analytics/frontend/dashboard/charts/MetricChart.stories.tsx b/products/marketing_analytics/frontend/dashboard/charts/MetricChart.stories.tsx
deleted file mode 100644
index b3105037699b..000000000000
--- a/products/marketing_analytics/frontend/dashboard/charts/MetricChart.stories.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { Meta, StoryObj } from '@storybook/react'
-
-import { MetricChartPreview } from './MetricChartPreview'
-
-const meta: Meta<typeof MetricChartPreview> = {
- title: 'Marketing Analytics/Dashboard/Metric chart',
- component: MetricChartPreview,
- args: {
- state: 'loaded',
- chartMode: 'breakdown',
- focusedBreakdownValue: null,
- format: 'number',
- queryId: '00000000-0000-4000-8000-000000000001',
- },
- render: (args) => <MetricChartPreview key={JSON.stringify(args)} {...args} />,
-}
-export default meta
-type Story = StoryObj<typeof meta>
-
-export const Interactive: Story = {}
-export const Total: Story = { args: { chartMode: 'total' } }
-export const Percentage: Story = { args: { format: 'percentage' } }
-export const Loading: Story = {
- args: { state: 'loading' },
- parameters: { testOptions: { waitForLoadersToDisappear: false } },
-}
-export const Refreshing: Story = { ...Loading, args: { state: 'refreshing' } }
-export const Empty: Story = { args: { state: 'empty' } }
-export const Error: Story = { args: { state: 'error' } }
-export const Narrow: Story = {
- args: { focusedBreakdownValue: '' },
- decorators: [
- (Story) => (
- // A 520 px scene models the space beside an open side panel.
- <div className="w-[32.5rem] max-w-full">
- <Story />
- </div>
- ),
- ],
-}
-export const NarrowError: Story = { args: Error.args, decorators: Narrow.decorators }
diff --git a/products/marketing_analytics/frontend/dashboard/charts/MetricChart.test.tsx b/products/marketing_analytics/frontend/dashboard/charts/MetricChart.test.tsx
deleted file mode 100644
index 1b6afe2bd02a..000000000000
--- a/products/marketing_analytics/frontend/dashboard/charts/MetricChart.test.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import {
- clickAtIndex,
- createDefaultTooltipAccessor,
- hoverUntilTooltip,
- renderChart,
-} from '@posthog/quill-charts/testing'
-
-import { MetricChart, MetricChartProps } from './MetricChart'
-
-const props: MetricChartProps = {
- label: 'Visitors',
- breakdownLabel: 'Channel',
- format: 'number',
- timezone: 'UTC',
- labels: ['2026-01-01', '2026-01-02', '2026-01-03'],
- series: [],
- chartMode: 'breakdown',
- focusedBreakdownValue: null,
- loading: false,
- error: null,
- onChartModeChange: jest.fn(),
- onFocus: jest.fn(),
-}
-
-describe('MetricChart', () => {
- it.each([
- { key: 'email', label: 'Email newsletter' },
- { key: '', label: 'No channel' },
- ])('selects the closest of several lines using the raw key "$key"', async ({ key, label }) => {
- const onFocus = jest.fn()
- const { chart } = renderChart(
- <MetricChart
- {...props}
- series={[
- { key: 'lower', label: 'Lower line', data: [0, 0, 0] },
- { key, label, data: [100, 100, 100] },
- { key: 'upper', label: 'Upper line', data: [200, 200, 200] },
- ]}
- onFocus={onFocus}
- />
- )
-
- await clickAtIndex(chart.element, 1, props.labels.length)
-
- expect(onFocus).toHaveBeenCalledWith(key)
- })
-
- it('formats fractional rates as percentages in the axis and tooltip', async () => {
- const { chart, container } = renderChart(
- <MetricChart
- {...props}
- format="percentage"
- series={[{ key: 'email', label: 'Email', data: [0, 0.42, 1] }]}
- />
- )
- const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 1, props.labels.length))
-
- expect(tooltip.value('Email')).toBe('42.0%')
- expect(container.textContent).toContain('100.0%')
- })
-
- it('shows the supplied error instead of stale data and hides it during retry', () => {
- const { container, rerender, getByText, queryByText } = renderChart(
- <MetricChart {...props} series={[{ key: 'email', label: 'Email', data: [0, 12, 8] }]} />
- )
- rerender(
- <MetricChart
- {...props}
- series={[{ key: 'email', label: 'Email', data: [0, 12, 8] }]}
- error={<span>Query ID: synthetic-query-id</span>}
- />
- )
-
- expect(getByText('Query ID: synthetic-query-id')).not.toBeNull()
- expect(container.querySelector('canvas')).toBeNull()
-
- rerender(<MetricChart {...props} loading error={<span>Query ID: synthetic-query-id</span>} />)
-
- expect(queryByText('Query ID: synthetic-query-id')).toBeNull()
- expect(container.querySelector('[aria-label="Loading chart"]')).not.toBeNull()
- })
-})
diff --git a/products/marketing_analytics/frontend/dashboard/charts/MetricChart.tsx b/products/marketing_analytics/frontend/dashboard/charts/MetricChart.tsx
deleted file mode 100644
index 82ffb46c20c0..000000000000
--- a/products/marketing_analytics/frontend/dashboard/charts/MetricChart.tsx
+++ /dev/null
@@ -1,152 +0,0 @@
-import { ReactNode, useMemo } from 'react'
-
-import { LemonButton, LemonSegmentedButton, LemonSkeleton } from '@posthog/lemon-ui'
-import { Series, TimeSeriesLineChart, TimeSeriesLineChartConfig } from '@posthog/quill-charts'
-
-import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
-import { humanFriendlyDuration } from 'lib/utils/durations'
-import { humanFriendlyNumber } from 'lib/utils/numbers'
-
-import { focusedSeries } from './seriesFocus'
-
-export interface MetricChartProps {
- label: string
- breakdownLabel: string
- format: 'number' | 'percentage' | 'duration' | 'decimal'
- timezone: string
- labels: string[]
- series: (Series & { key: string })[]
- chartMode: 'total' | 'breakdown'
- focusedBreakdownValue: string | null
- loading: boolean
- error: ReactNode
- onChartModeChange: (mode: 'total' | 'breakdown') => void
- onFocus: (value: string | null) => void
-}
-
-export function MetricChart({
- label,
- breakdownLabel,
- format,
- timezone,
- labels,
- series,
- chartMode,
- focusedBreakdownValue,
- loading,
- error,
- onChartModeChange,
- onFocus,
-}: MetricChartProps): JSX.Element {
- const theme = useChartTheme()
- const focused =
- chartMode === 'breakdown' && series.some((row) => row.key === focusedBreakdownValue)
- ? focusedBreakdownValue
- : null
- const chartSeries = useMemo(
- () =>
- series.map((row, index) => ({
- ...row,
- // Chart hit-testing needs a nonempty key; selection keeps the raw breakdown value.
- key: JSON.stringify(row.key),
- ...focusedSeries(focused, row.key, index, theme),
- })),
- [series, focused, theme]
- )
- const config = useChartConfig<TimeSeriesLineChartConfig>(() => {
- const formatValue = (value: number): string => {
- switch (format) {
- case 'percentage':
- return `${(value * 100).toFixed(1)}%`
- case 'duration':
- return humanFriendlyDuration(value) ?? String(value)
- case 'decimal':
- return value.toFixed(2)
- default:
- return humanFriendlyNumber(value)
- }
- }
- return {
- xAxis: { timezone },
- yAxis: { tickFormatter: formatValue },
- legend: { show: chartMode === 'breakdown', interactive: true, position: 'bottom' },
- tooltip: {
- placement: 'cursor',
- sortedByValue: true,
- valueFormatter: formatValue,
- pinnable: chartMode === 'breakdown',
- resolveClickToNearestSeries: true,
- },
- }
- }, [format, chartMode, timezone])
- const hasData = series.some((row) => row.data.some(Number.isFinite)) && labels.length > 0
-
- // Keep the canvas inside the rounded panel without changing its measured height.
- return (
- <div className="border rounded overflow-hidden bg-surface-primary flex flex-col" aria-busy={loading}>
- <div className="flex flex-wrap items-center justify-between gap-2 px-3 py-2">
- <h3 className="m-0 text-base font-semibold break-words min-w-0">{`${label} over time`}</h3>
- <div className="flex flex-wrap items-center gap-2">
- {focused !== null && (
- <LemonButton
- size="xsmall"
- onClick={() => onFocus(null)}
- disabledReason={loading ? 'Wait for the chart to finish loading' : undefined}
- data-attr="marketing-dashboard-chart-clear-focus"
- >
- Clear selection
- </LemonButton>
- )}
- <LemonSegmentedButton
- size="xsmall"
- value={chartMode}
- onChange={onChartModeChange}
- disabledReason={loading ? 'Wait for the chart to finish loading' : undefined}
- options={[
- {
- value: 'breakdown',
- label: `By ${breakdownLabel.toLowerCase()}`,
- 'data-attr': 'marketing-dashboard-chart-mode-breakdown',
- },
- { value: 'total', label: 'Total', 'data-attr': 'marketing-dashboard-chart-mode-total' },
- ]}
- />
- </div>
- </div>
- {loading && !hasData ? (
- <div className="h-64 px-3 pb-3" aria-label="Loading chart">
- <LemonSkeleton className="h-full w-full" />
- </div>
- ) : error && !loading ? (
- <div className="p-3">{error}</div>
- ) : !hasData ? (
- <div className="px-3 pb-6 text-secondary text-sm">
- No data for this metric. Try another date range or change your filters.
- </div>
- ) : (
- <div className="px-3 pb-3 relative">
- {/* The canvas needs a flex column with a real height or only the legend renders. */}
- <div className="flex flex-col h-64">
- <TimeSeriesLineChart
- key={chartMode}
- series={chartSeries}
- labels={labels}
- theme={theme}
- config={config}
- dataAttr="marketing-dashboard-metric-chart"
- onPointClick={
- chartMode === 'breakdown' && !loading
- ? ({ series: clicked }) =>
- onFocus(
- series.find((row) => JSON.stringify(row.key) === clicked.key)?.key ?? null
- )
- : undefined
- }
- />
- </div>
- {loading && <div className="absolute inset-0 bg-primary/40" aria-hidden />}
- </div>
- )}
- </div>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/charts/MetricChartPreview.tsx b/products/marketing_analytics/frontend/dashboard/charts/MetricChartPreview.tsx
deleted file mode 100644
index e44c0c6cd355..000000000000
--- a/products/marketing_analytics/frontend/dashboard/charts/MetricChartPreview.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { useState } from 'react'
-
-import { LemonBanner, LemonButton, LemonSelect } from '@posthog/lemon-ui'
-
-import { MetricChart, MetricChartProps } from './MetricChart'
-
-const LABELS = ['2026-01-01', '2026-01-02', '2026-01-03', '2026-01-04', '2026-01-05']
-const BREAKDOWN_SERIES = [
- { key: 'organic', label: 'Organic search', data: [48, 64, 52, 76, 60] },
- { key: 'email', label: 'Email newsletter for returning visitors', data: [20, 28, NaN, 30, 36] },
- { key: '', label: 'No channel', data: [0, 12, 8, 16, 20] },
-]
-const TOTAL_SERIES = [{ key: 'total', label: 'Visitors', data: [68, 104, 60, 122, 116] }]
-const RATE_SERIES = BREAKDOWN_SERIES.map((row) => ({ ...row, data: row.data.map((value) => value / 100) }))
-const TOTAL_RATE_SERIES = [{ key: 'total', label: 'Bounce rate', data: [0.4, 0.42, 0.3, 0.5, 0.45] }]
-
-interface MetricChartPreviewProps {
- state: 'loaded' | 'loading' | 'refreshing' | 'empty' | 'error'
- chartMode: MetricChartProps['chartMode']
- focusedBreakdownValue: string | null
- format: MetricChartProps['format']
- queryId: string | null
-}
-
-export function MetricChartPreview({
- state: initialState,
- chartMode: initialChartMode,
- focusedBreakdownValue: initialFocusedBreakdownValue,
- format,
- queryId,
-}: MetricChartPreviewProps): JSX.Element {
- const [state, setState] = useState(initialState)
- const [chartMode, setChartMode] = useState(initialChartMode)
- const [focusedBreakdownValue, setFocusedBreakdownValue] = useState(initialFocusedBreakdownValue)
- const total = format === 'percentage' ? TOTAL_RATE_SERIES : TOTAL_SERIES
- const breakdown = format === 'percentage' ? RATE_SERIES : BREAKDOWN_SERIES
- const series = state === 'empty' || state === 'loading' ? [] : chartMode === 'total' ? total : breakdown
-
- // Pin the scene width so visual snapshots cannot shrink to the controls.
- return (
- <div className="flex w-[60rem] max-w-full flex-col gap-4">
- <MetricChart
- label={format === 'percentage' ? 'Bounce rate' : 'Visitors'}
- breakdownLabel="Channel"
- format={format}
- timezone="UTC"
- labels={LABELS}
- series={series}
- chartMode={chartMode}
- focusedBreakdownValue={focusedBreakdownValue}
- onChartModeChange={(mode) => {
- setChartMode(mode)
- setFocusedBreakdownValue(null)
- }}
- onFocus={setFocusedBreakdownValue}
- loading={state === 'loading' || state === 'refreshing'}
- error={
- state === 'error' && (
- <LemonBanner type="error" action={{ children: 'Retry', onClick: () => setState('loaded') }}>
- <span>Couldn't load this chart. Try again.</span>
- {queryId && (
- <div className="text-muted text-xs break-all">
- <span>Query ID: </span>
- <span className="font-mono" translate="no">
- {queryId}
- </span>
- </div>
- )}
- </LemonBanner>
- )
- }
- />
- <div className="flex flex-wrap gap-2 items-center">
- <LemonSelect
- value={state}
- onChange={setState}
- options={[
- { value: 'loaded', label: 'Show data' },
- { value: 'loading', label: 'Show loading' },
- { value: 'refreshing', label: 'Show refreshing' },
- { value: 'empty', label: 'Show empty' },
- { value: 'error', label: 'Show error' },
- ]}
- />
- <LemonButton
- onClick={() => setFocusedBreakdownValue('')}
- disabledReason={chartMode === 'total' ? 'Switch to By channel' : undefined}
- >
- Select no channel
- </LemonButton>
- <span>{`Selected channel: ${focusedBreakdownValue === null ? 'None' : focusedBreakdownValue || 'No channel'}`}</span>
- </div>
- </div>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/charts/seriesFocus.test.ts b/products/marketing_analytics/frontend/dashboard/charts/seriesFocus.test.ts
deleted file mode 100644
index bf9e98b96ba2..000000000000
--- a/products/marketing_analytics/frontend/dashboard/charts/seriesFocus.test.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { focusedSeries } from './seriesFocus'
-
-describe('focusedSeries', () => {
- it('can focus an empty breakdown key without treating it as no selection', () => {
- const theme = { colors: ['#123456', '#654321'] }
-
- expect(focusedSeries('', '', 0, theme)).toEqual({ color: '#123456' })
- expect(focusedSeries('', 'organic', 1, theme)).toEqual({ color: 'rgba(101, 67, 33, 0.18)' })
- expect(focusedSeries(null, 'organic', 1, theme)).toBeNull()
- })
-})
diff --git a/products/marketing_analytics/frontend/dashboard/charts/seriesFocus.ts b/products/marketing_analytics/frontend/dashboard/charts/seriesFocus.ts
deleted file mode 100644
index 11fb5b28d1fe..000000000000
--- a/products/marketing_analytics/frontend/dashboard/charts/seriesFocus.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { ChartTheme } from '@posthog/quill-charts'
-
-/** Low enough to recede, high enough that the line is still traceable. */
-const DIMMED_ALPHA = 0.18
-
-/** The chart hands colours to the canvas unresolved, so an explicit colour has to be concrete. */
-export function dimColor(color: string, alpha: number): string {
- const hex = color.trim()
- const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex)
- if (match) {
- const body = match[1]
- const full = body.length === 3 ? [...body].map((char) => char + char).join('') : body
- const [r, g, b] = [0, 2, 4].map((offset) => parseInt(full.slice(offset, offset + 2), 16))
- return `rgba(${r}, ${g}, ${b}, ${alpha})`
- }
- const rgb = /^rgba?\(([^)]+)\)$/i.exec(hex)
- if (rgb) {
- const [r, g, b] = rgb[1].split(',').map((part) => part.trim())
- return `rgba(${r}, ${g}, ${b}, ${alpha})`
- }
- return color
-}
-
-export function focusedSeries(
- focused: string | null,
- name: string,
- index: number,
- theme: ChartTheme
-): { color: string } | null {
- if (focused === null) {
- return null
- }
- const palette = theme.colors ?? []
- const color = palette[index % Math.max(palette.length, 1)]
- if (!color) {
- return null
- }
- return { color: focused === name ? color : dimColor(color, DIMMED_ALPHA) }
-}
diff --git a/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.test.ts b/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.test.ts
deleted file mode 100644
index 6c8e4f7560e3..000000000000
--- a/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { WebOverviewItem } from '~/queries/schema/schema-general'
-
-import { customerAcquisitionMetrics } from './customerAcquisitionMetrics'
-
-describe('customerAcquisitionMetrics', () => {
- it.each([
- ['normal', 2, 10, 1, 10, 20, 10, 100],
- ['over 100%', 3, 1, 1, 1, 300, 100, 200],
- ['zero visitors', 2, 0, 1, 10, undefined, 10, undefined],
- ['missing visitors', 2, undefined, 1, undefined, undefined, undefined, undefined],
- ['comparison off', 2, 10, undefined, undefined, 20, undefined, undefined],
- ['zero prior visitors', 2, 10, 1, 0, 20, undefined, undefined],
- ['zero baseline', 2, 10, 0, 10, 20, 0, undefined],
- ['zero customers', 0, 10, 1, 10, 0, 10, -100],
- ['missing customers value', undefined, 10, undefined, 10, undefined, undefined, undefined],
- ] as const)('%s', (_, count, visitors, priorCount, priorVisitors, value, previous, change) => {
- const customers: WebOverviewItem = {
- key: 'unique conversions',
- kind: 'unit',
- value: count,
- previous: priorCount,
- isIncreaseBad: false,
- }
- const rate: WebOverviewItem = {
- key: 'conversion rate',
- kind: 'percentage',
- value: 99,
- previous: 99,
- changeFromPreviousPct: 999,
- isIncreaseBad: false,
- }
- const traffic: WebOverviewItem = {
- key: 'visitors',
- kind: 'unit',
- value: visitors,
- previous: priorVisitors,
- }
- const result = customerAcquisitionMetrics([rate, customers], [traffic])
- expect(result[0]).toBe(customers)
- expect(result[1]).toEqual({ ...rate, value, previous, changeFromPreviousPct: change })
- expect(rate.value).toBe(99)
- })
-
- it('handles missing responses and missing visitors item', () => {
- expect(customerAcquisitionMetrics(undefined, undefined)).toEqual([])
- const customers: WebOverviewItem = {
- key: 'unique conversions',
- kind: 'unit',
- value: 3,
- }
- for (const traffic of [undefined, []]) {
- expect(customerAcquisitionMetrics([customers], traffic)).toEqual([
- customers,
- {
- key: 'conversion rate',
- kind: 'percentage',
- value: undefined,
- previous: undefined,
- changeFromPreviousPct: undefined,
- },
- ])
- }
- })
-})
diff --git a/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.ts b/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.ts
deleted file mode 100644
index e17114c2ff50..000000000000
--- a/products/marketing_analytics/frontend/dashboard/customerAcquisitionMetrics.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { WebOverviewItem } from '~/queries/schema/schema-general'
-
-export function customerAcquisitionMetrics(
- customerResults: WebOverviewItem[] | undefined,
- trafficResults: WebOverviewItem[] | undefined
-): WebOverviewItem[] {
- const customers = customerResults?.find((item) => item.key === 'unique conversions')
- if (!customers) {
- return []
- }
- const visitors = trafficResults?.find((item) => item.key === 'visitors')
- const ratio = (numerator: number | undefined, denominator: number | undefined): number | undefined =>
- numerator != null && denominator != null && denominator > 0 ? (100 * numerator) / denominator : undefined
- const value = ratio(customers.value, visitors?.value)
- const previous = ratio(customers.previous, visitors?.previous)
- return [
- customers,
- {
- ...customerResults?.find((item) => item.key === 'conversion rate'),
- key: 'conversion rate',
- kind: 'percentage',
- value,
- previous,
- changeFromPreviousPct:
- value != null && previous != null && previous > 0
- ? Math.round((100 * (value - previous)) / previous)
- : undefined,
- },
- ]
-}
diff --git a/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.stories.tsx b/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.stories.tsx
deleted file mode 100644
index 978eb5bb020c..000000000000
--- a/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.stories.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { Meta, StoryObj } from '@storybook/react'
-import { useActions, useValues } from 'kea'
-
-import { LemonButton, LemonSelect } from '@posthog/lemon-ui'
-
-import { FEATURE_FLAGS } from 'lib/constants'
-import { urls } from 'scenes/urls'
-import {
- MarketingDashboardView,
- marketingAnalyticsLogic,
-} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
-import {
- BREAKDOWN_LABELS,
- DASHBOARD_BREAKDOWNS,
-} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown'
-
-import { MarketingAnalyticsAttributionBreakdown } from '~/queries/schema/schema-general'
-import { PropertyFilterType, PropertyOperator } from '~/types'
-
-import { MarketingSectionSwitcher } from './MarketingSectionSwitcher'
-
-function NavigationPreview(): JSX.Element {
- const { dashboardBreakdown, dashboardProperties } = useValues(marketingAnalyticsLogic)
- const { setDashboardBreakdown, setDashboardProperties } = useActions(marketingAnalyticsLogic)
-
- return (
- <div className="flex flex-col gap-4 w-full">
- <div className="flex">
- <MarketingSectionSwitcher />
- </div>
- <div className="flex flex-wrap items-center gap-2">
- <LemonSelect
- aria-label="Breakdown"
- value={dashboardBreakdown}
- onChange={(value) => value && setDashboardBreakdown(value)}
- options={DASHBOARD_BREAKDOWNS.map((value) => ({ value, label: BREAKDOWN_LABELS[value] }))}
- />
- <LemonButton
- onClick={() =>
- setDashboardProperties([
- {
- type: PropertyFilterType.Session,
- key: '$channel_type',
- operator: PropertyOperator.Exact,
- value: 'Direct',
- },
- ])
- }
- >
- Filter direct traffic
- </LemonButton>
- <span>{`Active filters: ${dashboardProperties.length}`}</span>
- </div>
- <div className="flex flex-wrap gap-2">
- <LemonButton
- to={`${urls.marketingAnalyticsApp()}?view=${MarketingDashboardView.RETENTION}&breakdown=${MarketingAnalyticsAttributionBreakdown.Source}`}
- >
- Open retention link
- </LemonButton>
- <LemonButton to={urls.marketingAnalyticsApp()}>Open default link</LemonButton>
- </div>
- </div>
- )
-}
-
-const meta: Meta<typeof MarketingSectionSwitcher> = {
- title: 'Marketing Analytics/Dashboard/Section switcher',
- component: MarketingSectionSwitcher,
- parameters: {
- featureFlags: [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
- pageUrl: urls.marketingAnalyticsApp(),
- },
-}
-export default meta
-type Story = StoryObj<typeof meta>
-
-export const InteractiveNavigation: Story = { render: () => <NavigationPreview /> }
-export const Narrow: Story = {
- render: () => (
- <div className="w-[32.5rem] max-w-full">
- <MarketingSectionSwitcher />
- </div>
- ),
-}
diff --git a/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.tsx b/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.tsx
deleted file mode 100644
index 74c05c84eff4..000000000000
--- a/products/marketing_analytics/frontend/dashboard/header/MarketingSectionSwitcher.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { IconCursor, IconPeople, IconPieChart, IconRetention, IconTarget } from '@posthog/icons'
-import { LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
-
-import {
- MarketingDashboardView,
- marketingAnalyticsLogic,
-} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
-
-const SECTIONS: { value: MarketingDashboardView; label: string; icon: JSX.Element }[] = [
- { value: MarketingDashboardView.OVERVIEW, label: 'Overview', icon: <IconPieChart /> },
- { value: MarketingDashboardView.ACQUISITION, label: 'Acquisition', icon: <IconPeople /> },
- { value: MarketingDashboardView.ENGAGEMENT, label: 'Engagement', icon: <IconCursor /> },
- { value: MarketingDashboardView.RETENTION, label: 'Retention', icon: <IconRetention /> },
- { value: MarketingDashboardView.CONVERSION, label: 'Conversion', icon: <IconTarget /> },
-]
-
-export function MarketingSectionSwitcher(): JSX.Element {
- const { dashboardView } = useValues(marketingAnalyticsLogic)
- const { setDashboardView } = useActions(marketingAnalyticsLogic)
-
- // Both controls render and a container query picks one, so the switch needs no measurement and
- // follows the space the header actually has rather than the window.
- return (
- <div className="@container flex-1 basis-56 min-w-0">
- <LemonSegmentedButton
- className="hidden @min-[36rem]:flex"
- size="small"
- value={dashboardView}
- onChange={(view) => setDashboardView(view)}
- options={SECTIONS.map((section) => ({
- value: section.value,
- label: section.label,
- icon: section.icon,
- 'data-attr': `marketing-dashboard-section-${section.value}`,
- }))}
- />
- <LemonSelect
- className="@min-[36rem]:hidden"
- size="small"
- value={dashboardView}
- onChange={(view) => view && setDashboardView(view)}
- options={SECTIONS.map((section) => ({
- value: section.value,
- label: section.label,
- icon: section.icon,
- }))}
- data-attr="marketing-dashboard-section-select"
- aria-label="Dashboard section"
- />
- </div>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic.ts b/products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic.ts
deleted file mode 100644
index 813b2c8a0f79..000000000000
--- a/products/marketing_analytics/frontend/dashboard/marketingAcquisitionLogic.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'
-
-import { isWebAnalyticsPropertyFilter } from 'lib/components/PropertyFilters/utils'
-import { marketingAnalyticsSettingsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic'
-import { attributableConversionGoals } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown'
-
-import {
- ActionsNode,
- ConversionGoalFilter,
- EventsNode,
- NodeKind,
- WebAnalyticsConversionGoal,
- WebAnalyticsOrderByFields,
- WebAnalyticsOrderByDirection,
-} from '~/queries/schema/schema-general'
-
-import { TrafficChartMetric, trafficChartSeries } from './trafficChartSeries'
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface marketingAcquisitionLogicValues {
- conversion_goals: ConversionGoalFilter[] // marketingAnalyticsSettingsLogic
- customerConversionGoal: WebAnalyticsConversionGoal | null
- customerGoalId: string | null
- customerGoals: ConversionGoalFilter[]
- selectedCustomerGoal: ConversionGoalFilter | null
- trafficChartMetric: TrafficChartMetric
- trafficChartSeries: ActionsNode | EventsNode
- trafficOrderBy: Record<string, [WebAnalyticsOrderByFields, WebAnalyticsOrderByDirection]>
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface marketingAcquisitionLogicActions {
- setCustomerGoalId: (customerGoalId: string) => {
- customerGoalId: string
- }
- setTrafficChartMetric: (trafficChartMetric: TrafficChartMetric) => {
- trafficChartMetric: 'new_customers' | 'pageviews' | 'sessions' | 'visitors'
- }
- toggleTrafficSort: (
- section: string,
- field: WebAnalyticsOrderByFields
- ) => {
- field: WebAnalyticsOrderByFields
- section: string
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface marketingAcquisitionLogicMeta {
- __keaTypeGenInternalSelectorTypes: {
- customerGoals: (conversion_goals: ConversionGoalFilter[]) => ConversionGoalFilter[]
- selectedCustomerGoal: (
- customerGoalId: string | null,
- customerGoals: ConversionGoalFilter[]
- ) => ConversionGoalFilter | null
- customerConversionGoal: (selectedCustomerGoal: ConversionGoalFilter | null) => WebAnalyticsConversionGoal | null
- trafficChartSeries: (
- trafficChartMetric: 'new_customers' | 'pageviews' | 'sessions' | 'visitors',
- customerConversionGoal: WebAnalyticsConversionGoal | null
- ) => ActionsNode | EventsNode
- }
-}
-
-export type marketingAcquisitionLogicType = MakeLogicType<
- marketingAcquisitionLogicValues,
- marketingAcquisitionLogicActions,
- Record<string, any>,
- marketingAcquisitionLogicMeta
->
-
-export const marketingAcquisitionLogic = kea<marketingAcquisitionLogicType>([
- path(['products', 'marketing_analytics', 'dashboard', 'marketingAcquisitionLogic']),
- connect(() => ({ values: [marketingAnalyticsSettingsLogic, ['conversion_goals']] })),
- actions({
- setCustomerGoalId: (customerGoalId: string) => ({ customerGoalId }),
- setTrafficChartMetric: (trafficChartMetric: TrafficChartMetric) => ({ trafficChartMetric }),
- toggleTrafficSort: (section: string, field: WebAnalyticsOrderByFields) => ({ section, field }),
- }),
- reducers({
- trafficOrderBy: [
- {} as Record<string, [WebAnalyticsOrderByFields, WebAnalyticsOrderByDirection]>,
- {
- toggleTrafficSort: (state, { section, field }) => ({
- ...state,
- [section]: [
- field,
- state[section]?.[0] === field && state[section]?.[1] === 'DESC' ? 'ASC' : 'DESC',
- ],
- }),
- },
- ],
- customerGoalId: [null as string | null, { setCustomerGoalId: (_, { customerGoalId }) => customerGoalId }],
- trafficChartMetric: [
- 'visitors' as TrafficChartMetric,
- { setTrafficChartMetric: (_, { trafficChartMetric }) => trafficChartMetric },
- ],
- }),
- selectors({
- customerGoals: [
- (s) => [s.conversion_goals],
- (goals: ConversionGoalFilter[]): ConversionGoalFilter[] =>
- attributableConversionGoals(goals).filter((goal) => goal.counts_as_customer),
- ],
- selectedCustomerGoal: [
- (s) => [s.customerGoalId, s.customerGoals],
- (id: string | null, goals: ConversionGoalFilter[]): ConversionGoalFilter | null =>
- goals.find((goal) => goal.conversion_goal_id === id) ?? goals[0] ?? null,
- ],
- customerConversionGoal: [
- (s) => [s.selectedCustomerGoal],
- (goal: ConversionGoalFilter | null): WebAnalyticsConversionGoal | null => {
- const properties = goal?.properties
- if (properties && !properties.every(isWebAnalyticsPropertyFilter)) {
- return null
- }
- if (goal?.kind === NodeKind.ActionsNode) {
- return { actionId: goal.id, properties }
- }
- if (goal?.kind === NodeKind.EventsNode && goal.event) {
- return { customEventName: goal.event, properties }
- }
- return null
- },
- ],
- trafficChartSeries: [
- (s) => [s.trafficChartMetric, s.customerConversionGoal],
- (metric: TrafficChartMetric, goal: WebAnalyticsConversionGoal | null): EventsNode | ActionsNode =>
- trafficChartSeries(metric, goal),
- ],
- }),
-])
diff --git a/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.test.ts b/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.test.ts
deleted file mode 100644
index 00318d8516e0..000000000000
--- a/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.test.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { WebOverviewItem } from '~/queries/schema/schema-general'
-import { CompareLabelType, TrendResult } from '~/types'
-
-import { ratioItem, seriesTotal, sumTrendSeries } from './marketingDashboardMetrics'
-
-const result = (
- order: number,
- aggregated_value: number,
- compare_label?: TrendResult['compare_label']
-): TrendResult => ({
- action: null,
- count: aggregated_value,
- data: [aggregated_value],
- days: ['2026-01-01'],
- label: `Series ${order}`,
- labels: ['1 Jan'],
- order,
- aggregated_value,
- compare_label,
-})
-
-describe('marketingDashboardMetrics', () => {
- // The conversion value query asks for the sum first and the average second, so picking by
- // position rather than by series order would swap the two cards.
- it('picks a series by its order, not its position', () => {
- const results = [result(1, 42), result(0, 13700)]
-
- expect(seriesTotal(results, 0).value).toBe(13700)
- expect(seriesTotal(results, 1).value).toBe(42)
- })
-
- it('keeps the compared period apart from the current one', () => {
- const results = [result(0, 13700), result(0, 9100, CompareLabelType.Previous)]
-
- expect(seriesTotal(results, 0)).toEqual({ value: 13700, previous: 9100 })
- })
-
- // An absent series has no value to show, which the cards render as N/A rather than as zero.
- it('reports no value for a series the response never returned', () => {
- expect(seriesTotal([result(0, 13700)], 1)).toEqual({})
- expect(seriesTotal(undefined, 0)).toEqual({})
- })
-
- it('sums multiple goals without mixing their compared periods', () => {
- expect(
- sumTrendSeries([
- result(0, 0),
- result(1, 20),
- result(0, 5, CompareLabelType.Previous),
- result(1, 10, CompareLabelType.Previous),
- ])
- ).toEqual({ value: 20, previous: 15 })
- expect(sumTrendSeries([result(0, 0)])).toEqual({ value: 0, previous: undefined })
- })
-
- it.each([
- [0, 5, 2, 4, 0, 0.5],
- [10, 5, 0, 4, 2, 0],
- [10, 5, 2, 0, 2, undefined],
- [10, 0, 2, 4, null, undefined],
- [undefined, 5, 2, 4, null, undefined],
- ])(
- 'distinguishes unavailable ratios from zero (%s/%s)',
- (count, total, priorCount, priorTotal, value, previous) => {
- const items: WebOverviewItem[] = [
- { key: 'count', kind: 'unit', value: count, previous: priorCount },
- { key: 'total', kind: 'unit', value: total, previous: priorTotal },
- ]
- const ratio = ratioItem(items, 'ratio', 'count', 'total')
- expect(
- ratio?.kind === 'metric' ? { value: ratio.item.value, previous: ratio.item.previous } : ratio
- ).toEqual(value === null ? null : { value, previous })
- }
- )
-})
diff --git a/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.ts b/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.ts
deleted file mode 100644
index 248dd4fd5744..000000000000
--- a/products/marketing_analytics/frontend/dashboard/marketingDashboardMetrics.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { getResultOrder } from 'scenes/insights/utils/resultSeries'
-
-import { OverviewMetricCardItem } from '~/queries/nodes/OverviewGrid/OverviewMetricCardGrid'
-import { WebOverviewItem } from '~/queries/schema/schema-general'
-import { TrendResult } from '~/types'
-
-import { MetricCardSpec, pctChange } from './cards/metricCardSpec'
-
-/** Sums a BoldNumber trends response, keeping the two compared periods apart. */
-export function sumTrendSeries(results: TrendResult[] | undefined): { value: number; previous: number | undefined } {
- if (!results?.length) {
- return { value: 0, previous: undefined }
- }
- let value = 0
- let previous: number | undefined
- for (const result of results) {
- const amount = result.aggregated_value ?? 0
- if (result.compare_label === 'previous') {
- previous = (previous ?? 0) + amount
- continue
- }
- value += amount
- }
- return { value, previous }
-}
-
-/** One series of a multi-series trends response, picked by the order the query asked for it in.
- * `value` is undefined when that series returned nothing, which the caller shows as N/A rather
- * than as a zero it cannot stand behind. */
-export function seriesTotal(results: TrendResult[] | undefined, order: number): { value?: number; previous?: number } {
- const matching = (results ?? []).filter((result) => getResultOrder(result) === order)
- if (!matching.length) {
- return {}
- }
- const current = matching.find((result) => result.compare_label !== 'previous')
- const previous = matching.find((result) => result.compare_label === 'previous')
- return {
- value: current?.aggregated_value,
- previous: previous?.aggregated_value,
- }
-}
-
-/** One overview scalar divided by another, as a card. Null when the denominator is missing or
- * zero, which the caller shows as a notice rather than as a misleading zero. */
-export function ratioItem(
- results: WebOverviewItem[] | undefined,
- key: string,
- numeratorKey: string,
- denominatorKey: string
-): MetricCardSpec | null {
- const numerator = results?.find((item) => item.key === numeratorKey)
- const denominator = results?.find((item) => item.key === denominatorKey)
- if (numerator?.value === undefined || !denominator?.value) {
- return null
- }
- const value = numerator.value / denominator.value
- const previous =
- numerator.previous !== undefined && denominator.previous ? numerator.previous / denominator.previous : undefined
- return {
- kind: 'metric',
- item: {
- key,
- kind: 'unit',
- value,
- previous,
- changeFromPreviousPct: pctChange(value, previous),
- } as OverviewMetricCardItem,
- }
-}
diff --git a/products/marketing_analytics/frontend/dashboard/marketingTrafficQueryContext.tsx b/products/marketing_analytics/frontend/dashboard/marketingTrafficQueryContext.tsx
deleted file mode 100644
index fa83219aac3f..000000000000
--- a/products/marketing_analytics/frontend/dashboard/marketingTrafficQueryContext.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { IconChevronDown } from '@posthog/icons'
-import { LemonButton } from '@posthog/lemon-ui'
-
-import { webAnalyticsDataTableQueryContext } from 'scenes/web-analytics/tiles/WebAnalyticsTile'
-
-import { WebAnalyticsOrderByDirection, WebAnalyticsOrderByFields } from '~/queries/schema/schema-general'
-import { QueryContext, QueryContextColumnTitleComponent } from '~/queries/types'
-
-export function marketingTrafficQueryContext(
- orderBy: [WebAnalyticsOrderByFields, WebAnalyticsOrderByDirection] | undefined,
- onSort: (field: WebAnalyticsOrderByFields) => void
-): QueryContext {
- const sortableTitle = (label: string, field: WebAnalyticsOrderByFields): QueryContextColumnTitleComponent =>
- function TrafficColumnTitle() {
- const selected = orderBy?.[0] === field
- return (
- <LemonButton
- size="xsmall"
- onClick={() => onSort(field)}
- sideIcon={
- <IconChevronDown
- className={selected ? (orderBy?.[1] === 'ASC' ? 'rotate-180' : '') : 'opacity-40'}
- />
- }
- aria-label={`Sort by ${label}${selected ? `, ${orderBy?.[1] === 'ASC' ? 'ascending' : 'descending'}` : ''}`}
- >
- {label}
- </LemonButton>
- )
- }
-
- return {
- ...webAnalyticsDataTableQueryContext,
- columns: {
- ...webAnalyticsDataTableQueryContext.columns,
- visitors: {
- ...webAnalyticsDataTableQueryContext.columns?.visitors,
- renderTitle: sortableTitle('Visitors', WebAnalyticsOrderByFields.Visitors),
- },
- sessions: {
- renderTitle: () => <>Sessions</>,
- render: webAnalyticsDataTableQueryContext.columns?.visitors?.render,
- align: 'right',
- },
- views: {
- ...webAnalyticsDataTableQueryContext.columns?.views,
- renderTitle: sortableTitle('Pageviews', WebAnalyticsOrderByFields.Views),
- },
- bounce_rate: {
- ...webAnalyticsDataTableQueryContext.columns?.bounce_rate,
- renderTitle: sortableTitle('Bounce rate', WebAnalyticsOrderByFields.BounceRate),
- },
- unique_conversions: {
- ...webAnalyticsDataTableQueryContext.columns?.unique_conversions,
- renderTitle: sortableTitle('New customers', WebAnalyticsOrderByFields.UniqueConversions),
- },
- conversion_rate: {
- ...webAnalyticsDataTableQueryContext.columns?.conversion_rate,
- renderTitle: sortableTitle('Customer-to-visitor ratio', WebAnalyticsOrderByFields.ConversionRate),
- },
- },
- }
-}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/ChangeValueCell.stories.tsx b/products/marketing_analytics/frontend/dashboard/tables/ChangeValueCell.stories.tsx
deleted file mode 100644
index ff5c28f4a638..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/ChangeValueCell.stories.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-import { Meta, StoryObj } from '@storybook/react'
-import { useState } from 'react'
-
-import { LemonButton, LemonMenu, LemonTable, LemonTextArea } from '@posthog/lemon-ui'
-
-import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
-
-import { CurrencyCode } from '~/queries/schema/schema-general'
-
-import { compareByCurrent } from './breakdownTableColumn'
-import { buildExportMenuItems, buildExportRows } from './breakdownTableExport'
-import { ChangeValueCell } from './ChangeValueCell'
-import { CONVERSION_VALUE_COLUMN, VISITORS_COLUMN } from './webStatsColumns'
-import { WebStatsRow } from './webStatsRows'
-
-const meta: Meta<typeof ChangeValueCell> = {
- title: 'Scenes-App/Marketing analytics/Dashboard/Change value cell',
- component: ChangeValueCell,
- args: { currency: CurrencyCode.USD, compare: true },
-}
-export default meta
-type Story = StoryObj<typeof meta>
-
-export const Number: Story = { args: { value: [150, 100] } }
-export const Rate: Story = { args: { value: [0.1, 0.08], kind: 'percentage' } }
-export const BounceRate: Story = { args: { value: [0.2, 0.3], kind: 'percentage', reverseColors: true } }
-export const Duration: Story = { args: { value: [90, 60], kind: 'duration' } }
-export const Currency: Story = { args: { value: [12.5, 10], kind: 'currency' } }
-export const NegativeCurrency: Story = { args: { value: [-12.5, -10], kind: 'currency' } }
-export const NoBaseline: Story = { args: { value: [0, null] } }
-export const Unavailable: Story = { args: { value: null } }
-export const RoundedFlat: Story = { args: { value: [0.10001, 0.1], kind: 'percentage' } }
-
-const rows: WebStatsRow[] = [
- { breakdownValue: 'Direct', visitors: [10, 5] },
- { breakdownValue: 'Paid search', visitors: [20, 10], conversion_value: [125, 100] },
- { breakdownValue: 'Email', visitors: [5, 10], conversion_value: [-12.5, -10] },
- { breakdownValue: 'Referral', visitors: [0, null], conversion_value: [0, null] },
- { breakdownValue: 'Organic search', visitors: [30, 25] },
-]
-const columns = [CONVERSION_VALUE_COLUMN, VISITORS_COLUMN]
-
-export const InteractiveTable: Story = {
- render: function Render(): JSX.Element {
- const [sorting, setSorting] = useState<Sorting | null>({ columnKey: 'conversion_value', order: 1 })
- const [pastedExport, setPastedExport] = useState('')
-
- return (
- // A 960 px scene keeps snapshots from shrinking the table to its minimum content width.
- <div className="flex w-[60rem] max-w-full flex-col gap-4">
- <LemonMenu
- items={buildExportMenuItems(
- () =>
- buildExportRows({
- columns,
- rows,
- breakdownLabel: 'Channel',
- breakdownValue: (row) => row.breakdownValue,
- compare: true,
- }),
- 'marketing-breakdown',
- true
- )}
- >
- <LemonButton type="secondary">Export</LemonButton>
- </LemonMenu>
- <LemonTable
- rowKey="breakdownValue"
- dataSource={rows}
- useURLForSorting={false}
- sorting={sorting}
- onSort={setSorting}
- noSortingCancellation
- columns={[
- { title: 'Channel', dataIndex: 'breakdownValue' },
- ...columns.map((column) => ({
- key: column.key,
- title: column.title,
- align: 'right' as const,
- sorter: compareByCurrent(column, sorting?.order ?? 1),
- render: (_: unknown, row: WebStatsRow) => (
- <ChangeValueCell
- value={column.value(row)}
- kind={column.kind}
- currency={CurrencyCode.USD}
- compare
- />
- ),
- })),
- ]}
- />
- <LemonTextArea
- aria-label="Paste exported rows"
- placeholder="Paste exported rows here"
- value={pastedExport}
- onChange={setPastedExport}
- />
- </div>
- )
- },
-}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/MarketingBreakdownTable.stories.tsx b/products/marketing_analytics/frontend/dashboard/tables/MarketingBreakdownTable.stories.tsx
deleted file mode 100644
index fd8e563cd516..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/MarketingBreakdownTable.stories.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { Meta, StoryObj } from '@storybook/react'
-
-import { TablePreview } from './TablePreview'
-
-const meta: Meta<typeof TablePreview> = {
- title: 'Marketing Analytics/Dashboard/Breakdown table',
- component: TablePreview,
-}
-export default meta
-type Story = StoryObj<typeof meta>
-
-export const Interactive: Story = {}
-export const Loading: Story = {
- parameters: { testOptions: { waitForLoadersToDisappear: false } },
- args: { initialState: 'loading' },
-}
-export const Empty: Story = { args: { initialState: 'empty' } }
-export const Error: Story = { args: { initialState: 'error' } }
-export const Narrow: Story = {
- parameters: Loading.parameters,
- args: Loading.args,
- decorators: [
- (Story) => (
- <div className="w-[32.5rem] max-w-full">
- {/* A 520 px scene models the space beside an open side panel. */}
- <Story />
- </div>
- ),
- ],
-}
-export const NarrowComparison: Story = {
- args: { initiallyCompare: true },
- decorators: Narrow.decorators,
-}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/MarketingBreakdownTable.tsx b/products/marketing_analytics/frontend/dashboard/tables/MarketingBreakdownTable.tsx
deleted file mode 100644
index 8089595a7f51..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/MarketingBreakdownTable.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { useId } from 'react'
-
-import { LemonBanner, LemonButton, LemonTable, LemonTableColumn } from '@posthog/lemon-ui'
-
-import { TileId } from 'scenes/web-analytics/common'
-import { displayBreakdownValue } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingBreakdown'
-import { WebTileHeader, WebTileHeaderProps } from 'scenes/web-analytics/WebTileHeader'
-
-import { CurrencyCode } from '~/queries/schema/schema-general'
-
-import { BreakdownTableColumn, compareByCurrent } from './breakdownTableColumn'
-import { buildExportMenuItems, buildExportRows } from './breakdownTableExport'
-import { ChangeValueCell } from './ChangeValueCell'
-import { marketingBreakdownTableLogic } from './marketingBreakdownTableLogic'
-
-export interface MarketingBreakdownTableProps<Row extends object> {
- tileId: TileId
- titlePrefix: string
- breakdownLabel: string
- titleDropdown?: WebTileHeaderProps['titleDropdown']
- rows: Row[]
- rowKey: (row: Row) => string
- breakdownValue: (row: Row) => string
- columns: BreakdownTableColumn<Row>[]
- defaultSortKey: string
- compare: boolean
- currency: CurrencyCode
- loading: boolean
- error: boolean
- onRetry: () => void
- emptyState: string
- footnote?: React.ReactNode
- exportFilename: string
- focusedBreakdownValue?: string | null
- onFocusBreakdown?: (value: string) => void
-}
-
-export function MarketingBreakdownTable<Row extends object>({
- tileId,
- titlePrefix,
- breakdownLabel,
- titleDropdown,
- rows,
- rowKey,
- breakdownValue,
- columns,
- defaultSortKey,
- compare,
- currency,
- loading,
- error,
- onRetry,
- emptyState,
- footnote,
- exportFilename,
- focusedBreakdownValue,
- onFocusBreakdown,
-}: MarketingBreakdownTableProps<Row>): JSX.Element {
- const tableKey = useId()
- const logic = marketingBreakdownTableLogic({ tableKey, defaultSortKey })
- const { sorting } = useValues(logic)
- const { setSorting } = useActions(logic)
- const tableColumns: LemonTableColumn<Row, keyof Row | undefined>[] = [
- {
- title: breakdownLabel,
- key: 'breakdown_value',
- render: (_, row) => {
- const value = breakdownValue(row)
- const label = displayBreakdownValue(value, breakdownLabel)
- return onFocusBreakdown ? (
- <LemonButton
- size="xsmall"
- onClick={() => onFocusBreakdown(value)}
- tooltip="Focus this line in the chart"
- aria-label={`Focus ${label} in the chart`}
- data-attr="marketing-breakdown-focus"
- className="max-w-full"
- >
- <span className="truncate" title={label}>
- {label}
- </span>
- </LemonButton>
- ) : (
- <span className="block truncate" title={label}>
- {label}
- </span>
- )
- },
- },
- ...columns.map(
- (column): LemonTableColumn<Row, keyof Row | undefined> => ({
- title: (
- <span className="whitespace-normal wrap-anywhere">
- <span className="hidden @min-[40rem]:inline">{column.title}</span>
- <span className="@min-[40rem]:hidden">
- {column.shortTitle?.replaceAll('/', '/\u200b') ?? column.title}
- </span>
- </span>
- ),
- key: column.key,
- align: 'right',
- tooltip: column.tooltip,
- sorter: compareByCurrent(column, sorting?.order ?? -1),
- render: (_, row) => (
- <ChangeValueCell
- value={column.value(row)}
- compare={compare}
- kind={column.kind}
- reverseColors={column.reverseColors}
- neutral={column.neutral}
- tooltipContent={column.tooltipContent?.(row)}
- currency={currency}
- />
- ),
- })
- ),
- ]
-
- return (
- <div className="@container border rounded bg-surface-primary flex flex-col">
- <WebTileHeader
- tileId={tileId}
- titlePrefix={titlePrefix}
- title={breakdownLabel}
- titleDropdown={titleDropdown}
- overflowMenuItems={buildExportMenuItems(
- () =>
- buildExportRows({
- columns,
- rows,
- breakdownLabel,
- breakdownValue: (row) => displayBreakdownValue(breakdownValue(row), breakdownLabel),
- compare,
- sorting,
- }),
- exportFilename,
- !loading && !error && rows.length > 0
- )}
- />
- {error && !loading ? (
- <div className="p-3">
- <LemonBanner
- type="error"
- action={{
- children: 'Retry',
- onClick: onRetry,
- 'data-attr': 'marketing-breakdown-table-retry',
- }}
- >
- Couldn't load this table. Try again.
- </LemonBanner>
- </div>
- ) : (
- <div className="max-h-[36rem] overflow-auto">
- {/* Cap long breakdowns so later dashboard sections stay within reach. */}
- <LemonTable
- className="@max-[40rem]:[&_th_svg]:hidden @max-[40rem]:[&_.sorting-indicator]:hidden"
- embedded
- tableLayout="fixed"
- size="small"
- firstColumnSticky
- useURLForSorting={false}
- columns={tableColumns}
- dataSource={loading ? [] : rows}
- loading={loading}
- loadingSkeletonRows={5}
- rowKey={rowKey}
- sorting={sorting}
- onSort={setSorting}
- emptyState={emptyState}
- // The sticky first column paints its own background, so a row class alone leaves it unhighlighted.
- rowStatus={(row) => (focusedBreakdownValue === breakdownValue(row) ? 'highlighted' : null)}
- />
- </div>
- )}
- {footnote && <div className="text-secondary text-xs px-3 pb-3">{footnote}</div>}
- </div>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/TablePreview.tsx b/products/marketing_analytics/frontend/dashboard/tables/TablePreview.tsx
deleted file mode 100644
index afad6b701f8b..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/TablePreview.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { useActions, useValues } from 'kea'
-import { useId } from 'react'
-
-import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'
-
-import { BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'
-import { TileId } from 'scenes/web-analytics/common'
-
-import { CurrencyCode } from '~/queries/schema/schema-general'
-
-import { MarketingBreakdownTable } from './MarketingBreakdownTable'
-import { TablePreviewState, tablePreviewLogic } from './tablePreviewLogic'
-import {
- BOUNCE_RATE_COLUMN,
- PAGES_PER_SESSION_COLUMN,
- SESSIONS_COLUMN,
- SESSION_DURATION_COLUMN,
-} from './webStatsColumns'
-import { WebStatsRow } from './webStatsRows'
-
-const rows: WebStatsRow[] = [
- {
- breakdownValue: 'Direct',
- sessions: [120, 100],
- views: [240, 180],
- session_duration: [90, 60],
- bounce_rate: [0.3, 0.4],
- },
- {
- breakdownValue: 'Paid search',
- sessions: [80, 100],
- views: [160, 200],
- session_duration: [45, 60],
- bounce_rate: [0.4, 0.3],
- },
- {
- breakdownValue: 'Email',
- sessions: [20, 10],
- views: [60, 20],
- session_duration: [120, 90],
- bounce_rate: [0.2, 0.25],
- },
- { breakdownValue: '', sessions: [0, null], views: [0, null], session_duration: [0, null], bounce_rate: [0, null] },
- { breakdownValue: BREAKDOWN_OTHER_STRING_LABEL, sessions: [5, 4], views: [10, 8], bounce_rate: [0.5, 0.5] },
-]
-
-export function TablePreview({
- initialState = 'loaded',
- initiallyCompare = false,
-}: {
- initialState?: TablePreviewState
- initiallyCompare?: boolean
-}): JSX.Element {
- const previewKey = useId()
- const logic = tablePreviewLogic({ previewKey, initialState, initiallyCompare })
- const { state, compare, focusedValue } = useValues(logic)
- const { setState, setCompare, setFocusedValue } = useActions(logic)
-
- return (
- <div className="flex flex-col gap-4">
- <MarketingBreakdownTable
- tileId={TileId.MARKETING}
- titlePrefix="Engagement by"
- breakdownLabel="Channel"
- rows={state === 'empty' ? [] : rows}
- rowKey={(row) => row.breakdownValue}
- breakdownValue={(row) => row.breakdownValue}
- columns={[SESSIONS_COLUMN, SESSION_DURATION_COLUMN, BOUNCE_RATE_COLUMN, PAGES_PER_SESSION_COLUMN]}
- defaultSortKey="sessions"
- compare={compare}
- currency={CurrencyCode.USD}
- loading={state === 'loading'}
- error={state === 'error'}
- onRetry={() => setState('loading')}
- emptyState="No sessions in this date range. Try a wider date range."
- footnote="Grouped by session entry. Visitors can appear in more than one row."
- exportFilename="marketing-engagement"
- focusedBreakdownValue={focusedValue}
- onFocusBreakdown={setFocusedValue}
- />
- <div className="flex flex-wrap items-center gap-2">
- <LemonButton data-attr="marketing-breakdown-story-show-loading" onClick={() => setState('loading')}>
- Show loading
- </LemonButton>
- <LemonButton data-attr="marketing-breakdown-story-show-data" onClick={() => setState('loaded')}>
- Show data
- </LemonButton>
- <LemonButton data-attr="marketing-breakdown-story-show-empty" onClick={() => setState('empty')}>
- Show empty
- </LemonButton>
- <LemonButton data-attr="marketing-breakdown-story-show-error" onClick={() => setState('error')}>
- Show error
- </LemonButton>
- <LemonSwitch
- data-attr="marketing-breakdown-story-compare"
- checked={compare}
- onChange={setCompare}
- label="Compare"
- />
- </div>
- </div>
- )
-}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.test.ts b/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.test.ts
deleted file mode 100644
index f9c71429b661..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.test.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { LemonMenuItemLeaf } from 'lib/lemon-ui/LemonMenu'
-import { copyToClipboard } from 'lib/utils/copyToClipboard'
-
-import { buildExportMenuItems, buildExportRows } from './breakdownTableExport'
-import { SESSIONS_PER_VISITOR_COLUMN, VISITORS_COLUMN } from './webStatsColumns'
-import { WebStatsRow } from './webStatsRows'
-
-jest.mock('lib/utils/copyToClipboard', () => ({ copyToClipboard: jest.fn() }))
-
-describe('buildExportRows', () => {
- const rows: WebStatsRow[] = [
- { breakdownValue: 'Email', visitors: [10, 0], sessions: [25, 5] },
- { breakdownValue: 'Direct', visitors: [0, null] },
- { breakdownValue: 'Organic' },
- ]
-
- it.each([false, true])('exports zeros, unavailable ratios, and previous periods (compare=%s)', (compare) => {
- expect(
- buildExportRows({
- columns: [VISITORS_COLUMN, SESSIONS_PER_VISITOR_COLUMN],
- rows,
- breakdownLabel: 'Channel',
- breakdownValue: (row) => row.breakdownValue,
- compare,
- })
- ).toEqual(
- compare
- ? [
- [
- 'Channel',
- 'Visitors (current)',
- 'Visitors (previous)',
- 'Sessions per visitor (current)',
- 'Sessions per visitor (previous)',
- ],
- ['Email', '10', '0', '2.50', ''],
- ['Direct', '0', '', '', ''],
- ['Organic', '', '', '', ''],
- ]
- : [
- ['Channel', 'Visitors', 'Sessions per visitor'],
- ['Email', '10', '2.50'],
- ['Direct', '0', ''],
- ['Organic', '', ''],
- ]
- )
- })
-
- it.each([
- [{ columnKey: 'visitors', order: 1 }, ['Direct', 'Email', 'Organic']],
- [{ columnKey: 'visitors', order: -1 }, ['Email', 'Direct', 'Organic']],
- [null, ['Organic', 'Direct', 'Email']],
- [{ columnKey: 'unavailable', order: 1 }, ['Organic', 'Direct', 'Email']],
- ] as const)('exports the visible row order for sorting=%j without changing input rows', (sorting, expected) => {
- const input = [rows[2], rows[1], rows[0]]
- const exported = buildExportRows({
- columns: [VISITORS_COLUMN],
- rows: input,
- breakdownLabel: 'Channel',
- breakdownValue: (row) => row.breakdownValue,
- compare: false,
- sorting,
- })
-
- expect(exported.slice(1).map((row) => row[0])).toEqual(expected)
- expect(input.map((row) => row.breakdownValue)).toEqual(['Organic', 'Direct', 'Email'])
- })
-
- it.each([
- ['Copy as CSV', 'Channel,Visitors\r\nEmail,0'],
- ['Copy for Excel', 'Channel\tVisitors\r\nEmail\t0'],
- ])('copies the latest rows through %s', (label, expected) => {
- let data = [['stale']]
- const item = buildExportMenuItems(() => data, 'engagement', true).find(
- (item) => item.label === label
- ) as LemonMenuItemLeaf
- data = [
- ['Channel', 'Visitors'],
- ['Email', '0'],
- ]
-
- item.onClick?.({} as React.MouseEvent)
-
- expect(copyToClipboard).toHaveBeenLastCalledWith(expected, 'table')
- })
-})
diff --git a/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.ts b/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.ts
deleted file mode 100644
index 9a90699f2614..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/breakdownTableExport.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { LemonMenuItem } from '@posthog/lemon-ui'
-
-import type { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
-import { downloadTableDataAsCsv } from 'scenes/web-analytics/webAnalyticsExportUtils'
-
-import { copyTableData } from '~/queries/nodes/InsightViz/exportAdapters'
-import { ExporterFormat } from '~/types'
-
-import { BreakdownTableColumn, compareByCurrent } from './breakdownTableColumn'
-
-export interface ExportRowsOptions<Row> {
- columns: BreakdownTableColumn<Row>[]
- rows: Row[]
- breakdownLabel: string
- breakdownValue: (row: Row) => string
- compare: boolean
- sorting?: Sorting | null
-}
-
-/** Rows as `string[][]` with the header first, which is the shape the shared export helpers take. */
-export function buildExportRows<Row>({
- columns,
- rows,
- breakdownLabel,
- breakdownValue,
- compare,
- sorting,
-}: ExportRowsOptions<Row>): string[][] {
- if (!rows.length) {
- return []
- }
-
- const format = (column: BreakdownTableColumn<Row>, value: number): string =>
- column.exportValue ? column.exportValue(value) : String(value)
-
- const header = [
- breakdownLabel,
- ...columns.flatMap((column) =>
- compare ? [`${column.exportLabel} (current)`, `${column.exportLabel} (previous)`] : [column.exportLabel]
- ),
- ]
-
- const sortColumn = sorting && columns.find((column) => column.key === sorting.columnKey)
- let sortedRows = rows
- if (sortColumn && sorting) {
- const sorter = compareByCurrent(sortColumn, sorting.order)
- sortedRows = rows.slice().sort((a, b) => sorting.order * sorter(a, b))
- }
-
- const body = sortedRows.map((row) => [
- breakdownValue(row),
- ...columns.flatMap((column) => {
- const value = column.value(row)
- const current = value ? format(column, value[0]) : ''
- if (!compare) {
- return [current]
- }
- return [current, value && value[1] !== null ? format(column, value[1]) : '']
- }),
- ])
-
- return [header, ...body]
-}
-
-export function buildExportMenuItems(getRows: () => string[][], filename: string, hasRows: boolean): LemonMenuItem[] {
- const disabledReason = hasRows ? undefined : 'No data to export yet'
- return [
- {
- label: 'Download CSV',
- disabledReason,
- onClick: () => downloadTableDataAsCsv(getRows(), `${filename}.csv`),
- },
- {
- label: 'Copy as CSV',
- disabledReason,
- onClick: () => copyTableData(getRows(), ExporterFormat.CSV),
- },
- {
- // A real .xlsx needs the server exporter, which cannot re-run an in-memory table.
- // Tab-separated text pastes into Excel as columns, which is what people want here.
- label: 'Copy for Excel',
- disabledReason,
- onClick: () => copyTableData(getRows(), ExporterFormat.XLSX),
- },
- ]
-}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.test.ts b/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.test.ts
deleted file mode 100644
index e93ac20a4b64..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'
-
-import { TrendResult } from '~/types'
-
-import { conversionValueRows } from './conversionValueRows'
-
-const result = (
- order: number,
- breakdownValue: string,
- aggregatedValue: number,
- compareLabel?: 'current' | 'previous'
-): TrendResult =>
- ({
- action: { order },
- breakdown_value: breakdownValue,
- aggregated_value: aggregatedValue,
- compare_label: compareLabel ?? 'current',
- }) as unknown as TrendResult
-
-describe('conversionValueRows', () => {
- it('pairs each breakdown with its previous period, by series order', () => {
- const rows = conversionValueRows([
- result(0, 'Paid Search', 4000),
- result(0, 'Paid Search', 3000, 'previous'),
- result(1, 'Paid Search', 80),
- result(1, 'Paid Search', 75, 'previous'),
- ])
-
- expect(rows.get('Paid Search')).toEqual({ total: [4000, 3000], average: [80, 75] })
- })
-
- it('leaves the previous period null when the breakdown is new', () => {
- const rows = conversionValueRows([result(0, 'Email', 900), result(1, 'Email', 45)])
-
- expect(rows.get('Email')).toEqual({ total: [900, null], average: [45, null] })
- })
-
- // The stats table reports an untagged visit as SQL NULL, which webStatsRows reads as ''. If
- // these two did not agree, that row's value cells would silently stay empty.
- it('keys the trends null sentinel the way the stats table keys an untagged row', () => {
- const rows = conversionValueRows([result(0, BREAKDOWN_NULL_STRING_LABEL, 120)])
-
- expect(rows.has(BREAKDOWN_NULL_STRING_LABEL)).toBe(false)
- expect(rows.get('')).toEqual({ total: [120, null] })
- })
-
- // The fold is a total over values the stats table lists one by one, so merging it would
- // attribute the whole tail to whichever row happened to carry that name.
- it('drops the folded "other" row', () => {
- const rows = conversionValueRows([result(0, BREAKDOWN_OTHER_STRING_LABEL, 5000), result(0, 'Direct', 100)])
-
- expect([...rows.keys()]).toEqual(['Direct'])
- })
-
- it('returns nothing for an absent response', () => {
- expect(conversionValueRows(undefined).size).toBe(0)
- })
-})
diff --git a/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.ts b/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.ts
deleted file mode 100644
index a9bf85091eb7..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/conversionValueRows.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'
-import { getResultOrder } from 'scenes/insights/utils/resultSeries'
-
-import { TrendResult } from '~/types'
-
-import type { ComparedValue } from './breakdownTableColumn'
-
-export interface ConversionValueByBreakdown {
- total?: ComparedValue
- average?: ComparedValue
-}
-
-/** Series order in `conversionValueSeries`. */
-const TOTAL_ORDER = 0
-const AVERAGE_ORDER = 1
-
-/** Trends reports an untagged visit as its own sentinel, while the stats table reports SQL NULL,
- * which `webStatsRows` reads as an empty string. Both have to land on the same key or the two
- * halves of a row never meet. */
-const joinKey = (breakdownValue: TrendResult['breakdown_value']): string => {
- const value = String(breakdownValue ?? '')
- return value === BREAKDOWN_NULL_STRING_LABEL ? '' : value
-}
-
-const pair = (current: number | undefined, previous: number | undefined): ComparedValue | undefined =>
- current === undefined ? undefined : [current, previous ?? null]
-
-/** Keyed by the raw breakdown value, not its display label. */
-export function conversionValueRows(results: TrendResult[] | undefined): Map<string, ConversionValueByBreakdown> {
- const byKey = new Map<string, ConversionValueByBreakdown>()
-
- for (const order of [TOTAL_ORDER, AVERAGE_ORDER]) {
- const rows = (results ?? []).filter(
- // The fold row is an aggregate over values the stats table lists individually, so
- // merging it would attribute the whole tail to one row.
- (result) => getResultOrder(result) === order && result.breakdown_value !== BREAKDOWN_OTHER_STRING_LABEL
- )
- const current = rows.filter((result) => result.compare_label !== 'previous')
- const previous = new Map(
- rows.filter((result) => result.compare_label === 'previous').map((r) => [joinKey(r.breakdown_value), r])
- )
-
- for (const row of current) {
- const key = joinKey(row.breakdown_value)
- const value = pair(row.aggregated_value, previous.get(key)?.aggregated_value)
- if (value === undefined) {
- continue
- }
- const existing = byKey.get(key) ?? {}
- byKey.set(key, order === TOTAL_ORDER ? { ...existing, total: value } : { ...existing, average: value })
- }
- }
-
- return byKey
-}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/marketingBreakdownTableLogic.test.ts b/products/marketing_analytics/frontend/dashboard/tables/marketingBreakdownTableLogic.test.ts
deleted file mode 100644
index eddd27e7f123..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/marketingBreakdownTableLogic.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { resetContext } from 'kea'
-
-import { marketingBreakdownTableLogic } from './marketingBreakdownTableLogic'
-
-describe('marketingBreakdownTableLogic', () => {
- it('keeps sorting and cancellation independent for tables with the same default metric', () => {
- resetContext()
- const engagement = marketingBreakdownTableLogic({ tableKey: 'engagement', defaultSortKey: 'sessions' })
- const acquisition = marketingBreakdownTableLogic({ tableKey: 'acquisition', defaultSortKey: 'sessions' })
- const unmountEngagement = engagement.mount()
- const unmountAcquisition = acquisition.mount()
-
- try {
- engagement.actions.setSorting({ columnKey: 'bounce_rate', order: 1 })
- expect(engagement.values.sorting).toEqual({ columnKey: 'bounce_rate', order: 1 })
- expect(acquisition.values.sorting).toEqual({ columnKey: 'sessions', order: -1 })
-
- engagement.actions.setSorting(null)
- expect(engagement.values.sorting).toBeNull()
- expect(acquisition.values.sorting).toEqual({ columnKey: 'sessions', order: -1 })
- } finally {
- unmountEngagement()
- unmountAcquisition()
- }
- })
-})
diff --git a/products/marketing_analytics/frontend/dashboard/tables/marketingBreakdownTableLogic.ts b/products/marketing_analytics/frontend/dashboard/tables/marketingBreakdownTableLogic.ts
deleted file mode 100644
index 8a4dc5322c0b..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/marketingBreakdownTableLogic.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { LogicWrapper, MakeLogicType, actions, kea, key, path, props, reducers } from 'kea'
-
-import type { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
-
-export interface MarketingBreakdownTableLogicProps {
- tableKey: string
- defaultSortKey: string
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface marketingBreakdownTableLogicValues {
- sorting: Sorting | null
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface marketingBreakdownTableLogicActions {
- setSorting: (sorting: Sorting | null) => {
- sorting: Sorting | null
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface marketingBreakdownTableLogicMeta {
- key: string
-}
-
-export type marketingBreakdownTableLogicType = MakeLogicType<
- marketingBreakdownTableLogicValues,
- marketingBreakdownTableLogicActions,
- MarketingBreakdownTableLogicProps,
- marketingBreakdownTableLogicMeta
->
-
-export const marketingBreakdownTableLogic: LogicWrapper<marketingBreakdownTableLogicType> =
- kea<marketingBreakdownTableLogicType>([
- props({} as MarketingBreakdownTableLogicProps),
- key((props) => props.tableKey),
- path((key) => [
- 'products',
- 'marketing_analytics',
- 'frontend',
- 'dashboard',
- 'tables',
- 'marketingBreakdownTableLogic',
- key,
- ]),
- actions({ setSorting: (sorting: Sorting | null) => ({ sorting }) }),
- reducers(({ props }) => ({
- sorting: [
- { columnKey: props.defaultSortKey, order: -1 } as Sorting | null,
- { setSorting: (_, { sorting }) => sorting },
- ],
- })),
- ])
diff --git a/products/marketing_analytics/frontend/dashboard/tables/tablePreviewLogic.ts b/products/marketing_analytics/frontend/dashboard/tables/tablePreviewLogic.ts
deleted file mode 100644
index 5aeeb6f3dc7a..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/tablePreviewLogic.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { LogicWrapper, MakeLogicType, actions, kea, key, path, props, reducers } from 'kea'
-
-export type TablePreviewState = 'loaded' | 'loading' | 'empty' | 'error'
-
-export interface TablePreviewLogicProps {
- previewKey: string
- initialState: TablePreviewState
- initiallyCompare: boolean
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface tablePreviewLogicValues {
- compare: boolean
- focusedValue: string | null
- state: TablePreviewState
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface tablePreviewLogicActions {
- setCompare: (compare: boolean) => {
- compare: boolean
- }
- setFocusedValue: (focusedValue: string) => {
- focusedValue: string
- }
- setState: (state: TablePreviewState) => {
- state: TablePreviewState
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface tablePreviewLogicMeta {
- key: string
-}
-
-export type tablePreviewLogicType = MakeLogicType<
- tablePreviewLogicValues,
- tablePreviewLogicActions,
- TablePreviewLogicProps,
- tablePreviewLogicMeta
->
-
-export const tablePreviewLogic: LogicWrapper<tablePreviewLogicType> = kea<tablePreviewLogicType>([
- props({} as TablePreviewLogicProps),
- key((props) => props.previewKey),
- path((key) => ['products', 'marketing_analytics', 'frontend', 'dashboard', 'tables', 'tablePreviewLogic', key]),
- actions({
- setState: (state: TablePreviewState) => ({ state }),
- setCompare: (compare: boolean) => ({ compare }),
- setFocusedValue: (focusedValue: string) => ({ focusedValue }),
- }),
- reducers(({ props }) => ({
- state: [props.initialState, { setState: (_, { state }) => state }],
- compare: [props.initiallyCompare, { setCompare: (_, { compare }) => compare }],
- focusedValue: [null as string | null, { setFocusedValue: (_, { focusedValue }) => focusedValue }],
- })),
-])
diff --git a/products/marketing_analytics/frontend/dashboard/tables/webStatsColumns.tsx b/products/marketing_analytics/frontend/dashboard/tables/webStatsColumns.tsx
deleted file mode 100644
index bf36b9f395ce..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/webStatsColumns.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-import { humanFriendlyDuration } from 'lib/utils/durations'
-
-import type { BreakdownTableColumn, ComparedValue } from './breakdownTableColumn'
-import type { WebStatsRow } from './webStatsRows'
-
-/** Divides two compared values, keeping the previous period only when both sides have one. */
-export const ratio = (
- numerator: ComparedValue | undefined,
- denominator: ComparedValue | undefined
-): ComparedValue | null => {
- if (!numerator || !denominator || !denominator[0]) {
- return null
- }
- const previous =
- numerator[1] !== null && denominator[1] !== null && denominator[1] !== 0 ? numerator[1] / denominator[1] : null
- return [numerator[0] / denominator[0], previous]
-}
-
-export const VISITORS_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'visitors',
- title: 'Visitors',
- tooltip: 'People with a pageview or screenview in the selected date range.',
- value: (row) => row.visitors ?? null,
- exportLabel: 'Visitors',
-}
-
-export const VIEWS_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'views',
- title: 'Pageviews',
- shortTitle: 'Views',
- value: (row) => row.views ?? null,
- exportLabel: 'Pageviews',
-}
-
-export const SESSIONS_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'sessions',
- title: 'Sessions',
- value: (row) => row.sessions ?? null,
- exportLabel: 'Sessions',
-}
-
-export const SESSIONS_PER_VISITOR_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'sessions_per_visitor',
- title: 'Sessions per visitor',
- shortTitle: 'Sessions/visitor',
- tooltip: 'Sessions divided by visitors.',
- value: (row) => ratio(row.sessions, row.visitors),
- kind: 'decimal',
- exportLabel: 'Sessions per visitor',
- exportValue: (value) => value.toFixed(2),
-}
-
-export const SESSION_DURATION_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'session_duration',
- title: 'Avg. session duration',
- shortTitle: 'Duration',
- tooltip: 'The average length of sessions that started here.',
- value: (row) => row.session_duration ?? null,
- kind: 'duration',
- exportLabel: 'Avg. session duration',
- exportValue: (value) => humanFriendlyDuration(value) ?? String(value),
-}
-
-export const PAGES_PER_SESSION_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'pages_per_session',
- title: 'Pages per session',
- shortTitle: 'Pages/session',
- tooltip: 'Pageviews divided by sessions.',
- value: (row) => ratio(row.views, row.sessions),
- kind: 'decimal',
- exportLabel: 'Pages per session',
- exportValue: (value) => value.toFixed(2),
-}
-
-export const PAGES_PER_VISITOR_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'pages_per_visitor',
- title: 'Pageviews per visitor',
- shortTitle: 'Views/visitor',
- tooltip: 'Pageviews divided by visitors.',
- value: (row) => ratio(row.views, row.visitors),
- kind: 'decimal',
- exportLabel: 'Pageviews per visitor',
- exportValue: (value) => value.toFixed(2),
-}
-
-export const BOUNCE_RATE_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'bounce_rate',
- title: 'Bounce rate',
- shortTitle: 'Bounce',
- tooltip: 'Sessions that left without a second pageview or any meaningful interaction.',
- value: (row) => row.bounce_rate ?? null,
- kind: 'percentage',
- reverseColors: true,
- exportLabel: 'Bounce rate',
-}
-
-export const CONVERSIONS_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'total_conversions',
- title: 'Conversions',
- value: (row) => row.total_conversions ?? null,
- exportLabel: 'Conversions',
-}
-
-export const CONVERSION_RATE_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'conversion_rate',
- title: 'Conversion rate',
- shortTitle: 'Conv. rate',
- tooltip: 'People who completed the goal, divided by visitors.',
- value: (row) => row.conversion_rate ?? null,
- kind: 'percentage',
- exportLabel: 'Conversion rate',
-}
-
-export const CONVERSION_VALUE_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'conversion_value',
- title: 'Conversion value',
- shortTitle: 'Value',
- tooltip: "The goal's value property, summed over the conversions of sessions that started here.",
- value: (row) => row.conversion_value ?? null,
- kind: 'currency',
- exportLabel: 'Conversion value',
- // A plain number, so a spreadsheet reads the export as money rather than as text.
- exportValue: (value) => value.toFixed(2),
-}
-
-export const AVG_CONVERSION_VALUE_COLUMN: BreakdownTableColumn<WebStatsRow> = {
- key: 'avg_conversion_value',
- title: 'Avg. conversion value',
- shortTitle: 'Avg. value',
- tooltip: "The goal's value property, averaged over the conversions of sessions that started here.",
- value: (row) => row.avg_conversion_value ?? null,
- kind: 'currency',
- exportLabel: 'Avg. conversion value',
- exportValue: (value) => value.toFixed(2),
-}
diff --git a/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.test.ts b/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.test.ts
deleted file mode 100644
index 6e681a734888..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { WebStatsTableQueryResponse } from '~/queries/schema/schema-general'
-
-import { webStatsRows } from './webStatsRows'
-
-describe('webStatsRows', () => {
- it('pairs metrics by column name while preserving zero and missing comparisons', () => {
- const response = {
- columns: [
- 'context.columns.sessions',
- 'context.columns.breakdown_value',
- 'context.columns.visitors',
- 'context.columns.ui_fill_fraction',
- 'context.columns.cross_sell',
- ],
- results: [
- [[0, 10], null, 0, 0.5, 'ignored'],
- [[12, null], 'Email', [7, 0], 1, 'ignored'],
- ],
- } as WebStatsTableQueryResponse
-
- expect(webStatsRows(response)).toEqual([
- { breakdownValue: '', sessions: [0, 10], visitors: [0, null] },
- { breakdownValue: 'Email', sessions: [12, null], visitors: [7, 0] },
- ])
- })
-
- it('leaves unavailable metrics absent instead of reporting zero', () => {
- expect(
- webStatsRows({
- columns: ['breakdown_value', 'visitors', 'sessions'],
- results: [['Direct', [null, 4], null]],
- } as WebStatsTableQueryResponse)
- ).toEqual([{ breakdownValue: 'Direct' }])
- expect(webStatsRows(undefined)).toEqual([])
- })
-})
diff --git a/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.ts b/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.ts
deleted file mode 100644
index d064d89e6be7..000000000000
--- a/products/marketing_analytics/frontend/dashboard/tables/webStatsRows.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { WebStatsTableQueryResponse } from '~/queries/schema/schema-general'
-
-import type { ComparedValue } from './breakdownTableColumn'
-
-export interface WebStatsRow {
- breakdownValue: string
- visitors?: ComparedValue
- sessions?: ComparedValue
- views?: ComparedValue
- bounce_rate?: ComparedValue
- session_duration?: ComparedValue
- total_conversions?: ComparedValue
- unique_conversions?: ComparedValue
- conversion_rate?: ComparedValue
- /** Merged in from the conversion value query, not returned by WebStatsTableQuery. */
- conversion_value?: ComparedValue
- avg_conversion_value?: ComparedValue
-}
-
-const COLUMN_PREFIX = 'context.columns.'
-
-/** Presentation columns the backend appends for the query table's own chrome. */
-const IGNORED_COLUMNS = new Set(['ui_fill_fraction', 'cross_sell'])
-
-const toCompared = (value: unknown): ComparedValue | undefined => {
- if (Array.isArray(value)) {
- const [current, previous] = value
- return typeof current === 'number' ? [current, typeof previous === 'number' ? previous : null] : undefined
- }
- return typeof value === 'number' ? [value, null] : undefined
-}
-
-/** Zips the response's parallel columns and rows into one object per breakdown value. */
-export function webStatsRows(response: WebStatsTableQueryResponse | undefined): WebStatsRow[] {
- const columns = (response?.columns ?? []) as string[]
- const results = (response?.results ?? []) as unknown[][]
-
- return results.map((row) => {
- const parsed: WebStatsRow = { breakdownValue: '' }
- columns.forEach((column, index) => {
- const name = column.startsWith(COLUMN_PREFIX) ? column.slice(COLUMN_PREFIX.length) : column
- if (IGNORED_COLUMNS.has(name)) {
- return
- }
- if (name === 'breakdown_value') {
- parsed.breakdownValue = String(row[index] ?? '')
- return
- }
- const compared = toCompared(row[index])
- if (compared) {
- ;(parsed as unknown as Record<string, ComparedValue>)[name] = compared
- }
- })
- return parsed
- })
-}
diff --git a/products/marketing_analytics/frontend/dashboard/trafficChartSeries.test.ts b/products/marketing_analytics/frontend/dashboard/trafficChartSeries.test.ts
deleted file mode 100644
index 913549c58974..000000000000
--- a/products/marketing_analytics/frontend/dashboard/trafficChartSeries.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { NodeKind } from '~/queries/schema/schema-general'
-import { BaseMathType } from '~/types'
-
-import { trafficChartSeries } from './trafficChartSeries'
-
-describe('trafficChartSeries', () => {
- const eventGoal = { customEventName: 'purchase' }
- const actionGoal = { actionId: 7 }
-
- it.each([
- ['visitors', null, { kind: NodeKind.EventsNode, event: null, math: BaseMathType.UniqueUsers }],
- ['sessions', eventGoal, { kind: NodeKind.EventsNode, event: null, math: BaseMathType.UniqueSessions }],
- ['pageviews', eventGoal, { kind: NodeKind.EventsNode, event: null, math: BaseMathType.TotalCount }],
- ['new_customers', eventGoal, { kind: NodeKind.EventsNode, event: 'purchase', math: BaseMathType.UniqueUsers }],
- ['new_customers', actionGoal, { kind: NodeKind.ActionsNode, id: 7, math: BaseMathType.UniqueUsers }],
- ['new_customers', null, { kind: NodeKind.EventsNode, event: null, math: BaseMathType.UniqueUsers }],
- ] as const)('%s with goal %j', (metric, goal, expected) => {
- expect(trafficChartSeries(metric, goal)).toMatchObject(expected)
- })
-})
diff --git a/products/marketing_analytics/frontend/dashboard/trafficChartSeries.ts b/products/marketing_analytics/frontend/dashboard/trafficChartSeries.ts
deleted file mode 100644
index d7c01315bde3..000000000000
--- a/products/marketing_analytics/frontend/dashboard/trafficChartSeries.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { ActionsNode, EventsNode, NodeKind, WebAnalyticsConversionGoal } from '~/queries/schema/schema-general'
-import { BaseMathType, PropertyFilterType, PropertyOperator } from '~/types'
-
-export const TRAFFIC_CHART_METRICS = [
- { value: 'visitors', label: 'Visitors' },
- { value: 'sessions', label: 'Sessions' },
- { value: 'pageviews', label: 'Page views' },
- { value: 'new_customers', label: 'New customers' },
-] as const
-
-export type TrafficChartMetric = (typeof TRAFFIC_CHART_METRICS)[number]['value']
-
-const pageviewOrScreen: EventsNode = {
- kind: NodeKind.EventsNode,
- event: null,
- properties: [
- {
- key: 'event',
- type: PropertyFilterType.EventMetadata,
- operator: PropertyOperator.Exact,
- value: ['$pageview', '$screen'],
- },
- ],
-}
-
-export function trafficChartSeries(
- metric: TrafficChartMetric,
- customerGoal: WebAnalyticsConversionGoal | null
-): EventsNode | ActionsNode {
- if (metric === 'sessions') {
- return { ...pageviewOrScreen, math: BaseMathType.UniqueSessions, custom_name: 'Sessions' }
- }
- if (metric === 'pageviews') {
- return { ...pageviewOrScreen, math: BaseMathType.TotalCount, custom_name: 'Page views' }
- }
- if (metric === 'new_customers' && customerGoal) {
- const shared = {
- properties: customerGoal.properties,
- math: BaseMathType.UniqueUsers,
- custom_name: 'New customers',
- }
- return 'actionId' in customerGoal
- ? { kind: NodeKind.ActionsNode, id: customerGoal.actionId, ...shared }
- : { kind: NodeKind.EventsNode, event: customerGoal.customEventName, ...shared }
- }
- return { ...pageviewOrScreen, math: BaseMathType.UniqueUsers, custom_name: 'Visitors' }
-}
diff --git a/products/marketing_analytics/frontend/emptyState/marketingAnalyticsEmptyState.tsx b/products/marketing_analytics/frontend/emptyState/marketingAnalyticsEmptyState.tsx
index 38a1153e707e..502f272e2c39 100644
--- a/products/marketing_analytics/frontend/emptyState/marketingAnalyticsEmptyState.tsx
+++ b/products/marketing_analytics/frontend/emptyState/marketingAnalyticsEmptyState.tsx
@@ -17,7 +17,6 @@ export const marketingAnalyticsEmptyState: SceneProductEmptyState = {
statusLogic: marketingAnalyticsSetupLogic,
// The whole product is behind this flag; its in-scene banner handles the flag-off case.
featureFlag: FEATURE_FLAGS.WEB_ANALYTICS_MARKETING,
- bypassFeatureFlag: FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD,
config: {
productKey: ProductKey.MARKETING_ANALYTICS,
productName: 'Marketing analytics',
diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx
index dbeb825ea81c..e090adb22488 100644
--- a/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx
+++ b/products/marketing_analytics/frontend/search/SearchPerformanceTab.stories.tsx
@@ -703,28 +703,10 @@ export const LegacyScene: Story = {
featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING, FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS],
},
}
-export const NewDashboardScene: Story = {
- ...LegacyScene,
- parameters: {
- ...LegacyScene.parameters,
- featureFlags: [
- FEATURE_FLAGS.WEB_ANALYTICS_MARKETING,
- FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD,
- FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS,
- ],
- },
-}
export const FlagOff: Story = {
...LegacyScene,
parameters: { ...LegacyScene.parameters, featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING] },
}
-export const NewDashboardFlagOff: Story = {
- ...LegacyScene,
- parameters: {
- ...LegacyScene.parameters,
- featureFlags: [FEATURE_FLAGS.WEB_ANALYTICS_MARKETING, FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
- },
-}
export const PositionMetrics: Story = {
...Comparison,
diff --git a/products/marketing_analytics/frontend/setup/DashboardSetupPrompt.stories.tsx b/products/marketing_analytics/frontend/setup/DashboardSetupPrompt.stories.tsx
index 5b2b667b6de8..ac3ba6fb4546 100644
--- a/products/marketing_analytics/frontend/setup/DashboardSetupPrompt.stories.tsx
+++ b/products/marketing_analytics/frontend/setup/DashboardSetupPrompt.stories.tsx
@@ -43,7 +43,6 @@ export const WithoutSetup: Story = {
parameters: {
featureFlags: {
[FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: false,
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: false,
},
},
}
diff --git a/products/marketing_analytics/frontend/setup/SetupConversionFlag.test.tsx b/products/marketing_analytics/frontend/setup/SetupConversionFlag.test.tsx
index 56da043d4883..977204cbc2fe 100644
--- a/products/marketing_analytics/frontend/setup/SetupConversionFlag.test.tsx
+++ b/products/marketing_analytics/frontend/setup/SetupConversionFlag.test.tsx
@@ -69,16 +69,13 @@ describe('conversion setup feature flag', () => {
})
it.each([
- [false, false, false, false],
- [false, false, true, false],
- [true, false, false, false],
- [true, false, true, true],
- [false, true, false, false],
- [false, true, true, true],
- ])('gates dashboard recommendations with setup=%s, new dashboard=%s, AI=%s', (setup, dashboard, ai, visible) => {
+ [false, false, false],
+ [false, true, false],
+ [true, false, false],
+ [true, true, true],
+ ])('gates dashboard recommendations with setup=%s, AI=%s', (setup, ai, visible) => {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: setup,
- [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: dashboard,
[FEATURE_FLAGS.MARKETING_ANALYTICS_CONVERSION_SETUP_AI]: ai,
[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING]: true,
})
diff --git a/products/web_analytics/frontend/marketing/marketingCrossSellUtils.ts b/products/web_analytics/frontend/marketing/marketingCrossSellUtils.ts
index 0679a0d650cc..0b89c1c21649 100644
--- a/products/web_analytics/frontend/marketing/marketingCrossSellUtils.ts
+++ b/products/web_analytics/frontend/marketing/marketingCrossSellUtils.ts
@@ -55,10 +55,7 @@ interface MarketingAnalyticsDestinationParams {
}
export function isMarketingSetupEnabled(featureFlags: FeatureFlagsSet): boolean {
- return !!(
- featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP] ||
- featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]
- )
+ return !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]
}
export function isMarketingCrossSellTestArm(featureFlags: FeatureFlagsSet): boolean {
diff --git a/products/web_analytics/frontend/pageReports/pageDirectoryLogic.ts b/products/web_analytics/frontend/pageReports/pageDirectoryLogic.ts
index 9c43d0d161e8..d8705b1357ba 100644
--- a/products/web_analytics/frontend/pageReports/pageDirectoryLogic.ts
+++ b/products/web_analytics/frontend/pageReports/pageDirectoryLogic.ts
@@ -205,7 +205,7 @@ export interface pageDirectoryLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface pageDirectoryLogicMeta {
- key: 'page-visibility' | 'web-analytics'
+ key: 'web-analytics'
__keaTypeGenInternalSelectorTypes: {
visibleMetrics: (conversionGoal: WebAnalyticsConversionGoal | null) => WebPageDirectoryMetric[]
baseQuery: (