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.

feat(marketing): show conversion recommendations in setup (#119659)

Javier Bahamondes9f80fb58bfcb
diff --git a/docs/internal/marketing-conversion-setup-ai-plan.md b/docs/internal/marketing-conversion-setup-ai-plan.md
index fd2e3d5ae17f..c54aa45e6ad7 100644
--- a/docs/internal/marketing-conversion-setup-ai-plan.md
+++ b/docs/internal/marketing-conversion-setup-ai-plan.md
@@ -1,27 +1,63 @@
# Conversion recommendations in Marketing analytics
Conversion recommendations scan a project's custom events and existing actions and suggest up to three business outcomes to measure.
-The API and MCP tools expose saved recommendations independently of the frontend.
-The `marketing-analytics-conversion-setup-ai` feature flag gates the API and MCP tools.
+They appear in the existing Marketing analytics Setup, under Suggestions and Conversion goals.
+With source onboarding enabled, the dashboard also shows the same conversion recommendations beside source setup.
+Dashboard suggestions have a dismiss button in their header when the Setup tab is available.
+Source onboarding, source loading failures, and connection diagnostics stay visible even when source suggestions have been dismissed.
+Dismiss hides the whole block for that user and project in the current browser and opens a dialog linking to the relevant Setup section.
+Setup keeps the sources and conversion recommendations available, with **Show suggestions on dashboard** to restore a hidden block.
+The `marketing-analytics-conversion-setup-ai` feature flag gates the UI, API, and MCP tools.
The existing Marketing analytics setup flag must also be enabled.
## Analysis lifecycle
-A start request begins the first analysis after checking permission to generate.
-Analyses cover 30 days until one completes successfully; later analyses cover 14 days and require an explicit refresh request.
-Runs and completed results are stored per project, so reading saved state does not start another analysis.
-After a successful scan, a project waits one hour from completion before starting another scan.
-Failed scans can be retried immediately, and active scans are reused.
-The backend enforces this interval for UI and MCP requests; it never starts a scheduled rescan.
+The first visit to Setup or the source onboarding dashboard starts an analysis once, after loading the saved state and checking permission to generate.
+Analyses cover 30 days until one completes successfully; later analyses cover 14 days and require an explicit **Scan again** action.
+Runs and completed results are stored per project, so returning to Setup does not start another analysis.
+After a successful scan, a project waits one hour from its completion before starting another scan.
+Failed scans can be retried immediately with **Scan again**, including after an interrupted run expires.
+An active scan is reused instead of starting another in parallel.
+The backend enforces this interval for UI and MCP requests and returns the existing run during the cooldown.
+The UI updates the countdown when it receives scan status, so a newly completed scan shows 60 minutes.
+It enables **Scan again** when the hour has passed and never starts a scheduled rescan.
An update retains the last completed recommendations while it runs.
Interrupted runs become failed after five minutes and require an explicit retry.
-Each recommendation includes its source event or action, an explanation, a proposed intent (conversion, customer, or revenue), and up to two actionable checks specific to the proposed goal.
+Recommendations appear as compact rows in a single panel.
+Each row shows its source event or action, proposed intent (conversion, customer, or revenue), and a **Review suggestion** action.
+Expanding the row shows the explanation, amount property, and up to two actionable checks specific to the proposed goal.
Count-only suggestions do not ask about revenue units, currency, or hypothetical revenue upgrades.
+Each row has **Dismiss**. Dismissed source references and names persist per user and project in the current browser and stay hidden across scans.
+**Dismissed suggestions** lists those sources and provides **Restore**.
+Restoring makes a source eligible to appear again; it appears immediately when the latest scan still recommends it and no goal for that event or action is configured.
+Earlier suggestions remain listed after a scan, without treating their old evidence as current results.
+**Scan details** contains the analysis period and discovery limits.
+**Scan again** scans recent events and actions and generates updated suggestions.
A revenue suggestion must reference a numeric property observed in the source metadata.
A missing amount mapping downgrades the suggestion to a conversion and adds a question about the missing mapping.
Numeric metadata alone does not prove that a value is money; the user still needs to confirm units, currency, payment status, and duplicate handling.
-Recommendations do not create or modify goals, and do not depend on conversion previews or the new dashboard.
+The **Configure goals** button opens the existing goal editor, scrolls it into view, and focuses the name field, including when the Conversion goals section is already open.
+It preserves any draft already in the editor.
+Recommendations do not automatically create or modify goals, and do not depend on conversion previews or the new dashboard.
+In Setup, **Review suggestion** opens the existing goal editor with the proposed name and event or action.
+Revenue suggestions select the sum of the proposed amount property; customer suggestions select the customer flag.
+Business questions remain visible for review, and nothing is saved until the user clicks **Add conversion goal**.
+The form blocks duplicate submissions and keeps the draft after a failed save so the user can retry.
+Recommendations for an event or action with a saved goal are hidden from the pending list, even if the user changed the name, measurement, filters, or revenue and customer flags before saving.
+Opening a stale suggestion reviews a goal for that source, preferring an exact measurement match when there are several.
+Manual goals still use full measurement equivalence to prevent duplicate saves while allowing distinct filtered goals for the same source.
+The list updates after a successful save, without another AI analysis.
+If no suggestions remain to review, the recommendation block disappears from the dashboard after a successful scan, including when all are configured or dismissed.
+Setup shows a compact confirmation and keeps **Scan again** available after the cooldown; saved goals remain in the configured goals list.
+A failed refresh explains that the latest attempt failed while the saved goals and last successful results remain available.
+An active scan or a failed request remains visible on the dashboard so its status and retry action are available.
+Deleting the last goal for a source makes its suggestion available again.
+The form also checks for an equivalent saved goal before submitting, including when settings changed after the draft opened.
+The setup plan no longer generates rules that suggest creating conversion goals or enabling Revenue or Customer.
+The backend removes those suggestions for both the UI and the setup plan's MCP tool, and stops running the event-ranking scan that supplied them.
+Misconfigured goal warnings and integration diagnostics remain available.
+Without AI recommendations enabled, users configure goals manually; capability readiness still explains missing revenue or customer definitions.
## Discovery and access
@@ -56,23 +92,16 @@ Starting a run persists an analysis record and enqueues a task after the transac
Concurrent starts reuse an active run, and repeated initial requests reuse the existing run.
The start endpoint is limited to five requests per hour per user.
-The setup plan no longer generates rules that suggest creating conversion goals or enabling Revenue or Customer.
-Misconfigured goal warnings and integration diagnostics remain available.
-Without AI recommendations enabled, users configure goals manually; capability readiness still explains missing revenue or customer definitions.
-
-## Frontend follow-up
-
-The Setup integration ships separately and consumes these endpoints.
-It starts the first analysis once, shows saved results, and offers explicit updates and navigation to the existing goal editor.
-The backend and MCP tools do not depend on that integration.
-
## Verification
The static IDOR coverage check verifies that recommendation runs appear in the generated environment-scoped model list.
After changing model scope, regenerate that list with `python .github/scripts/check-idor-model-coverage.py --regenerate-environment-models`, then run the same command without the regeneration flag.
Backend tests cover run reuse, refresh windows, permissions, consent, source filtering, output validation, and goal preservation.
-MCP tests cover tool schemas, feature flag gating, and access from read-only sessions.
+Frontend tests cover the initial run, manual updates, polling, project isolation, and the setup feature flag.
+Draft tests cover event and action mapping, explicit saves, duplicate-click prevention, and retries after failed saves.
+They also cover reviewing existing goals and avoiding duplicate saves from stale drafts.
+Storybook covers analysis in progress, saved results, updates, failure, empty results, missing consent, and narrow layouts.
The standalone recommendation evaluation uses eleven synthetic business cases and calls the same generator, gateway client, tool schema, and parser as production.
It does not exercise discovery queries, permissions, persistence, or Celery; those have separate tests.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ee855b1bcc91..cc118ed2c9f7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -12930,6 +12930,14 @@ snapshots:
hash: v1.k794b7964.4f22887d5bc31ce73966a3de58159aeeb35065bf97c2c9675f92bbd6876a6e03.7MLydZcCIlpjYZm38va65NDr9nQSJQkOFkZH0tgtEoM
scenes-app-marketing-analytics-cell-actions--source-cell-action-unmapped--light:
hash: v1.k794b7964.8e246cb2fa6d85a00b96808e3c85666499939eec7ee7b69cd13c6caa162b5b1e.Q6cxhXIN1jgte2LYSQZIu6M_SNQW7EMcDnrlf6B8roM
+ scenes-app-marketing-analytics-conversion-recommendation-card--action--dark:
+ hash: v1.k794b7964.a38595175b481249b162f0271fb7adaac5ee0a9fe2b6f06fe706d7fb90293240.eBRubPecDykEirdOWVQhIhd0mUBPx-QR0ADPYv45Utk
+ scenes-app-marketing-analytics-conversion-recommendation-card--action--light:
+ hash: v1.k794b7964.07d3e0eb1d01c1c3b66d1d335e6ab262e5b9be1977b761273b580ffb90b09896.gqL-G8T3OX3yWjSoXYGFcLhFKlzNWyi7liAK-91NxP8
+ scenes-app-marketing-analytics-conversion-recommendation-card--narrow--dark:
+ 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:
@@ -12970,6 +12978,22 @@ snapshots:
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:
+ hash: v1.k794b7964.1ac45f5ed734c96fc0f8f5c2ac2366aa57d9067e60069f2fee2476e59074542e.7AzyVn5eyYZsmYnFDwJG-R0J310iIa_F5ZuT72eB1eg
+ scenes-app-marketing-analytics-dismissible-setup-prompts--scanning--dark:
+ hash: v1.k794b7964.5939fd04127f641946e8408b4d5519ad90f136413d2d244585f6c9758d522411.kiyWr23DcnQ2VxamhTbtweez75hQ5B9PScAtQUTmtm8
+ scenes-app-marketing-analytics-dismissible-setup-prompts--scanning--light:
+ hash: v1.k794b7964.49a1a3605bb433648ef967c3abfe2b87521f88bd55796d41021354bfacf4843d.5khYCJNN4HPivdC1UcrZ5qQKWct9KMrcoK9Di1ZPzfQ
+ scenes-app-marketing-analytics-dismissible-setup-prompts--suggestions--dark:
+ hash: v1.k794b7964.ab682dd57b3f2891806ca9007823e3dac56e7bb86fe23c7cc4e4fea369091617.IGw21D1KQiIZLZNYYfG6POjgyfsiC5zQbxP3F3bamRI
+ scenes-app-marketing-analytics-dismissible-setup-prompts--suggestions--light:
+ hash: v1.k794b7964.4854e1f47b3d68d6482d77c54b5fcabeba09d1eb5f57a7408f2908552c3fdaf1._Mm44diMIdnRep3pHrnksp8rmboiducfGAMf9c4rs90
+ scenes-app-marketing-analytics-dismissible-setup-prompts--without-setup--dark:
+ hash: v1.k794b7964.b73cdfebd90f08032a9bae75b882177b0820ef6b6b5fca62e4a9544c8bb71a44.mFeqRlSaFAONCXvFYM3lsPacPRQ5Wkypera3O6w4hbs
+ scenes-app-marketing-analytics-dismissible-setup-prompts--without-setup--light:
+ hash: v1.k794b7964.057e79150a4b1c174a9c18d862c57f376c602ea6514dc6b61a1ed2878e480ab5.gqZ8hB3FeD2bKbPduK0mfzBhgZzX8-o1TD17iWdG_rA
scenes-app-marketing-analytics-freshness--behind--dark:
hash: v1.k794b7964.24e00c5991fdda65218358c71de110f4e94c84f483b6b550225da1bf405f1511.76cXtLdLAt40yxKRi1qT71n8DdikUm3oiMTL8IWwDwI
scenes-app-marketing-analytics-freshness--behind--light:
@@ -12982,6 +13006,38 @@ snapshots:
hash: v1.k794b7964.f9b440217e994a034cd41b83c7ce116d3f80c8ffe0a713e478f571d6d3a17523.nVNlflYTiAcXYQ-MYXqFWg3XELCQxOiOIbqp-I6G8pE
scenes-app-marketing-analytics-metric-cells--clickable-and-static--light:
hash: v1.k794b7964.a35385e9aafb9d78b1b0ef339b1e0979599718ff4678ebab9301a12e68851ac5.ZT4_n2eit5rOyZqjI8giGDt-iTrI3v2ZJSZ8KKQe6A8
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--consent-required--dark:
+ hash: v1.k794b7964.6b518ef694d9645756f342b734cb8071e6af9fe37119cb2aae995e0e2a5b7bf6.sCvbdJpyNHb_e-zZjs5UpzayGBCoE406ha2RYy-VIw0
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--consent-required--light:
+ hash: v1.k794b7964.c0520cec291ef5d2bedb6b1fc037ef2556fd7c60b773ad6474fcc555d45aaadd.VT4nrDPOI4bVB81nIz_NIL02Ph5_KihjEIBN-SCt9qY
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--dashboard--dark:
+ hash: v1.k794b7964.5b39c51e1f4a362c66fd95c54e0080de3d5d73661ec8a6ccf1c811d01eac691d.NSgquV97pS5ztLddXy0VPZnRrCMudFOp3yf-g87W16k
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--dashboard--light:
+ hash: v1.k794b7964.6b550a18f120f1b9b7c24f9a33fbebc44a28bb0b25ab9ee72fa24f89d3ed5c2f.aZyyFiZLlEsa2yUXP4hQfqn7_TC1fnQrmPOP_5NT-jw
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--empty--dark:
+ hash: v1.k794b7964.7fff008b78d2ee30f4703903f0c23561019b79a8f91a720b6a08ee2ef9034689.O6pQ1CrDM52wg-8vpI8KN0OK5r1Askd1YoFRtWVaGkw
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--empty--light:
+ hash: v1.k794b7964.0e04770eec8a140b4c939880a9837751c5f2c8b330e78e5588f2be2c9fe4291b.ruvCFoJ5RFU4Qitin9zcqV8ePGlXRSyh__QdTEr7NEg
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--failed--dark:
+ hash: v1.k794b7964.1523f8a4df752c7fc09a321c67897b377f557aa0178a14cc0c7d038aa98b2040.orfLH8NZFqlZa2NQcSZwf8va2jhCXE2u4P9l-GVhwXA
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--failed--light:
+ hash: v1.k794b7964.e5ff92777d9fbfac1b292f12d369b0173fe20d67eb1dbc595fc9b1e7fdabf70b.1prLuHo1zzgpfMvoSBwggHeDhT-LFOxC3a-B1dcMe4M
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--first-analysis--dark:
+ hash: v1.k794b7964.58bb3f760e45bec5be78fccf0336b28f39f5f4cea4f62b96fae5b8dcd1151169.jdPj5I3awgP3Dr9oLGvDSAb66op7mm36Xl8ta3hzzrU
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--first-analysis--light:
+ hash: v1.k794b7964.a097865357111cf596ee9564f88ced4a2cf0bc1ca33d2b35e08a66c8e8582185.QbuSlWA77nM2N5TAlAqFJQq0AyAGqLjs2TFt8rOOL34
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--narrow--dark:
+ hash: v1.k794b7964.7e16b61e687b6ca36f64a169eda6eb258f2773f7d3059c97830809ebdfb2b69a.sUlD3Bm8OH4AVTMZqZj5gihDxKGWBa7Wujer26xIKW0
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--narrow--light:
+ hash: v1.k794b7964.357332cfa8b8bbf3e7e8aaabd4389fb2b42588045a907d4d211e5334216d6b84.E12uqts1F14Dz9UjLiQACl9gyPyk5G0darE0WBFDTNw
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--ready--dark:
+ hash: v1.k794b7964.16b416598306829c1df8e641649690dacef947a57d37fee55737824996f207c7.hvIOEGurQk0olK7Br94XJx6vW9bz1ah1n9c19_JUZgE
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--ready--light:
+ hash: v1.k794b7964.fa654e449cd262f49cb3352ba45d3969f449b83da61527015db84452a96235ee.vzoFFzLSJgmVosT_JvcJUR_6s2QzJGbNUVh2Ze2ZJ_Y
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--updating--dark:
+ hash: v1.k794b7964.d0baebcb76e75b79c530d73650dd5208357a9224f87a4109366f080451653707.q9XYNba8hsN8JEhhiUrEvUpZyj7Ou_loKi1b3cSWq8U
+ scenes-app-marketing-analytics-persisted-conversion-recommendations--updating--light:
+ hash: v1.k794b7964.852abfd71814efc870cb2178a7acf97833babbd13866c0196d6976f8351999fb._dZPb-BB_XLmD7aRG3nBiePMXUZOzSzgVTK6xgccsF4
scenes-app-marketing-analytics-search-performance--awaiting-sync--dark:
hash: v1.k794b7964.a68e5069915d1416731bb56e1bd061b81020839cf35d98cdc01552a0c7fe0602.s7rS2bvBpMV8lvMnKn2C5VihtDFuU_Bq0x7vnTZ7jK4
scenes-app-marketing-analytics-search-performance--awaiting-sync--light:
@@ -13137,27 +13193,27 @@ snapshots:
scenes-app-marketing-analytics-source-onboarding--ad-performance-with-detected-sources--dark:
hash: v1.k794b7964.86e93f2243024c677ca7b0a2ba4e18e8bb164e1f172ecbd43f92f2a5359f0b9c.j492cCtgKRxf5KtvFw8hCZ_PSqqJeS_uLhwoq91xpSc
scenes-app-marketing-analytics-source-onboarding--ad-performance-with-detected-sources--light:
- hash: v1.k794b7964.c9e5175bd6ffae220128aa2e89089b002ed26e96577c745f6da1ce7f49664dbe.811Yf3YUcP2_Ykyxcp00tIDu7_MJoTZa_1HlzSfSZYM
+ hash: v1.k794b7964.7bf37574af4d6bca604ac213fdf33fda29fe29eb77141f2ffa8289103da12146.JBC8ovAgqywVc3O6P8YXOTM266u8aFp1XZDF4cTEDP0
scenes-app-marketing-analytics-source-onboarding--ad-performance-without-sources--dark:
- hash: v1.k794b7964.7e6800261efded0422685cf12692290fb8176c8a22de141b87d08a545e49c87a.pYa-gUWLGp3RzPiwjRwIevsSO8RvA7cRGc0-QbUVpFg
+ hash: v1.k794b7964.2f61731446eee725ffa421fddaec608f84963df2bae4f13989432968e65e1365.soADbqhjiLQeiDKAb4aoymNoRgIS8uzyN-3JPJvJAp8
scenes-app-marketing-analytics-source-onboarding--ad-performance-without-sources--light:
- hash: v1.k794b7964.2178b70edacffd0e8d886178c4a05243b8a16f171f8dcee471c181a2deaf7dc3.ZZc5b7Bo-2OKKSymOkCUK7kB1Z-jF4ytZXHVIazL3V4
+ hash: v1.k794b7964.ad062b7ed22bf491b5f7424f408b3e87826051a72950ea7b6df119ed373f74b7.-aUA6190l3xNUImj9eV8oyilLP0v4AKaPeF1p7Cu_NE
scenes-app-marketing-analytics-source-onboarding--dashboard-checking-connections-with-search--dark:
hash: v1.k794b7964.09fdd037ef04723ecc5b9fd749bcf29183c9b17ec9412e7f07829f471aef7c9f.NyHOQHB1risiaTQjKbpH5ZXh1HA8n3EumtgT6AolY2w
scenes-app-marketing-analytics-source-onboarding--dashboard-checking-connections-with-search--light:
hash: v1.k794b7964.39bf27f0ca6b50a6d7e28c2946290bb272f2d1b7820f45ca078d6a7595000214.bgxbrzwC6IVQ8hh5vmd7BeK-4BVkinpxZtSF2ptOv34
scenes-app-marketing-analytics-source-onboarding--dashboard-no-detections-with-search--dark:
- hash: v1.k794b7964.aaee0e2a04c3b6ec25d860b9b2a93b0a39fbc00d25427fa73335a0a74a39d26e.A7dtpsC32ZCLDIEcVhLjbrNJ-UeNqbiIu2xrqLWSV-8
+ hash: v1.k794b7964.6ef4c79a25add61c59db8dda3c96e8f908a0d69957df14dc48db4e3cb1b69656.f_uoobd2f3DAIQ1fbUaK8GK5PA1G2VvbOFwLzyVL2WU
scenes-app-marketing-analytics-source-onboarding--dashboard-no-detections-with-search--light:
- hash: v1.k794b7964.d777a83fff6631eda866258bd9f2b5ae6ef0d38e3fa92a1c19e017aae3585447.MT5Q8u5uzYxydgJ1W8s-9qCxr2Zc6zQZqEdUlbBAuu4
+ hash: v1.k794b7964.b173399f6e4b07f62c43185c690f0db6c2e77f66a1aa419a606141401252a9cb.mVpWgBiCGlrumkooogpH3mjYlsmyWs29TTvFic7MRBU
scenes-app-marketing-analytics-source-onboarding--dashboard-scan-failed-with-search--dark:
- hash: v1.k794b7964.c680af59db8f9fced6feaba1b1a3335c1c84613ab1431fea7b5dd5e6e6520c78.OaEay9P78ZBokGN8yhrqH17NCE17sG5xbaqWDnueJlg
+ hash: v1.k794b7964.36e73a10dc47fe907dff8de40bb9b33659b847ef4d77699f034ccf6b7e5ff633.SNxpVaP9qQR2qFgCifyM3B0vr7vCNSkSPNl260Fi078
scenes-app-marketing-analytics-source-onboarding--dashboard-scan-failed-with-search--light:
- hash: v1.k794b7964.8c9a2af564cad66fffd9c3899b0688e108b59478cea42274b1a804e0239cd03c.Amv9rM1pplsAOGtVkxqykLnb-GqaxNicqBkdwgLN5eY
+ hash: v1.k794b7964.ae1ab860d261fe021d876f2357b0094b12fb5a5d1aa14b9b73344671af094ae6.YJCpS5jkrvMyK4RhENDiXfgHcUnBF9mT0RsfS4nre_Q
scenes-app-marketing-analytics-source-onboarding--dashboard-scanning-with-search--dark:
- hash: v1.k794b7964.7fce2646f4f52fe06e3852c720b4d1c6505187a1a978b3835bbc977af4cd611c.1TU1RxzyXSKn9Otzwal9kPHU5PDP-0SMPU_CLlwUDI0
+ hash: v1.k794b7964.32c4a32168dac867098aa255283026f4c67d15203a18db35627b3ee6950615ca.xy23Hj8MC1Umx80h6FVp_9hKO-cBzt0MJ4KCeNkFD3w
scenes-app-marketing-analytics-source-onboarding--dashboard-scanning-with-search--light:
- hash: v1.k794b7964.d2adcc0da678fb56ecb53bc56e5c6f73fdfcef961359f857851e99ea1caa56b0.xnNciZPG-itXRQkC17sPFe6iPsCecMsAaiy0PPgF9Vc
+ hash: v1.k794b7964.82af8d7fc971f03bf36739952b9f436cdae9e03b052fba2f3c83af1428120b76.m-VTiI3gRppO6oQNhsW4BkfvmkEJaZcqKiBVq_vSWzA
scenes-app-marketing-analytics-source-onboarding--dashboard-scanning-with-search-console--dark:
hash: v1.k794b7964.f6c3227540c1daf5266cc94e80d1626e8a192906fb1f688a18c7457de0b9575e.htWZS2VejTaqYTr-fZioOWMdpole1T-s1QlBB09ls9U
scenes-app-marketing-analytics-source-onboarding--dashboard-scanning-with-search-console--light:
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index 965b9b2ddb03..a4190a8ea0ce 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -25,6 +25,8 @@ Actions for which we don't want to show error alerts,
mostly to avoid user confusion.
*/
const ERROR_FILTER_ALLOW_LIST = [
+ 'loadRecommendations',
+ 'startAnalysis',
'loadFacetValues', // Logs and tracing facets show an inline error icon on the failed facet.
'fetchLogs', // Logs and tracing show a warning icon on the pane whose query failed.
'fetchSpans',
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 52813b7e61a1..682680ec96e7 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -391,6 +391,7 @@ export const FEATURE_FLAGS = {
MARKETING_ANALYTICS_APPLE_ADS: 'marketing-analytics-apple-ads', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_ATTRIBUTION: 'marketing-analytics-attribution', // owner: @jabahamondes #team-web-analytics — gates the legacy Attribution explorer tab; the new dashboard ignores it
MARKETING_ANALYTICS_CONVERSION_RECORDINGS: 'marketing-analytics-conversion-recordings', // owner: @jabahamondes #team-web-analytics
+ MARKETING_ANALYTICS_CONVERSION_SETUP_AI: 'marketing-analytics-conversion-setup-ai', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_COSTS_PRECOMPUTATION: 'marketing-analytics-costs-precomputation', // owner: @jabahamondes #team-web-analytics — gates reading the native cost precompute table
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)
diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
index e30427b588ae..07cd57f84faf 100644
--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
@@ -39,6 +39,8 @@ import { SearchConsoleSource } from 'products/marketing_analytics/frontend/dashb
import { SourceSetupPanel } from 'products/marketing_analytics/frontend/dashboard/SourceSetupPanel'
import { marketingAnalyticsEmptyState } from 'products/marketing_analytics/frontend/emptyState/marketingAnalyticsEmptyState'
import { SearchPerformanceTab } from 'products/marketing_analytics/frontend/search/SearchPerformanceTab'
+import { DashboardConversionRecommendations } from 'products/marketing_analytics/frontend/setup/DashboardConversionRecommendations'
+import { DashboardSetupPrompt } from 'products/marketing_analytics/frontend/setup/DashboardSetupPrompt'
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
import { LegacyOAuthReconnectBanner } from '../web-analytics/tabs/marketing-analytics/frontend/components/LegacyOAuthReconnectBanner'
@@ -188,6 +190,7 @@ const SourceMarketingAnalyticsDashboard = (): JSX.Element => {
</div>
)}
<SearchConsoleSource />
+ <DashboardConversionRecommendations />
</>
)
}
@@ -196,6 +199,7 @@ const SourceMarketingAnalyticsDashboard = (): JSX.Element => {
return (
<>
<Onboarding completeOnboarding={completeOnboarding} />
+ <DashboardConversionRecommendations />
</>
)
}
@@ -222,10 +226,16 @@ const SourceMarketingAnalyticsDashboard = (): JSX.Element => {
>
Ad performance
</h2>
- <DetectedSources compact={hasSearchConsole && !hasSyncedMarketingSources} />
- {!dataWarehouseSources?.results.some((source) =>
- ['GoogleAds', 'BingAds', 'GoogleSearchConsole'].includes(source.source_type)
- ) && <SearchConsoleSource />}
+ <DetectedSources compact={hasSearchConsole && !hasSyncedMarketingSources} dismissible />
+ {!!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ORGANIC_KEYWORDS] &&
+ !dataWarehouseSources?.results.some((source) =>
+ ['GoogleAds', 'BingAds', 'GoogleSearchConsole'].includes(source.source_type)
+ ) && (
+ <DashboardSetupPrompt kind="sources">
+ {(dismissButton) => <SearchConsoleSource headerAction={dismissButton} />}
+ </DashboardSetupPrompt>
+ )}
+ <DashboardConversionRecommendations />
{hasSources && hasSyncedMarketingSources && (
<div className="mt-4 grid grid-cols-1 md:grid-cols-2 2xl:grid-cols-3 gap-x-4 gap-y-12">
{marketingTiles?.map((tile, i) => (
@@ -382,7 +392,8 @@ const LegacyMarketingAnalyticsDashboard = (): JSX.Element => {
const MarketingAnalyticsContent = (): JSX.Element => {
const { featureFlags } = useValues(featureFlagLogic)
- const { activeTab, hasSyncedMarketingSources, dataWarehouseSources } = useValues(marketingAnalyticsLogic)
+ const { activeTab, hasSyncedMarketingSources, dataWarehouseSources, setupEnabled } =
+ useValues(marketingAnalyticsLogic)
const { setActiveTab, setSetupSection } = useActions(marketingAnalyticsLogic)
const { integrationSettingsModal } = useValues(marketingAnalyticsSettingsLogic)
const { closeIntegrationSettingsModal } = useActions(marketingAnalyticsSettingsLogic)
@@ -439,15 +450,9 @@ const MarketingAnalyticsContent = (): JSX.Element => {
// Setup absorbs Integration health: while its flag is on, the audit lives inside
// Setup as a section rather than as a second top-level tab, so there's one door to
// "something is wrong with my setup" instead of two.
- const setupEnabled =
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP] ||
- !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]
-
// Setup absorbs the tabs it replaces, so a link or bookmark carrying one still lands
- // somewhere sensible. Here rather than in the logic because only the scene knows
- // whether Setup is rendering: with its flag off those tabs are still real and
- // resolve on their own. Above the early return below, since hooks have to run on
- // every render.
+ // somewhere sensible. With Setup disabled, those tabs still render and resolve
+ // on their own. Keep the effect above the early return so hooks run on every render.
const absorbed = setupEnabled ? SETUP_ABSORBED_TABS[activeTab] : undefined
useEffect(() => {
if (absorbed) {
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsx b/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsx
index 1020116e5d57..89730d5f0131 100644
--- a/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsx
+++ b/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsx
@@ -6,6 +6,8 @@ import { LemonButton, LemonSelect, LemonTag } from '@posthog/lemon-ui'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
import { IntegrationSettingsModal } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/IntegrationSettingsModal'
import {
SetupSection,
@@ -15,6 +17,10 @@ import { marketingAnalyticsSettingsLogic } from 'scenes/web-analytics/tabs/marke
import type { Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+import { conversionGoalFormLogic } from 'products/marketing_analytics/frontend/setup/conversionGoalFormLogic'
+import { ConversionGoalRecommendations } from 'products/marketing_analytics/frontend/setup/ConversionGoalRecommendations'
+import { dashboardSetupPromptsLogic } from 'products/marketing_analytics/frontend/setup/dashboardSetupPromptsLogic'
+
import { runNavigateOp } from './navigateOps'
import { suggestionsForSection } from './sectionRouting'
import { SectionSuggestions } from './SectionSuggestions'
@@ -43,6 +49,14 @@ function SectionBadge({
}
export function SetupTab(): JSX.Element {
+ const { currentTeamId } = useValues(teamLogic)
+ const { user } = useValues(userLogic)
+ const promptsLogic = dashboardSetupPromptsLogic({ projectId: currentTeamId ?? -1, userId: user?.uuid })
+ const { dismissed } = useValues(promptsLogic)
+ const { restore } = useActions(promptsLogic)
+ const { selectRecommendation, requestFormFocus } = useActions(
+ conversionGoalFormLogic({ projectId: currentTeamId ?? -1 })
+ )
const { featureFlags } = useValues(featureFlagLogic)
const { setupSection } = useValues(marketingAnalyticsLogic)
const { setSetupSection } = useActions(marketingAnalyticsLogic)
@@ -78,6 +92,12 @@ export function SetupTab(): JSX.Element {
}, [])
const active = sections.find((section) => section.key === setupSection) ?? sections[0]
+ const dismissedPrompt =
+ active.key === SetupSection.SOURCES && dismissed.sources
+ ? 'sources'
+ : active.key === SetupSection.CONVERSION_GOALS && dismissed['conversion-goals']
+ ? 'conversion-goals'
+ : null
useEffect(() => {
posthog.capture('marketing analytics setup section viewed', {
@@ -118,9 +138,35 @@ export function SetupTab(): JSX.Element {
<h2 className="mb-1">{active.label}</h2>
{active.description && <p className="text-secondary mb-0">{active.description}</p>}
</div>
+ {dismissedPrompt && (
+ <LemonButton
+ type="secondary"
+ onClick={() => restore(dismissedPrompt)}
+ data-attr="marketing-restore-dashboard-suggestions"
+ >
+ Show suggestions on dashboard
+ </LemonButton>
+ )}
{/* Skipped for "Suggested setup", which renders the whole ranked list
itself and would otherwise show everything twice. */}
- {active.key !== SetupSection.SUGGESTIONS && <SectionSuggestions section={active.key} />}
+ {active.key !== SetupSection.SUGGESTIONS &&
+ !(
+ active.key === SetupSection.SOURCES &&
+ featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SOURCE_ONBOARDING]
+ ) && <SectionSuggestions section={active.key} />}
+ {featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_CONVERSION_SETUP_AI] &&
+ (active.key === SetupSection.SUGGESTIONS || active.key === SetupSection.CONVERSION_GOALS) && (
+ <ConversionGoalRecommendations
+ onConfigureGoals={() => {
+ setSetupSection(SetupSection.CONVERSION_GOALS)
+ requestFormFocus()
+ }}
+ onUseSuggestion={(recommendation) => {
+ selectRecommendation(recommendation)
+ setSetupSection(SetupSection.CONVERSION_GOALS)
+ }}
+ />
+ )}
{active.key === SetupSection.SOURCES && (
<LemonButton
size="small"
diff --git a/frontend/src/scenes/marketing-analytics/Setup/setupSections.tsx b/frontend/src/scenes/marketing-analytics/Setup/setupSections.tsx
index e02c37e99983..c698ab0536dc 100644
--- a/frontend/src/scenes/marketing-analytics/Setup/setupSections.tsx
+++ b/frontend/src/scenes/marketing-analytics/Setup/setupSections.tsx
@@ -9,6 +9,8 @@ import { ExternalDataSourceConfiguration } from 'scenes/web-analytics/tabs/marke
import { UtmAuditTab } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/UtmAuditTab/UtmAuditTab'
import { SetupSection } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+import { DetectedSources } from 'products/marketing_analytics/frontend/dashboard/DetectedSources'
+
import { SECTION_LABEL } from './sectionRouting'
import { SuggestedActions } from './SuggestedActions'
@@ -36,6 +38,7 @@ export const SETUP_SECTIONS: SetupSectionDef[] = [
content: (
<>
<LegacyOAuthReconnectBanner />
+ <DetectedSources showRescan={false} />
<ExternalDataSourceConfiguration />
</>
),
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ConversionGoalsConfiguration.tsx b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ConversionGoalsConfiguration.tsx
index 7d8f4aad8d3b..342de61e5e2e 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ConversionGoalsConfiguration.tsx
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ConversionGoalsConfiguration.tsx
@@ -1,19 +1,21 @@
import { useActions, useValues } from 'kea'
-import { useMemo, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
import { IconCheck, IconPencil, IconPlusSmall, IconTrash, IconWarning, IconX } from '@posthog/icons'
-import { LemonButton, LemonInput } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonInput } from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TeamMembershipLevel } from 'lib/constants'
import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
import { LemonTable } from 'lib/lemon-ui/LemonTable'
-import { uuid } from 'lib/utils/dom'
import { QUERY_TYPES_METADATA } from 'scenes/saved-insights/insightTypesMetadata'
+import { teamLogic } from 'scenes/teamLogic'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
import { ConversionGoalFilter, NodeKind } from '~/queries/schema/schema-general'
+import { conversionGoalFormLogic } from 'products/marketing_analytics/frontend/setup/conversionGoalFormLogic'
+
import { marketingAnalyticsSettingsLogic } from '../../logic/marketingAnalyticsSettingsLogic'
import { ConversionGoalDropdown } from '../common/ConversionGoalDropdown'
import {
@@ -23,21 +25,10 @@ import {
import {
conversionGoalDescription,
conversionGoalNamePlaceholder,
- defaultConversionGoalFilter,
getConfiguredConversionGoalsLabel,
} from './constants'
import { revenueDisabledReason, withValidFlags } from './conversionGoalFlags'
-interface ConversionGoalFormState {
- filter: ConversionGoalFilter
- name: string
-}
-
-const createEmptyFormState = (): ConversionGoalFormState => ({
- filter: defaultConversionGoalFilter,
- name: '',
-})
-
function CountsAsToggles({
goal,
onChange,
@@ -76,7 +67,30 @@ export function ConversionGoalsConfiguration({
}): JSX.Element {
const { conversion_goals } = useValues(marketingAnalyticsSettingsLogic)
const { addOrUpdateConversionGoal, removeConversionGoal } = useActions(marketingAnalyticsSettingsLogic)
- const [formState, setFormState] = useState<ConversionGoalFormState>(createEmptyFormState)
+ const { currentTeamId } = useValues(teamLogic)
+ const formLogic = conversionGoalFormLogic({ projectId: currentTeamId ?? -1 })
+ const {
+ filter,
+ name,
+ recommendation,
+ editingGoalId: reviewingGoalId,
+ duplicateGoal,
+ formFocusRequested,
+ isFormValid,
+ isSaving,
+ currentTeamLoading,
+ saveError,
+ } = useValues(formLogic)
+ const { setName, setFilter, saveGoal, clearDraft, reviewGoal, formFocused } = useActions(formLogic)
+ const formRef = useRef<HTMLDivElement>(null)
+ const nameInputRef = useRef<HTMLInputElement>(null)
+ useEffect(() => {
+ if (formFocusRequested) {
+ formRef.current?.scrollIntoView({ block: 'nearest' })
+ nameInputRef.current?.focus({ preventScroll: true })
+ formFocused()
+ }
+ }, [formFocusRequested, formFocused])
const [editingGoalId, setEditingGoalId] = useState<string | null>(null)
const [editingGoal, setEditingGoal] = useState<ConversionGoalFilter | null>(null)
const restrictedReason = useRestrictedArea({
@@ -86,21 +100,6 @@ export function ConversionGoalsConfiguration({
const validationWarnings = useMemo(() => validateConversionGoals(conversion_goals), [conversion_goals])
- const handleAddConversionGoal = (): void => {
- let conversionGoalName = formState.name.trim()
- if (conversionGoalName === '') {
- conversionGoalName = formState.filter.custom_name || formState.filter.name || 'No name'
- }
- const newGoal: ConversionGoalFilter = withValidFlags({
- ...formState.filter,
- conversion_goal_id: formState.filter.conversion_goal_id || uuid(),
- conversion_goal_name: conversionGoalName,
- })
-
- addOrUpdateConversionGoal(newGoal)
- setFormState(createEmptyFormState())
- }
-
const handleStartEdit = (goal: ConversionGoalFilter): void => {
setEditingGoalId(goal.conversion_goal_id)
setEditingGoal({ ...goal })
@@ -123,7 +122,8 @@ export function ConversionGoalsConfiguration({
removeConversionGoal(goalId)
}
- const isFormValid = defaultConversionGoalFilter.name !== formState.filter.name
+ const formDisabledReason =
+ restrictedReason || (isSaving ? 'Wait for this conversion goal to finish saving.' : undefined)
return (
<SceneSection
@@ -135,58 +135,75 @@ export function ConversionGoalsConfiguration({
)}
{/* Add New Conversion Goal Form */}
- <div className="border rounded p-4 space-y-4">
- <h4 className="font-medium">Add new conversion goal</h4>
+ <div ref={formRef} className="border rounded p-4 space-y-4" data-attr="marketing-conversion-goal-form">
+ <h4 className="font-medium">
+ {reviewingGoalId ? 'Review conversion goal' : 'Add new conversion goal'}
+ </h4>
+ {!!recommendation?.questions.length && (
+ <LemonBanner type="info">
+ Review these questions before saving the goal:
+ <ul className="pl-5 mb-0 mt-2 space-y-1">
+ {recommendation.questions.map((question, index) => (
+ <li key={index}>{question}</li>
+ ))}
+ </ul>
+ </LemonBanner>
+ )}
+ {duplicateGoal && (
+ <LemonBanner
+ type="info"
+ action={{
+ children: 'Review goal',
+ onClick: () => reviewGoal(duplicateGoal.conversion_goal_id),
+ disabledReason:
+ formDisabledReason ||
+ (currentTeamLoading ? 'Wait for the project settings to finish saving.' : undefined),
+ }}
+ >
+ <span>{`Already configured as "${duplicateGoal.conversion_goal_name}". Review the existing goal.`}</span>
+ </LemonBanner>
+ )}
+ {saveError && <LemonBanner type="error">{saveError}</LemonBanner>}
<div className="space-y-3">
<div>
<LemonInput
- value={formState.name}
- onChange={(value) => setFormState((prev) => ({ ...prev, name: value }))}
+ inputRef={nameInputRef}
+ value={name}
+ onChange={setName}
placeholder={conversionGoalNamePlaceholder}
- disabledReason={restrictedReason}
+ disabledReason={formDisabledReason}
/>
</div>
<div>
<ConversionGoalDropdown
- value={formState.filter}
+ value={filter}
typeKey="conversion-goal"
- onChange={(newFilter) =>
- setFormState((prev) => ({
- ...prev,
- filter: {
- ...newFilter,
- conversion_goal_id: newFilter.conversion_goal_id || uuid(),
- },
- }))
- }
- disabledReason={restrictedReason}
+ onChange={setFilter}
+ disabledReason={formDisabledReason}
/>
</div>
- <CountsAsToggles
- goal={formState.filter}
- onChange={(filter) => setFormState((prev) => ({ ...prev, filter }))}
- disabledReason={restrictedReason}
- />
+ <CountsAsToggles goal={filter} onChange={setFilter} disabledReason={formDisabledReason} />
<div className="flex gap-2">
<LemonButton
type="primary"
- onClick={handleAddConversionGoal}
- disabled={!isFormValid}
+ onClick={saveGoal}
+ loading={isSaving}
+ disabled={!isFormValid || currentTeamLoading}
size="small"
- icon={<IconPlusSmall />}
- disabledReason={restrictedReason}
+ icon={reviewingGoalId ? <IconCheck /> : <IconPlusSmall />}
+ disabledReason={
+ formDisabledReason ||
+ (duplicateGoal ? 'Review the existing goal instead of adding a duplicate.' : undefined)
+ }
>
- Add conversion goal
+ {reviewingGoalId ? 'Save changes' : 'Add conversion goal'}
</LemonButton>
- <LemonButton
- onClick={() => setFormState(createEmptyFormState())}
- disabledReason={restrictedReason}
- >
+ <LemonButton onClick={clearDraft} disabledReason={formDisabledReason}>
Clear
</LemonButton>
</div>
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 6bc83d7c4fbc..6ab72b85e8b7 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
@@ -420,6 +420,7 @@ export interface marketingAnalyticsLogicValues {
nativeSourcesHierarchyStatus: NativeSourceHierarchyStatus[]
optionsOpen: boolean
overviewQuery: MarketingAnalyticsAggregatedQuery
+ setupEnabled: boolean
setupSection: SetupSection
shouldFilterTestAccounts: boolean
sourceValidation: SourceValidationApi
@@ -660,6 +661,7 @@ export interface marketingAnalyticsLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface marketingAnalyticsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ setupEnabled: (featureFlags: FeatureFlagsSet) => boolean
isAdPerformance: (activeTab: MarketingAnalyticsTab, featureFlags: FeatureFlagsSet) => boolean
includeConversionGoals: (
isAdPerformance: boolean,
@@ -1145,6 +1147,12 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
}
}),
selectors({
+ setupEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean =>
+ !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP] ||
+ !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD],
+ ],
isAdPerformance: [
(s) => [s.activeTab, s.featureFlags],
(activeTab: MarketingAnalyticsTab, featureFlags: FeatureFlagsSet): boolean =>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0e4dce3e0d54..e8acb2d21560 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -4202,6 +4202,12 @@ importers:
specifier: 18.3.1
version: 18.3.1
devDependencies:
+ '@testing-library/jest-dom':
+ specifier: ^5.17.0
+ version: 5.17.0
+ '@testing-library/react':
+ specifier: ^14.3.1
kea-test-utils:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
diff --git a/products/marketing_analytics/frontend/dashboard/DetectedSources.tsx b/products/marketing_analytics/frontend/dashboard/DetectedSources.tsx
index 00646fed9b16..5becff2d217b 100644
--- a/products/marketing_analytics/frontend/dashboard/DetectedSources.tsx
+++ b/products/marketing_analytics/frontend/dashboard/DetectedSources.tsx
@@ -14,11 +14,20 @@ import {
nativeSourceDisplayLabel,
} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/utils'
+import { DashboardSetupPrompt } from '../setup/DashboardSetupPrompt'
import { detectedSourcesLogic } from './detectedSourcesLogic'
import { SourceCatalog } from './SourceCatalog'
import { SourceSetupPanel } from './SourceSetupPanel'
-export function DetectedSources({ compact = false }: { compact?: boolean }): JSX.Element | null {
+export function DetectedSources({
+ compact = false,
+ showRescan = true,
+ dismissible = false,
+}: {
+ compact?: boolean
+ showRescan?: boolean
+ dismissible?: boolean
+}): JSX.Element | null {
const {
visibleSuggestions,
dismissedSuggestions,
@@ -84,38 +93,46 @@ export function DetectedSources({ compact = false }: { compact?: boolean }): JSX
<MarketingAnalyticsSourceStatusBanner
hiddenSourceIds={pendingConnections.map((connection) => connection.id)}
/>
- <SourceSetupPanel
- compact={compact || hasSyncedMarketingSources}
- state={
- pendingConnections.length
- ? 'waiting'
- : !setupPlan
- ? setupPlanFailed
- ? 'error'
- : 'scanning'
- : sources.length
- ? 'suggestions'
- : dismissedSuggestions.some((suggestion) => suggestion.kind === 'connect_source')
- ? 'dismissed'
- : 'empty'
- }
- suggestions={sources}
- connections={pendingConnections}
- onRetry={rescanSources}
- rescanLoading={setupPlanLoading}
- rescanDisabledReason={sourceScanDisabledReason}
- onDismiss={dismissSource}
- onRestore={restoreAllDismissed}
- footer={
- <LemonButton
- type={sources.length || connections.length ? 'secondary' : 'primary'}
- onClick={openIntegrations}
- data-attr="marketing-dashboard-connect-source"
- >
- Browse integrations
- </LemonButton>
- }
- />
+ <DashboardSetupPrompt
+ kind="sources"
+ dismissible={dismissible && !pendingConnections.length && !!setupPlan && !setupPlanFailed}
+ >
+ {(dismissButton) => (
+ <SourceSetupPanel
+ headerAction={dismissButton}
+ compact={compact || hasSyncedMarketingSources}
+ state={
+ pendingConnections.length
+ ? 'waiting'
+ : !setupPlan
+ ? setupPlanFailed
+ ? 'error'
+ : 'scanning'
+ : sources.length
+ ? 'suggestions'
+ : dismissedSuggestions.some((suggestion) => suggestion.kind === 'connect_source')
+ ? 'dismissed'
+ : 'empty'
+ }
+ suggestions={sources}
+ connections={pendingConnections}
+ onRetry={showRescan ? rescanSources : undefined}
+ rescanLoading={setupPlanLoading}
+ rescanDisabledReason={sourceScanDisabledReason}
+ onDismiss={dismissSource}
+ onRestore={restoreAllDismissed}
+ footer={
+ <LemonButton
+ type={sources.length || connections.length ? 'secondary' : 'primary'}
+ onClick={openIntegrations}
+ data-attr="marketing-dashboard-connect-source"
+ >
+ Browse integrations
+ </LemonButton>
+ }
+ />
+ )}
+ </DashboardSetupPrompt>
</>
)
}
diff --git a/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsx b/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsx
index 6d7ba649c60b..f565d097b3e2 100644
--- a/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsx
+++ b/products/marketing_analytics/frontend/dashboard/SearchConsoleSource.tsx
@@ -1,4 +1,5 @@
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'
@@ -15,7 +16,7 @@ import { sourcesDataLogic } from 'products/data_warehouse/frontend/shared/logics
const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlass)
-export function SearchConsoleSource(): JSX.Element | null {
+export function SearchConsoleSource({ headerAction }: { headerAction?: ReactNode }): JSX.Element | null {
const { featureFlags } = useValues(featureFlagLogic)
const { dataWarehouseSources } = useValues(marketingAnalyticsLogic)
const { sourcesLoadError, dataWarehouseSourcesLoading } = useValues(sourcesDataLogic)
@@ -30,7 +31,10 @@ export function SearchConsoleSource(): JSX.Element | null {
if (!dataWarehouseSources) {
return (
<section className="max-w-3xl w-full mx-auto mt-8 mb-6">
- <h2 className="mb-4">Search performance</h2>
+ <h2 className="mb-4 flex items-center justify-between gap-2">
+ <span>Search performance</span>
+ {headerAction}
+ </h2>
{sourcesLoadError ? (
<LemonBanner
type="error"
@@ -74,6 +78,7 @@ export function SearchConsoleSource(): JSX.Element | null {
</p>
</div>
<HedgehogMagnifyingGlass className="w-20 shrink-0" />
+ {headerAction}
</div>
<div className="divide-y">
{sources.map((source) => (
diff --git a/products/marketing_analytics/frontend/dashboard/SourceSetupPanel.tsx b/products/marketing_analytics/frontend/dashboard/SourceSetupPanel.tsx
index ed72c62694c0..55a5ec02c308 100644
--- a/products/marketing_analytics/frontend/dashboard/SourceSetupPanel.tsx
+++ b/products/marketing_analytics/frontend/dashboard/SourceSetupPanel.tsx
@@ -28,6 +28,7 @@ export interface SourceSetupPanelProps {
}[]
compact?: boolean
footer?: ReactNode
+ headerAction?: ReactNode
onRetry?: () => void
rescanLoading?: boolean
rescanDisabledReason?: string | null
@@ -40,6 +41,7 @@ export function SourceSetupPanel({
suggestions = [],
connections = [],
footer,
+ headerAction,
compact = false,
onRetry,
rescanLoading = false,
@@ -113,6 +115,7 @@ export function SourceSetupPanel({
<p className="text-secondary mb-0 max-w-xl">{description}</p>
</div>
{!busy && <HedgehogMoney className={compact ? 'w-12 shrink-0' : 'w-20 shrink-0'} />}
+ {headerAction}
</div>
{state === 'empty' && (
<p className="text-secondary text-sm mb-4">
diff --git a/products/marketing_analytics/frontend/setup/ConversionGoalRecommendations.stories.tsx b/products/marketing_analytics/frontend/setup/ConversionGoalRecommendations.stories.tsx
new file mode 100644
index 000000000000..3bd109fe4649
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/ConversionGoalRecommendations.stories.tsx
@@ -0,0 +1,158 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import type { ConversionRecommendationApi, ConversionRecommendationStateApi } from '../generated/api.schemas'
+import { ConversionGoalRecommendations } from './ConversionGoalRecommendations'
+import { DashboardConversionRecommendations } from './DashboardConversionRecommendations'
+
+const run = {
+ id: 'synthetic-analysis',
+ status: 'completed' as const,
+ lookback_days: 30,
+ date_from: '2026-09-01T00:00:00Z',
+ date_to: '2026-10-01T00:00:00Z',
+ created_at: '2026-10-01T00:00:00Z',
+ completed_at: '2026-10-01T00:01:00Z',
+ error: '',
+}
+const recommendation: ConversionRecommendationApi = {
+ source_ref: 'event:order_settled',
+ name: 'Settled orders',
+ intent: 'revenue',
+ amount_property: 'order_value',
+ reason: 'This event may record completed payments. Confirm its business meaning before using it as revenue.',
+ questions: ['Confirm payment status, amount units, currency, refunds, and one event per transaction.'],
+ candidate: {
+ source_ref: 'event:order_settled',
+ name: 'order_settled',
+ kind: 'EventsNode',
+ event: 'order_settled',
+ count: 42,
+ numeric_properties: ['order_value'],
+ },
+}
+const completed: ConversionRecommendationStateApi = {
+ latest_run: run,
+ result_run: run,
+ can_generate: true,
+ generation_disabled_reason: null,
+ results: {
+ recommendations: [
+ recommendation,
+ {
+ ...recommendation,
+ source_ref: 'event:quote_requested',
+ name: 'Quote requests',
+ intent: 'conversion',
+ amount_property: null,
+ reason: 'A quote request may indicate purchase intent.',
+ questions: ['Does this event exclude duplicate requests?'],
+ candidate: {
+ source_ref: 'event:quote_requested',
+ name: 'quote_requested',
+ kind: 'EventsNode',
+ event: 'quote_requested',
+ count: 18,
+ },
+ },
+ {
+ ...recommendation,
+ source_ref: 'action:2',
+ name: 'Activated accounts',
+ intent: 'customer',
+ amount_property: null,
+ reason: 'This action may identify newly activated accounts.',
+ questions: ['Does this action fire once for each new customer?'],
+ candidate: { source_ref: 'action:2', name: 'Activated accounts', kind: 'ActionsNode', action_id: 2 },
+ },
+ ],
+ limitations: [
+ 'Discovery considers up to 20 custom events and 20 existing actions. Business definitions need your review.',
+ ],
+ },
+}
+function withState(state: ConversionRecommendationStateApi): ReturnType<typeof mswDecorator> {
+ return mswDecorator({
+ get: {
+ '/api/projects/:team_id/marketing_analytics/conversion_recommendations/': state,
+ },
+ post: {
+ '/api/projects/:team_id/marketing_analytics/conversion_recommendations/start/': {
+ ...state,
+ latest_run: { ...run, status: 'pending', lookback_days: state.result_run ? 14 : 30 },
+ },
+ },
+ })
+}
+const meta: Meta<typeof ConversionGoalRecommendations> = {
+ title: 'Scenes-App/Marketing Analytics/Persisted conversion recommendations',
+ component: ConversionGoalRecommendations,
+ args: { onConfigureGoals: () => {}, onUseSuggestion: () => {} },
+ parameters: {
+ layout: 'padded',
+ featureFlags: [FEATURE_FLAGS.MARKETING_ANALYTICS_CONVERSION_SETUP_AI, FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP],
+ },
+ decorators: [
+ (Story, { parameters }) => (
+ <div className={parameters.narrow ? 'w-[520px] max-w-full' : 'w-240 max-w-full'}>
+ <Story />
+ </div>
+ ),
+ ],
+}
+export default meta
+type Story = StoryObj<typeof ConversionGoalRecommendations>
+
+export const FirstAnalysis: Story = {
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+ decorators: [
+ withState({
+ ...completed,
+ latest_run: { ...run, status: 'pending' },
+ result_run: null,
+ results: { recommendations: [] },
+ }),
+ ],
+}
+export const Ready: Story = { decorators: [withState(completed)] }
+export const Dashboard: Story = {
+ render: () => <DashboardConversionRecommendations />,
+ decorators: [withState(completed)],
+}
+export const Updating: Story = {
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+ decorators: [withState({ ...completed, latest_run: { ...run, status: 'running', lookback_days: 14 } })],
+}
+export const Empty: Story = { decorators: [withState({ ...completed, results: { recommendations: [] } })] }
+export const Failed: Story = {
+ decorators: [
+ withState({
+ ...completed,
+ latest_run: {
+ ...run,
+ status: 'failed',
+ error: 'Could not analyze the sources. Scan again to retry.',
+ },
+ }),
+ ],
+}
+export const Narrow: Story = {
+ parameters: { narrow: true },
+ decorators: [withState(completed)],
+}
+
+export const ConsentRequired: Story = {
+ decorators: [
+ withState({
+ ...completed,
+ latest_run: null,
+ result_run: null,
+ results: { recommendations: [] },
+ can_generate: false,
+ generation_disabled_reason: 'Ask an organization admin to enable AI data processing.',
+ }),
+ ],
+}
diff --git a/products/marketing_analytics/frontend/setup/ConversionGoalRecommendations.tsx b/products/marketing_analytics/frontend/setup/ConversionGoalRecommendations.tsx
new file mode 100644
index 000000000000..ee2f5a809bb4
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/ConversionGoalRecommendations.tsx
@@ -0,0 +1,256 @@
+import { useActions, useValues } from 'kea'
+import type { ReactNode } from 'react'
+
+import { LemonBanner, LemonButton, LemonCard, LemonCollapse } from '@posthog/lemon-ui'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TZLabel } from 'lib/components/TZLabel'
+import { FEATURE_FLAGS, TeamMembershipLevel } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import type { ConversionRecommendationApi } from '../generated/api.schemas'
+import { conversionGoalFormLogic } from './conversionGoalFormLogic'
+import { ConversionRecommendationCard } from './ConversionRecommendationCard'
+import { conversionRecommendationsLogic } from './conversionRecommendationsLogic'
+
+export function ConversionGoalRecommendations({
+ onConfigureGoals,
+ onUseSuggestion,
+ headerAction,
+ hideWhenConfigured = false,
+}: {
+ onConfigureGoals: () => void
+ onUseSuggestion: (recommendation: ConversionRecommendationApi) => void
+ headerAction?: ReactNode
+ hideWhenConfigured?: boolean
+}): JSX.Element | null {
+ const { currentTeamId, currentTeamLoading } = useValues(teamLogic)
+ const { isSaving } = useValues(conversionGoalFormLogic({ projectId: currentTeamId ?? -1 }))
+ const restrictedReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
+ const { user } = useValues(userLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const enabled = !!featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_CONVERSION_SETUP_AI]
+ const logic = conversionRecommendationsLogic({
+ projectId: currentTeamId ?? -1,
+ enabled,
+ userId: user?.uuid,
+ })
+ const {
+ state,
+ stateLoading,
+ isAnalyzing,
+ error,
+ pendingRecommendations,
+ allRecommendationsConfigured,
+ allRecommendationsHandled,
+ dismissedRecommendationEntries,
+ scanCooldownRemaining,
+ scanDisabledReason,
+ } = useValues(logic)
+ const { requestAnalysis, loadRecommendations, dismissRecommendation, restoreRecommendation } = useActions(logic)
+
+ if (
+ !enabled ||
+ currentTeamId === null ||
+ (hideWhenConfigured &&
+ allRecommendationsHandled &&
+ !stateLoading &&
+ !isAnalyzing &&
+ !error &&
+ state?.latest_run?.status !== 'failed')
+ ) {
+ return null
+ }
+ return (
+ <LemonCard
+ hoverEffect={false}
+ className="p-0 mt-4 overflow-hidden"
+ data-attr="marketing-conversion-recommendations"
+ >
+ <div className="p-4 space-y-3">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <h3 className="text-base mb-1">
+ {allRecommendationsConfigured ? 'Conversion goals' : 'Suggested conversion goals'}
+ </h3>
+ <p className="mb-0 text-secondary text-sm">
+ {allRecommendationsConfigured
+ ? 'All suggestions from your last successful scan are configured.'
+ : allRecommendationsHandled && dismissedRecommendationEntries.length > 0
+ ? 'No pending suggestions. You can review and restore dismissed suggestions below.'
+ : 'Review suggested events and actions before adding a goal.'}
+ </p>
+ </div>
+ {headerAction}
+ </div>
+ {state?.generation_disabled_reason && (
+ <LemonBanner type="info">{state.generation_disabled_reason}</LemonBanner>
+ )}
+ {!state && stateLoading && <LemonBanner type="info">Loading conversion recommendations…</LemonBanner>}
+ {isAnalyzing && (
+ <LemonBanner type="info">
+ Scanning events and actions from the last {state?.latest_run?.lookback_days} days.{' '}
+ {state?.result_run
+ ? 'Previous suggestions remain available.'
+ : 'You can leave this page while it runs.'}
+ </LemonBanner>
+ )}
+ {error && (
+ <LemonBanner
+ type="error"
+ action={{
+ children: 'Retry loading',
+ onClick: () => loadRecommendations(),
+ disabledReason: stateLoading ? 'Wait for the current request.' : undefined,
+ }}
+ >
+ {error}
+ </LemonBanner>
+ )}
+ {state?.latest_run?.status === 'failed' && (
+ <LemonBanner type="warning">
+ {allRecommendationsConfigured
+ ? 'The latest scan failed. Your configured goals are unchanged. Scan again to retry.'
+ : state.result_run
+ ? 'The latest scan failed. Suggestions from your last successful scan are still available. Scan again to retry.'
+ : 'Could not scan events and actions. Scan again to retry.'}
+ </LemonBanner>
+ )}
+ {state?.result_run && (state.results.recommendations?.length ?? 0) === 0 && (
+ <LemonBanner type="info">
+ No additional goals were found. Review your configured goals or scan again after more data
+ arrives.
+ </LemonBanner>
+ )}
+ {pendingRecommendations.length > 0 && (
+ <div className="divide-y border-t">
+ {pendingRecommendations.map((recommendation) => (
+ <ConversionRecommendationCard
+ key={recommendation.source_ref}
+ recommendation={recommendation}
+ onUseSuggestion={() => onUseSuggestion(recommendation)}
+ onDismiss={() => dismissRecommendation(recommendation)}
+ disabledReason={
+ restrictedReason ||
+ (currentTeamLoading || isSaving
+ ? 'Wait for the project settings to finish saving.'
+ : undefined)
+ }
+ />
+ ))}
+ </div>
+ )}
+ {dismissedRecommendationEntries.length > 0 && (
+ <LemonCollapse
+ embedded
+ size="small"
+ panels={[
+ {
+ key: 'dismissed-suggestions',
+ header: `Dismissed suggestions (${dismissedRecommendationEntries.length})`,
+ content: (
+ <div className="space-y-2">
+ <p className="text-secondary text-sm mb-0">
+ Hidden for you in this browser. Restore a suggestion to show it again if it
+ is in the latest scan, or allow it in future scans.
+ </p>
+ <div className="divide-y">
+ {dismissedRecommendationEntries.map((recommendation) => (
+ <div
+ key={recommendation.source_ref}
+ className="flex flex-wrap items-center justify-between gap-2 py-2"
+ >
+ <div className="min-w-0 flex-1 basis-48">
+ <strong className="break-words">{recommendation.name}</strong>
+ <p className="text-secondary text-xs mb-0 break-all">
+ {recommendation.source_ref}
+ </p>
+ </div>
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={() => restoreRecommendation(recommendation.source_ref)}
+ data-attr="marketing-conversion-restore-suggestion"
+ >
+ Restore
+ </LemonButton>
+ </div>
+ ))}
+ </div>
+ </div>
+ ),
+ },
+ ]}
+ />
+ )}
+ {(state?.result_run ||
+ state?.latest_run?.status === 'failed' ||
+ !!state?.results.limitations?.length) && (
+ <LemonCollapse
+ embedded
+ size="small"
+ panels={[
+ {
+ key: 'scan-details',
+ header: 'Scan details',
+ content: (
+ <div className="text-secondary text-sm space-y-2">
+ {state?.result_run && (
+ <p className="mb-0">
+ <span>Analysis period: </span>
+ <TZLabel time={state.result_run.date_from} timestampStyle="absolute" />
+ <span> to </span>
+ <TZLabel time={state.result_run.date_to} timestampStyle="absolute" />
+ <span>. Applied suggestions are hidden.</span>
+ </p>
+ )}
+ {state?.latest_run?.status === 'failed' && state.latest_run.error && (
+ <p className="mb-0">{state.latest_run.error}</p>
+ )}
+ {!!state?.results.limitations?.length && (
+ <ul className="pl-5 mb-0">
+ {state.results.limitations.map((limitation) => (
+ <li key={limitation}>{limitation}</li>
+ ))}
+ </ul>
+ )}
+ </div>
+ ),
+ },
+ ]}
+ />
+ )}
+ </div>
+ <div className="border-t px-4 py-3 flex flex-wrap items-center justify-between gap-2 bg-bg-light">
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={onConfigureGoals}
+ data-attr="marketing-conversion-configure-goals"
+ >
+ Configure goals
+ </LemonButton>
+ <div className="flex flex-wrap items-center gap-2">
+ {!isAnalyzing && scanCooldownRemaining > 0 && state?.can_generate && (
+ <span className="text-secondary text-sm">{scanDisabledReason}</span>
+ )}
+ <LemonButton
+ type="secondary"
+ size="small"
+ loading={isAnalyzing || stateLoading}
+ disabledReason={scanDisabledReason}
+ onClick={() => requestAnalysis(true)}
+ data-attr="marketing-conversion-update-recommendations"
+ >
+ {isAnalyzing ? 'Scanning…' : state?.latest_run ? 'Scan again' : 'Scan events'}
+ </LemonButton>
+ </div>
+ </div>
+ </LemonCard>
+ )
+}
diff --git a/products/marketing_analytics/frontend/setup/ConversionRecommendationCard.stories.tsx b/products/marketing_analytics/frontend/setup/ConversionRecommendationCard.stories.tsx
new file mode 100644
index 000000000000..3923cc978dcf
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/ConversionRecommendationCard.stories.tsx
@@ -0,0 +1,35 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { ConversionRecommendationCard } from './ConversionRecommendationCard'
+
+const meta: Meta<typeof ConversionRecommendationCard> = {
+ title: 'Scenes-App/Marketing Analytics/Conversion recommendation card',
+ component: ConversionRecommendationCard,
+ decorators: [
+ (Story, { parameters }) => (
+ <div className={parameters.narrow ? 'w-[520px] max-w-full' : 'w-240 max-w-full'}>
+ <Story />
+ </div>
+ ),
+ ],
+ args: {
+ onUseSuggestion: () => {},
+ onDismiss: () => {},
+ recommendation: {
+ source_ref: 'action:1',
+ name: 'Qualified requests',
+ reason: 'This action may represent qualified requests. Review its existing filters.',
+ intent: 'conversion',
+ amount_property: null,
+ questions: ['Does this action exclude test and duplicate requests?'],
+ candidate: { source_ref: 'action:1', name: 'Qualified requests', kind: 'ActionsNode', action_id: 1 },
+ },
+ },
+}
+export default meta
+type Story = StoryObj<typeof ConversionRecommendationCard>
+export const Action: Story = {}
+export const Narrow: Story = {
+ parameters: { narrow: true },
+ decorators: [],
+}
diff --git a/products/marketing_analytics/frontend/setup/ConversionRecommendationCard.tsx b/products/marketing_analytics/frontend/setup/ConversionRecommendationCard.tsx
new file mode 100644
index 000000000000..fcac97b6ab94
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/ConversionRecommendationCard.tsx
@@ -0,0 +1,84 @@
+import { LemonButton, LemonCollapse, LemonTag } from '@posthog/lemon-ui'
+
+import type { ConversionRecommendationApi } from '../generated/api.schemas'
+
+export function ConversionRecommendationCard({
+ recommendation,
+ onUseSuggestion,
+ onDismiss,
+ disabledReason,
+}: {
+ recommendation: ConversionRecommendationApi
+ onUseSuggestion: () => void
+ onDismiss?: () => void
+ disabledReason?: string | null
+}): JSX.Element {
+ return (
+ <div className="flex flex-wrap items-start gap-2 py-2 min-w-0">
+ <LemonCollapse
+ embedded
+ size="small"
+ className="flex-1 min-w-0 basis-64"
+ panels={[
+ {
+ key: recommendation.source_ref,
+ header: {
+ className: 'py-1',
+ children: (
+ <div className="min-w-0 text-left">
+ <div className="flex flex-wrap items-center gap-2">
+ <strong className="break-words">{recommendation.name}</strong>
+ <LemonTag size="small">
+ {recommendation.intent === 'revenue'
+ ? 'Potential revenue goal'
+ : recommendation.intent === 'customer'
+ ? 'Potential customer goal'
+ : 'Potential conversion goal'}
+ </LemonTag>
+ </div>
+ <div className="text-secondary text-xs font-normal break-all mt-1">
+ <span>{recommendation.candidate.name}</span>
+ {recommendation.candidate.count != null && (
+ <span>{` · ${recommendation.candidate.count.toLocaleString()} events`}</span>
+ )}
+ </div>
+ </div>
+ ),
+ },
+ content: (
+ <div className="space-y-2 text-sm break-words">
+ <p className="mb-0">{recommendation.reason}</p>
+ {recommendation.amount_property && (
+ <p className="mb-0 text-secondary">{`Amount property: ${recommendation.amount_property}`}</p>
+ )}
+ {recommendation.questions.length > 0 && (
+ <ul className="pl-5 mb-0 space-y-1">
+ {recommendation.questions.map((question, index) => (
+ <li key={index}>{question}</li>
+ ))}
+ </ul>
+ )}
+ </div>
+ ),
+ },
+ ]}
+ />
+ <div className="flex flex-wrap items-center gap-1 mt-1 ml-auto">
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={onUseSuggestion}
+ disabledReason={disabledReason}
+ data-attr="marketing-conversion-use-suggestion"
+ >
+ Review suggestion
+ </LemonButton>
+ {onDismiss && (
+ <LemonButton size="small" onClick={onDismiss} data-attr="marketing-conversion-dismiss-suggestion">
+ Dismiss
+ </LemonButton>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/products/marketing_analytics/frontend/setup/DashboardConversionRecommendations.tsx b/products/marketing_analytics/frontend/setup/DashboardConversionRecommendations.tsx
new file mode 100644
index 000000000000..a88905ff5f4c
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/DashboardConversionRecommendations.tsx
@@ -0,0 +1,46 @@
+import { useActions, useValues } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
+import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+
+import { conversionGoalFormLogic } from './conversionGoalFormLogic'
+import { ConversionGoalRecommendations } from './ConversionGoalRecommendations'
+import { DashboardSetupPrompt } from './DashboardSetupPrompt'
+import { dashboardSetupPromptsLogic } from './dashboardSetupPromptsLogic'
+
+export function DashboardConversionRecommendations(): JSX.Element | null {
+ const { setupEnabled } = useValues(marketingAnalyticsLogic)
+ const { currentTeamId } = useValues(teamLogic)
+ const { user } = useValues(userLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { openSetup } = useActions(dashboardSetupPromptsLogic({ projectId: currentTeamId ?? -1, userId: user?.uuid }))
+ const { selectRecommendation, requestFormFocus } = useActions(
+ conversionGoalFormLogic({ projectId: currentTeamId ?? -1 })
+ )
+
+ if (!setupEnabled || !featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_CONVERSION_SETUP_AI]) {
+ return null
+ }
+
+ return (
+ <DashboardSetupPrompt kind="conversion-goals">
+ {(dismissButton) => (
+ <ConversionGoalRecommendations
+ headerAction={dismissButton}
+ hideWhenConfigured
+ onConfigureGoals={() => {
+ requestFormFocus()
+ openSetup('conversion-goals')
+ }}
+ onUseSuggestion={(recommendation) => {
+ selectRecommendation(recommendation)
+ openSetup('conversion-goals')
+ }}
+ />
+ )}
+ </DashboardSetupPrompt>
+ )
+}
diff --git a/products/marketing_analytics/frontend/setup/DashboardSetupPrompt.stories.tsx b/products/marketing_analytics/frontend/setup/DashboardSetupPrompt.stories.tsx
new file mode 100644
index 000000000000..5b2b667b6de8
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/DashboardSetupPrompt.stories.tsx
@@ -0,0 +1,49 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { SourceSetupPanel } from '../dashboard/SourceSetupPanel'
+import { DashboardSetupPrompt } from './DashboardSetupPrompt'
+
+const meta: Meta<typeof DashboardSetupPrompt> = {
+ title: 'Scenes-App/Marketing Analytics/Dismissible setup prompts',
+ component: DashboardSetupPrompt,
+ parameters: { layout: 'padded', featureFlags: [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP] },
+ decorators: [
+ (Story) => (
+ <div className="w-[520px] max-w-full">
+ <Story />
+ </div>
+ ),
+ ],
+ args: { kind: 'sources' },
+}
+export default meta
+type Story = StoryObj<typeof DashboardSetupPrompt>
+
+export const Scanning: Story = {
+ args: {
+ dismissible: false,
+ children: (dismissButton) => <SourceSetupPanel state="scanning" headerAction={dismissButton} />,
+ },
+ parameters: { testOptions: { waitForLoadersToDisappear: false } },
+}
+export const Failed: Story = {
+ args: {
+ dismissible: false,
+ children: (dismissButton) => <SourceSetupPanel state="error" onRetry={() => {}} headerAction={dismissButton} />,
+ },
+}
+
+export const Suggestions: Story = {
+ args: { children: (dismissButton) => <SourceSetupPanel state="empty" headerAction={dismissButton} /> },
+}
+export const WithoutSetup: Story = {
+ ...Suggestions,
+ parameters: {
+ featureFlags: {
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: false,
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_NEW_DASHBOARD]: false,
+ },
+ },
+}
diff --git a/products/marketing_analytics/frontend/setup/DashboardSetupPrompt.tsx b/products/marketing_analytics/frontend/setup/DashboardSetupPrompt.tsx
new file mode 100644
index 000000000000..0753da4d328f
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/DashboardSetupPrompt.tsx
@@ -0,0 +1,53 @@
+import { useActions, useValues } from 'kea'
+import type { ReactNode } from 'react'
+
+import { IconX } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
+import { marketingAnalyticsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+
+import { DashboardSetupPromptKind, dashboardSetupPromptsLogic } from './dashboardSetupPromptsLogic'
+
+export function DashboardSetupPrompt({
+ kind,
+ children,
+ dismissible = true,
+}: {
+ kind: DashboardSetupPromptKind
+ dismissible?: boolean
+ children: (dismissButton: ReactNode) => ReactNode
+}): JSX.Element | null {
+ const { setupEnabled } = useValues(marketingAnalyticsLogic)
+ const canDismiss = setupEnabled && dismissible
+ const { currentTeamId } = useValues(teamLogic)
+ const { user } = useValues(userLogic)
+ const logic = dashboardSetupPromptsLogic({ projectId: currentTeamId ?? -1, userId: user?.uuid })
+ const { dismissed } = useValues(logic)
+ const { dismiss } = useActions(logic)
+
+ if (!currentTeamId || (canDismiss && dismissed[kind])) {
+ return null
+ }
+
+ return (
+ <div data-attr={`marketing-dashboard-${kind}-prompt`}>
+ {children(
+ canDismiss ? (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ icon={<IconX />}
+ aria-label={
+ kind === 'sources' ? 'Dismiss source suggestions' : 'Dismiss conversion recommendations'
+ }
+ tooltip="Dismiss"
+ onClick={() => dismiss(kind)}
+ data-attr={`marketing-dashboard-dismiss-${kind}`}
+ />
+ ) : null
+ )}
+ </div>
+ )
+}
diff --git a/products/marketing_analytics/frontend/setup/SetupConversionFlag.test.tsx b/products/marketing_analytics/frontend/setup/SetupConversionFlag.test.tsx
new file mode 100644
index 000000000000..8537fb1064f0
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/SetupConversionFlag.test.tsx
@@ -0,0 +1,132 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { SetupTab } from 'scenes/marketing-analytics/Setup/SetupTab'
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { ConversionGoalRecommendations } from './ConversionGoalRecommendations'
+import { DashboardConversionRecommendations } from './DashboardConversionRecommendations'
+import { DashboardSetupPrompt } from './DashboardSetupPrompt'
+import { dashboardSetupPromptsLogic } from './dashboardSetupPromptsLogic'
+
+jest.mock('./ConversionGoalRecommendations', () => ({
+ ConversionGoalRecommendations: jest.fn(() => <button>Review recommendations</button>),
+}))
+jest.mock('scenes/marketing-analytics/Setup/setupSections', () => ({
+ SETUP_SECTIONS: [
+ {
+ key: 'conversion-goals',
+ label: 'Conversion goals',
+ content: <button>Add conversion goal</button>,
+ },
+ ],
+}))
+jest.mock('scenes/marketing-analytics/Setup/SectionSuggestions', () => ({ SectionSuggestions: () => null }))
+jest.mock('scenes/marketing-analytics/Setup/SuggestionModal', () => ({ SuggestionModal: () => null }))
+jest.mock(
+ 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/IntegrationSettingsModal',
+ () => ({ IntegrationSettingsModal: () => null })
+)
+
+describe('conversion setup feature flag', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ useMocks({ get: { '/api/environments/:team_id/marketing_analytics/setup_plan/': { suggestions: [] } } })
+ initKeaTests()
+ jest.clearAllMocks()
+ })
+ afterEach(cleanup)
+
+ it('keeps manual setup mounted and only mounts AI recommendations while their flag is enabled', () => {
+ render(<SetupTab />)
+ expect(screen.getByText('Add conversion goal')).toBeVisible()
+ expect(ConversionGoalRecommendations).not.toHaveBeenCalled()
+
+ act(() =>
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.MARKETING_ANALYTICS_CONVERSION_SETUP_AI], {
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_CONVERSION_SETUP_AI]: true,
+ })
+ )
+ expect(screen.getByText('Review recommendations')).toBeVisible()
+ expect(screen.getByText('Add conversion goal')).toBeVisible()
+
+ act(() =>
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.MARKETING_ANALYTICS_CONVERSION_SETUP_AI]: false,
+ })
+ )
+ expect(screen.queryByText('Review recommendations')).not.toBeInTheDocument()
+ expect(screen.getByText('Add conversion goal')).toBeVisible()
+ })
+
+ 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) => {
+ 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,
+ })
+ render(<DashboardConversionRecommendations />)
+ expect(!!screen.queryByText('Review recommendations')).toBe(visible)
+ expect(!!jest.mocked(ConversionGoalRecommendations).mock.calls.length).toBe(visible)
+ })
+
+ it('keeps dismissed sources accessible without Setup and restores them from Setup', () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: true })
+ render(
+ <DashboardSetupPrompt kind="sources">
+ {(dismissButton) => <div>Source suggestions{dismissButton}</div>}
+ </DashboardSetupPrompt>
+ )
+ fireEvent.click(screen.getByLabelText('Dismiss source suggestions'))
+ expect(screen.queryByText('Source suggestions')).not.toBeInTheDocument()
+ act(() => featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: false }))
+ expect(screen.getByText('Source suggestions')).toBeVisible()
+ expect(screen.queryByLabelText('Dismiss source suggestions')).not.toBeInTheDocument()
+ act(() => featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: true }))
+ expect(screen.queryByText('Source suggestions')).not.toBeInTheDocument()
+ act(() =>
+ dashboardSetupPromptsLogic({
+ projectId: teamLogic.values.currentTeamId!,
+ userId: userLogic.values.user?.uuid,
+ }).actions.restore('sources')
+ )
+ expect(screen.getByText('Source suggestions')).toBeVisible()
+ })
+
+ it('keeps an error and its retry visible after the source suggestions were dismissed', () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.MARKETING_ANALYTICS_SETUP]: true })
+ const { rerender } = render(
+ <DashboardSetupPrompt kind="sources">
+ {(dismissButton) => <div>Source suggestions{dismissButton}</div>}
+ </DashboardSetupPrompt>
+ )
+ fireEvent.click(screen.getByLabelText('Dismiss source suggestions'))
+ rerender(
+ <DashboardSetupPrompt kind="sources" dismissible={false}>
+ {(dismissButton) => (
+ <div>
+ <button>Retry source scan</button>
+ {dismissButton}
+ </div>
+ )}
+ </DashboardSetupPrompt>
+ )
+ expect(screen.getByText('Retry source scan')).toBeVisible()
+ expect(screen.queryByLabelText('Dismiss source suggestions')).not.toBeInTheDocument()
+ })
+})
diff --git a/products/marketing_analytics/frontend/setup/conversionGoalFormLogic.test.ts b/products/marketing_analytics/frontend/setup/conversionGoalFormLogic.test.ts
new file mode 100644
index 000000000000..b16473c5507c
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/conversionGoalFormLogic.test.ts
@@ -0,0 +1,256 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { teamLogic } from 'scenes/teamLogic'
+import { marketingAnalyticsSettingsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { BaseMathType, PropertyFilterType, PropertyMathType, PropertyOperator, TeamType } from '~/types'
+
+import type { ConversionRecommendationApi } from '../generated/api.schemas'
+import { conversionGoalFormLogic } from './conversionGoalFormLogic'
+import { conversionRecommendationsLogic } from './conversionRecommendationsLogic'
+import { recommendationToGoal } from './recommendationToGoal'
+
+const recommendation: ConversionRecommendationApi = {
+ source_ref: 'event:order_settled',
+ name: 'Settled orders',
+ reason: 'This event may record completed payments.',
+ intent: 'revenue',
+ amount_property: 'order_value',
+ questions: ['Does this exclude refunds and duplicate transactions?'],
+ candidate: {
+ source_ref: 'event:order_settled',
+ name: 'order_settled',
+ kind: 'EventsNode',
+ event: 'order_settled',
+ numeric_properties: ['order_value'],
+ },
+}
+
+describe('conversion goal drafts', () => {
+ beforeEach(() => {
+ useMocks({})
+ initKeaTests()
+ })
+
+ it.each([
+ [
+ recommendation,
+ {
+ kind: NodeKind.EventsNode,
+ event: 'order_settled',
+ math: PropertyMathType.Sum,
+ math_property: 'order_value',
+ counts_as_revenue: true,
+ counts_as_customer: false,
+ },
+ ],
+ [
+ {
+ ...recommendation,
+ intent: 'customer',
+ amount_property: null,
+ candidate: { source_ref: 'action:42', kind: 'ActionsNode', action_id: 42, name: 'Qualified requests' },
+ },
+ {
+ kind: NodeKind.ActionsNode,
+ id: 42,
+ math: BaseMathType.TotalCount,
+ counts_as_revenue: false,
+ counts_as_customer: true,
+ },
+ ],
+ [
+ { ...recommendation, intent: 'conversion', amount_property: null },
+ { math: BaseMathType.TotalCount, counts_as_revenue: false, counts_as_customer: false },
+ ],
+ ] as const)('preserves the source and measurement for %j', (suggestion, expected) => {
+ const goal = recommendationToGoal(suggestion)
+ expect(goal).toMatchObject(expected)
+ if (goal.kind === NodeKind.ActionsNode) {
+ expect(goal).not.toHaveProperty('event')
+ }
+ })
+
+ it('prefills without saving, submits only once, and preserves a failed draft for retry', async () => {
+ const logic = conversionGoalFormLogic({ projectId: teamLogic.values.currentTeamId! })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const originalGoals = marketingAnalyticsSettingsLogic.values.conversion_goals
+ let release!: () => void
+ let responseReady = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ let status = 500
+ const writes: Partial<TeamType>[] = []
+ useMocks({
+ patch: {
+ '/api/environments/:team_id': async ({ request }) => {
+ const payload = (await request.json()) as Partial<TeamType>
+ writes.push(payload)
+ await responseReady
+ return [status, { ...teamLogic.values.currentTeam, ...payload }]
+ },
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.selectRecommendation(recommendation)).toFinishAllListeners()
+ expect(writes).toHaveLength(0)
+ expect(marketingAnalyticsSettingsLogic.values.conversion_goals).toEqual(originalGoals)
+ expect(logic.values.filter).toMatchObject({ event: 'order_settled', math_property: 'order_value' })
+ expect(logic.values.name).toBe('Settled orders')
+ expect(logic.values.recommendation?.questions).toEqual(recommendation.questions)
+
+ logic.actions.setName('Reviewed payments')
+ logic.actions.setFilter({ ...logic.values.filter, counts_as_customer: true })
+ logic.actions.saveGoal()
+ logic.actions.saveGoal()
+ expect(logic.values.isSaving).toBe(true)
+ release()
+ await expectLogic(teamLogic).toFinishAllListeners()
+ expect(writes).toHaveLength(1)
+ expect(logic.values.isSaving).toBe(false)
+ expect(logic.values.saveError).toBeTruthy()
+ expect(logic.values.name).toBe('Reviewed payments')
+ const goalId = logic.values.filter.conversion_goal_id
+ expect(goalId).toBeTruthy()
+
+ status = 200
+ responseReady = Promise.resolve()
+ await expectLogic(logic, () => logic.actions.saveGoal()).toFinishAllListeners()
+ await expectLogic(teamLogic).toFinishAllListeners()
+ expect(writes).toHaveLength(2)
+ expect(
+ writes[1].marketing_analytics_config?.conversion_goals?.filter((goal) => goal.conversion_goal_id === goalId)
+ ).toEqual([
+ expect.objectContaining({
+ conversion_goal_name: 'Reviewed payments',
+ math: PropertyMathType.Sum,
+ math_property: 'order_value',
+ counts_as_revenue: true,
+ counts_as_customer: true,
+ }),
+ ])
+ expect(logic.values.isSaving).toBe(false)
+ expect(logic.values.saveError).toBeNull()
+ expect(logic.values.isFormValid).toBe(false)
+ expect(logic.values.recommendation).toBeNull()
+ expect(logic.values.findExistingGoal(recommendation)?.conversion_goal_id).toBe(goalId)
+ const recommendations = conversionRecommendationsLogic({
+ projectId: teamLogic.values.currentTeamId!,
+ enabled: false,
+ })
+ recommendations.mount()
+ const run = {
+ id: 'scan',
+ status: 'completed' as const,
+ lookback_days: 30,
+ date_from: '2026-01-01',
+ date_to: '2026-01-31',
+ created_at: '2026-01-31',
+ completed_at: '2026-01-31',
+ error: '',
+ }
+ recommendations.actions.loadRecommendationsSuccess({
+ latest_run: run,
+ result_run: run,
+ results: { recommendations: [recommendation] },
+ can_generate: true,
+ generation_disabled_reason: null,
+ })
+ expect(recommendations.values.pendingRecommendations).toEqual([])
+ expect(recommendations.values.allRecommendationsConfigured).toBe(true)
+ recommendations.unmount()
+ logic.unmount()
+ })
+
+ it.each(
+ [false, true].flatMap((staleDraft) => [
+ { staleDraft, changes: {} },
+ { staleDraft, changes: { counts_as_customer: true } },
+ { staleDraft, changes: { math: PropertyMathType.Average, counts_as_revenue: false } },
+ {
+ staleDraft,
+ changes: {
+ properties: [
+ {
+ key: 'status',
+ value: 'paid',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event as const,
+ },
+ ],
+ },
+ },
+ ])
+ )('reviews a configured source without creating a duplicate: %j', async ({ staleDraft, changes }) => {
+ const logic = conversionGoalFormLogic({ projectId: teamLogic.values.currentTeamId! })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const existing = {
+ ...recommendationToGoal(recommendation),
+ conversion_goal_id: 'saved-payments',
+ conversion_goal_name: 'Reviewed payments',
+ ...changes,
+ }
+ const writes: Partial<TeamType>[] = []
+ useMocks({
+ patch: {
+ '/api/environments/:team_id': async ({ request }) => {
+ const payload = (await request.json()) as Partial<TeamType>
+ writes.push(payload)
+ return [200, { ...teamLogic.values.currentTeam, ...payload }]
+ },
+ },
+ })
+ if (staleDraft) {
+ logic.actions.selectRecommendation(recommendation)
+ }
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...teamLogic.values.currentTeam!,
+ marketing_analytics_config: { conversion_goals: [existing] },
+ })
+ expect(logic.values.findExistingGoal(recommendation)).toEqual(existing)
+ if (staleDraft) {
+ logic.actions.saveGoal()
+ } else {
+ logic.actions.selectRecommendation(recommendation)
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ expect(writes).toHaveLength(0)
+ expect(logic.values.filter).toEqual(existing)
+ expect(logic.values.name).toBe('Reviewed payments')
+ expect(logic.values.editingGoalId).toBe(existing.conversion_goal_id)
+ expect(logic.values.duplicateGoal).toBeNull()
+
+ logic.actions.setName('Confirmed payments')
+ await expectLogic(logic, () => logic.actions.saveGoal()).toFinishAllListeners()
+ await expectLogic(teamLogic).toFinishAllListeners()
+ expect(writes).toHaveLength(1)
+ expect(writes[0].marketing_analytics_config?.conversion_goals).toEqual([
+ { ...existing, conversion_goal_name: 'Confirmed payments' },
+ ])
+ expect(logic.values.editingGoalId).toBeNull()
+ logic.unmount()
+ })
+
+ it('keeps drafts separate and rejects saving a draft for a different project', async () => {
+ const projectId = teamLogic.values.currentTeamId!
+ const current = conversionGoalFormLogic({ projectId })
+ const other = conversionGoalFormLogic({ projectId: projectId + 1 })
+ current.mount()
+ other.mount()
+ await expectLogic(current).toFinishAllListeners()
+ current.actions.selectRecommendation(recommendation)
+ expect(other.values.isFormValid).toBe(false)
+ other.actions.selectRecommendation(recommendation)
+ await expectLogic(other, () => other.actions.saveGoal()).toNotHaveDispatchedActions(['saveStarted'])
+ expect(other.values.isSaving).toBe(false)
+ expect(other.values.configuredGoals).toEqual([])
+ expect(other.values.findExistingGoal(recommendation)).toBeUndefined()
+ current.unmount()
+ other.unmount()
+ })
+})
diff --git a/products/marketing_analytics/frontend/setup/conversionGoalFormLogic.ts b/products/marketing_analytics/frontend/setup/conversionGoalFormLogic.ts
new file mode 100644
index 000000000000..0d7f1ea4a78f
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/conversionGoalFormLogic.ts
@@ -0,0 +1,317 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+
+import { uuid } from 'lib/utils/dom'
+import { teamLogic } from 'scenes/teamLogic'
+import { defaultConversionGoalFilter } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/constants'
+import { withValidFlags } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/conversionGoalFlags'
+import { marketingAnalyticsSettingsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic'
+
+import { ConversionGoalFilter, NodeKind } from '~/queries/schema/schema-general'
+import { TeamPublicType, TeamType } from '~/types'
+
+import type { ConversionRecommendationApi } from '../generated/api.schemas'
+import { findConversionGoalForSource, findEquivalentConversionGoal } from './findEquivalentConversionGoal'
+import { recommendationToGoal } from './recommendationToGoal'
+
+export interface ConversionGoalFormLogicProps {
+ projectId: number
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface conversionGoalFormLogicValues {
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
+ currentTeamId: number | null // teamLogic
+ currentTeamLoading: boolean // teamLogic
+ configuredGoals: ConversionGoalFilter[]
+ duplicateGoal: ConversionGoalFilter | null
+ editingGoalId: string | null
+ filter: ConversionGoalFilter
+ findExistingGoal: (recommendation: ConversionRecommendationApi) => ConversionGoalFilter | undefined
+ formFocusRequested: boolean
+ isFormValid: boolean
+ isSaving: boolean
+ name: string
+ recommendation: ConversionRecommendationApi | null
+ saveError: string | null
+ savingGoalId: string | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface conversionGoalFormLogicActions {
+ addOrUpdateConversionGoal: (conversionGoal: ConversionGoalFilter) => {
+ conversionGoal: ConversionGoalFilter
+ } // marketingAnalyticsSettingsLogic
+ clearDraft: () => {
+ value: true
+ }
+ formFocused: () => {
+ value: true
+ }
+ requestFormFocus: () => {
+ value: true
+ }
+ reviewGoal: (goalId: string) => {
+ goalId: string
+ }
+ saveFinished: (error: string | null) => {
+ error: string | null
+ }
+ saveGoal: () => {
+ value: true
+ }
+ saveStarted: (goal: ConversionGoalFilter) => {
+ goal: ConversionGoalFilter
+ }
+ selectRecommendation: (recommendation: ConversionRecommendationApi) => {
+ recommendation: ConversionRecommendationApi
+ }
+ setDraft: (
+ filter: ConversionGoalFilter,
+ recommendation: ConversionRecommendationApi | null,
+ editing?: boolean
+ ) => {
+ editing: boolean
+ filter: ConversionGoalFilter
+ recommendation: ConversionRecommendationApi | null
+ }
+ setFilter: (filter: ConversionGoalFilter) => {
+ filter: ConversionGoalFilter
+ }
+ setName: (name: string) => {
+ name: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface conversionGoalFormLogicMeta {
+ key: number
+ __keaTypeGenInternalSelectorTypes: {
+ configuredGoals: (currentTeam: TeamPublicType | TeamType | null) => ConversionGoalFilter[]
+ findExistingGoal: (
+ configuredGoals: ConversionGoalFilter[]
+ ) => (recommendation: ConversionRecommendationApi) => ConversionGoalFilter | undefined
+ duplicateGoal: (
+ configuredGoals: ConversionGoalFilter[],
+ filter: ConversionGoalFilter,
+ editingGoalId: string | null
+ ) => ConversionGoalFilter | null
+ isFormValid: (filter: ConversionGoalFilter) => boolean
+ isSaving: (savingGoalId: string | null) => boolean
+ }
+}
+
+export type conversionGoalFormLogicType = MakeLogicType<
+ conversionGoalFormLogicValues,
+ conversionGoalFormLogicActions,
+ ConversionGoalFormLogicProps,
+ conversionGoalFormLogicMeta
+>
+
+export const conversionGoalFormLogic: LogicWrapper<conversionGoalFormLogicType> = kea<conversionGoalFormLogicType>([
+ props({} as ConversionGoalFormLogicProps),
+ key(({ projectId }: ConversionGoalFormLogicProps) => projectId),
+ path((key) => ['products', 'marketing_analytics', 'setup', 'conversionGoalFormLogic', key]),
+ connect(() => ({
+ values: [teamLogic, ['currentTeam', 'currentTeamId', 'currentTeamLoading']],
+ actions: [marketingAnalyticsSettingsLogic, ['addOrUpdateConversionGoal']],
+ })),
+ actions({
+ selectRecommendation: (recommendation: ConversionRecommendationApi) => ({ recommendation }),
+ setDraft: (
+ filter: ConversionGoalFilter,
+ recommendation: ConversionRecommendationApi | null,
+ editing: boolean = false
+ ) => ({
+ filter,
+ recommendation,
+ editing,
+ }),
+ reviewGoal: (goalId: string) => ({ goalId }),
+ setName: (name: string) => ({ name }),
+ setFilter: (filter: ConversionGoalFilter) => ({ filter }),
+ clearDraft: true,
+ requestFormFocus: true,
+ formFocused: true,
+ saveGoal: true,
+ saveStarted: (goal: ConversionGoalFilter) => ({ goal }),
+ saveFinished: (error: string | null) => ({ error }),
+ }),
+ reducers({
+ formFocusRequested: [
+ false,
+ {
+ requestFormFocus: () => true,
+ setDraft: () => true,
+ formFocused: () => false,
+ clearDraft: () => false,
+ },
+ ],
+ filter: [
+ defaultConversionGoalFilter,
+ {
+ setDraft: (_, { filter }) => filter,
+ setFilter: (_, { filter }) => filter,
+ saveStarted: (_, { goal }) => goal,
+ clearDraft: () => defaultConversionGoalFilter,
+ },
+ ],
+ name: [
+ '',
+ {
+ setDraft: (_, { filter }) => filter.conversion_goal_name,
+ setName: (_, { name }) => name,
+ clearDraft: () => '',
+ },
+ ],
+ recommendation: [
+ null as ConversionRecommendationApi | null,
+ {
+ setDraft: (_, { recommendation }) => recommendation,
+ clearDraft: () => null,
+ },
+ ],
+ editingGoalId: [
+ null as string | null,
+ {
+ setDraft: (_, { filter, editing }) => (editing ? filter.conversion_goal_id : null),
+ clearDraft: () => null,
+ },
+ ],
+ savingGoalId: [
+ null as string | null,
+ {
+ saveStarted: (_, { goal }) => goal.conversion_goal_id,
+ saveFinished: () => null,
+ },
+ ],
+ saveError: [
+ null as string | null,
+ {
+ saveFinished: (_, { error }) => error,
+ saveStarted: () => null,
+ setDraft: () => null,
+ clearDraft: () => null,
+ },
+ ],
+ }),
+ selectors(({ props }) => ({
+ configuredGoals: [
+ (s) => [s.currentTeam],
+ (currentTeam: TeamType | TeamPublicType | null): ConversionGoalFilter[] =>
+ currentTeam?.id === props.projectId
+ ? (currentTeam.marketing_analytics_config?.conversion_goals ?? [])
+ : [],
+ ],
+ findExistingGoal: [
+ (s) => [s.configuredGoals],
+ (
+ goals: ConversionGoalFilter[]
+ ): ((recommendation: ConversionRecommendationApi) => ConversionGoalFilter | undefined) =>
+ (recommendation) => {
+ const candidate = recommendationToGoal(recommendation)
+ return (
+ findEquivalentConversionGoal(goals, candidate) ?? findConversionGoalForSource(goals, candidate)
+ )
+ },
+ ],
+ duplicateGoal: [
+ (s) => [s.configuredGoals, s.filter, s.editingGoalId],
+ (
+ goals: ConversionGoalFilter[],
+ filter: ConversionGoalFilter,
+ editingGoalId: string | null
+ ): ConversionGoalFilter | null =>
+ findEquivalentConversionGoal(
+ goals.filter((goal) => goal.conversion_goal_id !== editingGoalId),
+ withValidFlags(filter)
+ ) ?? null,
+ ],
+ isFormValid: [
+ (s) => [s.filter],
+ (filter: ConversionGoalFilter): boolean =>
+ filter.kind === NodeKind.EventsNode
+ ? !!filter.event
+ : filter.kind === NodeKind.ActionsNode
+ ? !!filter.id
+ : !!filter.table_name,
+ ],
+ isSaving: [(s) => [s.savingGoalId], (savingGoalId: string | null): boolean => savingGoalId !== null],
+ })),
+ listeners(({ actions, values, props }) => ({
+ selectRecommendation: ({ recommendation }) => {
+ if (!values.isSaving && !values.currentTeamLoading && values.currentTeamId === props.projectId) {
+ const existingGoal = values.findExistingGoal(recommendation)
+ actions.setDraft(existingGoal ?? recommendationToGoal(recommendation), recommendation, !!existingGoal)
+ }
+ },
+ reviewGoal: ({ goalId }) => {
+ const goal = values.configuredGoals.find((goal) => goal.conversion_goal_id === goalId)
+ if (goal && !values.isSaving && !values.currentTeamLoading) {
+ actions.setDraft(goal, values.recommendation, true)
+ }
+ },
+ saveGoal: () => {
+ if (
+ !values.isFormValid ||
+ values.isSaving ||
+ values.currentTeamLoading ||
+ values.currentTeamId !== props.projectId
+ ) {
+ return
+ }
+ const configuredSuggestion =
+ values.recommendation && !values.editingGoalId
+ ? findConversionGoalForSource(values.configuredGoals, values.filter)
+ : undefined
+ const existingGoal = values.duplicateGoal ?? configuredSuggestion
+ if (existingGoal) {
+ actions.reviewGoal(existingGoal.conversion_goal_id)
+ return
+ }
+ if (
+ values.editingGoalId &&
+ !values.configuredGoals.some((goal) => goal.conversion_goal_id === values.editingGoalId)
+ ) {
+ actions.saveFinished('This conversion goal was removed. Clear the form to configure a new goal.')
+ return
+ }
+ const goal = withValidFlags({
+ ...values.filter,
+ conversion_goal_id: values.filter.conversion_goal_id || uuid(),
+ conversion_goal_name:
+ values.name.trim() || values.filter.custom_name || values.filter.name || 'No name',
+ })
+ actions.saveStarted(goal)
+ actions.addOrUpdateConversionGoal(goal)
+ },
+ [teamLogic.actionTypes.updateCurrentTeamSuccess]: ({ currentTeam, payload }) => {
+ if (
+ currentTeam.id === props.projectId &&
+ values.savingGoalId &&
+ payload?.marketing_analytics_config?.conversion_goals?.some(
+ (goal: ConversionGoalFilter) => goal.conversion_goal_id === values.savingGoalId
+ )
+ ) {
+ actions.saveFinished(null)
+ actions.clearDraft()
+ }
+ },
+ [teamLogic.actionTypes.updateCurrentTeamFailure]: () => {
+ if (values.isSaving) {
+ actions.saveFinished('Could not save this conversion goal. Review the settings and try again.')
+ }
+ },
+ })),
+])
diff --git a/products/marketing_analytics/frontend/setup/conversionRecommendationsLogic.test.ts b/products/marketing_analytics/frontend/setup/conversionRecommendationsLogic.test.ts
new file mode 100644
index 000000000000..9df6e219bc9f
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/conversionRecommendationsLogic.test.ts
@@ -0,0 +1,123 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import * as api from '../generated/api'
+import type { ConversionRecommendationStateApi } from '../generated/api.schemas'
+import { conversionRecommendationsLogic } from './conversionRecommendationsLogic'
+
+jest.mock('../generated/api', () => ({
+ ...jest.requireActual('../generated/api'),
+ marketingAnalyticsConversionRecommendationsRetrieve: jest.fn(),
+ marketingAnalyticsConversionRecommendationsStartCreate: jest.fn(),
+}))
+
+const empty: ConversionRecommendationStateApi = {
+ latest_run: null,
+ result_run: null,
+ results: { recommendations: [], limitations: [] },
+ can_generate: true,
+ generation_disabled_reason: null,
+}
+const run = {
+ id: 'analysis',
+ status: 'completed' as const,
+ lookback_days: 30,
+ date_from: '2026-01-01',
+ date_to: '2026-01-31',
+ created_at: '2026-01-31',
+ completed_at: '2026-01-31',
+ error: '',
+}
+const complete: ConversionRecommendationStateApi = { ...empty, latest_run: run, result_run: run }
+
+describe('conversion recommendation lifecycle', () => {
+ beforeEach(() => {
+ useMocks({})
+ initKeaTests()
+ jest.clearAllMocks()
+ })
+
+ it('starts once automatically and only updates after an explicit action', async () => {
+ jest.mocked(api.marketingAnalyticsConversionRecommendationsRetrieve)
+ .mockResolvedValueOnce(empty)
+ .mockResolvedValue(complete)
+ jest.mocked(api.marketingAnalyticsConversionRecommendationsStartCreate).mockResolvedValue(complete)
+ const logic = conversionRecommendationsLogic({ projectId: 17, enabled: true, userId: 'reader' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(api.marketingAnalyticsConversionRecommendationsStartCreate).toHaveBeenCalledTimes(1)
+ expect(api.marketingAnalyticsConversionRecommendationsStartCreate).toHaveBeenLastCalledWith('17', {
+ refresh: false,
+ })
+ await expectLogic(logic, () => logic.actions.loadRecommendations()).toFinishAllListeners()
+ expect(api.marketingAnalyticsConversionRecommendationsStartCreate).toHaveBeenCalledTimes(1)
+ await expectLogic(logic, () => logic.actions.requestAnalysis(true)).toFinishAllListeners()
+ expect(api.marketingAnalyticsConversionRecommendationsStartCreate).toHaveBeenLastCalledWith('17', {
+ refresh: true,
+ })
+ logic.unmount()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(api.marketingAnalyticsConversionRecommendationsStartCreate).toHaveBeenCalledTimes(2)
+ logic.unmount()
+ })
+
+ it('preserves previous results and blocks duplicate update clicks while the request is in flight', async () => {
+ jest.mocked(api.marketingAnalyticsConversionRecommendationsRetrieve).mockResolvedValue(complete)
+ let resolve!: (state: ConversionRecommendationStateApi) => void
+ jest.mocked(api.marketingAnalyticsConversionRecommendationsStartCreate).mockReturnValue(
+ new Promise((done) => {
+ resolve = done
+ })
+ )
+ const logic = conversionRecommendationsLogic({ projectId: 17, enabled: true, userId: 'reader' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.requestAnalysis(true)
+ logic.actions.requestAnalysis(true)
+ expect(api.marketingAnalyticsConversionRecommendationsStartCreate).toHaveBeenCalledTimes(1)
+ expect(logic.values.state?.result_run).toEqual(run)
+ resolve({
+ ...complete,
+ latest_run: { ...run, id: 'update', status: 'failed', lookback_days: 14, error: 'Retry the analysis.' },
+ })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.state?.result_run).toEqual(run)
+ expect(logic.values.state?.latest_run?.status).toBe('failed')
+ expect(api.marketingAnalyticsConversionRecommendationsStartCreate).toHaveBeenCalledTimes(1)
+ logic.unmount()
+ })
+
+ it.each(['loadRecommendationsSuccess', 'startAnalysisSuccess'] as const)(
+ 'starts the cooldown at 60 minutes when %s receives a newly completed scan',
+ async (successAction) => {
+ const now = jest.spyOn(Date, 'now').mockReturnValue(0)
+ const logic = conversionRecommendationsLogic({ projectId: 17, enabled: false, userId: 'reader' })
+ logic.mount()
+ try {
+ now.mockReturnValue(5000)
+ const completedRun = { ...run, completed_at: new Date(5000).toISOString() }
+ logic.actions[successAction]({ ...complete, latest_run: completedRun, result_run: completedRun })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.scanDisabledReason).toBe('You can scan again in 60 minutes.')
+ } finally {
+ logic.unmount()
+ now.mockRestore()
+ }
+ }
+ )
+
+ it('does not query when disabled and keeps another project or reader in a separate state', async () => {
+ const disabled = conversionRecommendationsLogic({ projectId: 17, enabled: false, userId: 'reader' })
+ disabled.mount()
+ await expectLogic(disabled).toFinishAllListeners()
+ expect(api.marketingAnalyticsConversionRecommendationsRetrieve).not.toHaveBeenCalled()
+ const other = conversionRecommendationsLogic({ projectId: 18, enabled: false, userId: 'reader' })
+ const otherReader = conversionRecommendationsLogic({ projectId: 17, enabled: false, userId: 'another-reader' })
+ expect(other.key).not.toBe(disabled.key)
+ expect(otherReader.key).not.toBe(disabled.key)
+ disabled.unmount()
+ })
+})
diff --git a/products/marketing_analytics/frontend/setup/conversionRecommendationsLogic.ts b/products/marketing_analytics/frontend/setup/conversionRecommendationsLogic.ts
new file mode 100644
index 000000000000..a08db63502de
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/conversionRecommendationsLogic.ts
@@ -0,0 +1,332 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { dayjs } from 'lib/dayjs'
+
+import type { ConversionGoalFilter } from '~/queries/schema/schema-general'
+
+import * as api from '../generated/api'
+import type { ConversionRecommendationApi, ConversionRecommendationStateApi } from '../generated/api.schemas'
+import { conversionGoalFormLogic } from './conversionGoalFormLogic'
+
+export interface ConversionRecommendationsProps {
+ projectId: number
+ enabled: boolean
+ userId?: string
+}
+
+type DismissedRecommendation = Pick<ConversionRecommendationApi, 'source_ref' | 'name'>
+
+const POLL_INTERVAL_MS = 5000
+const SCAN_COOLDOWN_MS = 60 * 60 * 1000
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface conversionRecommendationsLogicValues {
+ findExistingGoal: (recommendation: ConversionRecommendationApi) => ConversionGoalFilter | undefined // conversionGoalFormLogic
+ allRecommendationsConfigured: boolean
+ allRecommendationsHandled: boolean
+ dismissedRecommendationEntries: DismissedRecommendation[]
+ dismissedRecommendations: Record<string, DismissedRecommendation>
+ error: string | null
+ isAnalyzing: boolean
+ pendingRecommendations: ConversionRecommendationApi[]
+ scanClock: number
+ scanCooldownRemaining: number
+ scanDisabledReason: string | null
+ state: ConversionRecommendationStateApi | null
+ stateLoading: boolean
+ unconfiguredRecommendations: ConversionRecommendationApi[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface conversionRecommendationsLogicActions {
+ dismissRecommendation: (recommendation: ConversionRecommendationApi) => {
+ recommendation: ConversionRecommendationApi
+ }
+ loadRecommendations: (_: void) => void
+ loadRecommendationsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadRecommendationsSuccess: (
+ state: ConversionRecommendationStateApi,
+ payload?: void
+ ) => {
+ state: ConversionRecommendationStateApi
+ payload?: void
+ }
+ requestAnalysis: (refresh: boolean) => {
+ refresh: boolean
+ }
+ restoreRecommendation: (sourceRef: string) => {
+ sourceRef: string
+ }
+ setScanClock: (now: number) => {
+ now: number
+ }
+ startAnalysis: ({ refresh }: { refresh: boolean }) => {
+ refresh: boolean
+ }
+ startAnalysisFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ startAnalysisSuccess: (
+ state: ConversionRecommendationStateApi,
+ payload?: {
+ refresh: boolean
+ }
+ ) => {
+ state: ConversionRecommendationStateApi
+ payload?: {
+ refresh: boolean
+ }
+ }
+ syncPolling: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface conversionRecommendationsLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ scanCooldownRemaining: (state: ConversionRecommendationStateApi | null, scanClock: number) => number
+ scanDisabledReason: (
+ state: ConversionRecommendationStateApi | null,
+ scanCooldownRemaining: number
+ ) => string | null
+ unconfiguredRecommendations: (
+ state: ConversionRecommendationStateApi | null,
+ findExistingGoal: (recommendation: ConversionRecommendationApi) => ConversionGoalFilter | undefined // conversionGoalFormLogic
+ ) => ConversionRecommendationApi[]
+ pendingRecommendations: (
+ unconfiguredRecommendations: ConversionRecommendationApi[],
+ dismissedRecommendations: Record<string, DismissedRecommendation>
+ ) => ConversionRecommendationApi[]
+ dismissedRecommendationEntries: (
+ dismissedRecommendations: Record<string, DismissedRecommendation>
+ ) => DismissedRecommendation[]
+ allRecommendationsHandled: (
+ state: ConversionRecommendationStateApi | null,
+ pendingRecommendations: ConversionRecommendationApi[]
+ ) => boolean
+ allRecommendationsConfigured: (
+ state: ConversionRecommendationStateApi | null,
+ unconfiguredRecommendations: ConversionRecommendationApi[]
+ ) => boolean
+ isAnalyzing: (state: ConversionRecommendationStateApi | null) => boolean
+ }
+}
+
+export type conversionRecommendationsLogicType = MakeLogicType<
+ conversionRecommendationsLogicValues,
+ conversionRecommendationsLogicActions,
+ ConversionRecommendationsProps,
+ conversionRecommendationsLogicMeta
+>
+
+export const conversionRecommendationsLogic: LogicWrapper<conversionRecommendationsLogicType> =
+ kea<conversionRecommendationsLogicType>([
+ props({} as ConversionRecommendationsProps),
+ key(({ projectId, enabled, userId }) => `${userId}:${projectId}:${enabled}`),
+ path((key) => ['products', 'marketing_analytics', 'setup', 'conversionRecommendationsLogic', key]),
+ connect(({ projectId }: ConversionRecommendationsProps) => ({
+ values: [conversionGoalFormLogic({ projectId }), ['findExistingGoal']],
+ })),
+ actions({
+ requestAnalysis: (refresh: boolean) => ({ refresh }),
+ dismissRecommendation: (recommendation: ConversionRecommendationApi) => ({ recommendation }),
+ restoreRecommendation: (sourceRef: string) => ({ sourceRef }),
+ syncPolling: true,
+ setScanClock: (now: number) => ({ now }),
+ }),
+ loaders(({ props }) => ({
+ state: [
+ null as ConversionRecommendationStateApi | null,
+ {
+ loadRecommendations: async (_: void, breakpoint) => {
+ const state = await api.marketingAnalyticsConversionRecommendationsRetrieve(
+ String(props.projectId)
+ )
+ breakpoint()
+ return state
+ },
+ startAnalysis: async ({ refresh }: { refresh: boolean }, breakpoint) => {
+ const state = await api.marketingAnalyticsConversionRecommendationsStartCreate(
+ String(props.projectId),
+ { refresh }
+ )
+ breakpoint()
+ return state
+ },
+ },
+ ],
+ })),
+ reducers(({ props }) => ({
+ dismissedRecommendations: [
+ {} as Record<string, DismissedRecommendation>,
+ { persist: true, prefix: `${props.userId}:${props.projectId}__` },
+ {
+ dismissRecommendation: (state, { recommendation }) => ({
+ ...state,
+ [recommendation.source_ref]: {
+ source_ref: recommendation.source_ref,
+ name: recommendation.name,
+ },
+ }),
+ restoreRecommendation: (state, { sourceRef }) => {
+ const next = { ...state }
+ delete next[sourceRef]
+ return next
+ },
+ },
+ ],
+ scanClock: [
+ Date.now(),
+ {
+ setScanClock: (_, { now }) => now,
+ loadRecommendationsSuccess: () => Date.now(),
+ startAnalysisSuccess: () => Date.now(),
+ },
+ ],
+ error: [
+ null as string | null,
+ {
+ loadRecommendationsSuccess: () => null,
+ startAnalysisSuccess: () => null,
+ loadRecommendationsFailure: () =>
+ 'Could not load recommendations. Retry loading to check the latest results.',
+ startAnalysisFailure: () =>
+ 'Could not confirm the analysis started. Reload its status before trying again.',
+ },
+ ],
+ })),
+ selectors({
+ scanCooldownRemaining: [
+ (s) => [s.state, s.scanClock],
+ (state: ConversionRecommendationStateApi | null, scanClock: number): number => {
+ if (state?.latest_run?.status !== 'completed') {
+ return 0
+ }
+ const availableAt =
+ dayjs(state.latest_run.completed_at ?? state.latest_run.created_at).valueOf() + SCAN_COOLDOWN_MS
+ return Math.max(0, Math.ceil((availableAt - scanClock) / 60_000))
+ },
+ ],
+ scanDisabledReason: [
+ (s) => [s.state, s.scanCooldownRemaining],
+ (state: ConversionRecommendationStateApi | null, scanCooldownRemaining: number): string | null => {
+ if (!state?.can_generate) {
+ return state?.generation_disabled_reason ?? 'Project admin access is required to scan events.'
+ }
+ return scanCooldownRemaining > 0
+ ? `You can scan again in ${scanCooldownRemaining} ${scanCooldownRemaining === 1 ? 'minute' : 'minutes'}.`
+ : null
+ },
+ ],
+ unconfiguredRecommendations: [
+ (s) => [s.state, s.findExistingGoal],
+ (
+ state: ConversionRecommendationStateApi | null,
+ findExistingGoal: (recommendation: ConversionRecommendationApi) => ConversionGoalFilter | undefined
+ ): ConversionRecommendationApi[] =>
+ (state?.results.recommendations ?? []).filter(
+ (recommendation) => !findExistingGoal(recommendation)
+ ),
+ ],
+ pendingRecommendations: [
+ (s) => [s.unconfiguredRecommendations, s.dismissedRecommendations],
+ (
+ recommendations: ConversionRecommendationApi[],
+ dismissed: Record<string, DismissedRecommendation>
+ ): ConversionRecommendationApi[] =>
+ recommendations.filter((recommendation) => !dismissed[recommendation.source_ref]),
+ ],
+ dismissedRecommendationEntries: [
+ (s) => [s.dismissedRecommendations],
+ (dismissed: Record<string, DismissedRecommendation>): DismissedRecommendation[] =>
+ Object.values(dismissed),
+ ],
+ allRecommendationsHandled: [
+ (s) => [s.state, s.pendingRecommendations],
+ (state: ConversionRecommendationStateApi | null, pending: ConversionRecommendationApi[]): boolean =>
+ !!state?.result_run && pending.length === 0,
+ ],
+ allRecommendationsConfigured: [
+ (s) => [s.state, s.unconfiguredRecommendations],
+ (
+ state: ConversionRecommendationStateApi | null,
+ pendingRecommendations: ConversionRecommendationApi[]
+ ): boolean =>
+ !!state?.result_run &&
+ !!state.results.recommendations?.length &&
+ pendingRecommendations.length === 0,
+ ],
+ isAnalyzing: [
+ (s) => [s.state],
+ (state: ConversionRecommendationStateApi | null): boolean =>
+ state?.latest_run?.status === 'pending' || state?.latest_run?.status === 'running',
+ ],
+ }),
+ listeners(({ actions, values, cache, props }) => ({
+ requestAnalysis: ({ refresh }) => {
+ actions.setScanClock(Date.now())
+ if (props.enabled && !values.scanDisabledReason && !values.stateLoading && !values.isAnalyzing) {
+ actions.startAnalysis({ refresh })
+ }
+ },
+ loadRecommendationsSuccess: ({ state }) => {
+ if (!state.latest_run && state.can_generate && !cache.initialAttempted) {
+ cache.initialAttempted = true
+ actions.requestAnalysis(false)
+ }
+ actions.syncPolling()
+ },
+ startAnalysisSuccess: () => actions.syncPolling(),
+ loadRecommendationsFailure: () => cache.disposables.dispose('analysisPoll'),
+ startAnalysisFailure: () => cache.disposables.dispose('analysisPoll'),
+ syncPolling: () => {
+ cache.disposables.dispose('analysisPoll')
+ if (values.isAnalyzing) {
+ cache.disposables.add(() => {
+ const timer = setInterval(() => {
+ if (!values.stateLoading) {
+ actions.loadRecommendations()
+ }
+ }, POLL_INTERVAL_MS)
+ return () => clearInterval(timer)
+ }, 'analysisPoll')
+ }
+ },
+ })),
+ afterMount(({ actions, props, cache }) => {
+ if (props.enabled && props.projectId > 0) {
+ cache.disposables.add(() => {
+ actions.setScanClock(Date.now())
+ const timer = setInterval(() => actions.setScanClock(Date.now()), 30_000)
+ return () => clearInterval(timer)
+ }, 'scanClock')
+ actions.loadRecommendations()
+ }
+ }),
+ ])
diff --git a/products/marketing_analytics/frontend/setup/dashboardSetupPromptsLogic.ts b/products/marketing_analytics/frontend/setup/dashboardSetupPromptsLogic.ts
new file mode 100644
index 000000000000..9e483f5ecb33
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/dashboardSetupPromptsLogic.ts
@@ -0,0 +1,69 @@
+import { MakeLogicType, actions, kea, key, listeners, path, props, reducers } from 'kea'
+
+import { LemonDialog } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+import {
+ MarketingAnalyticsTab,
+ SetupSection,
+ marketingAnalyticsLogic,
+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+
+export type DashboardSetupPromptKind = 'sources' | 'conversion-goals'
+
+interface DashboardSetupPromptsProps {
+ projectId: number
+ userId?: string
+}
+
+export const dashboardSetupPromptsLogic = kea<
+ MakeLogicType<
+ { dismissed: Record<DashboardSetupPromptKind, boolean> },
+ {
+ dismiss: (kind: DashboardSetupPromptKind) => { kind: DashboardSetupPromptKind }
+ restore: (kind: DashboardSetupPromptKind) => { kind: DashboardSetupPromptKind }
+ openSetup: (kind: DashboardSetupPromptKind) => { kind: DashboardSetupPromptKind }
+ },
+ DashboardSetupPromptsProps
+ >
+>([
+ props({} as DashboardSetupPromptsProps),
+ key(({ projectId, userId }) => `${userId}:${projectId}`),
+ path((key) => ['products', 'marketing_analytics', 'setup', 'dashboardSetupPromptsLogic', key]),
+ actions({
+ dismiss: (kind: DashboardSetupPromptKind) => ({ kind }),
+ restore: (kind: DashboardSetupPromptKind) => ({ kind }),
+ openSetup: (kind: DashboardSetupPromptKind) => ({ kind }),
+ }),
+ reducers(({ props }) => ({
+ dismissed: [
+ { sources: false, 'conversion-goals': false },
+ { persist: true, prefix: `${props.userId}:${props.projectId}__` },
+ {
+ dismiss: (state, { kind }) => ({ ...state, [kind]: true }),
+ restore: (state, { kind }) => ({ ...state, [kind]: false }),
+ },
+ ],
+ })),
+ listeners(({ actions, props }) => ({
+ dismiss: ({ kind }) => {
+ LemonDialog.open({
+ title: kind === 'sources' ? 'Source suggestions hidden' : 'Conversion recommendations hidden',
+ content:
+ kind === 'sources'
+ ? 'You can review your sources and show these suggestions again in Setup → Ad platforms & sources.'
+ : 'You can review your recommendations and show them again in Setup → Conversion goals.',
+ primaryButton: { children: 'Got it' },
+ secondaryButton: { children: 'Open Setup', onClick: () => actions.openSetup(kind) },
+ })
+ },
+ openSetup: ({ kind }) => {
+ if (teamLogic.values.currentTeamId === props.projectId) {
+ marketingAnalyticsLogic.actions.setSetupSection(
+ kind === 'sources' ? SetupSection.SOURCES : SetupSection.CONVERSION_GOALS
+ )
+ marketingAnalyticsLogic.actions.setActiveTab(MarketingAnalyticsTab.SETUP)
+ }
+ },
+ })),
+])
diff --git a/products/marketing_analytics/frontend/setup/findEquivalentConversionGoal.test.ts b/products/marketing_analytics/frontend/setup/findEquivalentConversionGoal.test.ts
new file mode 100644
index 000000000000..99ff27b1c7fb
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/findEquivalentConversionGoal.test.ts
@@ -0,0 +1,72 @@
+import { defaultConversionGoalFilter } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/constants'
+
+import { ConversionGoalFilter, NodeKind } from '~/queries/schema/schema-general'
+import { BaseMathType, PropertyMathType, PropertyOperator } from '~/types'
+
+import { findEquivalentConversionGoal } from './findEquivalentConversionGoal'
+
+const goal: ConversionGoalFilter = {
+ ...defaultConversionGoalFilter,
+ conversion_goal_id: 'saved-goal',
+ conversion_goal_name: 'Payments',
+ kind: NodeKind.EventsNode,
+ event: 'payment_completed',
+ math: PropertyMathType.Sum,
+ math_property: 'amount',
+ counts_as_revenue: true,
+}
+
+describe('equivalent conversion goals', () => {
+ it.each([
+ [
+ 'different display name',
+ { conversion_goal_name: 'Revenue', name: 'Renamed event', custom_name: 'Custom label' },
+ true,
+ ],
+ [
+ 'explicit defaults',
+ { properties: [], fixedProperties: [], counts_as_customer: false, math_multiplier: 1 },
+ true,
+ ],
+ ['different event', { event: 'refund_completed' }, false],
+ ['action instead of event', { kind: NodeKind.ActionsNode, id: 12 }, false],
+ ['different calculation', { math: PropertyMathType.Average }, false],
+ ['different amount', { math_property: 'net_amount' }, false],
+ ['different currency mapping', { math_property_revenue_currency: { property: 'currency' } }, false],
+ ['different multiplier', { math_multiplier: 0.01 }, false],
+ ['different revenue flag', { counts_as_revenue: false }, false],
+ ['different customer flag', { counts_as_customer: true }, false],
+ [
+ 'different filters',
+ { properties: [{ key: 'status', value: 'paid', operator: PropertyOperator.Exact, type: 'event' }] },
+ false,
+ ],
+ [
+ 'different fixed filters',
+ { fixedProperties: [{ key: 'status', value: 'paid', operator: PropertyOperator.Exact, type: 'event' }] },
+ false,
+ ],
+ ['different attribution mapping', { schema_map: { ...goal.schema_map, utm_source_name: 'source' } }, false],
+ ] as const)('compares %s', (_, changes, matches) => {
+ const candidate = { ...goal, ...changes, conversion_goal_id: '' } as ConversionGoalFilter
+ expect(findEquivalentConversionGoal([goal], candidate)).toEqual(matches ? goal : undefined)
+ })
+
+ it('matches an action by ID, with omitted count math and flags treated as defaults', () => {
+ const action: ConversionGoalFilter = {
+ ...defaultConversionGoalFilter,
+ conversion_goal_id: 'action-goal',
+ kind: NodeKind.ActionsNode,
+ id: 12,
+ math: undefined,
+ }
+ expect(
+ findEquivalentConversionGoal([action], {
+ ...action,
+ math: BaseMathType.TotalCount,
+ counts_as_revenue: false,
+ })
+ ).toBe(action)
+ expect(findEquivalentConversionGoal([action], { ...action, id: 13 })).toBeUndefined()
+ })
+})
diff --git a/products/marketing_analytics/frontend/setup/findEquivalentConversionGoal.ts b/products/marketing_analytics/frontend/setup/findEquivalentConversionGoal.ts
new file mode 100644
index 000000000000..55af2f5ebcbf
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/findEquivalentConversionGoal.ts
@@ -0,0 +1,49 @@
+import { objectsEqual } from 'lib/utils/objects'
+import { defaultConversionGoalFilter } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/constants'
+
+import { ConversionGoalFilter, NodeKind } from '~/queries/schema/schema-general'
+import { BaseMathType } from '~/types'
+
+function measurement(goal: ConversionGoalFilter): Record<string, unknown> {
+ return {
+ kind: goal.kind,
+ source: goal.kind === NodeKind.EventsNode ? goal.event : goal.id,
+ math: goal.math ?? BaseMathType.TotalCount,
+ math_property: goal.math_property,
+ math_property_type: goal.math_property_type,
+ math_property_revenue_currency: goal.math_property_revenue_currency,
+ math_multiplier: goal.math_multiplier ?? 1,
+ math_hogql: goal.math_hogql,
+ math_group_type_index: goal.math_group_type_index,
+ properties: goal.properties ?? [],
+ fixedProperties: goal.fixedProperties ?? [],
+ counts_as_revenue: !!goal.counts_as_revenue,
+ counts_as_customer: !!goal.counts_as_customer,
+ schema_map: { ...defaultConversionGoalFilter.schema_map, ...goal.schema_map },
+ }
+}
+
+export function findConversionGoalForSource(
+ goals: ConversionGoalFilter[],
+ candidate: ConversionGoalFilter
+): ConversionGoalFilter | undefined {
+ return goals.find((goal) =>
+ candidate.kind === NodeKind.EventsNode
+ ? goal.kind === NodeKind.EventsNode && !!candidate.event && goal.event === candidate.event
+ : candidate.kind === NodeKind.ActionsNode &&
+ goal.kind === NodeKind.ActionsNode &&
+ !!candidate.id &&
+ goal.id === candidate.id
+ )
+}
+
+export function findEquivalentConversionGoal(
+ goals: ConversionGoalFilter[],
+ candidate: ConversionGoalFilter
+): ConversionGoalFilter | undefined {
+ if (candidate.kind === NodeKind.DataWarehouseNode) {
+ return undefined
+ }
+ const candidateMeasurement = measurement(candidate)
+ return goals.find((goal) => objectsEqual(measurement(goal), candidateMeasurement))
+}
diff --git a/products/marketing_analytics/frontend/setup/recommendationToGoal.ts b/products/marketing_analytics/frontend/setup/recommendationToGoal.ts
new file mode 100644
index 000000000000..a81e9b1fec18
--- /dev/null
+++ b/products/marketing_analytics/frontend/setup/recommendationToGoal.ts
@@ -0,0 +1,28 @@
+import { defaultConversionGoalFilter } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/constants'
+
+import { ConversionGoalFilter, NodeKind } from '~/queries/schema/schema-general'
+import { BaseMathType, PropertyMathType } from '~/types'
+
+import type { ConversionRecommendationApi } from '../generated/api.schemas'
+
+export function recommendationToGoal(recommendation: ConversionRecommendationApi): ConversionGoalFilter {
+ const { candidate, intent, amount_property } = recommendation
+ const isRevenue = intent === 'revenue' && !!amount_property
+ const source =
+ candidate.kind === 'ActionsNode'
+ ? { kind: NodeKind.ActionsNode as const, id: candidate.action_id ?? 0 }
+ : { kind: NodeKind.EventsNode as const, event: candidate.event ?? '' }
+
+ return {
+ ...source,
+ name: candidate.name,
+ conversion_goal_id: '',
+ conversion_goal_name: recommendation.name,
+ schema_map: { ...defaultConversionGoalFilter.schema_map },
+ properties: [],
+ math: isRevenue ? PropertyMathType.Sum : BaseMathType.TotalCount,
+ ...(isRevenue ? { math_property: amount_property } : {}),
+ counts_as_revenue: isRevenue,
+ counts_as_customer: intent === 'customer',
+ }
+}
diff --git a/products/marketing_analytics/package.json b/products/marketing_analytics/package.json
index cf09ef590ffd..9f19b735da78 100644
--- a/products/marketing_analytics/package.json
+++ b/products/marketing_analytics/package.json
@@ -10,6 +10,8 @@
"kea-subscriptions": "catalog:"
},
"devDependencies": {
+ "@testing-library/jest-dom": "^5.17.0",
+ "@testing-library/react": "^14.3.1",
"kea-test-utils": "catalog:"
},
"peerDependencies": {