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-analytics): add the Setup tab (#81234)

Javier Bahamondes58d50c29420c
diff --git a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
index 793e4bf37714..32bbb2afd4fe 100644
--- a/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
+++ b/frontend/src/scenes/marketing-analytics/MarketingAnalyticsScene.tsx
@@ -31,6 +31,7 @@ import { MarketingAnalyticsFilters } from '../web-analytics/tabs/marketing-analy
import { MarketingAnalyticsSourceStatusBanner } from '../web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsSourceStatusBanner'
import {
MarketingAnalyticsTab,
+ SETUP_ABSORBED_TABS,
marketingAnalyticsLogic,
} from '../web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
import { marketingAnalyticsSettingsLogic } from '../web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic'
@@ -41,6 +42,7 @@ import {
import { NewMarketingAnalyticsDashboard } from './NewMarketingAnalyticsDashboard'
import { marketingOnboardingLogic } from './Onboarding/marketingOnboardingLogic'
import { Onboarding } from './Onboarding/Onboarding'
+import { SetupTab } from './Setup/SetupTab'
export const scene: SceneExport = {
component: MarketingAnalyticsScene,
@@ -208,7 +210,7 @@ const MarketingAnalyticsDashboard = (): JSX.Element => {
const MarketingAnalyticsContent = (): JSX.Element => {
const { featureFlags } = useValues(featureFlagLogic)
const { activeTab } = useValues(marketingAnalyticsLogic)
- const { setActiveTab } = useActions(marketingAnalyticsLogic)
+ const { setActiveTab, setSetupSection } = useActions(marketingAnalyticsLogic)
// The redesigned dashboard replaces the current one under the same "Dashboard" tab when its flag is
// on, so the eventual cutover is just flipping the flag — no tab rename, no extra tab key to strand.
@@ -221,8 +223,29 @@ 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]
+
+ // 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.
+ const absorbed = setupEnabled ? SETUP_ABSORBED_TABS[activeTab] : undefined
+ useEffect(() => {
+ if (absorbed) {
+ setActiveTab(MarketingAnalyticsTab.SETUP)
+ setSetupSection(absorbed)
+ }
+ }, [absorbed, setActiveTab, setSetupSection])
+
const tabs = [
{ key: MarketingAnalyticsTab.DASHBOARD, label: 'Dashboard', content: dashboard },
+ // Untouched by Setup: the explorer compares attribution models against each
+ // other, which is analysis. Setup's Attribution section is the two config
+ // fields (mode and lookback), which is a different thing with the same name.
...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_ATTRIBUTION]
? [
{
@@ -232,24 +255,39 @@ const MarketingAnalyticsContent = (): JSX.Element => {
},
]
: []),
- ...(featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_UTM_AUDIT]
- ? [
- {
- key: MarketingAnalyticsTab.INTEGRATION_HEALTH,
- label: 'Integration health',
- content: <UtmAuditTab />,
- },
- ]
- : []),
+ ...(setupEnabled
+ ? [{ key: MarketingAnalyticsTab.SETUP, label: 'Setup', content: <SetupTab /> }]
+ : featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_UTM_AUDIT]
+ ? [
+ {
+ key: MarketingAnalyticsTab.INTEGRATION_HEALTH,
+ label: 'Integration health',
+ content: <UtmAuditTab />,
+ },
+ ]
+ : []),
]
+ // A stored tab can still name one no flag is rendering — a key persisted from before
+ // a flag was turned off. Normalising the state rather than just what LemonTabs
+ // highlights: `activeTab` also feeds the scene description and `?tab=`, so leaving it
+ // invalid describes a tab you aren't on and writes it back into the URL on the next
+ // filter change. Above the early return, since hooks run on every render.
+ const tabIsRendered = tabs.some((tab) => tab.key === activeTab)
+ useEffect(() => {
+ if (!tabIsRendered && !absorbed) {
+ setActiveTab(MarketingAnalyticsTab.DASHBOARD)
+ }
+ }, [tabIsRendered, absorbed, setActiveTab])
+ const selectedTab = tabIsRendered ? activeTab : MarketingAnalyticsTab.DASHBOARD
+
// Only surface the tab bar once a secondary tab is enabled; otherwise show the dashboard directly.
if (tabs.length === 1) {
return dashboard
}
return (
- <LemonTabs activeKey={activeTab} onChange={(key) => setActiveTab(key as MarketingAnalyticsTab)} tabs={tabs} />
+ <LemonTabs activeKey={selectedTab} onChange={(key) => setActiveTab(key as MarketingAnalyticsTab)} tabs={tabs} />
)
}
@@ -260,6 +298,8 @@ const TAB_DESCRIPTIONS: Record<string, string> = {
'Compare how each attribution model credits your conversions, to see which marketing you might be over or under valuing.',
[MarketingAnalyticsTab.INTEGRATION_HEALTH]:
'Check that your ad platform campaigns are properly linked to UTM tracking in PostHog.',
+ [MarketingAnalyticsTab.SETUP]:
+ 'Everything Marketing analytics needs to work: connected ad platforms, conversion goals, UTM mapping and attribution.',
}
const MarketingAnalyticsAIToolWrapper = ({ children }: { children: React.ReactNode }): JSX.Element => {
diff --git a/frontend/src/scenes/marketing-analytics/Setup/ReadinessHeader.tsx b/frontend/src/scenes/marketing-analytics/Setup/ReadinessHeader.tsx
new file mode 100644
index 000000000000..0ef7d87beab8
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/ReadinessHeader.tsx
@@ -0,0 +1,149 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import type {
+ Capability,
+ CapabilityReadiness,
+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+/** Each capability is a column or chart in Marketing analytics, so the chip has to
+ * name the thing the user will actually see — an acronym on its own is a riddle. */
+export const CAPABILITY_COPY: Record<Capability, { label: string; what: string }> = {
+ cost: { label: 'Cost', what: 'What you spent, per platform and campaign.' },
+ attribution: { label: 'Attribution', what: 'Which channel a visit or conversion came from.' },
+ roas: { label: 'ROAS', what: 'Return on ad spend — revenue divided by cost.' },
+ cac: { label: 'Cost per customer', what: 'Ad spend divided by new customers acquired.' },
+}
+
+const STATUS_COPY: Record<CapabilityReadiness['status'], string> = {
+ unlocked: 'Ready to use',
+ partial: 'Partly available',
+ blocked: 'Not available yet',
+}
+
+function CapabilityChip({
+ readiness,
+ blockerCount,
+ focused,
+ onFocus,
+}: {
+ readiness: CapabilityReadiness
+ blockerCount: number
+ focused: boolean
+ onFocus: () => void
+}): JSX.Element {
+ const copy = CAPABILITY_COPY[readiness.capability]
+ const label = copy?.label ?? readiness.capability
+ const clickable = blockerCount > 0
+
+ const tooltip = (
+ <div className="deprecated-space-y-1 max-w-xs">
+ <div className="font-semibold">
+ {label} · {STATUS_COPY[readiness.status]}
+ </div>
+ {copy && <div>{copy.what}</div>}
+ <div className="text-secondary">{readiness.explanation}</div>
+ {clickable && (
+ <div className="text-secondary">
+ Click to show the {blockerCount} suggestion{blockerCount === 1 ? '' : 's'} that would change this.
+ </div>
+ )}
+ </div>
+ )
+
+ // Only `unlocked` gets full-strength text, since only `unlocked` counts towards
+ // "N of M ready" above. No status colour either — background means focused and
+ // nothing else, and status is already in the tooltip, count and progress bar.
+ const ready = readiness.status === 'unlocked'
+
+ return (
+ <Tooltip title={tooltip}>
+ <button
+ type="button"
+ // Guarded click rather than `disabled`, which would drop the chip out of
+ // the tab order and leave its tooltip with no keyboard path.
+ onClick={clickable ? onFocus : undefined}
+ aria-pressed={clickable ? focused : undefined}
+ aria-label={`${label} · ${STATUS_COPY[readiness.status]}`}
+ className={`flex items-center gap-1.5 rounded border px-2 py-1 text-sm ${
+ focused ? 'border-accent bg-accent-highlight-secondary' : 'bg-bg-light'
+ } ${clickable ? 'cursor-pointer' : 'cursor-default'}`}
+ >
+ <span className={ready || focused ? undefined : 'text-muted'}>{label}</span>
+ {clickable && (
+ <span className="text-xs text-secondary tabular-nums" aria-label={`${blockerCount} suggestions`}>
+ {blockerCount}
+ </span>
+ )}
+ </button>
+ </Tooltip>
+ )
+}
+
+export function ReadinessHeader(): JSX.Element {
+ const { readiness, degraded, truncated, setupPlanLoading, visibleSuggestions, focusedCapability } =
+ useValues(setupPlanLogic)
+ const { focusCapability } = useActions(setupPlanLogic)
+
+ if (setupPlanLoading && !readiness.length) {
+ return (
+ <div className="deprecated-space-y-2">
+ <LemonSkeleton className="h-4 w-64" />
+ <LemonSkeleton className="h-8 w-full" />
+ </div>
+ )
+ }
+
+ const unlocked = readiness.filter((entry) => entry.status === 'unlocked').length
+ const total = readiness.length
+
+ return (
+ <div className="deprecated-space-y-3">
+ {total > 0 && (
+ <div className="deprecated-space-y-2">
+ {/* Without this line the chips read as a list of failures rather than
+ of metrics, most of which a new project legitimately lacks. */}
+ <div className="flex items-baseline gap-2 text-xs text-secondary">
+ <span className="font-semibold uppercase tracking-wide">What you can measure right now</span>
+ <span>
+ {unlocked} of {total} ready
+ </span>
+ </div>
+ <div className="flex items-center flex-wrap gap-2">
+ {readiness.map((entry) => (
+ <CapabilityChip
+ key={entry.capability}
+ readiness={entry}
+ blockerCount={
+ visibleSuggestions.filter((suggestion) =>
+ suggestion.unlocks.includes(entry.capability)
+ ).length
+ }
+ focused={focusedCapability === entry.capability}
+ onFocus={() => focusCapability(entry.capability)}
+ />
+ ))}
+ </div>
+ <LemonProgress percent={(unlocked / total) * 100} />
+ </div>
+ )}
+
+ {/* The plan is assembled from independently failing services over capped
+ queries; hiding that makes a partial answer look authoritative. */}
+ {degraded.length > 0 && (
+ <LemonBanner type="warning">
+ Some checks could not run ({degraded.join(', ')}), so this list is incomplete. Reload to try again.
+ </LemonBanner>
+ )}
+ {truncated && (
+ <LemonBanner type="info">
+ You have more campaigns or UTM values than we analyse in one pass, so the figures below are
+ approximate — they cover your highest-spend campaigns and highest-volume UTM values.
+ </LemonBanner>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SectionSuggestions.test.ts b/frontend/src/scenes/marketing-analytics/Setup/SectionSuggestions.test.ts
new file mode 100644
index 000000000000..0143b7cdc60c
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/SectionSuggestions.test.ts
@@ -0,0 +1,84 @@
+import { SetupSection } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+import type { Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import { SECTION_BY_KIND, suggestionsForSection } from './sectionRouting'
+
+const suggestion = (kind: string, id = kind): Suggestion =>
+ ({
+ id,
+ kind,
+ source: 'deterministic',
+ severity: 'warning',
+ confidence: 0.8,
+ title: kind,
+ evidence: '',
+ unlocks: [],
+ apply: null,
+ also_recommended: [],
+ safe_to_batch: false,
+ rank_score: 0,
+ integration: null,
+ deep_link: null,
+ docs_url: null,
+ spend_at_risk: 0,
+ event_volume: 0,
+ }) as Suggestion
+
+describe('suggestionsForSection', () => {
+ it('routes each kind to the section that owns it', () => {
+ const all = [
+ suggestion('fix_sync'),
+ suggestion('reconnect_oauth'),
+ suggestion('add_source_mapping'),
+ suggestion('remove_mapping'),
+ suggestion('mark_goal_as_revenue'),
+ suggestion('fix_platform_urls'),
+ ]
+
+ expect(suggestionsForSection(all, SetupSection.SOURCES).map((s) => s.kind)).toEqual([
+ 'fix_sync',
+ 'reconnect_oauth',
+ ])
+ expect(suggestionsForSection(all, SetupSection.UTM_MAPPING).map((s) => s.kind)).toEqual([
+ 'add_source_mapping',
+ 'remove_mapping',
+ ])
+ expect(suggestionsForSection(all, SetupSection.CONVERSION_GOALS).map((s) => s.kind)).toEqual([
+ 'mark_goal_as_revenue',
+ ])
+ expect(suggestionsForSection(all, SetupSection.INTEGRATION_HEALTH).map((s) => s.kind)).toEqual([
+ 'fix_platform_urls',
+ ])
+ })
+
+ it('leaves an unrouted kind out of every section rather than guessing', () => {
+ // A kind added backend-first still shows in "Suggested setup"; it just doesn't
+ // claim a section it might not belong to.
+ const all = [suggestion('some_future_kind')]
+
+ for (const section of Object.values(SetupSection)) {
+ expect(suggestionsForSection(all, section)).toEqual([])
+ }
+ })
+
+ it('routes every kind the plan can emit', () => {
+ // Guards against a new backend kind silently never appearing in a section.
+ const emitted = [
+ 'connect_source',
+ 'reconnect_oauth',
+ 'fix_sync',
+ 'map_schema_columns',
+ 'add_source_mapping',
+ 'add_campaign_name_mapping',
+ 'switch_campaign_match_field',
+ 'remove_mapping',
+ 'fix_platform_urls',
+ 'create_conversion_goal',
+ 'fix_conversion_goal',
+ 'mark_goal_as_revenue',
+ 'mark_goal_as_customer',
+ ]
+
+ expect(emitted.filter((kind) => !SECTION_BY_KIND[kind])).toEqual([])
+ })
+})
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SectionSuggestions.tsx b/frontend/src/scenes/marketing-analytics/Setup/SectionSuggestions.tsx
new file mode 100644
index 000000000000..80d37f13752b
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/SectionSuggestions.tsx
@@ -0,0 +1,32 @@
+import { useActions, useValues } from 'kea'
+
+import { SetupSection } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import { suggestionsForSection } from './sectionRouting'
+import { SuggestionRow } from './SuggestionRow'
+
+/** One section's suggestions, above its manual controls. The same rows as "Suggested
+ * setup" rather than a summary, so there's no second rendering to keep in sync. */
+export function SectionSuggestions({ section }: { section: SetupSection }): JSX.Element | null {
+ const { visibleSuggestions } = useValues(setupPlanLogic)
+ const { reviewSuggestion } = useActions(setupPlanLogic)
+
+ const forSection = suggestionsForSection(visibleSuggestions, section)
+ if (!forSection.length) {
+ return null
+ }
+
+ return (
+ <div className="border rounded bg-bg-light mb-4">
+ {forSection.map((suggestion) => (
+ <SuggestionRow
+ key={suggestion.id}
+ suggestion={suggestion}
+ onReview={reviewSuggestion}
+ currentSection={section}
+ />
+ ))}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsx b/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsx
new file mode 100644
index 000000000000..ff9fa67a6e20
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/SetupTab.tsx
@@ -0,0 +1,136 @@
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { LemonButton, LemonTag } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { IntegrationSettingsModal } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/IntegrationSettingsModal'
+import {
+ SetupSection,
+ marketingAnalyticsLogic,
+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+import { marketingAnalyticsSettingsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic'
+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 { runNavigateOp } from './navigateOps'
+import { suggestionsForSection } from './sectionRouting'
+import { SectionSuggestions } from './SectionSuggestions'
+import { SETUP_SECTIONS } from './setupSections'
+import { SuggestionModal } from './SuggestionModal'
+
+/** Count of open suggestions in a section, and whether any of them is blocking.
+ * Shown in the nav so you can see where the problems are without opening each one. */
+function SectionBadge({
+ suggestions,
+ section,
+}: {
+ suggestions: Suggestion[]
+ section: SetupSection
+}): JSX.Element | null {
+ const forSection = suggestionsForSection(suggestions, section)
+ if (!forSection.length) {
+ return null
+ }
+ const hasError = forSection.some((suggestion) => suggestion.severity === 'error')
+ return (
+ <LemonTag type={hasError ? 'danger' : 'warning'} size="small">
+ {forSection.length}
+ </LemonTag>
+ )
+}
+
+export function SetupTab(): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { setupSection } = useValues(marketingAnalyticsLogic)
+ const { setSetupSection } = useActions(marketingAnalyticsLogic)
+ const { setupPlan, visibleSuggestions, reviewingSuggestion, isReviewingBatch, safeBatch, applyingIds } =
+ useValues(setupPlanLogic)
+ const { loadSetupPlan, reviewSuggestion, confirmReviewedSuggestion, confirmReviewedBatch } =
+ useActions(setupPlanLogic)
+ const { integrationSettingsModal } = useValues(marketingAnalyticsSettingsLogic)
+ const { closeIntegrationSettingsModal } = useActions(marketingAnalyticsSettingsLogic)
+
+ // Keep the audit gated for one release so the two flags can roll independently;
+ // drop this once Setup is the only way in.
+ const sections = SETUP_SECTIONS.filter(
+ (section) =>
+ section.key !== SetupSection.INTEGRATION_HEALTH || featureFlags[FEATURE_FLAGS.MARKETING_ANALYTICS_UTM_AUDIT]
+ )
+
+ // Once on arrival and never again on its own — the plan is six ClickHouse queries
+ // deep, one unioning every ad adapter.
+ useEffect(() => {
+ if (!setupPlan) {
+ loadSetupPlan()
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
+ const active = sections.find((section) => section.key === setupSection) ?? sections[0]
+
+ return (
+ <div className="flex flex-col md:flex-row gap-6 mt-4">
+ <nav className="md:w-56 shrink-0 flex flex-row md:flex-col gap-px overflow-x-auto">
+ {sections.map((section) => (
+ <LemonButton
+ key={section.key}
+ size="small"
+ fullWidth
+ active={section.key === active.key}
+ onClick={() => setSetupSection(section.key)}
+ sideIcon={<SectionBadge suggestions={visibleSuggestions} section={section.key} />}
+ >
+ {section.label}
+ </LemonButton>
+ ))}
+ </nav>
+
+ <div className="grow min-w-0 deprecated-space-y-4">
+ <div>
+ <h2 className="mb-1">{active.label}</h2>
+ {active.description && <p className="text-secondary mb-0">{active.description}</p>}
+ </div>
+ {/* 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.content}
+ </div>
+
+ {/* At the tab, not in a section: a row anywhere can open either, and they
+ must survive the user switching sections behind them. */}
+ <SuggestionModal
+ suggestion={reviewingSuggestion}
+ batch={isReviewingBatch ? safeBatch : []}
+ isApplying={
+ isReviewingBatch
+ ? safeBatch.some((item) => applyingIds.includes(item.id))
+ : !!reviewingSuggestion && applyingIds.includes(reviewingSuggestion.id)
+ }
+ onClose={() => reviewSuggestion(null)}
+ onConfirm={(item) => {
+ // Navigate ops finish here; everything else goes to the server.
+ if (item.apply && runNavigateOp(item.apply)) {
+ reviewSuggestion(null)
+ return
+ }
+ confirmReviewedSuggestion(item)
+ }}
+ onConfirmBatch={confirmReviewedBatch}
+ />
+ {/* UtmAuditTab renders this same modal off the same shared state, so the
+ Integration health section would mount two copies of it. */}
+ {integrationSettingsModal.integration && active.key !== SetupSection.INTEGRATION_HEALTH && (
+ <IntegrationSettingsModal
+ integrationName={integrationSettingsModal.integration}
+ isOpen={integrationSettingsModal.isOpen}
+ onClose={closeIntegrationSettingsModal}
+ initialTab={integrationSettingsModal.initialTab}
+ initialUtmValue={integrationSettingsModal.initialUtmValue}
+ initialCampaignName={integrationSettingsModal.initialCampaignName}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SuggestedActions.tsx b/frontend/src/scenes/marketing-analytics/Setup/SuggestedActions.tsx
new file mode 100644
index 000000000000..dbfffd54b41a
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/SuggestedActions.tsx
@@ -0,0 +1,171 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCheckCircle, IconRefresh } from '@posthog/icons'
+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import { CAPABILITY_COPY, ReadinessHeader } from './ReadinessHeader'
+import { SuggestionRow } from './SuggestionRow'
+
+function EmptyState({ scanned, degraded }: { scanned: boolean; degraded: string[] }): JSX.Element {
+ if (!scanned) {
+ return (
+ <div className="text-center py-8 text-secondary">
+ <p>Scan your project to see what's worth fixing.</p>
+ </div>
+ )
+ }
+ // A degraded plan is missing whole checks, so "every check passed" is a clean bill
+ // of health we can't give.
+ if (degraded.length) {
+ return (
+ <div className="flex items-center justify-center gap-2 py-8 text-secondary">
+ <span>Nothing to fix in the checks that ran — {degraded.length} couldn't be completed.</span>
+ </div>
+ )
+ }
+ return (
+ <div className="flex items-center justify-center gap-2 py-8 text-secondary">
+ <IconCheckCircle className="text-success text-xl" />
+ <span>Nothing to fix — every check passed.</span>
+ </div>
+ )
+}
+
+export function SuggestedActions(): JSX.Element {
+ const {
+ visibleSuggestions,
+ listedSuggestions,
+ focusedCapability,
+ safeBatch,
+ setupPlan,
+ setupPlanLoading,
+ applyingIds,
+ dismissedSuggestions,
+ showDismissed,
+ degraded,
+ } = useValues(setupPlanLogic)
+ const {
+ loadSetupPlan,
+ reviewSafeBatch,
+ reviewSuggestion,
+ focusCapability,
+ toggleShowDismissed,
+ restoreAllDismissed,
+ } = useActions(setupPlanLogic)
+
+ const isBatchApplying = safeBatch.some((s) => applyingIds.includes(s.id))
+
+ return (
+ <div className="deprecated-space-y-4">
+ <div className="flex items-start justify-between gap-4">
+ <p className="text-secondary max-w-xl mb-0">
+ What we found in your data, and what to do about it. Every suggestion shows the numbers behind it,
+ so you can check it before applying.
+ </p>
+ <div className="flex items-center gap-2 shrink-0">
+ {/* Hidden while filtered: the batch is over every safe suggestion,
+ not the handful on screen, and a count that disagrees with the
+ list is how someone applies more than they meant to. */}
+ {safeBatch.length > 0 && !focusedCapability && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ loading={isBatchApplying}
+ onClick={reviewSafeBatch}
+ // "Safe" is about what can go in one batch, not a verdict on
+ // the rest — say so, because the label alone reads as one.
+ tooltip="Reversible changes we're confident enough about to apply together — you still get a preview of exactly what they change. The rest aren't risky, they need a decision only you can make."
+ >
+ Review {safeBatch.length} safe change{safeBatch.length === 1 ? '' : 's'}
+ </LemonButton>
+ )}
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconRefresh />}
+ loading={setupPlanLoading}
+ // A rescan while an apply is in flight lands a plan built before
+ // that change, and the row it fixed comes back.
+ disabledReason={applyingIds.length ? 'Waiting for the current change to finish' : undefined}
+ onClick={() => loadSetupPlan({ refresh: true })}
+ >
+ {setupPlan ? 'Rescan' : 'Scan'}
+ </LemonButton>
+ </div>
+ </div>
+
+ {setupPlan && <ReadinessHeader />}
+
+ {focusedCapability && (
+ <div className="flex items-center gap-2 text-sm text-secondary">
+ <span>
+ Showing the {listedSuggestions.length} of {visibleSuggestions.length} suggestions that affect{' '}
+ <strong>{CAPABILITY_COPY[focusedCapability]?.label ?? focusedCapability}</strong>.
+ </span>
+ <LemonButton size="xsmall" type="tertiary" onClick={() => focusCapability(null)}>
+ Show all
+ </LemonButton>
+ </div>
+ )}
+
+ {setupPlanLoading && !setupPlan ? (
+ <div className="deprecated-space-y-2">
+ <LemonSkeleton className="h-16 w-full" />
+ <LemonSkeleton className="h-16 w-full" />
+ <LemonSkeleton className="h-16 w-full" />
+ </div>
+ ) : listedSuggestions.length ? (
+ <div className="border rounded bg-bg-light">
+ {listedSuggestions.map((suggestion) => (
+ <SuggestionRow key={suggestion.id} suggestion={suggestion} onReview={reviewSuggestion} />
+ ))}
+ </div>
+ ) : focusedCapability ? (
+ // Reachable: a capability can be blocked by something we surface no
+ // suggestion for.
+ <div className="flex items-center justify-center gap-2 py-8 text-secondary">
+ <span>Nothing here changes that metric.</span>
+ <LemonButton size="small" type="secondary" onClick={() => focusCapability(null)}>
+ Show everything
+ </LemonButton>
+ </div>
+ ) : (
+ <EmptyState scanned={!!setupPlan} degraded={degraded} />
+ )}
+
+ {/* So dismissing isn't a one-way door — a dismissal that turns out to matter
+ costs one click to get back. */}
+ {dismissedSuggestions.length > 0 && (
+ <div className="deprecated-space-y-2">
+ <div className="flex items-center justify-between gap-4 text-sm text-secondary">
+ <span>
+ {dismissedSuggestions.length} hidden. Dismissing hides a suggestion — it doesn't fix it.
+ </span>
+ <div className="flex items-center gap-1 shrink-0">
+ <LemonButton size="small" type="secondary" onClick={toggleShowDismissed}>
+ {showDismissed ? 'Hide' : 'Review hidden'}
+ </LemonButton>
+ <LemonButton size="small" type="tertiary" onClick={restoreAllDismissed}>
+ Restore all
+ </LemonButton>
+ </div>
+ </div>
+ {showDismissed && (
+ <div className="border rounded bg-bg-light opacity-75">
+ {dismissedSuggestions.map((suggestion) => (
+ <SuggestionRow
+ key={suggestion.id}
+ suggestion={suggestion}
+ onReview={reviewSuggestion}
+ isDismissed
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SuggestionIcon.test.tsx b/frontend/src/scenes/marketing-analytics/Setup/SuggestionIcon.test.tsx
new file mode 100644
index 000000000000..d5b496e04cb9
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/SuggestionIcon.test.tsx
@@ -0,0 +1,91 @@
+import { cleanup, render, waitFor } from '@testing-library/react'
+
+import type { Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { SuggestionIcon } from './SuggestionIcon'
+
+const suggestion = (overrides: Partial<Suggestion> = {}): Suggestion =>
+ ({
+ id: 'fix_sync:google_ads',
+ kind: 'fix_sync',
+ source: 'deterministic',
+ severity: 'error',
+ title: 'Retry the Google Ads sync',
+ evidence: 'Last sync is 3 days old.',
+ unlocks: [],
+ apply: null,
+ also_recommended: [],
+ safe_to_batch: false,
+ rank_score: 10,
+ integration: 'GoogleAds',
+ deep_link: null,
+ docs_url: null,
+ spend_at_risk: 0,
+ event_volume: 0,
+ ...overrides,
+ }) as Suggestion
+
+/** Scoped to one render's container: this repo has no RTL auto-cleanup, so a
+ * document-wide query picks up every earlier render in the file. */
+function slotIn(container: HTMLElement): HTMLElement {
+ const found = container.querySelector<HTMLElement>('[data-attr="suggestion-icon"]')
+ if (!found) {
+ throw new Error('no suggestion icon rendered')
+ }
+ return found
+}
+
+describe('SuggestionIcon', () => {
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/external_data_sources/wizard': () => [
+ 200,
+ { GoogleAds: { name: 'GoogleAds', iconPath: '/static/services/google-ads.png' } },
+ ],
+ },
+ })
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('reserves the same width whether or not a logo resolves', async () => {
+ // The point of the fixed slot: a ranked list must not indent each row
+ // differently depending on whether its platform happened to resolve a logo,
+ // and must not re-flow when one 404s.
+ const withLogo = render(<SuggestionIcon suggestion={suggestion()} />)
+ await waitFor(() => expect(slotIn(withLogo.container).querySelector('img')).toBeTruthy())
+
+ const withoutLogo = render(<SuggestionIcon suggestion={suggestion({ integration: null })} />)
+
+ // Same class list on both, so the width can't drift between the two branches
+ // without this failing — which is the whole invariant.
+ expect(slotIn(withoutLogo.container).className).toBe(slotIn(withLogo.container).className)
+ expect(slotIn(withLogo.container).className).toContain('size-[30px]')
+ })
+
+ it('falls back to the severity glyph when there is no platform', () => {
+ // A collapsed group, a conversion goal, traffic untagged everywhere: nothing to
+ // put a logo on, so severity has to carry the slot on its own.
+ const { container } = render(<SuggestionIcon suggestion={suggestion({ integration: null })} />)
+
+ expect(slotIn(container).querySelector('img')).toBeNull()
+ expect(slotIn(container).querySelector('svg')).toBeTruthy()
+ })
+
+ it('falls back when the platform is absent from the source catalogue', async () => {
+ // `availableSources` is also null when the wizard endpoint 403s, and SourceIcon
+ // renders an indefinite skeleton in that state rather than giving up — which is
+ // why `usePlatformLogo` checks the catalogue itself.
+ const { container } = render(<SuggestionIcon suggestion={suggestion({ integration: 'NotARealPlatform' })} />)
+
+ await waitFor(() => expect(slotIn(container).querySelector('svg')).toBeTruthy())
+ expect(slotIn(container).querySelector('img')).toBeNull()
+ })
+})
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SuggestionIcon.tsx b/frontend/src/scenes/marketing-analytics/Setup/SuggestionIcon.tsx
new file mode 100644
index 000000000000..29a5290d64a5
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/SuggestionIcon.tsx
@@ -0,0 +1,83 @@
+import { useValues } from 'kea'
+
+import { IconInfo, IconWarning } from '@posthog/icons'
+import { Tooltip } from '@posthog/lemon-ui'
+
+import type { Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import { availableSourcesLogic } from 'products/data_warehouse/frontend/scenes/NewSourceScene/availableSourcesLogic'
+import { SourceIcon } from 'products/data_warehouse/frontend/shared/components/SourceIcon'
+
+const SEVERITY_LABEL: Record<Suggestion['severity'], string> = {
+ error: 'Blocking — a metric is unavailable or wrong until this is fixed',
+ warning: 'Worth fixing — some data is missing or misattributed',
+ info: 'Optional improvement',
+}
+
+const SEVERITY_DOT: Record<Suggestion['severity'], string> = {
+ error: 'bg-danger',
+ warning: 'bg-warning',
+ info: 'bg-muted',
+}
+
+function SeverityGlyph({ severity }: { severity: Suggestion['severity'] }): JSX.Element {
+ if (severity === 'info') {
+ return <IconInfo className="text-secondary text-lg" />
+ }
+ return <IconWarning className={severity === 'error' ? 'text-danger text-lg' : 'text-warning text-lg'} />
+}
+
+/** Checking the catalogue first because `SourceIcon` renders a skeleton while
+ * `availableSources` is null — which is also its terminal state when the wizard
+ * endpoint 403s, so no warehouse access would mean a skeleton forever.
+ *
+ * `disableTooltip` because SourceIcon otherwise links to its docs page, and the row
+ * already has a primary action.
+ */
+export function usePlatformLogo(integration: string | null): JSX.Element | null {
+ const { availableSources } = useValues(availableSourcesLogic)
+
+ if (!integration || !availableSources?.[integration]) {
+ return null
+ }
+ return <SourceIcon type={integration} size="small" disableTooltip />
+}
+
+/** The platform logo with severity as a corner dot, falling back to the bare severity
+ * glyph when the finding belongs to no single platform. */
+export function SuggestionIcon({ suggestion }: { suggestion: Suggestion }): JSX.Element {
+ const logo = usePlatformLogo(suggestion.integration)
+
+ return (
+ <Tooltip
+ title={
+ suggestion.integration
+ ? `${suggestion.integration} · ${SEVERITY_LABEL[suggestion.severity]}`
+ : SEVERITY_LABEL[suggestion.severity]
+ }
+ >
+ {/* Fixed 30px — `SourceIcon`'s `small` — so rows don't go ragged when a logo
+ is missing, and not `size-8` because 32 puts the logo off-centre. */}
+ <span
+ className="relative shrink-0 flex items-center justify-center cursor-help size-[30px]"
+ data-attr="suggestion-icon"
+ // Severity is otherwise colour and glyph shape only.
+ tabIndex={0}
+ aria-label={
+ suggestion.integration
+ ? `${suggestion.integration} · ${SEVERITY_LABEL[suggestion.severity]}`
+ : SEVERITY_LABEL[suggestion.severity]
+ }
+ >
+ {logo ?? <SeverityGlyph severity={suggestion.severity} />}
+ {logo && (
+ <span
+ className={`absolute -bottom-0.5 -right-0.5 size-2 rounded-full border border-bg-light ${
+ SEVERITY_DOT[suggestion.severity]
+ }`}
+ />
+ )}
+ </span>
+ </Tooltip>
+ )
+}
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SuggestionModal.test.tsx b/frontend/src/scenes/marketing-analytics/Setup/SuggestionModal.test.tsx
new file mode 100644
index 000000000000..662d3bed331d
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/SuggestionModal.test.tsx
@@ -0,0 +1,85 @@
+import { cleanup, render, screen } from '@testing-library/react'
+
+import type { Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { SuggestionModal } from './SuggestionModal'
+
+const suggestion = (overrides: Partial<Suggestion> = {}): Suggestion =>
+ ({
+ id: 'fix_conversion_goal:cg_ghost',
+ kind: 'fix_conversion_goal',
+ source: 'deterministic',
+ severity: 'error',
+ title: "Remove or repoint the 'Ghost action (broken)' conversion goal",
+ evidence: 'Action 999999 does not exist or is deleted.',
+ unlocks: [],
+ apply: { op: 'delete_conversion_goal', conversion_goal_id: 'cg_ghost' },
+ also_recommended: [],
+ safe_to_batch: false,
+ rank_score: 10,
+ integration: null,
+ deep_link: null,
+ docs_url: null,
+ spend_at_risk: 0,
+ event_volume: 0,
+ ...overrides,
+ }) as Suggestion
+
+function renderModal(item: Suggestion): void {
+ render(
+ <SuggestionModal
+ suggestion={item}
+ batch={[]}
+ isApplying={false}
+ onClose={() => {}}
+ onConfirm={() => {}}
+ onConfirmBatch={() => {}}
+ />
+ )
+}
+
+describe('SuggestionModal', () => {
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/external_data_sources/wizard': () => [200, {}],
+ },
+ })
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('says Remove rather than leaving a strikethrough to carry the meaning', () => {
+ renderModal(suggestion())
+
+ // A minus glyph and struck-through text were the entire signal that a
+ // destructive change was about to be approved.
+ expect(screen.getByText('Remove')).toBeTruthy()
+ })
+
+ it('names the act on the confirm button', () => {
+ renderModal(suggestion())
+
+ // "Apply change" on a button that deletes a conversion goal is accurate and
+ // useless.
+ expect(screen.getByText('Remove goal')).toBeTruthy()
+ expect(screen.queryByText('Apply change')).toBeNull()
+ })
+
+ it('keeps the generic label for an additive config edit', () => {
+ renderModal(
+ suggestion({
+ apply: { op: 'add_custom_source_mapping', integration: 'MetaAds', raw_utm_source: 'fb-ads' },
+ })
+ )
+
+ expect(screen.getByText('Apply change')).toBeTruthy()
+ expect(screen.getByText('Add')).toBeTruthy()
+ })
+})
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SuggestionModal.tsx b/frontend/src/scenes/marketing-analytics/Setup/SuggestionModal.tsx
new file mode 100644
index 000000000000..c5277f91f696
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/SuggestionModal.tsx
@@ -0,0 +1,247 @@
+import { useValues } from 'kea'
+
+import { IconMinus, IconPlus } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonModal } from '@posthog/lemon-ui'
+
+import { marketingAnalyticsSettingsLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic'
+import type { ApplyOp, Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import { buildApplyDiff, type DiffLine } from './applyDiff'
+import { usePlatformLogo } from './SuggestionIcon'
+
+/** Navigate-only ops change no config, so there's no diff to preview — the modal says
+ * what will happen instead. */
+const NAVIGATE_EXPLANATIONS: Record<string, (op: ApplyOp) => string> = {
+ retry_sync: (op) =>
+ `Starts a fresh sync of ${op.display_name} from the ad platform. It runs in the background and can take several minutes — the numbers here won't change immediately.`,
+ retry_syncs: (op) => {
+ const names = (op.sources as { display_name: string }[]).map((source) => source.display_name)
+ return `Starts a fresh sync of ${names.join(', ')} — ${names.length} in total. Each runs in the background and can take several minutes, so the numbers here won't change immediately. One failing doesn't stop the others.`
+ },
+ open_sources_section: () =>
+ 'Takes you to Ad platforms & sources, where each platform has its own row. These need fixing one at a time — they share a symptom, not a single fix.',
+ open_oauth: () =>
+ 'Opens the ad platform in a new tab to re-authorise PostHog. Spend stops updating until this is done, and nothing changes here until you finish there.',
+ open_source_wizard: () =>
+ 'Opens the data warehouse source wizard in a new tab, with this platform preselected. Connecting it is what makes its spend available.',
+ open_schemas: (op) =>
+ `Opens ${op.display_name}'s Schemas tab in a new tab. Tick the missing table there and it starts importing on the next sync — no amount of retrying selects it for you.`,
+ open_source_columns: (op) =>
+ `Jumps to ${op.display_name} under Ad platforms & sources, where you pick which warehouse column holds spend, campaign and date. Only you know which column is which, so this one can't be applied for you.`,
+ open_goal_editor: () => "Opens this goal's editor below, so you can point it at something that exists.",
+ open_mapping_editor: () =>
+ 'Opens the campaign mapping editor with these values filled in. Choosing the wrong one attributes this traffic to the wrong spend, which is why it is not done automatically.',
+ open_settings: () => 'Opens marketing analytics settings in a new tab.',
+}
+
+/** Only the destructive and the creative — everything else is an additive config edit
+ * that the default "Apply change" describes honestly. */
+const APPLY_LABEL: Record<string, string> = {
+ delete_conversion_goal: 'Remove goal',
+ create_conversion_goal: 'Create goal',
+ remove_custom_source_mapping: 'Remove mapping',
+ remove_campaign_name_mapping: 'Remove mapping',
+}
+
+function explanationFor(op: ApplyOp): ((op: ApplyOp) => string) | undefined {
+ // `in` rather than a plain lookup: TS types a Record index as always-defined, so
+ // `explain ? ... : ...` would be a constant-true branch.
+ return op.op in NAVIGATE_EXPLANATIONS ? NAVIGATE_EXPLANATIONS[op.op] : undefined
+}
+
+/** Spelled out because a strikethrough and a minus sign are otherwise the whole signal
+ * that a row is about to be deleted. */
+const CHANGE_VERB: Record<DiffLine['change'], { label: string; className: string }> = {
+ add: { label: 'Add', className: 'text-success' },
+ remove: { label: 'Remove', className: 'text-danger' },
+ update: { label: 'Change', className: 'text-secondary' },
+}
+
+function DiffRow({ line }: { line: DiffLine }): JSX.Element {
+ const verb = CHANGE_VERB[line.change]
+ return (
+ <div className="flex items-start gap-2 py-1.5 border-b last:border-b-0">
+ <span className="shrink-0 mt-0.5">
+ {line.change === 'add' ? (
+ <IconPlus className="text-success" />
+ ) : line.change === 'remove' ? (
+ <IconMinus className="text-danger" />
+ ) : (
+ <span className="text-muted text-xs font-mono">~</span>
+ )}
+ </span>
+ <div className="grow min-w-0">
+ <div className="text-xs text-secondary">
+ <span className={`font-semibold ${verb.className}`}>{verb.label}</span>
+ {` · ${line.setting}`}
+ {line.subject ? ` · ${line.subject}` : ''}
+ </div>
+ <div className="font-mono text-sm break-all">
+ {line.change === 'update' ? (
+ <>
+ <span className="line-through text-muted">{line.before}</span>
+ <span className="mx-1.5 text-secondary">→</span>
+ <span>{line.after}</span>
+ </>
+ ) : (
+ <span className={line.change === 'remove' ? 'line-through text-muted' : undefined}>
+ {line.after}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
+
+function DiffBlock({ lines }: { lines: DiffLine[] }): JSX.Element {
+ return (
+ <div>
+ <h4 className="mb-1">This will change</h4>
+ <div className="border rounded px-3 bg-bg-light">
+ {lines.map((line, index) => (
+ <DiffRow key={index} line={line} />
+ ))}
+ </div>
+ </div>
+ )
+}
+
+function UrlFixBanner({ fix }: { fix: ApplyOp }): JSX.Element {
+ return (
+ <LemonBanner type="warning">
+ A mapping works around the tagging, it doesn't fix it. The lasting fix is to tag the ad URLs with{' '}
+ <code className="font-mono">
+ utm_source={String(fix.expected_utm_source)}
+ {fix.expected_utm_campaign ? `&utm_campaign=${String(fix.expected_utm_campaign)}` : ''}
+ </code>{' '}
+ in the platform.
+ </LemonBanner>
+ )
+}
+
+/** Review-then-apply. The before/after is computed from the same op the server will
+ * execute, so the preview can't drift from the change. */
+export function SuggestionModal({
+ suggestion,
+ batch,
+ onClose,
+ onConfirm,
+ onConfirmBatch,
+ isApplying,
+}: {
+ suggestion: Suggestion | null
+ /** Non-empty when reviewing "apply all safe" rather than one row. */
+ batch: Suggestion[]
+ onClose: () => void
+ onConfirm: (suggestion: Suggestion) => void
+ onConfirmBatch: (suggestions: Suggestion[]) => void
+ isApplying: boolean
+}): JSX.Element | null {
+ const { marketingAnalyticsConfig } = useValues(marketingAnalyticsSettingsLogic)
+ // Above the early returns below — hook order has to match on every render.
+ const logo = usePlatformLogo(suggestion?.integration ?? null)
+
+ if (batch.length) {
+ const lines = batch.flatMap((item) =>
+ item.apply ? buildApplyDiff(item.apply, marketingAnalyticsConfig).lines : []
+ )
+ return (
+ <LemonModal
+ isOpen
+ onClose={onClose}
+ title={`Apply ${batch.length} safe change${batch.length === 1 ? '' : 's'}`}
+ description="High-confidence, reversible changes only. Anything needing a judgement call was left out."
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={onClose}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ loading={isApplying}
+ onClick={() => (lines.length ? onConfirmBatch(batch) : onClose())}
+ >
+ {lines.length ? `Apply ${lines.length} change${lines.length === 1 ? '' : 's'}` : 'Close'}
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="deprecated-space-y-3 max-w-xl">
+ {lines.length ? (
+ <DiffBlock lines={lines} />
+ ) : (
+ <LemonBanner type="info">These are already applied — nothing would change.</LemonBanner>
+ )}
+ <ul className="text-sm text-secondary mb-0 pl-4 list-disc">
+ {batch.map((item) => (
+ <li key={item.id}>{item.title}</li>
+ ))}
+ </ul>
+ </div>
+ </LemonModal>
+ )
+ }
+
+ if (!suggestion?.apply) {
+ return null
+ }
+
+ const op = suggestion.apply
+ const explain = explanationFor(op)
+ const diff = explain ? null : buildApplyDiff(op, marketingAnalyticsConfig)
+ const urlFix = suggestion.also_recommended.find((candidate) => candidate.op === 'fix_platform_urls')
+
+ return (
+ <LemonModal
+ isOpen
+ onClose={onClose}
+ title={
+ logo ? (
+ <span className="flex items-center gap-2">
+ {logo}
+ {suggestion.title}
+ </span>
+ ) : (
+ suggestion.title
+ )
+ }
+ description={suggestion.evidence}
+ footer={
+ <>
+ <LemonButton type="secondary" onClick={onClose}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ loading={isApplying}
+ status={
+ suggestion.kind === 'remove_mapping' || op.op === 'delete_conversion_goal'
+ ? 'danger'
+ : undefined
+ }
+ // Applying a no-op would report "applied" and hand back an Undo
+ // that strips config the user already had.
+ onClick={() => (diff?.isNoop && !explain ? onClose() : onConfirm(suggestion))}
+ >
+ {explain ? 'Continue' : diff?.isNoop ? 'Close' : (APPLY_LABEL[op.op] ?? 'Apply change')}
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="deprecated-space-y-3 max-w-xl">
+ {explain ? (
+ <p className="mb-0">{explain(op)}</p>
+ ) : diff?.isNoop ? (
+ <LemonBanner type="info">
+ This is already applied — nothing would change. It'll disappear from the list on the next scan.
+ </LemonBanner>
+ ) : (
+ <DiffBlock lines={diff?.lines ?? []} />
+ )}
+
+ {urlFix ? <UrlFixBanner fix={urlFix} /> : null}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.test.tsx b/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.test.tsx
new file mode 100644
index 000000000000..1ec266416c6b
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.test.tsx
@@ -0,0 +1,90 @@
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+
+import { SetupSection } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+import type { Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { SuggestionRow } from './SuggestionRow'
+
+const suggestion = (overrides: Partial<Suggestion> = {}): Suggestion =>
+ ({
+ id: 'fix_sync:bing_ads',
+ kind: 'fix_sync',
+ source: 'deterministic',
+ severity: 'error',
+ confidence: 0.9,
+ title: 'Fix the Bing Ads sync',
+ evidence: 'Last successful sync is older than 24h.',
+ unlocks: [],
+ apply: null,
+ also_recommended: [],
+ safe_to_batch: false,
+ rank_score: 10,
+ integration: 'BingAds',
+ deep_link: null,
+ docs_url: null,
+ spend_at_risk: 0,
+ event_volume: 0,
+ ...overrides,
+ }) as Suggestion
+
+describe('SuggestionRow', () => {
+ beforeEach(() => {
+ useMocks({ get: { '/api/projects/:team_id/marketing_analytics/utm_audit': () => [200, {}] } })
+ initKeaTests()
+ })
+
+ afterEach(cleanup)
+
+ /** A suggestion with no `apply` is still actionable — the plan says where the fix
+ * lives. Offering only Dismiss is how a real finding reads as a dead end. */
+ it('links out when the fix lives outside the tab', async () => {
+ const { container } = render(
+ <SuggestionRow suggestion={suggestion({ deep_link: '/warehouse/1/schemas' })} onReview={() => {}} />
+ )
+
+ await waitFor(() => expect(screen.getByText('Open source')).toBeTruthy())
+ // `deep_link` arrives project-relative, and LemonButton scopes it to the current project.
+ expect(container.querySelector('a')?.getAttribute('href')).toContain('/warehouse/1/schemas')
+ })
+
+ it('offers the owning section when there is no link', async () => {
+ render(<SuggestionRow suggestion={suggestion({ kind: 'fix_platform_urls' })} onReview={() => {}} />)
+
+ await waitFor(() => expect(screen.getByText('Integration health')).toBeTruthy())
+ })
+
+ /** Setup re-hosts the settings components, so sending someone out to a new tab to
+ * reach the same editor is a detour. */
+ it('keeps an open_settings fix inside the tab', async () => {
+ render(
+ <SuggestionRow
+ suggestion={
+ {
+ ...suggestion({ kind: 'fix_conversion_goal' }),
+ apply: { op: 'open_settings', anchor: 'environment-marketing-analytics' },
+ } as Suggestion
+ }
+ onReview={() => {}}
+ />
+ )
+
+ await waitFor(() => expect(screen.getByText('Conversion goals')).toBeTruthy())
+ expect(screen.queryByText('Open settings')).toBeNull()
+ })
+
+ it('does not offer the section it is already rendered in', async () => {
+ render(
+ <SuggestionRow
+ suggestion={suggestion({ kind: 'fix_platform_urls' })}
+ onReview={() => {}}
+ currentSection={SetupSection.INTEGRATION_HEALTH}
+ />
+ )
+
+ await waitFor(() => expect(screen.getByText('Dismiss')).toBeTruthy())
+ expect(screen.queryByText('Integration health')).toBeNull()
+ })
+})
diff --git a/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.tsx b/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.tsx
new file mode 100644
index 000000000000..437d10c6a10c
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/SuggestionRow.tsx
@@ -0,0 +1,168 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import {
+ SetupSection,
+ marketingAnalyticsLogic,
+} from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+import type { ApplyOp, Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+import { setupPlanLogic } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import { CAPABILITY_COPY } from './ReadinessHeader'
+import { SECTION_BY_KIND, SECTION_LABEL } from './sectionRouting'
+import { SuggestionIcon } from './SuggestionIcon'
+
+function findOp(ops: ApplyOp[], op: string): ApplyOp | undefined {
+ return ops.find((candidate) => candidate.op === op)
+}
+
+const CTA_LABEL: Record<string, string> = {
+ retry_sync: 'Retry sync',
+ retry_syncs: 'Retry all',
+ open_sources_section: 'Go to sources',
+ open_oauth: 'Reconnect',
+ open_source_wizard: 'Connect',
+ open_schemas: 'Select tables',
+ open_source_columns: 'Map columns',
+ open_goal_editor: 'Fix goal',
+ open_mapping_editor: 'Choose',
+ open_settings: 'Open settings',
+}
+
+/** Advice, never an apply button — the mapping is the workaround, retagging the ad URL
+ * is the fix. */
+function UrlFixHint({ fix }: { fix: ApplyOp }): JSX.Element {
+ const expectedSource = fix.expected_utm_source as string
+ const expectedCampaign = fix.expected_utm_campaign as string
+ const snippet = [
+ expectedSource ? `utm_source=${expectedSource}` : null,
+ expectedCampaign ? `utm_campaign=${expectedCampaign}` : null,
+ ]
+ .filter(Boolean)
+ .join('&')
+
+ if (!snippet) {
+ return (
+ <span className="text-xs text-secondary">
+ Better fix: tag the ad URLs in the platform so the UTM values match.
+ </span>
+ )
+ }
+
+ return (
+ <div className="flex items-center gap-2 text-xs text-secondary">
+ <span>Better fix — tag the ad URLs with</span>
+ <code className="font-mono">{snippet}</code>
+ <LemonButton size="xsmall" type="tertiary" onClick={() => void copyToClipboard(snippet, 'UTM parameters')}>
+ Copy
+ </LemonButton>
+ </div>
+ )
+}
+
+export function SuggestionRow({
+ suggestion,
+ onReview,
+ isDismissed = false,
+ currentSection,
+}: {
+ suggestion: Suggestion
+ onReview: (suggestion: Suggestion) => void
+ /** Set when the row is rendered inside a section, so it doesn't offer to send you
+ * where you already are. */
+ currentSection?: SetupSection
+ /** Set inside the hidden list, which swaps Dismiss for Restore. */
+ isDismissed?: boolean
+}): JSX.Element {
+ const { applyingIds } = useValues(setupPlanLogic)
+ const { dismissSuggestion, restoreSuggestion } = useActions(setupPlanLogic)
+ const { setSetupSection } = useActions(marketingAnalyticsLogic)
+
+ const isApplying = applyingIds.includes(suggestion.id)
+ const urlFix = findOp(suggestion.also_recommended, 'fix_platform_urls')
+ // Nothing to apply doesn't mean nothing to do: `deep_link` for fixes that live
+ // outside this tab, the owning section for the rest.
+ const section = SECTION_BY_KIND[suggestion.kind]
+ // Setup re-hosts the marketing settings components, so `open_settings` on a
+ // suggestion we have a section for is a detour back into the same editor.
+ const settlesInTab = suggestion.apply?.op === 'open_settings' && !!section
+ const ctaLabel = suggestion.apply && !settlesInTab ? (CTA_LABEL[suggestion.apply.op] ?? 'Review change') : null
+ const sectionCta = !ctaLabel && section && section !== currentSection ? section : null
+
+ return (
+ <div className="flex items-start gap-3 py-3 px-3 border-b last:border-b-0">
+ <SuggestionIcon suggestion={suggestion} />
+
+ <div className="grow min-w-0 deprecated-space-y-1">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="font-semibold">{suggestion.title}</span>
+ {suggestion.source === 'ai' && (
+ <Tooltip title="Suggested by AI from your data. Review the evidence before applying.">
+ <LemonTag type="completion" size="small">
+ AI
+ </LemonTag>
+ </Tooltip>
+ )}
+ </div>
+
+ <div className="text-sm text-secondary">{suggestion.evidence}</div>
+
+ {suggestion.unlocks.length > 0 && (
+ <div className="flex items-center gap-1 flex-wrap text-xs text-secondary">
+ <Tooltip title="The metrics this fix makes available. They stay empty or wrong until it's done.">
+ <span className="border-b border-dotted border-secondary cursor-help">Unlocks</span>
+ </Tooltip>
+ {suggestion.unlocks.map((capability) => (
+ <Tooltip key={capability} title={CAPABILITY_COPY[capability]?.what}>
+ <LemonTag size="small" type="muted">
+ {CAPABILITY_COPY[capability]?.label ?? capability}
+ </LemonTag>
+ </Tooltip>
+ ))}
+ </div>
+ )}
+
+ {urlFix && <UrlFixHint fix={urlFix} />}
+ </div>
+
+ <div className="flex items-center gap-1 shrink-0">
+ {ctaLabel && (
+ <LemonButton type="primary" size="small" loading={isApplying} onClick={() => onReview(suggestion)}>
+ {ctaLabel}
+ </LemonButton>
+ )}
+ {!ctaLabel && suggestion.deep_link && (
+ <LemonButton type="secondary" size="small" to={suggestion.deep_link} targetBlank>
+ Open source
+ </LemonButton>
+ )}
+ {!suggestion.deep_link && sectionCta && (
+ <LemonButton type="secondary" size="small" onClick={() => setSetupSection(sectionCta)}>
+ {SECTION_LABEL[sectionCta]}
+ </LemonButton>
+ )}
+ {isDismissed ? (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ tooltip="Put this back in the list"
+ onClick={() => restoreSuggestion(suggestion.id)}
+ >
+ Restore
+ </LemonButton>
+ ) : (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ tooltip="Hide this — it stays hidden across rescans until you restore it, and nothing is fixed"
+ onClick={() => dismissSuggestion(suggestion.id)}
+ >
+ Dismiss
+ </LemonButton>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/marketing-analytics/Setup/applyDiff.test.ts b/frontend/src/scenes/marketing-analytics/Setup/applyDiff.test.ts
new file mode 100644
index 000000000000..9395d376871f
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/applyDiff.test.ts
@@ -0,0 +1,107 @@
+import type { MarketingAnalyticsConfig } from '~/queries/schema/schema-general'
+
+import { buildApplyDiff } from './applyDiff'
+
+const config = (overrides: Partial<MarketingAnalyticsConfig> = {}): MarketingAnalyticsConfig =>
+ ({
+ custom_source_mappings: {},
+ campaign_name_mappings: {},
+ campaign_field_preferences: {},
+ conversion_goals: [],
+ ...overrides,
+ }) as MarketingAnalyticsConfig
+
+describe('buildApplyDiff', () => {
+ it('describes adding a source mapping', () => {
+ const diff = buildApplyDiff(
+ { op: 'add_custom_source_mapping', integration: 'MetaAds', raw_utm_source: 'fb-ads' },
+ config()
+ )
+
+ expect(diff.isNoop).toBe(false)
+ expect(diff.lines).toEqual([
+ { setting: 'Custom source mappings', subject: 'Meta Ads', change: 'add', after: 'fb-ads' },
+ ])
+ })
+
+ it('reports a no-op when the mapping already exists', () => {
+ // The apply endpoint treats this as an idempotent success, so the modal has to
+ // say "nothing would change" rather than render an empty diff that reads as a bug.
+ const diff = buildApplyDiff(
+ { op: 'add_custom_source_mapping', integration: 'MetaAds', raw_utm_source: 'fb-ads' },
+ config({ custom_source_mappings: { MetaAds: ['fb-ads'] } })
+ )
+
+ expect(diff.isNoop).toBe(true)
+ expect(diff.lines).toEqual([])
+ })
+
+ it('shows the default as the before value for match field', () => {
+ // An absent preference means campaign_name. Showing "not set" would suggest
+ // matching wasn't happening at all, which isn't true.
+ const diff = buildApplyDiff(
+ { op: 'set_campaign_field_preference', integration: 'GoogleAds', match_field: 'campaign_id' },
+ config()
+ )
+
+ expect(diff.lines[0]).toMatchObject({ change: 'update', before: 'campaign name', after: 'campaign id' })
+ })
+
+ it('only lists the raw values a campaign mapping actually adds', () => {
+ const diff = buildApplyDiff(
+ {
+ op: 'add_campaign_name_mapping',
+ integration: 'GoogleAds',
+ clean_name: 'spring_sale',
+ raw_values: ['sprng_sale', 'spring_sle'],
+ },
+ config({ campaign_name_mappings: { GoogleAds: { spring_sale: ['sprng_sale'] } } })
+ )
+
+ expect(diff.lines.map((line) => line.after)).toEqual(['spring_sle'])
+ })
+
+ it('names the goal being removed rather than its id', () => {
+ const diff = buildApplyDiff(
+ { op: 'delete_conversion_goal', conversion_goal_id: 'cg_demos' },
+ config({ conversion_goals: [{ conversion_goal_id: 'cg_demos', conversion_goal_name: 'Demos' }] as any })
+ )
+
+ expect(diff.lines[0]).toMatchObject({ change: 'remove', after: 'Demos' })
+ })
+
+ it('renders a goal flag update as a readable before and after', () => {
+ const diff = buildApplyDiff(
+ { op: 'update_conversion_goal', conversion_goal_id: 'cg_1', patch: { counts_as_revenue: true } },
+ config({ conversion_goals: [{ conversion_goal_id: 'cg_1', conversion_goal_name: 'Purchase' }] as any })
+ )
+
+ expect(diff.lines[0]).toMatchObject({ change: 'update', before: 'not set', after: 'yes' })
+ })
+
+ it('names goal fields the way the goal editor names them', () => {
+ // A preview reading `counts_as_revenue` asks the user to know the schema in
+ // order to approve a change to it.
+ const diff = buildApplyDiff(
+ { op: 'update_conversion_goal', conversion_goal_id: 'cg_1', patch: { counts_as_revenue: true } },
+ config({ conversion_goals: [{ conversion_goal_id: 'cg_1', conversion_goal_name: 'Purchase' }] as any })
+ )
+
+ expect(diff.lines[0].subject).toBe('Purchase › Each conversion is worth money')
+ })
+
+ it('passes an unmapped goal field through readably', () => {
+ // A field added backend-first should look unpolished, not invisible.
+ const diff = buildApplyDiff(
+ { op: 'update_conversion_goal', conversion_goal_id: 'cg_1', patch: { some_new_flag: true } },
+ config({ conversion_goals: [{ conversion_goal_id: 'cg_1', conversion_goal_name: 'Purchase' }] as any })
+ )
+
+ expect(diff.lines[0].subject).toBe('Purchase › some new flag')
+ })
+
+ it('produces nothing for an op it cannot describe', () => {
+ // Navigate ops have no config change; the modal explains them in words instead.
+ expect(buildApplyDiff({ op: 'open_oauth', kind: 'google-ads' }, config()).lines).toEqual([])
+ })
+})
diff --git a/frontend/src/scenes/marketing-analytics/Setup/applyDiff.ts b/frontend/src/scenes/marketing-analytics/Setup/applyDiff.ts
new file mode 100644
index 000000000000..26bd9648e7b4
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/applyDiff.ts
@@ -0,0 +1,184 @@
+import type { ApplyOp } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+import type { MarketingAnalyticsConfig } from '~/queries/schema/schema-general'
+
+/** One line of a change preview: a setting, and what happens to it. */
+export interface DiffLine {
+ /** Human-facing setting name, e.g. "Custom source mappings". */
+ setting: string
+ /** What the change applies to within that setting, e.g. "Meta Ads". */
+ subject?: string
+ change: 'add' | 'remove' | 'update'
+ /** Present for `update`; absent for add/remove. */
+ before?: string
+ after: string
+}
+
+export interface ApplyDiff {
+ lines: DiffLine[]
+ /** True when the op changes nothing — re-applying a mapping that already exists.
+ * The UI says so rather than showing an empty diff, which reads as a bug. */
+ isNoop: boolean
+}
+
+const SETTING_LABELS = {
+ customSourceMappings: 'Custom source mappings',
+ campaignNameMappings: 'Campaign name mappings',
+ campaignFieldPreferences: 'Campaign matching',
+ conversionGoals: 'Conversion goals',
+} as const
+
+function integrationLabel(integration: unknown): string {
+ // Config keys are PascalCase source types ("GoogleAds"); split them for reading.
+ return String(integration ?? '').replace(/([a-z])([A-Z])/g, '$1 $2')
+}
+
+/** Named as the goal editor names them, so approving a change doesn't require knowing
+ * the schema. */
+const GOAL_FIELD_LABELS: Record<string, string> = {
+ counts_as_revenue: 'Each conversion is worth money',
+ counts_as_customer: 'Counts as a new customer',
+ conversion_goal_name: 'Name',
+ math: 'Aggregation',
+ math_property: 'Amount property',
+ math_property_revenue_currency: 'Currency',
+}
+
+function goalFieldLabel(key: string): string {
+ // A field added backend-first should look unpolished, not invisible.
+ return GOAL_FIELD_LABELS[key] ?? key.replace(/_/g, ' ')
+}
+
+/** What a config-mutating op will change, derived from the same `ApplyOp` the server
+ * will execute so the preview can't drift. Undescribable ops return no lines. */
+export function buildApplyDiff(op: ApplyOp, config: MarketingAnalyticsConfig | null | undefined): ApplyDiff {
+ const lines: DiffLine[] = []
+
+ switch (op.op) {
+ case 'add_custom_source_mapping': {
+ const existing = config?.custom_source_mappings?.[op.integration as string] ?? []
+ if (!existing.includes(op.raw_utm_source as string)) {
+ lines.push({
+ setting: SETTING_LABELS.customSourceMappings,
+ subject: integrationLabel(op.integration),
+ change: 'add',
+ after: String(op.raw_utm_source),
+ })
+ }
+ break
+ }
+
+ case 'remove_custom_source_mapping': {
+ const existing = config?.custom_source_mappings?.[op.integration as string] ?? []
+ if (existing.includes(op.raw_utm_source as string)) {
+ lines.push({
+ setting: SETTING_LABELS.customSourceMappings,
+ subject: integrationLabel(op.integration),
+ change: 'remove',
+ after: String(op.raw_utm_source),
+ })
+ }
+ break
+ }
+
+ case 'add_campaign_name_mapping': {
+ const existing = config?.campaign_name_mappings?.[op.integration as string]?.[op.clean_name as string] ?? []
+ const added = (op.raw_values as string[]).filter((value) => !existing.includes(value))
+ for (const value of added) {
+ lines.push({
+ setting: SETTING_LABELS.campaignNameMappings,
+ subject: `${integrationLabel(op.integration)} › ${op.clean_name}`,
+ change: 'add',
+ after: value,
+ })
+ }
+ break
+ }
+
+ case 'remove_campaign_name_mapping': {
+ const existing = config?.campaign_name_mappings?.[op.integration as string]?.[op.clean_name as string] ?? []
+ const removed = (op.raw_values as string[]).filter((value) => existing.includes(value))
+ for (const value of removed) {
+ lines.push({
+ setting: SETTING_LABELS.campaignNameMappings,
+ subject: `${integrationLabel(op.integration)} › ${op.clean_name}`,
+ change: 'remove',
+ after: value,
+ })
+ }
+ break
+ }
+
+ case 'set_campaign_field_preference': {
+ // An absent preference means campaign_name, the documented default —
+ // "not set" would suggest no matching was happening at all.
+ const before =
+ config?.campaign_field_preferences?.[op.integration as string]?.match_field ?? 'campaign_name'
+ if (before !== op.match_field) {
+ lines.push({
+ setting: SETTING_LABELS.campaignFieldPreferences,
+ subject: integrationLabel(op.integration),
+ change: 'update',
+ before: String(before).replace(/_/g, ' '),
+ after: String(op.match_field).replace(/_/g, ' '),
+ })
+ }
+ break
+ }
+
+ case 'create_conversion_goal': {
+ const goal = op.goal as Record<string, unknown>
+ lines.push({
+ setting: SETTING_LABELS.conversionGoals,
+ change: 'add',
+ after: String(goal.conversion_goal_name ?? goal.event ?? 'New goal'),
+ })
+ break
+ }
+
+ case 'delete_conversion_goal': {
+ const goal = config?.conversion_goals?.find(
+ (candidate) => candidate.conversion_goal_id === op.conversion_goal_id
+ )
+ lines.push({
+ setting: SETTING_LABELS.conversionGoals,
+ change: 'remove',
+ after: goal?.conversion_goal_name ?? String(op.conversion_goal_id),
+ })
+ break
+ }
+
+ case 'update_conversion_goal': {
+ const goal = config?.conversion_goals?.find(
+ (candidate) => candidate.conversion_goal_id === op.conversion_goal_id
+ )
+ const patch = op.patch as Record<string, unknown>
+ for (const [key, value] of Object.entries(patch)) {
+ const before = goal ? (goal as unknown as Record<string, unknown>)[key] : undefined
+ if (before === value) {
+ continue
+ }
+ lines.push({
+ setting: SETTING_LABELS.conversionGoals,
+ subject: `${goal?.conversion_goal_name ?? op.conversion_goal_id} › ${goalFieldLabel(key)}`,
+ change: 'update',
+ before: formatValue(before),
+ after: formatValue(value),
+ })
+ }
+ break
+ }
+ }
+
+ return { lines, isNoop: lines.length === 0 }
+}
+
+function formatValue(value: unknown): string {
+ if (value === undefined || value === null) {
+ return 'not set'
+ }
+ if (typeof value === 'boolean') {
+ return value ? 'yes' : 'no'
+ }
+ return String(value)
+}
diff --git a/frontend/src/scenes/marketing-analytics/Setup/navigateOps.ts b/frontend/src/scenes/marketing-analytics/Setup/navigateOps.ts
new file mode 100644
index 000000000000..6347a72c647c
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/navigateOps.ts
@@ -0,0 +1,38 @@
+import api from 'lib/api'
+import { urls } from 'scenes/urls'
+import type { ApplyOp } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+/** Perform an op the browser owns, returning whether it handled it.
+ *
+ * In the view rather than `setupPlanLogic` to keep the scene's dependency graph —
+ * sourceManagementLogic and friends — out of everything that touches a suggestion.
+ *
+ * New tabs throughout: the user is midway through a checklist and navigating away
+ * loses their place in it.
+ */
+export function runNavigateOp(op: ApplyOp): boolean {
+ switch (op.op) {
+ case 'open_oauth':
+ window.open(
+ api.integrations.authorizeUrl({
+ kind: op.kind as string,
+ next: window.location.pathname + window.location.search,
+ }),
+ '_blank',
+ 'noopener'
+ )
+ return true
+ case 'open_source_wizard':
+ window.open(
+ urls.dataWarehouseSourceNew(op.kind as string, urls.marketingAnalyticsApp(), 'Marketing analytics'),
+ '_blank',
+ 'noopener'
+ )
+ return true
+ case 'open_settings':
+ window.open(urls.settings(op.anchor as any, 'marketing-settings'), '_blank', 'noopener')
+ return true
+ default:
+ return false
+ }
+}
diff --git a/frontend/src/scenes/marketing-analytics/Setup/sectionRouting.ts b/frontend/src/scenes/marketing-analytics/Setup/sectionRouting.ts
new file mode 100644
index 000000000000..6245a38cd1d0
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/sectionRouting.ts
@@ -0,0 +1,41 @@
+import { SetupSection } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic'
+import type { Suggestion } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic'
+
+/** Section names, kept here rather than in `SETUP_SECTIONS` so a suggestion row can
+ * name where it's sending you without importing every settings component. */
+export const SECTION_LABEL: Record<SetupSection, string> = {
+ [SetupSection.SUGGESTIONS]: 'Suggested setup',
+ [SetupSection.SOURCES]: 'Ad platforms & sources',
+ [SetupSection.CONVERSION_GOALS]: 'Conversion goals',
+ [SetupSection.UTM_MAPPING]: 'UTM & campaign mapping',
+ [SetupSection.INTEGRATION_HEALTH]: 'Integration health',
+ [SetupSection.ATTRIBUTION]: 'Attribution',
+ [SetupSection.GENERAL]: 'General',
+}
+
+/** Which part of Setup owns each kind of suggestion. A missing kind still shows up in
+ * "Suggested setup", just not in a section — the safe direction for one added
+ * backend-first. */
+export const SECTION_BY_KIND: Record<string, SetupSection> = {
+ connect_source: SetupSection.SOURCES,
+ reconnect_oauth: SetupSection.SOURCES,
+ fix_sync: SetupSection.SOURCES,
+ map_schema_columns: SetupSection.SOURCES,
+
+ add_source_mapping: SetupSection.UTM_MAPPING,
+ add_campaign_name_mapping: SetupSection.UTM_MAPPING,
+ switch_campaign_match_field: SetupSection.UTM_MAPPING,
+ remove_mapping: SetupSection.UTM_MAPPING,
+
+ // Untagged ad URLs and orphaned campaigns are what the audit is about.
+ fix_platform_urls: SetupSection.INTEGRATION_HEALTH,
+
+ create_conversion_goal: SetupSection.CONVERSION_GOALS,
+ fix_conversion_goal: SetupSection.CONVERSION_GOALS,
+ mark_goal_as_revenue: SetupSection.CONVERSION_GOALS,
+ mark_goal_as_customer: SetupSection.CONVERSION_GOALS,
+}
+
+export function suggestionsForSection(suggestions: Suggestion[], section: SetupSection): Suggestion[] {
+ return suggestions.filter((suggestion) => SECTION_BY_KIND[suggestion.kind] === section)
+}
diff --git a/frontend/src/scenes/marketing-analytics/Setup/setupSections.tsx b/frontend/src/scenes/marketing-analytics/Setup/setupSections.tsx
new file mode 100644
index 000000000000..e02c37e99983
--- /dev/null
+++ b/frontend/src/scenes/marketing-analytics/Setup/setupSections.tsx
@@ -0,0 +1,81 @@
+import { BaseCurrency } from 'lib/components/BaseCurrency/BaseCurrency'
+import { LegacyOAuthReconnectBanner } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/LegacyOAuthReconnectBanner'
+import { AttributionSettings } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/AttributionSettings'
+import { CampaignFieldPreferencesConfiguration } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/CampaignFieldPreferencesConfiguration'
+import { CampaignNameMappingsConfiguration } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/CampaignNameMappingsConfiguration'
+import { ConversionGoalsConfiguration } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ConversionGoalsConfiguration'
+import { CustomSourceMappingsConfiguration } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/CustomSourceMappingsConfiguration'
+import { ExternalDataSourceConfiguration } from 'scenes/web-analytics/tabs/marketing-analytics/frontend/components/settings/ExternalDataSourceConfiguration'
+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 { SECTION_LABEL } from './sectionRouting'
+import { SuggestedActions } from './SuggestedActions'
+
+export interface SetupSectionDef {
+ key: SetupSection
+ label: string
+ description: string
+ content: JSX.Element
+}
+
+/** The manual half of the tab. Each entry re-hosts existing components, so this and
+ * /settings/environment-marketing-analytics are two entry points over one set of
+ * components rather than a fork. */
+export const SETUP_SECTIONS: SetupSectionDef[] = [
+ {
+ key: SetupSection.SUGGESTIONS,
+ label: SECTION_LABEL[SetupSection.SUGGESTIONS],
+ description: '',
+ content: <SuggestedActions />,
+ },
+ {
+ key: SetupSection.SOURCES,
+ label: SECTION_LABEL[SetupSection.SOURCES],
+ description: 'Connect ad platforms and map their spend columns.',
+ content: (
+ <>
+ <LegacyOAuthReconnectBanner />
+ <ExternalDataSourceConfiguration />
+ </>
+ ),
+ },
+ {
+ key: SetupSection.CONVERSION_GOALS,
+ label: SECTION_LABEL[SetupSection.CONVERSION_GOALS],
+ description: 'The events that count as a conversion, and what each one is worth.',
+ content: <ConversionGoalsConfiguration />,
+ },
+ {
+ key: SetupSection.UTM_MAPPING,
+ label: SECTION_LABEL[SetupSection.UTM_MAPPING],
+ // Reachable until now only through a modal behind the
+ // `advance-marketing-analytics-settings` flag.
+ description: 'Map UTM values that do not match what the ad platform reports.',
+ content: (
+ <div className="deprecated-space-y-6">
+ <CustomSourceMappingsConfiguration />
+ <CampaignNameMappingsConfiguration />
+ <CampaignFieldPreferencesConfiguration />
+ </div>
+ ),
+ },
+ {
+ key: SetupSection.INTEGRATION_HEALTH,
+ label: SECTION_LABEL[SetupSection.INTEGRATION_HEALTH],
+ description: 'Where ad-platform campaigns and UTM tags disagree.',
+ content: <UtmAuditTab />,
+ },
+ {
+ key: SetupSection.ATTRIBUTION,
+ label: SECTION_LABEL[SetupSection.ATTRIBUTION],
+ description: 'Attribution mode and lookback window.',
+ content: <AttributionSettings />,
+ },
+ {
+ key: SetupSection.GENERAL,
+ label: SECTION_LABEL[SetupSection.GENERAL],
+ description: 'Currency and other project-wide settings.',
+ content: <BaseCurrency />,
+ },
+]
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 67751bb46961..6c697353e616 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
@@ -69,7 +69,33 @@ export type NativeSourceHierarchyStatus = {
export enum MarketingAnalyticsTab {
DASHBOARD = 'dashboard',
ATTRIBUTION = 'attribution',
+ // Still the tab key when Setup's flag is off, which is everywhere until it rolls
+ // out. Removing it would change the URL and the header copy for every user of the
+ // audit — which is fully rolled out — for no gain.
INTEGRATION_HEALTH = 'integration-health',
+ SETUP = 'setup',
+}
+
+/** Section within the Setup tab, synced to `?section=`. Declared here rather than
+ * alongside the components so the logic doesn't import from the scene, which imports
+ * the logic back. */
+export enum SetupSection {
+ SUGGESTIONS = 'suggestions',
+ SOURCES = 'sources',
+ CONVERSION_GOALS = 'conversion-goals',
+ UTM_MAPPING = 'utm-mapping',
+ INTEGRATION_HEALTH = 'integration-health',
+ ATTRIBUTION = 'attribution',
+ GENERAL = 'general',
+}
+
+export const DEFAULT_SETUP_SECTION = SetupSection.SUGGESTIONS
+
+/** Where a tab key lands once Setup absorbs it. Applied by the scene, which is what
+ * knows whether Setup is rendering — with its flag off `integration-health` is still a
+ * real tab and resolves on its own. */
+export const SETUP_ABSORBED_TABS: Partial<Record<MarketingAnalyticsTab, SetupSection>> = {
+ [MarketingAnalyticsTab.INTEGRATION_HEALTH]: SetupSection.INTEGRATION_HEALTH,
}
const EXTENDED_DRILL_DOWN_LEVELS = new Set<MarketingAnalyticsDrillDownLevel>([
@@ -279,6 +305,7 @@ export interface marketingAnalyticsLogicValues {
nativeSources: ExternalDataSource[]
nativeSourcesHierarchyStatus: NativeSourceHierarchyStatus[]
overviewQuery: MarketingAnalyticsAggregatedQuery
+ setupSection: SetupSection
tileColumnSelection: validColumnsForTiles
uniqueConversionGoalName: string
validExternalTables: ExternalTable[]
@@ -404,6 +431,9 @@ export interface marketingAnalyticsLogicActions {
setIntegrationFilter: (integrationFilter: IntegrationFilter) => {
integrationFilter: IntegrationFilter
}
+ setSetupSection: (section: SetupSection) => {
+ section: SetupSection
+ }
setTileColumnSelection: (column: validColumnsForTiles) => {
column: validColumnsForTiles
}
@@ -582,6 +612,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
})),
actions({
setActiveTab: (tab: MarketingAnalyticsTab) => ({ tab }),
+ setSetupSection: (section: SetupSection) => ({ section }),
// Low-level state setters (used by listeners)
setDraftConversionGoal: (goal: ConversionGoalFilter | null) => ({ goal }),
@@ -633,6 +664,12 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
setActiveTab: (_, { tab }) => tab,
},
],
+ setupSection: [
+ DEFAULT_SETUP_SECTION as SetupSection,
+ {
+ setSetupSection: (_, { section }) => section,
+ },
+ ],
initialized: [
false,
{
@@ -1219,6 +1256,11 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
searchParams.set('tab', values.activeTab)
}
+ // Section is meaningless outside Setup, and the default is implied.
+ if (values.activeTab === MarketingAnalyticsTab.SETUP && values.setupSection !== DEFAULT_SETUP_SECTION) {
+ searchParams.set('section', values.setupSection)
+ }
+
// Date filters
if (values.dateFilter.dateFrom) {
searchParams.set('date_from', values.dateFilter.dateFrom)
@@ -1263,6 +1305,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
return {
setActiveTab: buildUrl,
+ setSetupSection: buildUrl,
setDates: buildUrl,
setDateInterval: buildUrl,
setDatesAndInterval: buildUrl,
@@ -1376,9 +1419,14 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
const searchParams = new URLSearchParams(window.location.search)
const params: Parameters<typeof actions.syncFromUrl>[0] = {}
- const tab = searchParams.get('tab') as MarketingAnalyticsTab | null
- if (tab && Object.values(MarketingAnalyticsTab).includes(tab)) {
- actions.setActiveTab(tab)
+ const rawTab = searchParams.get('tab')
+ if (rawTab && Object.values(MarketingAnalyticsTab).includes(rawTab as MarketingAnalyticsTab)) {
+ actions.setActiveTab(rawTab as MarketingAnalyticsTab)
+ }
+
+ const section = searchParams.get('section') as SetupSection | null
+ if (section && Object.values(SetupSection).includes(section)) {
+ actions.setSetupSection(section)
}
const dateFrom = searchParams.get('date_from')
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.test.ts
new file mode 100644
index 000000000000..3f0f12293dcf
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.test.ts
@@ -0,0 +1,440 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { marketingAnalyticsSettingsLogic } from './marketingAnalyticsSettingsLogic'
+import type { ApplyOp, SetupPlanResponse, Suggestion } from './setupPlanLogic'
+import { setupPlanLogic } from './setupPlanLogic'
+
+const suggestion = (overrides: Partial<Suggestion> = {}): Suggestion => ({
+ id: 'add_source_mapping:meta_ads:fb-ads',
+ kind: 'add_source_mapping',
+ source: 'deterministic',
+ severity: 'warning',
+ confidence: 0.8,
+ title: "Map utm_source 'fb-ads' to Meta Ads",
+ evidence: '500 events arrive tagged fb-ads.',
+ unlocks: ['attribution'],
+ apply: { op: 'add_custom_source_mapping', integration: 'MetaAds', raw_utm_source: 'fb-ads' },
+ also_recommended: [],
+ safe_to_batch: true,
+ rank_score: 10,
+ integration: 'MetaAds',
+ deep_link: null,
+ docs_url: null,
+ spend_at_risk: 0,
+ event_volume: 500,
+ ...overrides,
+})
+
+const plan = (suggestions: Suggestion[]): SetupPlanResponse => ({
+ suggestions,
+ readiness: [],
+ degraded: [],
+ truncated: false,
+ summary: `${suggestions.length} suggestion(s)`,
+})
+
+const UNDO_OPS: ApplyOp[] = [{ op: 'remove_custom_source_mapping', integration: 'MetaAds', raw_utm_source: 'fb-ads' }]
+
+describe('setupPlanLogic', () => {
+ let logic: ReturnType<typeof setupPlanLogic.build>
+ let applyRequests: any[]
+
+ beforeEach(() => {
+ applyRequests = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/marketing_analytics/setup_plan': () => [200, plan([suggestion()])],
+ '/api/environments/:team_id/marketing_analytics/utm_audit': () => [200, {}],
+ },
+ post: {
+ '/api/projects/:team_id/marketing_analytics/apply_setup_ops': async ({ request }) => {
+ applyRequests.push(await request.json())
+ return [200, { applied: [], undo_ops: UNDO_OPS }]
+ },
+ },
+ })
+ initKeaTests()
+ logic = setupPlanLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it('loads the plan', async () => {
+ await expectLogic(logic, () => logic.actions.loadSetupPlan())
+ .toFinishAllListeners()
+ .toMatchValues({ suggestions: [expect.objectContaining({ id: suggestion().id })] })
+ })
+
+ it('sends the apply payload verbatim', async () => {
+ await expectLogic(logic, () => logic.actions.applySuggestion(suggestion())).toFinishAllListeners()
+
+ expect(applyRequests[0].ops).toEqual([suggestion().apply])
+ })
+
+ it('collapses the row optimistically once the op succeeds', async () => {
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+ expect(logic.values.visibleSuggestions).toHaveLength(1)
+
+ await expectLogic(logic, () => logic.actions.applySuggestion(suggestion())).toDispatchActions(['markApplied'])
+ })
+
+ it('marks only the rows the request owns, not whatever is applying', async () => {
+ // An undo starts no rows of its own. Reading the global applying set meant it
+ // adopted a concurrent apply's ids and collapsed those rows when it landed.
+ // Asserting on the action payload rather than the reducer: the reload in the
+ // listener's `finally` clears locallyAppliedIds, so the value is empty either way.
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+
+ logic.actions.setApplying(['someone-elses-suggestion'], true)
+ await expectLogic(logic, () =>
+ logic.actions.applyOps(
+ [{ op: 'remove_custom_source_mapping', integration: 'MetaAds', raw_utm_source: 'fb-ads' }],
+ { label: 'Undone', source: 'setup_tab' }
+ )
+ )
+ .toDispatchActions([
+ (action) => action.type === logic.actionTypes.markApplied && action.payload.ids.length === 0,
+ ])
+ .toFinishAllListeners()
+ })
+
+ it('refreshes the sibling logics that would otherwise go stale', async () => {
+ // apply_setup_ops writes config server-side, bypassing updateCurrentTeam. If
+ // these don't fire, the manual settings sections show stale data right next to
+ // the suggestion that just changed it — which reads as a bug.
+ await expectLogic(logic, () => logic.actions.applySuggestion(suggestion())).toDispatchActions([
+ 'loadSetupPlan',
+ 'loadCurrentTeam',
+ marketingAnalyticsSettingsLogic.actionTypes.loadMarketingAnalyticsConfig,
+ 'loadAuditData',
+ ])
+ })
+
+ it('undoes by POSTing the server-computed inverse', async () => {
+ await expectLogic(logic, () =>
+ logic.actions.applyOps(UNDO_OPS, { label: 'Undone', source: 'setup_tab' })
+ ).toFinishAllListeners()
+
+ expect(applyRequests[0].ops).toEqual(UNDO_OPS)
+ })
+
+ it('batches only the safe suggestions', async () => {
+ const unsafe = suggestion({ id: 'unsafe', safe_to_batch: false })
+ useMocks({
+ get: {
+ '/api/projects/:team_id/marketing_analytics/setup_plan': () => [200, plan([suggestion(), unsafe])],
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+ expect(logic.values.safeBatch.map((s) => s.id)).toEqual([suggestion().id])
+
+ await expectLogic(logic, () => logic.actions.applyAllSafe()).toFinishAllListeners()
+ expect(applyRequests[0].ops).toEqual([suggestion().apply])
+ // `source` is recorded against the change server-side, so a one-item batch still
+ // has to report where the click came from rather than being inferred from length.
+ expect(applyRequests[0].source).toEqual('apply_all_safe')
+ })
+
+ it('clears the safe batch once the applied suggestion leaves the plan', async () => {
+ // Reported symptom: apply the batch, and "Apply 1 safe" is still there. The
+ // count is derived from the reloaded plan, so this pins the whole cycle —
+ // apply, reload, recount — rather than any one step of it.
+ let loads = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/marketing_analytics/setup_plan': () => {
+ loads += 1
+ return [200, loads === 1 ? plan([suggestion()]) : plan([])]
+ },
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+ expect(logic.values.safeBatch).toHaveLength(1)
+
+ await expectLogic(logic, () => logic.actions.confirmReviewedBatch(logic.values.safeBatch))
+ .toFinishAllListeners()
+ .toFinishAllListeners()
+
+ expect(logic.values.safeBatch).toHaveLength(0)
+ })
+
+ it('keeps the batch visible when applying fails', async () => {
+ // The opposite guarantee: a failed apply must not hide the row, or the user
+ // thinks it worked. This is the shape the reported bug would take if the
+ // request were 400ing.
+ useMocks({
+ post: {
+ '/api/projects/:team_id/marketing_analytics/apply_setup_ops': () => [400, { ops: 'nope' }],
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.confirmReviewedBatch(logic.values.safeBatch))
+ .toFinishAllListeners()
+ .toFinishAllListeners()
+
+ expect(logic.values.safeBatch).toHaveLength(1)
+ })
+
+ it('skips the audit reload for ops the audit cannot see', async () => {
+ // The audit reruns the campaign and UTM-catalogue ClickHouse queries the plan just
+ // ran. A conversion-goal change moves neither, so reloading it pays twice for a
+ // scan whose answer can't have changed.
+ await expectLogic(logic, () =>
+ logic.actions.applySuggestion(
+ suggestion({
+ id: 'mark_goal_as_revenue:sign_up',
+ kind: 'mark_goal_as_revenue',
+ apply: { op: 'update_conversion_goal', conversion_goal_id: 'abc', patch: {} },
+ })
+ )
+ )
+ .toDispatchActions(['loadSetupPlan'])
+ .toNotHaveDispatchedActions(['loadAuditData'])
+ .toFinishAllListeners()
+ })
+
+ it('keeps the review modal open when applying fails', async () => {
+ // The reducers used to close on `loadSetupPlanSuccess`, which the listener fires
+ // from `finally` — so the reload succeeding closed the modal even though the apply
+ // had failed, losing the error and the retry.
+ useMocks({
+ post: {
+ '/api/projects/:team_id/marketing_analytics/apply_setup_ops': () => [400, { ops: 'nope' }],
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.reviewSuggestion(suggestion())).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.confirmReviewedSuggestion(suggestion())).toFinishAllListeners()
+
+ expect(logic.values.reviewingSuggestion).not.toBeNull()
+ })
+
+ it('closes the review modal once the apply lands', async () => {
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.reviewSuggestion(suggestion())).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.confirmReviewedSuggestion(suggestion())).toFinishAllListeners()
+
+ expect(logic.values.reviewingSuggestion).toBeNull()
+ })
+
+ it('does not apply a suggestion with no op', async () => {
+ await expectLogic(logic, () =>
+ logic.actions.applySuggestion(suggestion({ apply: null }))
+ ).toFinishAllListeners()
+
+ expect(applyRequests).toHaveLength(0)
+ })
+
+ it('hides a dismissed suggestion without applying anything', async () => {
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+
+ logic.actions.dismissSuggestion(suggestion().id)
+
+ expect(logic.values.visibleSuggestions).toHaveLength(0)
+ expect(applyRequests).toHaveLength(0)
+ })
+
+ describe('reviewing what was dismissed', () => {
+ beforeEach(async () => {
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+ logic.actions.dismissSuggestion(suggestion().id)
+ })
+
+ it('keeps dismissed rows reachable instead of only counting them', () => {
+ // Dismissing used to be a one-way door: a count, and no way to see or undo
+ // what was behind it.
+ expect(logic.values.dismissedSuggestions.map((s) => s.id)).toEqual([suggestion().id])
+ })
+
+ it('restores one back into the list', () => {
+ logic.actions.restoreSuggestion(suggestion().id)
+
+ expect(logic.values.visibleSuggestions).toHaveLength(1)
+ expect(logic.values.dismissedSuggestions).toHaveLength(0)
+ })
+
+ it('restores all at once', () => {
+ logic.actions.restoreAllDismissed()
+
+ expect(logic.values.dismissedIds).toEqual([])
+ expect(logic.values.visibleSuggestions).toHaveLength(1)
+ })
+
+ it('does not count a dismissal whose finding is gone', async () => {
+ // `dismissedIds` is persisted, so its ids outlive the findings: dismiss a
+ // broken sync, fix the sync, and the id sits in localStorage forever.
+ // Counting it would advertise hidden work that no longer exists.
+ useMocks({
+ get: {
+ '/api/projects/:team_id/marketing_analytics/setup_plan': () => [200, plan([])],
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+
+ expect(logic.values.dismissedIds).toEqual([suggestion().id])
+ expect(logic.values.dismissedSuggestions).toEqual([])
+ })
+ })
+
+ it('asks the server for a fresh scan only when the user asks for one', async () => {
+ // The mount-time load is happy with the server's short cache — that's what
+ // stops section navigation re-running six ClickHouse queries. An explicit
+ // Rescan has to bypass it or the button looks broken.
+ const urls: string[] = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/marketing_analytics/setup_plan': ({ request }) => {
+ urls.push(request.url)
+ return [200, plan([])]
+ },
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.loadSetupPlan({ refresh: true })).toFinishAllListeners()
+
+ expect(urls[0]).not.toContain('refresh')
+ expect(urls[1]).toContain('refresh=true')
+ })
+
+ describe('retrying syncs', () => {
+ const TARGETS = [
+ { source_id: 'src-a', display_name: 'Google Ads' },
+ { source_id: 'src-b', display_name: 'Meta Ads' },
+ { source_id: 'src-c', display_name: 'Bing Ads' },
+ ]
+ const collapsed = (): Suggestion =>
+ suggestion({
+ id: 'fix_sync:cause:stale',
+ kind: 'fix_sync',
+ apply: { op: 'retry_syncs', sources: TARGETS },
+ })
+
+ let reloaded: string[]
+ let failing: string[]
+
+ beforeEach(() => {
+ reloaded = []
+ failing = []
+ useMocks({
+ post: {
+ '/api/environments/:team_id/external_data_sources/:id/reload': (req: any) => {
+ const id = req.params.id as string
+ reloaded.push(id)
+ return failing.includes(id) ? [500, { detail: 'nope' }] : [200, {}]
+ },
+ },
+ })
+ })
+
+ it('reloads every source in the collapsed group', async () => {
+ await expectLogic(logic, () => logic.actions.confirmReviewedSuggestion(collapsed())).toFinishAllListeners()
+
+ expect(reloaded).toEqual(['src-a', 'src-b', 'src-c'])
+ // Never through apply_setup_ops: the warehouse owns this action and its
+ // permissions, and that endpoint only mutates marketing config.
+ expect(applyRequests).toHaveLength(0)
+ })
+
+ it('keeps going when one source fails', async () => {
+ // Independent sources. Stopping at the first error would leave the group
+ // half-retried with nothing saying which half.
+ failing = ['src-b']
+
+ await expectLogic(logic, () => logic.actions.confirmReviewedSuggestion(collapsed())).toFinishAllListeners()
+
+ expect(reloaded).toEqual(['src-a', 'src-b', 'src-c'])
+ })
+
+ it('still handles a single-source retry through the same path', async () => {
+ const single = suggestion({
+ id: 'fix_sync:google_ads',
+ apply: { op: 'retry_sync', source_id: 'src-a', display_name: 'Google Ads' },
+ })
+
+ await expectLogic(logic, () => logic.actions.confirmReviewedSuggestion(single)).toFinishAllListeners()
+
+ expect(reloaded).toEqual(['src-a'])
+ })
+ })
+
+ it('clears the optimistic list on reload so the server view wins', async () => {
+ await expectLogic(logic, () => logic.actions.applySuggestion(suggestion())).toFinishAllListeners()
+
+ expect(logic.values.locallyAppliedIds).toEqual([])
+ })
+
+ describe('focusing a capability', () => {
+ const cost = suggestion({ id: 'fix_sync:google_ads', unlocks: ['cost', 'roas'] })
+ const attribution = suggestion({ id: 'add_source_mapping:x', unlocks: ['attribution'] })
+
+ beforeEach(async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/marketing_analytics/setup_plan': () => [200, plan([cost, attribution])],
+ },
+ })
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+ })
+
+ it('narrows the list to what changes that metric', () => {
+ logic.actions.focusCapability('roas')
+
+ expect(logic.values.listedSuggestions.map((s) => s.id)).toEqual([cost.id])
+ })
+
+ it('leaves the section views alone', () => {
+ // The nav badges and per-section blocks read `visibleSuggestions`. A filter
+ // chosen in Suggested setup emptying the Sources section would read as data
+ // loss, not as a filter.
+ logic.actions.focusCapability('roas')
+
+ expect(logic.values.visibleSuggestions).toHaveLength(2)
+ })
+
+ it('clears when the same chip is clicked again', () => {
+ logic.actions.focusCapability('roas')
+ logic.actions.focusCapability('roas')
+
+ expect(logic.values.focusedCapability).toBeNull()
+ expect(logic.values.listedSuggestions).toHaveLength(2)
+ })
+
+ it('drops the filter on rescan', async () => {
+ logic.actions.focusCapability('roas')
+
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+
+ // A rescan can remove the capability entirely; holding the filter across it
+ // leaves an empty list with nothing on screen explaining why.
+ expect(logic.values.focusedCapability).toBeNull()
+ })
+ })
+
+ it('surfaces degraded and truncated from the response', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/marketing_analytics/setup_plan': () => [
+ 200,
+ { ...plan([]), degraded: ['attribution_health'], truncated: true },
+ ],
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.loadSetupPlan()).toFinishAllListeners()
+
+ expect(logic.values.degraded).toEqual(['attribution_health'])
+ expect(logic.values.truncated).toBe(true)
+ })
+})
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts
new file mode 100644
index 000000000000..bdff28c846be
--- /dev/null
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/setupPlanLogic.ts
@@ -0,0 +1,572 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+
+import type {
+ CapabilityReadinessApi,
+ SetupPlanResponseApi,
+ SuggestionApi,
+} from 'products/marketing_analytics/frontend/generated/api.schemas'
+
+import { marketingAnalyticsSettingsLogic } from './marketingAnalyticsSettingsLogic'
+import { utmAuditLogic } from './utmAuditLogic'
+
+export type SuggestionSeverity = 'error' | 'warning' | 'info'
+export type SuggestionSource = 'deterministic' | 'ai'
+export type ReadinessStatus = 'unlocked' | 'partial' | 'blocked'
+
+/** Ops whose writes change what the UTM audit reports. The audit reruns the campaign
+ * and UTM-catalogue queries the setup plan just ran, so reloading it for a goal change
+ * pays twice for a scan that can't have moved. */
+const AUDIT_AFFECTING_OPS = new Set([
+ 'add_custom_source_mapping',
+ 'remove_custom_source_mapping',
+ 'add_campaign_name_mapping',
+ 'remove_campaign_name_mapping',
+ 'set_campaign_field_preference',
+])
+
+const teamId = window.POSTHOG_APP_CONTEXT?.current_team?.id
+/** Suggestion ids are semantic and project-independent — `connect_source:google_ads`
+ * is the same string in every project — so an unprefixed bucket would hide a finding
+ * in one project because it was dismissed in another. Matches marketingAnalyticsLogic. */
+const persistConfig = { persist: true, prefix: `${teamId}__` }
+
+export type Capability = 'cost' | 'attribution' | 'roas' | 'cac'
+
+/** Recorded server-side against the change, so it must describe the real origin. */
+export type ApplySource = 'setup_tab' | 'apply_all_safe'
+
+/** Mirrors the `ApplyOp` union in `services/setup_types.py`. Passed back to
+ * apply_setup_ops verbatim — never construct one client-side. */
+export interface ApplyOp {
+ op: string
+ [key: string]: unknown
+}
+
+/** The serializer's shape, with the fields it can only describe as `string` or
+ * `unknown` narrowed to what the backend actually puts in them. Built on the generated
+ * type rather than restated, so a field the backend renames or drops fails to compile
+ * here instead of arriving as undefined at runtime. */
+export type Suggestion = Omit<SuggestionApi, 'source' | 'severity' | 'unlocks' | 'apply' | 'also_recommended'> & {
+ source: SuggestionSource
+ severity: SuggestionSeverity
+ unlocks: Capability[]
+ apply: ApplyOp | null
+ also_recommended: ApplyOp[]
+}
+
+/** One warehouse source to re-sync. Mirrors `SyncTarget` in `setup_types.py`. */
+export interface SyncTarget {
+ source_id: string
+ display_name: string
+}
+
+export type CapabilityReadiness = Omit<CapabilityReadinessApi, 'capability' | 'status'> & {
+ capability: Capability
+ status: ReadinessStatus
+}
+
+export type SetupPlanResponse = Omit<SetupPlanResponseApi, 'suggestions' | 'readiness'> & {
+ suggestions: Suggestion[]
+ readiness: CapabilityReadiness[]
+}
+
+interface ApplyResponse {
+ applied: ApplyOp[]
+ undo_ops: ApplyOp[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface setupPlanLogicValues {
+ currentTeamId: number | null // teamLogic
+ appliedCount: number
+ applyingIds: string[]
+ degraded: string[]
+ dismissedIds: string[]
+ dismissedSuggestions: Suggestion[]
+ focusedCapability: Capability | null
+ isReviewingBatch: boolean
+ listedSuggestions: Suggestion[]
+ locallyAppliedIds: string[]
+ readiness: CapabilityReadiness[]
+ reviewingSuggestion: Suggestion | null
+ safeBatch: Suggestion[]
+ setupPlan: SetupPlanResponse | null
+ setupPlanLoading: boolean
+ showDismissed: boolean
+ suggestions: Suggestion[]
+ truncated: boolean
+ visibleSuggestions: Suggestion[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface setupPlanLogicActions {
+ loadMarketingAnalyticsConfig: () => any // marketingAnalyticsSettingsLogic
+ loadCurrentTeam: () => any // teamLogic
+ loadAuditData: () => any // utmAuditLogic
+ applyAllSafe: () => {
+ value: true
+ }
+ applyOps: (
+ ops: ApplyOp[],
+ options: {
+ label: string
+ source: ApplySource
+ suggestionIds?: string[]
+ undoable?: boolean
+ }
+ ) => {
+ ops: ApplyOp[]
+ options: {
+ label: string
+ source: ApplySource
+ suggestionIds?: string[] | undefined
+ undoable?: boolean | undefined
+ }
+ }
+ applySuggestion: (suggestion: Suggestion) => {
+ suggestion: Suggestion
+ }
+ confirmReviewedBatch: (suggestions: Suggestion[]) => {
+ suggestions: Suggestion[]
+ }
+ confirmReviewedSuggestion: (suggestion: Suggestion) => {
+ suggestion: Suggestion
+ }
+ dismissSuggestion: (id: string) => {
+ id: string
+ }
+ focusCapability: (capability: Capability | null) => {
+ capability: Capability | null
+ }
+ loadSetupPlan: ({ refresh }?: any) => any
+ loadSetupPlanFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSetupPlanSuccess: (
+ setupPlan: SetupPlanResponse,
+ payload?: any
+ ) => {
+ setupPlan: SetupPlanResponse
+ payload?: any
+ }
+ markApplied: (ids: string[]) => {
+ ids: string[]
+ }
+ restoreAllDismissed: () => {
+ value: true
+ }
+ restoreSuggestion: (id: string) => {
+ id: string
+ }
+ retrySync: (
+ suggestionId: string,
+ targets: SyncTarget[]
+ ) => {
+ suggestionId: string
+ targets: SyncTarget[]
+ }
+ reviewSafeBatch: () => {
+ value: true
+ }
+ reviewSuggestion: (suggestion: Suggestion | null) => {
+ suggestion: Suggestion | null
+ }
+ setApplying: (
+ ids: string[],
+ applying: boolean
+ ) => {
+ applying: boolean
+ ids: string[]
+ }
+ toggleShowDismissed: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface setupPlanLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ suggestions: (setupPlan: SetupPlanResponse | null) => Suggestion[]
+ readiness: (setupPlan: SetupPlanResponse | null) => CapabilityReadiness[]
+ degraded: (setupPlan: SetupPlanResponse | null) => string[]
+ truncated: (setupPlan: SetupPlanResponse | null) => boolean
+ visibleSuggestions: (
+ suggestions: Suggestion[],
+ dismissedIds: string[],
+ locallyAppliedIds: string[]
+ ) => Suggestion[]
+ safeBatch: (visibleSuggestions: Suggestion[]) => Suggestion[]
+ appliedCount: (suggestions: Suggestion[], visibleSuggestions: Suggestion[]) => number
+ dismissedSuggestions: (suggestions: Suggestion[], dismissedIds: string[]) => Suggestion[]
+ listedSuggestions: (visibleSuggestions: Suggestion[], focusedCapability: Capability | null) => Suggestion[]
+ }
+}
+
+export type setupPlanLogicType = MakeLogicType<
+ setupPlanLogicValues,
+ setupPlanLogicActions,
+ Record<string, any>,
+ setupPlanLogicMeta
+>
+
+export const setupPlanLogic = kea<setupPlanLogicType>([
+ path(['scenes', 'web-analytics', 'tabs', 'marketing-analytics', 'frontend', 'logic', 'setupPlanLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ actions: [
+ teamLogic,
+ ['loadCurrentTeam'],
+ marketingAnalyticsSettingsLogic,
+ ['loadMarketingAnalyticsConfig'],
+ utmAuditLogic,
+ ['loadAuditData'],
+ ],
+ })),
+ actions({
+ applySuggestion: (suggestion: Suggestion) => ({ suggestion }),
+ applyAllSafe: true,
+ applyOps: (
+ ops: ApplyOp[],
+ options: { label: string; source: ApplySource; undoable?: boolean; suggestionIds?: string[] }
+ ) => ({
+ ops,
+ options,
+ }),
+ setApplying: (ids: string[], applying: boolean) => ({ ids, applying }),
+ markApplied: (ids: string[]) => ({ ids }),
+ dismissSuggestion: (id: string) => ({ id }),
+ /** Put a dismissed suggestion back. Dismissing was a one-way door: the count
+ * was shown with no way to see what was behind it, while the tooltip claimed
+ * the row was "hidden until you clear it" with nothing able to clear it. */
+ restoreSuggestion: (id: string) => ({ id }),
+ restoreAllDismissed: true,
+ toggleShowDismissed: true,
+ /** Kick off one or more warehouse syncs. A list rather than a single source so
+ * the collapsed "5 platforms are stale" row can retry the group in one click,
+ * with N=1 as the ordinary case rather than a separate path. */
+ retrySync: (suggestionId: string, targets: SyncTarget[]) => ({ suggestionId, targets }),
+ /** Open the review modal for a suggestion, or close it with null. Every action
+ * goes through review — a preview costs one click and buys the user the
+ * ability to disagree before their config changes. */
+ reviewSuggestion: (suggestion: Suggestion | null) => ({ suggestion }),
+ /** Review the whole safe batch at once. Same modal, so "apply all" can't be
+ * the one action that changes config without showing what it changes. */
+ reviewSafeBatch: true,
+ confirmReviewedSuggestion: (suggestion: Suggestion) => ({ suggestion }),
+ confirmReviewedBatch: (suggestions: Suggestion[]) => ({ suggestions }),
+ /** Narrow the list to what unblocks one capability, or null for everything.
+ * The readiness chips are the only entry point: "ROAS is locked" is a useless
+ * fact unless the next click is "so show me what unlocks it". */
+ focusCapability: (capability: Capability | null) => ({ capability }),
+ }),
+ loaders(({ values }) => ({
+ setupPlan: [
+ null as SetupPlanResponse | null,
+ {
+ /** `refresh` forces a fresh scan past the server's short cache.
+ *
+ * The mount-time load is happy with a cached plan — that's the whole
+ * point of the cache, so switching sections doesn't re-run six
+ * ClickHouse queries. An explicit Rescan click is a request for
+ * current data and has to mean it, or the button looks broken. */
+ loadSetupPlan: async ({ refresh } = { refresh: false }) => {
+ const response = await api.get(
+ `api/projects/${values.currentTeamId}/marketing_analytics/setup_plan${
+ refresh ? '?refresh=true' : ''
+ }`
+ )
+ return response as SetupPlanResponse
+ },
+ },
+ ],
+ })),
+ reducers({
+ applyingIds: [
+ [] as string[],
+ {
+ setApplying: (state, { ids, applying }) =>
+ applying ? [...new Set([...state, ...ids])] : state.filter((id) => !ids.includes(id)),
+ },
+ ],
+ // Collapse a row the moment its op succeeds, so the list reflects the click
+ // before the plan has finished reloading. Cleared on every reload — the
+ // server's view of what's still outstanding wins.
+ locallyAppliedIds: [
+ [] as string[],
+ {
+ markApplied: (state, { ids }) => [...new Set([...state, ...ids])],
+ loadSetupPlanSuccess: () => [],
+ },
+ ],
+ reviewingSuggestion: [
+ null as Suggestion | null,
+ {
+ reviewSuggestion: (_, { suggestion }) => suggestion,
+ reviewSafeBatch: () => null,
+ // `markApplied`, not `loadSetupPlanSuccess`: the reload runs in the
+ // listener's `finally` and succeeds even when the apply didn't, so keying
+ // off it closed the modal on failure — the opposite of the intent. This
+ // only fires inside the `try`, so a failed apply keeps the modal open with
+ // its error rather than vanishing.
+ markApplied: () => null,
+ },
+ ],
+ isReviewingBatch: [
+ false,
+ {
+ reviewSafeBatch: () => true,
+ reviewSuggestion: () => false,
+ markApplied: () => false,
+ },
+ ],
+ dismissedIds: [
+ [] as string[],
+ persistConfig,
+ {
+ dismissSuggestion: (state, { id }) => [...new Set([...state, id])],
+ restoreSuggestion: (state, { id }) => state.filter((dismissed: string) => dismissed !== id),
+ restoreAllDismissed: () => [],
+ },
+ ],
+ showDismissed: [
+ false,
+ {
+ toggleShowDismissed: (state) => !state,
+ // Nothing left to look at once they're all back.
+ restoreAllDismissed: () => false,
+ },
+ ],
+ focusedCapability: [
+ null as Capability | null,
+ {
+ // Toggle: clicking the chip you're already filtered by clears it, so the
+ // chip is both the way in and the way out.
+ focusCapability: (state, { capability }) => (state === capability ? null : capability),
+ // A rescan can change which capabilities exist at all; holding a filter
+ // across it risks an empty list with no visible cause.
+ loadSetupPlanSuccess: () => null,
+ },
+ ],
+ }),
+ selectors({
+ suggestions: [(s) => [s.setupPlan], (plan: SetupPlanResponse | null): Suggestion[] => plan?.suggestions ?? []],
+ readiness: [
+ (s) => [s.setupPlan],
+ (plan: SetupPlanResponse | null): CapabilityReadiness[] => plan?.readiness ?? [],
+ ],
+ degraded: [(s) => [s.setupPlan], (plan: SetupPlanResponse | null): string[] => plan?.degraded ?? []],
+ truncated: [(s) => [s.setupPlan], (plan: SetupPlanResponse | null): boolean => plan?.truncated ?? false],
+ visibleSuggestions: [
+ (s) => [s.suggestions, s.dismissedIds, s.locallyAppliedIds],
+ (suggestions: Suggestion[], dismissedIds: string[], locallyAppliedIds: string[]): Suggestion[] =>
+ suggestions.filter(
+ (suggestion: Suggestion) =>
+ !dismissedIds.includes(suggestion.id) && !locallyAppliedIds.includes(suggestion.id)
+ ),
+ ],
+ // AI-sourced suggestions are never batchable server-side, so this is
+ // deterministic-only by construction rather than by an extra filter here.
+ safeBatch: [
+ (s) => [s.visibleSuggestions],
+ (suggestions: Suggestion[]): Suggestion[] =>
+ suggestions.filter((suggestion: Suggestion) => suggestion.safe_to_batch && suggestion.apply),
+ ],
+ appliedCount: [
+ (s) => [s.suggestions, s.visibleSuggestions],
+ (all: Suggestion[], visible: Suggestion[]): number => all.length - visible.length,
+ ],
+ /** The dismissed rows the current plan still reports.
+ *
+ * Intersected with the plan rather than read straight off `dismissedIds`,
+ * because that list is persisted and its ids outlive the findings: dismiss a
+ * broken sync, fix the sync, and the id stays in localStorage forever. Counting
+ * it would advertise hidden work that no longer exists and can't be shown.
+ */
+ dismissedSuggestions: [
+ (s) => [s.suggestions, s.dismissedIds],
+ (suggestions: Suggestion[], dismissedIds: string[]): Suggestion[] =>
+ suggestions.filter((suggestion: Suggestion) => dismissedIds.includes(suggestion.id)),
+ ],
+ /** What the ranked list renders. Separate from `visibleSuggestions` because the
+ * per-section blocks and the nav badges must keep showing everything — a filter
+ * chosen in "Suggested setup" silently emptying the Sources section would read
+ * as a bug, not as a filter. */
+ listedSuggestions: [
+ (s) => [s.visibleSuggestions, s.focusedCapability],
+ (suggestions: Suggestion[], capability: Capability | null): Suggestion[] =>
+ capability
+ ? suggestions.filter((suggestion: Suggestion) => suggestion.unlocks.includes(capability))
+ : suggestions,
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ retrySync: async ({ suggestionId, targets }) => {
+ // Goes straight to the warehouse endpoint rather than through
+ // apply_setup_ops: the warehouse owns this action and its permissions, and
+ // the apply endpoint only mutates marketing config.
+ actions.setApplying([suggestionId], true)
+ try {
+ // Sequential, and one failure does not abandon the rest: these are
+ // independent sources, and stopping at the first error would leave the
+ // group half-retried with no way to tell which half.
+ const failed: string[] = []
+ for (const target of targets) {
+ try {
+ await api.externalDataSources.reload(target.source_id)
+ } catch {
+ failed.push(target.display_name)
+ }
+ }
+ if (failed.length === targets.length) {
+ lemonToast.error(`Could not retry ${failed.join(', ')}.`)
+ } else if (failed.length) {
+ lemonToast.warning(
+ `Retrying ${targets.length - failed.length} of ${targets.length}. Failed: ${failed.join(', ')}.`
+ )
+ } else {
+ lemonToast.success(
+ targets.length === 1
+ ? `Retrying the ${targets[0].display_name} sync`
+ : `Retrying ${targets.length} syncs`
+ )
+ }
+ } finally {
+ actions.setApplying([suggestionId], false)
+ actions.reviewSuggestion(null)
+ // A sync takes minutes, so the plan won't change yet — reload anyway so
+ // a status that did change (a second click after it finished) is picked up.
+ actions.loadSetupPlan()
+ }
+ },
+ confirmReviewedSuggestion: ({ suggestion }) => {
+ // Navigation is handled by the view (see `runNavigateOp`), which owns the
+ // router and the modals. This only knows how to change config and to kick
+ // off a sync.
+ if (suggestion.apply?.op === 'retry_sync') {
+ actions.retrySync(suggestion.id, [
+ {
+ source_id: suggestion.apply.source_id as string,
+ display_name: suggestion.apply.display_name as string,
+ },
+ ])
+ return
+ }
+ if (suggestion.apply?.op === 'retry_syncs') {
+ actions.retrySync(suggestion.id, suggestion.apply.sources as SyncTarget[])
+ return
+ }
+ actions.applySuggestion(suggestion)
+ },
+ applySuggestion: ({ suggestion }) => {
+ if (!suggestion.apply) {
+ return
+ }
+ actions.setApplying([suggestion.id], true)
+ actions.applyOps([suggestion.apply], {
+ label: suggestion.title,
+ source: 'setup_tab',
+ undoable: true,
+ suggestionIds: [suggestion.id],
+ })
+ },
+ confirmReviewedBatch: ({ suggestions }) => {
+ if (!suggestions.length) {
+ return
+ }
+ actions.setApplying(
+ suggestions.map((s) => s.id),
+ true
+ )
+ actions.applyOps(
+ suggestions.map((s) => s.apply as ApplyOp),
+ {
+ label: `Applied ${suggestions.length} suggestion${suggestions.length === 1 ? '' : 's'}`,
+ source: 'apply_all_safe',
+ undoable: true,
+ suggestionIds: suggestions.map((s) => s.id),
+ }
+ )
+ },
+ applyAllSafe: () => {
+ const batch = values.safeBatch
+ if (!batch.length) {
+ return
+ }
+ actions.setApplying(
+ batch.map((s) => s.id),
+ true
+ )
+ actions.applyOps(
+ batch.map((s) => s.apply as ApplyOp),
+ {
+ label: `Applied ${batch.length} suggestion${batch.length === 1 ? '' : 's'}`,
+ source: 'apply_all_safe',
+ undoable: true,
+ suggestionIds: batch.map((s) => s.id),
+ }
+ )
+ },
+ applyOps: async ({ ops, options }) => {
+ // The rows this request owns, not whatever happens to be applying. Reading
+ // the global set meant an undo — which starts no rows of its own — would
+ // adopt a concurrent apply's ids and mark those rows applied when it landed.
+ const inFlight = options.suggestionIds ?? []
+ try {
+ const response: ApplyResponse = await api.create(
+ `api/projects/${values.currentTeamId}/marketing_analytics/apply_setup_ops`,
+ { ops, source: options.source }
+ )
+
+ actions.markApplied(inFlight)
+ lemonToast.success(options.label, {
+ button:
+ options.undoable && response.undo_ops.length
+ ? {
+ label: 'Undo',
+ // The server computes the inverse from the pre-change
+ // state, so undo is just another apply — the client
+ // never reconstructs what the config used to be.
+ action: () =>
+ actions.applyOps(response.undo_ops, {
+ label: 'Undone',
+ source: options.source,
+ }),
+ }
+ : undefined,
+ })
+ } catch (error: any) {
+ lemonToast.error(error?.detail ?? 'Could not apply that change.')
+ } finally {
+ actions.setApplying(inFlight, false)
+ actions.loadSetupPlan()
+ // apply_setup_ops writes the config server-side, bypassing
+ // `updateCurrentTeam`. Nothing else would know: the manual settings
+ // sections below read `savedMarketingAnalyticsConfig`, which keys off
+ // that action, and utmAuditLogic only reloads on the update*Mappings
+ // actions. Without these the manual sections show stale data right next
+ // to the suggestion that just changed it.
+ //
+ // Awaited, not fire-and-forget: `loadMarketingAnalyticsConfig` reads
+ // `values.currentTeam` synchronously, so dispatching it in the same tick
+ // reads the pre-apply team every time.
+ await teamLogic.asyncActions.loadCurrentTeam()
+ actions.loadMarketingAnalyticsConfig()
+ // Only for ops that touch what the audit reports on. It reruns the same
+ // UTM-catalogue and campaign-spend ClickHouse queries the plan just ran,
+ // so a conversion-goal change would pay for a scan it can't affect.
+ if (ops.some((candidate) => AUDIT_AFFECTING_OPS.has(candidate.op))) {
+ actions.loadAuditData()
+ }
+ }
+ },
+ })),
+])