:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(marketing-analytics): add the setup plan service (#78062)
Javier Bahamondes78bf5761b027
diff --git a/products/marketing_analytics/backend/services/native_integrations.py b/products/marketing_analytics/backend/services/native_integrations.pyindex f84ad35c42dd..6f89ad2978a4 100644--- a/products/marketing_analytics/backend/services/native_integrations.py+++ b/products/marketing_analytics/backend/services/native_integrations.py@@ -67,10 +67,28 @@ DISPLAY_NAMES: dict[NativeMarketingSource, str] = {}+# What `api/integrations/authorize?kind=` expects. Spelled out because no kebab-case rule gets+# both Snapchat ("snapchat") and TikTok ("tiktok-ads") right; pinned by a test to `supported_kinds`.+OAUTH_KIND_BY_NATIVE: dict[NativeMarketingSource, str] = {+ NativeMarketingSource.GOOGLE_ADS: "google-ads",+ NativeMarketingSource.META_ADS: "meta-ads",+ NativeMarketingSource.BING_ADS: "bing-ads",+ NativeMarketingSource.LINKEDIN_ADS: "linkedin-ads",+ NativeMarketingSource.REDDIT_ADS: "reddit-ads",+ NativeMarketingSource.PINTEREST_ADS: "pinterest-ads",+ NativeMarketingSource.SNAPCHAT_ADS: "snapchat",+ NativeMarketingSource.TIK_TOK_ADS: "tiktok-ads",+}++def display_name_for_key(key: NativeIntegration) -> str:return DISPLAY_NAMES[KEY_TO_NATIVE[key]]+def oauth_kind_for(native: NativeMarketingSource) -> str | None:+ return OAUTH_KIND_BY_NATIVE.get(native)++def normalize(value: str) -> str:"""Lowercase and strip non-alphanumerics. `Facebook-Ads` → `facebookads`."""return "".join(c.lower() for c in value if c.isalnum())diff --git a/products/marketing_analytics/backend/services/setup_plan.py b/products/marketing_analytics/backend/services/setup_plan.pynew file mode 100644index 000000000000..2e5c96b725f7--- /dev/null+++ b/products/marketing_analytics/backend/services/setup_plan.py@@ -0,0 +1,735 @@+"""The marketing analytics setup plan: what to fix next, in machine-applicable form.++`marketing_diagnostic` explains *what is wrong*. This says *what to do about it* —+a ranked list of `Suggestion`s, each carrying an `ApplyOp` the apply endpoint can+execute, plus a readiness block saying which capabilities (cost, ROAS, CAC,+retention by channel) are unlocked and which suggestion is blocking each one.++Composition: this wraps `get_marketing_diagnostic` rather than re-deriving from the+leaf services. The diagnostic is the only service that does cross-domain reasoning+and it owns the `IntegrationStatus` ladder that the connect/reconnect/fix-sync/+map-schema suggestions map onto; re-deriving would fork that truth. The extra leaves+it doesn't expose — candidate events, the UTM catalogue, campaign rows — are fetched+alongside it in one `gather`.++Every leaf is allowed to fail independently: the diagnostic is required (without it+there's nothing to say), everything else degrades to a missing section recorded in+`degraded`, so the UI can avoid presenting a partial plan as a complete one.+"""++import asyncio+from typing import Any, cast++from django.utils import timezone++import structlog++from posthog.schema import DateRange++from posthog.hogql_queries.utils.query_date_range import QueryDateRange+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.sync import database_sync_to_async++from products.marketing_analytics.backend.services.attribution_health import (+ AttributionHealthResponse,+ get_attribution_health,+)+from products.marketing_analytics.backend.services.campaign_field_suggester import (+ FieldPreferenceSuggestion,+ suggest_campaign_field_preferences,+)+from products.marketing_analytics.backend.services.campaign_mapping_suggester import (+ CampaignMappingProposal,+ CampaignMappingSuggestions,+ suggest_campaign_name_mappings,+)+from products.marketing_analytics.backend.services.conversion_goals_inspector import (+ ConversionGoalsListResponse,+ ConversionGoalSummary,+)+from products.marketing_analytics.backend.services.event_suggestions import (+ CandidateEvent,+ EventSuggestionsResponse,+ suggest_conversion_goals,+)+from products.marketing_analytics.backend.services.mapping_suggester import (+ SourceMappingSuggestion,+ UtmMappingSuggestionsResponse,+ suggest_utm_mappings,+)+from products.marketing_analytics.backend.services.marketing_diagnostic import (+ IntegrationDiagnostic,+ MarketingDiagnosticResponse,+ get_marketing_diagnostic,+)+from products.marketing_analytics.backend.services.native_integrations import (+ KEY_TO_NATIVE,+ NativeIntegration,+ display_name_for_key,+ oauth_kind_for,+)+from products.marketing_analytics.backend.services.setup_types import (+ AddCampaignNameMapping,+ AddCustomSourceMapping,+ ApplyOp,+ Capability,+ CapabilityReadiness,+ FixPlatformUrls,+ OpenOauth,+ OpenSettings,+ OpenSourceWizard,+ ReadinessStatus,+ SetCampaignFieldPreference,+ SetupPlan,+ Severity,+ Suggestion,+ SuggestionKind,+ UpdateConversionGoal,+ sort_suggestions,+)+from products.marketing_analytics.backend.services.types import TeamMappings+from products.marketing_analytics.backend.services.utm_audit import (+ build_audit,+ get_campaigns_with_spend_async,+ get_utm_campaign_catalogue_async,+)+from products.marketing_analytics.backend.services.utm_matching import load_team_mappings++logger = structlog.get_logger(__name__)++# Matches `suggest_utm_mappings`' own default so the injected attribution fits.+ATTRIBUTION_LOOKBACK_DAYS = 90++# Every rate derived from these is a top-N subtotal, which the response flags as `truncated`.+UTM_CATALOGUE_LIMIT = 5000+CAMPAIGN_LIMIT = 500++MARKETING_SETTINGS_ANCHOR = "environment-marketing-analytics"+++async def get_setup_plan(+ team: Team,+ *,+ date_from: str = "-30d",+ user: User | None = None,+) -> SetupPlan:+ """Build the ranked setup plan for a team."""+ date_range = QueryDateRange(+ date_range=DateRange(date_from=date_from, date_to=None),+ team=team,+ interval=None,+ now=timezone.now(),+ )++ results = await asyncio.gather(+ get_marketing_diagnostic(team, include_conversion_goals=True, user=user),+ get_attribution_health(team, lookback_days=ATTRIBUTION_LOOKBACK_DAYS),+ suggest_conversion_goals(team),+ get_campaigns_with_spend_async(team, date_range, user=user),+ get_utm_campaign_catalogue_async(team, date_range, user=user),+ _load_mappings(team),+ _load_goal_flags(team),+ return_exceptions=True,+ )+ (+ diagnostic_result,+ attribution_result,+ candidates_result,+ campaigns_result,+ utm_events_result,+ mappings_result,+ goal_flags_result,+ ) = results++ if isinstance(diagnostic_result, BaseException):+ # An empty plan reads as "you're all set", which is worse than an error.+ logger.exception("setup_plan.diagnostic_failed", team_id=team.pk)+ raise diagnostic_result+ # `gather` over heterogeneous coroutines collapses to a union, so narrow by position.+ diagnostic = cast(MarketingDiagnosticResponse, diagnostic_result)++ degraded: list[str] = []+ attribution = _or_degraded(attribution_result, "attribution_health", degraded, team)+ candidates = _or_degraded(candidates_result, "event_suggestions", degraded, team)+ campaigns = _or_degraded(campaigns_result, "campaigns", degraded, team) or []+ utm_events = _or_degraded(utm_events_result, "utm_catalogue", degraded, team) or {}+ mappings = _or_degraded(mappings_result, "team_mappings", degraded, team)+ goal_flags = _or_degraded(goal_flags_result, "goal_flags", degraded, team) or {}++ suggestions: list[Suggestion] = []+ suggestions.extend(_integration_suggestions(diagnostic))++ # Ahead of the mapping suggester so its proposals can be injected there.+ campaign_mappings: CampaignMappingSuggestions | None = None+ if campaigns and mappings is not None:+ # Wrapped like the gathered leaves: an unwrapped raise here would lose the diagnostic+ # and attribution results already in hand. All three together, since they read one set of rows.+ try:+ audit = build_audit(campaigns, utm_events, mappings)+ suggestions.extend(+ _field_preference_suggestions(+ suggest_campaign_field_preferences(campaigns, utm_events, mappings, audit.results)+ )+ )+ campaign_mappings = suggest_campaign_name_mappings(campaigns, utm_events, mappings)+ suggestions.extend(_campaign_mapping_suggestions(campaign_mappings))+ except Exception as error:+ logger.warning("setup_plan.leaf_failed", leaf="campaign_suggesters", team_id=team.pk, error=str(error))+ degraded.append("campaign_suggesters")+ campaign_mappings = None++ if attribution is not None:+ utm_mappings = await _safe_utm_mappings(team, attribution, campaign_mappings, degraded)+ if utm_mappings is not None:+ suggestions.extend(_source_mapping_suggestions(utm_mappings))++ suggestions.extend(_conversion_goal_suggestions(diagnostic.conversion_goals, candidates, goal_flags))++ ranked = sort_suggestions(suggestions)+ readiness = _build_readiness(+ diagnostic=diagnostic,+ attribution=attribution,+ goal_flags=goal_flags,+ suggestions=ranked,+ )++ return SetupPlan(+ suggestions=ranked,+ readiness=readiness,+ degraded=degraded,+ truncated=len(campaigns) >= CAMPAIGN_LIMIT or len(utm_events) >= UTM_CATALOGUE_LIMIT,+ summary=_summary(ranked, readiness, degraded),+ )+++def _or_degraded(result: Any, name: str, degraded: list[str], team: Team) -> Any:+ if isinstance(result, BaseException):+ logger.warning("setup_plan.leaf_failed", leaf=name, team_id=team.pk, error=str(result))+ degraded.append(name)+ return None+ return result+++async def _safe_utm_mappings(+ team: Team,+ attribution: AttributionHealthResponse,+ campaign_proposals: CampaignMappingSuggestions | None,+ degraded: list[str],+) -> UtmMappingSuggestionsResponse | None:+ """Run after the gather because it consumes the gathered attribution result.++ Both inputs are injected rather than left to derive themselves: this function already holds+ them, and deriving re-reads campaigns, the UTM catalogue and team mappings from the database.+ `campaign_proposals` is None only when the plan couldn't compute them either, in which case+ letting the suggester try is the better answer.+ """+ try:+ return await suggest_utm_mappings(team, attribution=attribution, campaign_proposals=campaign_proposals)+ except Exception as error:+ logger.warning("setup_plan.leaf_failed", leaf="mapping_suggester", team_id=team.pk, error=str(error))+ degraded.append("mapping_suggester")+ return None+++@database_sync_to_async+def _load_mappings(team: Team) -> TeamMappings:+ return load_team_mappings(team)+++@database_sync_to_async+def _load_goal_flags(team: Team) -> dict[str, dict[str, Any]]:+ """`conversion_goal_id` -> the raw goal dict.++ `ConversionGoalSummary` doesn't carry `counts_as_revenue` / `counts_as_customer`,+ and those two booleans are exactly what gates the ROAS and CAC columns — so read+ the stored goals directly rather than widening the inspector's shape.+ """+ config = getattr(team, "marketing_analytics_config", None)+ if config is None:+ return {}+ return {+ str(goal.get("conversion_goal_id")): goal+ for goal in (config.conversion_goals or [])+ if goal.get("conversion_goal_id")+ }+++# --- Suggestion builders ---------------------------------------------------+++def _integration_suggestions(diagnostic: MarketingDiagnosticResponse) -> list[Suggestion]:+ suggestions: list[Suggestion] = []+ for integration in diagnostic.integrations:+ suggestion = _integration_suggestion(integration)+ if suggestion is not None:+ suggestions.append(suggestion)+ return suggestions+++def _looks_like_auth_failure(last_error: str | None) -> bool:+ if not last_error:+ return False+ lowered = last_error.lower()+ return any(token in lowered for token in ("token", "unauthor", "auth", "credential", "expired", "401", "403"))+++def _integration_suggestion(integration: IntegrationDiagnostic) -> Suggestion | None:+ key: NativeIntegration = integration.integration_key+ native = KEY_TO_NATIVE.get(key)+ display = integration.display_name+ status = integration.overall_status+ source_type = integration.source_type+ ds = integration.data_source+ volume = integration.attribution.events_unmatched_likely_yours_last_7d if integration.attribution else 0++ if status == "events_only":+ # Traffic arrives but no spend data, so cost, ROAS and CAC are all unavailable.+ return Suggestion(+ id=f"connect_source:{key}",+ kind=SuggestionKind.CONNECT_SOURCE,+ severity=Severity.ERROR,+ confidence=0.95,+ title=f"Connect {display}",+ evidence=(+ f"{volume:,} events in the last 7 days carry a {display} utm_source, but the platform "+ "isn't connected — none of that traffic has cost attached."+ ),+ unlocks=[Capability.COST, Capability.ROAS, Capability.CAC],+ apply=OpenSourceWizard(kind=source_type),+ integration=source_type,+ event_volume=volume,+ )++ if status == "sync_broken":+ is_auth = _looks_like_auth_failure(ds.last_error if ds else None)+ oauth_kind = oauth_kind_for(native) if native else None+ if is_auth and oauth_kind:+ return Suggestion(+ id=f"reconnect_oauth:{key}",+ kind=SuggestionKind.RECONNECT_OAUTH,+ severity=Severity.ERROR,+ confidence=0.9,+ title=f"Reconnect {display}",+ evidence=(ds.diagnosis if ds else f"{display} authentication failed.")+ + " Spend stops updating until it's reconnected.",+ unlocks=[Capability.COST, Capability.ROAS, Capability.CAC],+ apply=OpenOauth(kind=oauth_kind),+ integration=source_type,+ deep_link=ds.schemas_url if ds else None,+ )+ return Suggestion(+ id=f"fix_sync:{key}",+ kind=SuggestionKind.FIX_SYNC,+ severity=Severity.ERROR,+ confidence=0.9,+ title=f"Fix the {display} sync",+ evidence=ds.diagnosis if ds else f"{display} is not syncing.",+ unlocks=[Capability.COST, Capability.ROAS, Capability.CAC],+ apply=None,+ integration=source_type,+ deep_link=(ds.schemas_url or ds.settings_url) if ds else None,+ )++ if status == "schema_misconfigured":+ missing = ds.schema_columns_required_missing if ds else []+ return Suggestion(+ id=f"map_schema_columns:{key}",+ kind=SuggestionKind.MAP_SCHEMA_COLUMNS,+ severity=Severity.ERROR,+ confidence=0.95,+ title=f"Map required columns for {display}",+ evidence=(+ f"{display} is syncing, but {len(missing)} required column(s) aren't mapped "+ f"({', '.join(missing[:4])}). Its spend can't be read until they are."+ ),+ unlocks=[Capability.COST, Capability.ROAS, Capability.CAC],+ apply=None,+ integration=source_type,+ deep_link=(ds.settings_url if ds else None),+ )++ if status == "events_broken":+ return Suggestion(+ id=f"fix_platform_urls:{key}",+ kind=SuggestionKind.FIX_PLATFORM_URLS,+ severity=Severity.WARNING,+ confidence=0.7,+ title=f"Add UTM tags to {display} ads",+ evidence=(+ f"{display} is syncing fine but no events with a matching utm_source arrived in the "+ "last 7 days — its clicks can't be tied to anything that happens on your site."+ ),+ unlocks=[Capability.ATTRIBUTION, Capability.ROAS, Capability.CAC],+ apply=None,+ also_recommended=[+ FixPlatformUrls(+ integration=source_type,+ campaign_name="",+ expected_utm_campaign="",+ expected_utm_source=key.replace("_ads", ""),+ )+ ],+ integration=source_type,+ )++ return None+++def _source_mapping_suggestions(utm_mappings: UtmMappingSuggestionsResponse) -> list[Suggestion]:+ return [_source_mapping_suggestion(s) for s in utm_mappings.source_suggestions]+++def _source_mapping_suggestion(suggestion: SourceMappingSuggestion) -> Suggestion:+ native = KEY_TO_NATIVE[suggestion.suggested_target]+ display = display_name_for_key(suggestion.suggested_target)+ fix = FixPlatformUrls(+ integration=native.value,+ campaign_name="",+ expected_utm_campaign="",+ # Mapping makes the wrong value work; changing the ad URL makes it right.+ expected_utm_source=suggestion.suggested_target.replace("_ads", ""),+ )+ return Suggestion(+ id=f"add_source_mapping:{suggestion.suggested_target}:{suggestion.raw_utm_source}",+ kind=SuggestionKind.ADD_SOURCE_MAPPING,+ severity=Severity.WARNING,+ confidence=0.8,+ title=f"Map utm_source '{suggestion.raw_utm_source}' to {display}",+ evidence=(+ f"{suggestion.event_count_30d:,} events arrive tagged "+ f"utm_source={suggestion.raw_utm_source!r}, which no integration claims. "+ f"{suggestion.reason}"+ ),+ unlocks=[Capability.ATTRIBUTION, Capability.ROAS, Capability.CAC],+ apply=AddCustomSourceMapping(integration=native.value, raw_utm_source=suggestion.raw_utm_source),+ safe_to_batch=True,+ integration=native.value,+ event_volume=suggestion.event_count_30d,+ also_recommended=[fix],+ )+++def _field_preference_suggestions(field_suggestions: list[FieldPreferenceSuggestion]) -> list[Suggestion]:+ return [+ Suggestion(+ id=f"switch_campaign_match_field:{s.integration}",+ kind=SuggestionKind.SWITCH_CAMPAIGN_MATCH_FIELD,+ severity=Severity.ERROR if not s.triggered_by_collision else Severity.WARNING,+ confidence=s.confidence,+ title=f"Match {s.integration_display_name} campaigns by {s.suggested_match_field.replace('_', ' ')}",+ evidence=s.reason,+ unlocks=[Capability.ROAS, Capability.CAC],+ apply=SetCampaignFieldPreference(+ integration=s.integration,+ match_field=s.suggested_match_field,+ ),+ safe_to_batch=s.safe_to_batch,+ integration=s.integration,+ spend_at_risk=s.spend_at_risk,+ )+ for s in field_suggestions+ ]+++def _campaign_mapping_suggestions(result: CampaignMappingSuggestions) -> list[Suggestion]:+ suggestions = [_campaign_mapping_suggestion(p) for p in result.proposals]++ for unresolved in result.unresolved[:5]:+ suggestions.append(+ Suggestion(+ id=f"fix_platform_urls:orphan:{unresolved.raw_utm_campaign}",+ kind=SuggestionKind.FIX_PLATFORM_URLS,+ severity=Severity.WARNING,+ confidence=0.6,+ title=f"'{unresolved.raw_utm_campaign}' matches no campaign",+ evidence=(+ f"{unresolved.event_count:,} events arrive tagged "+ f"utm_campaign={unresolved.raw_utm_campaign!r} (utm_source="+ f"{unresolved.observed_utm_source!r}). {unresolved.reason}"+ ),+ unlocks=[Capability.ATTRIBUTION],+ apply=None,+ event_volume=unresolved.event_count,+ )+ )+ return suggestions+++def _campaign_mapping_suggestion(proposal: CampaignMappingProposal) -> Suggestion:+ fix = FixPlatformUrls(+ integration=proposal.integration,+ campaign_name=proposal.clean_name,+ expected_utm_campaign=proposal.expected_utm_campaign,+ expected_utm_source=proposal.expected_utm_source,+ )+ return Suggestion(+ id=f"add_campaign_name_mapping:{proposal.integration}:{proposal.raw_utm_campaign}",+ kind=SuggestionKind.ADD_CAMPAIGN_NAME_MAPPING,+ severity=Severity.WARNING,+ confidence=proposal.confidence,+ title=f"Link '{proposal.raw_utm_campaign}' to '{proposal.clean_name}'",+ evidence=proposal.reason,+ unlocks=[Capability.ROAS, Capability.CAC],+ apply=AddCampaignNameMapping(+ integration=proposal.integration,+ clean_name=proposal.clean_name,+ raw_values=[proposal.raw_utm_campaign],+ ),+ safe_to_batch=proposal.safe_to_batch,+ integration=proposal.integration,+ spend_at_risk=proposal.campaign_spend,+ event_volume=proposal.event_count,+ also_recommended=[fix],+ )+++def _conversion_goal_suggestions(+ goals: ConversionGoalsListResponse | None,+ candidates: EventSuggestionsResponse | None,+ goal_flags: dict[str, dict[str, Any]],+) -> list[Suggestion]:+ # `_missing_flag_suggestion` returns None when no goal is worth it; the comprehension drops those.+ suggestions: list[Suggestion | None] = []++ if goals is None or not goals.goals:+ suggestions.extend(_create_goal_suggestions(candidates))+ return [s for s in suggestions if s is not None]++ for goal in goals.goals:+ if goal.is_misconfigured:+ suggestions.append(_fix_goal_suggestion(goal))++ if not any(goal_flags.get(g.id, {}).get("counts_as_revenue") for g in goals.goals):+ suggestions.append(_missing_flag_suggestion(goals.goals, goal_flags, revenue=True))+ if not any(goal_flags.get(g.id, {}).get("counts_as_customer") for g in goals.goals):+ suggestions.append(_missing_flag_suggestion(goals.goals, goal_flags, revenue=False))++ return [s for s in suggestions if s is not None]+++def _create_goal_suggestions(candidates: EventSuggestionsResponse | None) -> list[Suggestion]:+ if candidates is None or not candidates.candidates:+ return [+ Suggestion(+ id="create_conversion_goal:none",+ kind=SuggestionKind.CREATE_CONVERSION_GOAL,+ severity=Severity.WARNING,+ confidence=0.9,+ title="Add a conversion goal",+ evidence=(+ "No conversion goals are configured, so the dashboard can only show spend — "+ "no conversions, ROAS or cost per customer."+ ),+ unlocks=[Capability.ROAS, Capability.CAC],+ apply=OpenSettings(anchor=MARKETING_SETTINGS_ANCHOR),+ )+ ]++ # Name the best candidate and link out. Picking the revenue property is a semantic call the+ # AI layer makes, not a volume ranking.+ top: CandidateEvent = candidates.candidates[0]+ return [+ Suggestion(+ id="create_conversion_goal:top_candidate",+ kind=SuggestionKind.CREATE_CONVERSION_GOAL,+ severity=Severity.WARNING,+ confidence=0.75,+ title=f"Make '{top.event_name}' a conversion goal",+ evidence=(+ f"No conversion goals are configured. '{top.event_name}' fired {top.last_30d_count:,} times "+ f"in the last 30 days across {top.distinct_users_30d:,} users, and "+ f"{top.pct_with_utm_source:.0%} of those carry a utm_source — the best-attributable "+ "candidate in your data."+ ),+ unlocks=[Capability.ROAS, Capability.CAC],+ apply=OpenSettings(anchor=MARKETING_SETTINGS_ANCHOR),+ event_volume=top.last_30d_count,+ )+ ]+++def _fix_goal_suggestion(goal: ConversionGoalSummary) -> Suggestion:+ return Suggestion(+ id=f"fix_conversion_goal:{goal.id}",+ kind=SuggestionKind.FIX_CONVERSION_GOAL,+ severity=Severity.ERROR,+ confidence=0.95,+ title=f"Fix the '{goal.name}' conversion goal",+ evidence=goal.misconfig_reason or "This goal references something that no longer exists.",+ unlocks=[Capability.ROAS, Capability.CAC],+ apply=OpenSettings(anchor=MARKETING_SETTINGS_ANCHOR),+ )+++def _missing_flag_suggestion(+ goals: list[ConversionGoalSummary],+ goal_flags: dict[str, dict[str, Any]],+ *,+ revenue: bool,+) -> Suggestion | None:+ """Nudge to flag one goal as revenue- or customer-bearing.++ Without `counts_as_revenue` there is no ROAS column, and without+ `counts_as_customer` there is no cost-per-customer — the goals exist but the+ two headline metrics stay empty, with nothing on the dashboard explaining why.+ Which goal deserves the flag is a business call, so this links out rather than+ picking one.+ """+ candidate = max(goals, key=lambda g: g.last_30d_count, default=None)+ if candidate is None:+ return None++ kind = SuggestionKind.MARK_GOAL_AS_REVENUE if revenue else SuggestionKind.MARK_GOAL_AS_CUSTOMER+ metric = "ROAS" if revenue else "cost per customer"+ flag = "counts_as_revenue" if revenue else "counts_as_customer"+ return Suggestion(+ id=f"{kind.value}:any",+ kind=kind,+ severity=Severity.WARNING,+ confidence=0.7,+ title=f"Mark a conversion goal as {'revenue-bearing' if revenue else 'customer-defining'}",+ evidence=(+ f"{len(goals)} conversion goal(s) are configured but none has `{flag}` set, so the "+ f"{metric} column stays empty. '{candidate.name}' is the highest-volume candidate "+ f"({candidate.last_30d_count:,} in 30 days)."+ ),+ unlocks=[Capability.ROAS if revenue else Capability.CAC],+ # Which goal counts as revenue is a business decision, not a config fix.+ apply=UpdateConversionGoal(conversion_goal_id=candidate.id, patch={flag: True}),+ safe_to_batch=False,+ event_volume=candidate.last_30d_count,+ )+++# --- Readiness -------------------------------------------------------------+++def _blockers(suggestions: list[Suggestion], capability: Capability) -> list[str]:+ return [s.id for s in suggestions if capability in s.unlocks]+++def _build_readiness(+ *,+ diagnostic: MarketingDiagnosticResponse,+ attribution: AttributionHealthResponse | None,+ goal_flags: dict[str, dict[str, Any]],+ suggestions: list[Suggestion],+) -> list[CapabilityReadiness]:+ healthy = [i for i in diagnostic.integrations if i.overall_status in ("healthy", "events_unmatched")]+ relevant = [i for i in diagnostic.integrations if i.overall_status != "not_connected"]++ if not relevant:+ cost_status, cost_why = ReadinessStatus.BLOCKED, "No ad platform is connected, so there is no spend data."+ elif len(healthy) == len(relevant):+ cost_status, cost_why = ReadinessStatus.UNLOCKED, f"{len(healthy)} integration(s) are syncing spend."+ elif healthy:+ cost_status = ReadinessStatus.PARTIAL+ cost_why = f"Spend is available for {len(healthy)} of {len(relevant)} connected integrations."+ else:+ cost_status, cost_why = ReadinessStatus.BLOCKED, "Every connected integration has a problem reading spend."++ attribution_status, attribution_why = _attribution_readiness(attribution)+ has_revenue_goal = any(g.get("counts_as_revenue") for g in goal_flags.values())+ has_customer_goal = any(g.get("counts_as_customer") for g in goal_flags.values())++ return [+ CapabilityReadiness(+ capability=Capability.COST,+ status=cost_status,+ explanation=cost_why,+ blocked_by=_blockers(suggestions, Capability.COST),+ ),+ CapabilityReadiness(+ capability=Capability.ATTRIBUTION,+ status=attribution_status,+ explanation=attribution_why,+ blocked_by=_blockers(suggestions, Capability.ATTRIBUTION),+ ),+ _metric_readiness(+ Capability.ROAS,+ cost_status,+ has_goal=has_revenue_goal,+ goal_hint="no conversion goal is marked `counts_as_revenue`",+ suggestions=suggestions,+ ),+ _metric_readiness(+ Capability.CAC,+ cost_status,+ has_goal=has_customer_goal,+ goal_hint="no conversion goal is marked `counts_as_customer`",+ suggestions=suggestions,+ ),+ ]+++def _attribution_readiness(attribution: AttributionHealthResponse | None) -> tuple[ReadinessStatus, str]:+ if attribution is None:+ return ReadinessStatus.BLOCKED, "Attribution health could not be read."+ total = attribution.total_events_with_utm+ if total == 0:+ return (+ ReadinessStatus.BLOCKED,+ "No events with a utm_source arrived in the window — nothing can be attributed to a channel.",+ )+ matched_pct = attribution.total_events_matched_to_any_integration / total+ approx = " (top-N subtotal)" if attribution.utm_source_catalogue_truncated else ""+ if matched_pct >= 0.8:+ return ReadinessStatus.UNLOCKED, f"{matched_pct:.0%} of UTM-tagged events match a connected platform{approx}."+ if matched_pct > 0:+ return (+ ReadinessStatus.PARTIAL,+ f"Only {matched_pct:.0%} of UTM-tagged events match a connected platform{approx}; the rest "+ "can't be attributed to spend.",+ )+ return ReadinessStatus.BLOCKED, "UTM-tagged events arrive but none match a connected platform."+++def _metric_readiness(+ capability: Capability,+ cost_status: ReadinessStatus,+ *,+ has_goal: bool,+ goal_hint: str,+ suggestions: list[Suggestion],+) -> CapabilityReadiness:+ blocked_by = _blockers(suggestions, capability)+ if cost_status == ReadinessStatus.BLOCKED and not has_goal:+ explanation = f"Needs spend data and a conversion goal: spend is unavailable and {goal_hint}."+ status = ReadinessStatus.BLOCKED+ elif not has_goal:+ explanation = f"Spend is available, but {goal_hint}."+ status = ReadinessStatus.BLOCKED+ elif cost_status == ReadinessStatus.BLOCKED:+ explanation = "A goal is flagged, but there is no spend data to divide by."+ status = ReadinessStatus.BLOCKED+ elif cost_status == ReadinessStatus.PARTIAL:+ explanation = "Available, but only for the integrations whose spend is readable."+ status = ReadinessStatus.PARTIAL+ else:+ explanation = "Spend and a flagged conversion goal are both in place."+ status = ReadinessStatus.UNLOCKED+ return CapabilityReadiness(capability=capability, status=status, explanation=explanation, blocked_by=blocked_by)+++def _summary(suggestions: list[Suggestion], readiness: list[CapabilityReadiness], degraded: list[str]) -> str:+ if not suggestions:+ return "Nothing to fix — every check passed."+ errors = sum(1 for s in suggestions if s.severity == Severity.ERROR)+ unlocked = sum(1 for r in readiness if r.status == ReadinessStatus.UNLOCKED)+ partial = sum(1 for r in readiness if r.status == ReadinessStatus.PARTIAL)+ # Partial counted separately: "0 of 4 unlocked" reads as nothing working, and a team whose+ # four capabilities are all partial is in a very different place from one where they're blocked.+ capabilities = f"{unlocked} of {len(readiness)} capabilities unlocked"+ if partial:+ capabilities += f", {partial} partial"+ parts = [+ f"{len(suggestions)} suggestion(s), {errors} blocking.",+ f"{capabilities}.",+ ]+ if degraded:+ parts.append(f"Incomplete: {', '.join(degraded)} could not be read.")+ return " ".join(parts)+++__all__ = ["ApplyOp", "get_setup_plan"]diff --git a/products/marketing_analytics/backend/services/setup_types.py b/products/marketing_analytics/backend/services/setup_types.pynew file mode 100644index 000000000000..8b87e55d126c--- /dev/null+++ b/products/marketing_analytics/backend/services/setup_types.py@@ -0,0 +1,316 @@+"""Vocabulary for the marketing analytics setup plan.++`setup_plan`, `setup_ai_enrichment` and `apply_setup_ops` share these types, the last validating+incoming ops against the same union it emits — which is why ops are Pydantic models rather than+dataclasses like the sibling services use. One definition for both emit and validate is what keeps+a hallucinated op out of the config.++`APPLICABLE_OPS` mutate config server-side; `NAVIGATE_OPS` need a browser or are advice only.+"""++from enum import StrEnum+from typing import Annotated, Any, Literal++from pydantic import BaseModel, ConfigDict, Field, model_validator+++class SuggestionKind(StrEnum):+ CONNECT_SOURCE = "connect_source"+ RECONNECT_OAUTH = "reconnect_oauth"+ FIX_SYNC = "fix_sync"+ MAP_SCHEMA_COLUMNS = "map_schema_columns"+ ADD_SOURCE_MAPPING = "add_source_mapping"+ SWITCH_CAMPAIGN_MATCH_FIELD = "switch_campaign_match_field"+ ADD_CAMPAIGN_NAME_MAPPING = "add_campaign_name_mapping"+ FIX_PLATFORM_URLS = "fix_platform_urls"+ CREATE_CONVERSION_GOAL = "create_conversion_goal"+ FIX_CONVERSION_GOAL = "fix_conversion_goal"+ MARK_GOAL_AS_REVENUE = "mark_goal_as_revenue"+ MARK_GOAL_AS_CUSTOMER = "mark_goal_as_customer"+ SET_ACTIVITY_EVENT = "set_activity_event"+ SET_SIGNUP_EVENT = "set_signup_event"+ SET_PAYMENT_EVENT = "set_payment_event"+ SET_SUBSCRIPTION_EVENT = "set_subscription_event"+++class Capability(StrEnum):+ """What a working setup buys you. Every suggestion says which of these it+ unlocks, so the UI can answer "why should I care?" without extra copy."""++ COST = "cost"+ ATTRIBUTION = "attribution"+ ROAS = "roas"+ CAC = "cac"+ RETENTION_BY_CHANNEL = "retention_by_channel"+ LTV_BY_CHANNEL = "ltv_by_channel"+++class ReadinessStatus(StrEnum):+ UNLOCKED = "unlocked"+ PARTIAL = "partial"+ BLOCKED = "blocked"+++class Severity(StrEnum):+ ERROR = "error"+ WARNING = "warning"+ INFO = "info"+++# A mapping is a band-aid over a tagging bug, so each must carry `fix_platform_urls` — the cure.+# Enforced by the validator below, not at each builder, so a new mapping kind can't skip it.+MAPPING_KINDS = frozenset({SuggestionKind.ADD_SOURCE_MAPPING, SuggestionKind.ADD_CAMPAIGN_NAME_MAPPING})+++class SuggestionSource(StrEnum):+ DETERMINISTIC = "deterministic"+ AI = "ai"+++# Which kinds, once fixed, make other kinds worth doing. Drives ranking.+UNBLOCKS: dict[SuggestionKind, frozenset[SuggestionKind]] = {+ SuggestionKind.CONNECT_SOURCE: frozenset(+ {+ SuggestionKind.SWITCH_CAMPAIGN_MATCH_FIELD,+ SuggestionKind.ADD_CAMPAIGN_NAME_MAPPING,+ SuggestionKind.ADD_SOURCE_MAPPING,+ SuggestionKind.MARK_GOAL_AS_REVENUE,+ SuggestionKind.MARK_GOAL_AS_CUSTOMER,+ }+ ),+ SuggestionKind.RECONNECT_OAUTH: frozenset(+ {+ SuggestionKind.SWITCH_CAMPAIGN_MATCH_FIELD,+ SuggestionKind.ADD_CAMPAIGN_NAME_MAPPING,+ }+ ),+ SuggestionKind.FIX_SYNC: frozenset(+ {+ SuggestionKind.SWITCH_CAMPAIGN_MATCH_FIELD,+ SuggestionKind.ADD_CAMPAIGN_NAME_MAPPING,+ }+ ),+ SuggestionKind.MAP_SCHEMA_COLUMNS: frozenset(+ {+ SuggestionKind.SWITCH_CAMPAIGN_MATCH_FIELD,+ SuggestionKind.ADD_CAMPAIGN_NAME_MAPPING,+ }+ ),+ SuggestionKind.CREATE_CONVERSION_GOAL: frozenset(+ {+ SuggestionKind.MARK_GOAL_AS_REVENUE,+ SuggestionKind.MARK_GOAL_AS_CUSTOMER,+ }+ ),+ SuggestionKind.SET_ACTIVITY_EVENT: frozenset(+ {+ SuggestionKind.SET_PAYMENT_EVENT,+ SuggestionKind.SET_SUBSCRIPTION_EVENT,+ }+ ),+}++_SEVERITY_RANK = {Severity.ERROR: 2, Severity.WARNING: 1, Severity.INFO: 0}+++class _Op(BaseModel):+ # Reject unknown keys so a hallucinated op fails at the boundary, not silently on defaults.+ model_config = ConfigDict(extra="forbid")+++# --- Applicable: the server mutates config ---------------------------------+++class AddCustomSourceMapping(_Op):+ op: Literal["add_custom_source_mapping"] = "add_custom_source_mapping"+ integration: str+ raw_utm_source: str+++class SetCampaignFieldPreference(_Op):+ op: Literal["set_campaign_field_preference"] = "set_campaign_field_preference"+ integration: str+ match_field: Literal["campaign_name", "campaign_id"]+++class AddCampaignNameMapping(_Op):+ op: Literal["add_campaign_name_mapping"] = "add_campaign_name_mapping"+ integration: str+ clean_name: str+ raw_values: list[str] = Field(min_length=1)+++class CreateConversionGoal(_Op):+ op: Literal["create_conversion_goal"] = "create_conversion_goal"+ # Validated against `ConversionGoalFilter` by the apply endpoint, which owns that adapter.+ goal: dict[str, Any]+++class UpdateConversionGoal(_Op):+ op: Literal["update_conversion_goal"] = "update_conversion_goal"+ conversion_goal_id: str+ patch: dict[str, Any]+++class DeleteConversionGoal(_Op):+ op: Literal["delete_conversion_goal"] = "delete_conversion_goal"+ conversion_goal_id: str+++class SetSourceColumnMapping(_Op):+ op: Literal["set_source_column_mapping"] = "set_source_column_mapping"+ table_id: str+ field_mappings: dict[str, str]+++class SetCustomerAnalyticsEvent(_Op):+ op: Literal["set_customer_analytics_event"] = "set_customer_analytics_event"+ field: Literal[+ "activity_event",+ "signup_pageview_event",+ "signup_event",+ "subscription_event",+ "payment_event",+ ]+ event_node: dict[str, Any]+++# --- Navigate-only: the browser does it, or it's advice --------------------+++class OpenOauth(_Op):+ op: Literal["open_oauth"] = "open_oauth"+ # Integration `kind` as `api/integrations/authorize` expects it, e.g. "google-ads".+ kind: str+++class OpenSourceWizard(_Op):+ op: Literal["open_source_wizard"] = "open_source_wizard"+ # `ExternalDataSource.source_type` — what `urls.dataWarehouseSourceNew` matches on.+ kind: str+++class OpenSettings(_Op):+ op: Literal["open_settings"] = "open_settings"+ anchor: str+++class FixPlatformUrls(_Op):+ """Advice, never an action. Attached to every mapping suggestion because the+ mapping is a band-aid and correcting the ad platform's tracking template is the+ actual cure."""++ op: Literal["fix_platform_urls"] = "fix_platform_urls"+ integration: str+ campaign_name: str+ expected_utm_campaign: str+ expected_utm_source: str+++ApplyOp = Annotated[+ AddCustomSourceMapping+ | SetCampaignFieldPreference+ | AddCampaignNameMapping+ | CreateConversionGoal+ | UpdateConversionGoal+ | DeleteConversionGoal+ | SetSourceColumnMapping+ | SetCustomerAnalyticsEvent+ | OpenOauth+ | OpenSourceWizard+ | OpenSettings+ | FixPlatformUrls,+ Field(discriminator="op"),+]++APPLICABLE_OPS: frozenset[str] = frozenset(+ {+ "add_custom_source_mapping",+ "set_campaign_field_preference",+ "add_campaign_name_mapping",+ "create_conversion_goal",+ "update_conversion_goal",+ "delete_conversion_goal",+ "set_source_column_mapping",+ "set_customer_analytics_event",+ }+)++NAVIGATE_OPS: frozenset[str] = frozenset(+ {+ "open_oauth",+ "open_source_wizard",+ "open_settings",+ "fix_platform_urls",+ }+)+++class Suggestion(BaseModel):+ """One row in the setup plan."""++ # Stable across scans: the frontend remembers dismissals by this.+ id: str+ kind: SuggestionKind+ source: SuggestionSource = SuggestionSource.DETERMINISTIC+ severity: Severity+ confidence: float = Field(ge=0.0, le=1.0)+ title: str+ evidence: str+ unlocks: list[Capability] = Field(default_factory=list)+ apply: ApplyOp | None = None+ also_recommended: list[ApplyOp] = Field(default_factory=list)+ safe_to_batch: bool = False+ rank_score: float = 0.0+ integration: str | None = None+ deep_link: str | None = None+ spend_at_risk: float = 0.0+ event_volume: int = 0++ @model_validator(mode="after")+ def _mapping_suggestions_carry_the_url_fix(self) -> "Suggestion":+ if self.kind in MAPPING_KINDS and not any(op.op == "fix_platform_urls" for op in self.also_recommended):+ raise ValueError(+ f"{self.kind.value} suggestions must carry a fix_platform_urls op in also_recommended: "+ "the mapping is a workaround, and offering it without the cure teaches the wrong fix."+ )+ return self+++class CapabilityReadiness(BaseModel):+ capability: Capability+ status: ReadinessStatus+ explanation: str+ # `Suggestion.id`s — the link from "ROAS is blocked" to the rows that unblock it.+ blocked_by: list[str] = Field(default_factory=list)+++class SetupPlan(BaseModel):+ suggestions: list[Suggestion] = Field(default_factory=list)+ readiness: list[CapabilityReadiness] = Field(default_factory=list)+ degraded: list[str] = Field(default_factory=list)+ # Rates are over the queries' top-N rows, so a percentage is a subtotal.+ truncated: bool = False+ summary: str = ""+++def rank_score(suggestion: Suggestion, present_kinds: set[SuggestionKind], max_impact: float) -> float:+ """Unblocking-first, then severity, then impact.++ An action that unblocks others outranks one that doesn't, however big the latter's number.+ `max_impact` normalises so impact can't outweigh the two structural terms.+ """+ unblocked = len(UNBLOCKS.get(suggestion.kind, frozenset()) & present_kinds)+ impact = suggestion.spend_at_risk or float(suggestion.event_volume)+ normalised_impact = (impact / max_impact) if max_impact > 0 else 0.0+ return (100 * unblocked) + (10 * _SEVERITY_RANK[suggestion.severity]) + normalised_impact+++def sort_suggestions(suggestions: list[Suggestion]) -> list[Suggestion]:+ """Score and sort, returning a new list. Ties break on `id` so output is byte-identical run+ to run — snapshot tests depend on it, and so does a UI that shouldn't reshuffle."""+ present_kinds = {s.kind for s in suggestions}+ max_impact = max((s.spend_at_risk or float(s.event_volume) for s in suggestions), default=0.0)+ for suggestion in suggestions:+ suggestion.rank_score = rank_score(suggestion, present_kinds, max_impact)+ return sorted(suggestions, key=lambda s: (-s.rank_score, s.id))diff --git a/products/marketing_analytics/backend/services/test_native_integrations.py b/products/marketing_analytics/backend/services/test_native_integrations.pyindex 361cd332d30b..1459ea666ce6 100644--- a/products/marketing_analytics/backend/services/test_native_integrations.py+++ b/products/marketing_analytics/backend/services/test_native_integrations.py@@ -1,10 +1,13 @@from parameterized import parameterized+from posthog.models.integration import OauthIntegration+from products.marketing_analytics.backend.services.native_integrations import (DISPLAY_NAMES,EXTERNAL_SOURCE_TYPE_TO_NATIVE,KEY_TO_NATIVE,NATIVE_TO_KEY,+ OAUTH_KIND_BY_NATIVE,aliases_for,canonical_source_aliases,display_name_for_key,@@ -127,3 +130,14 @@ class TestStructuralInvariants:for source_type, native in EXTERNAL_SOURCE_TYPE_TO_NATIVE.items():assert native in NATIVE_TO_KEYassert isinstance(source_type, str)++ def test_every_oauth_kind_is_one_the_authorize_endpoint_accepts(self):+ # Spelled out means it can drift, and a kind `authorize` rejects is a Connect button+ # that 400s. `supported_kinds` is what that endpoint validates against.+ unknown = set(OAUTH_KIND_BY_NATIVE.values()) - set(OauthIntegration.supported_kinds)++ assert not unknown, f"{sorted(unknown)} are not kinds the authorize endpoint accepts"++ def test_every_native_integration_has_an_oauth_kind(self):+ for native in NATIVE_TO_KEY:+ assert native in OAUTH_KIND_BY_NATIVE, f"{native} has no OAuth kind, so it can't be connected"diff --git a/products/marketing_analytics/backend/services/test_setup_plan.py b/products/marketing_analytics/backend/services/test_setup_plan.pynew file mode 100644index 000000000000..2e5accba90a4--- /dev/null+++ b/products/marketing_analytics/backend/services/test_setup_plan.py@@ -0,0 +1,606 @@+import pytest+from posthog.test.base import APIBaseTest+from unittest.mock import AsyncMock, patch++from pydantic import ValidationError++from products.marketing_analytics.backend.services.attribution_health import AttributionHealthResponse+from products.marketing_analytics.backend.services.conversion_goals_inspector import (+ ConversionGoalsListResponse,+ ConversionGoalSummary,+)+from products.marketing_analytics.backend.services.event_suggestions import CandidateEvent, EventSuggestionsResponse+from products.marketing_analytics.backend.services.mapping_suggester import (+ SourceMappingSuggestion,+ UtmMappingSuggestionsResponse,+)+from products.marketing_analytics.backend.services.marketing_diagnostic import (+ IntegrationDiagnostic,+ MarketingDiagnosticResponse,+)+from products.marketing_analytics.backend.services.setup_plan import get_setup_plan+from products.marketing_analytics.backend.services.setup_types import (+ MAPPING_KINDS,+ Capability,+ OpenOauth,+ ReadinessStatus,+ Severity,+ Suggestion,+ SuggestionKind,+)+from products.marketing_analytics.backend.services.types import Campaign, TeamMappings++_MODULE = "products.marketing_analytics.backend.services.setup_plan"++NO_MAPPINGS = TeamMappings(source_to_integration={}, campaign_aliases={}, field_preferences={})+++def _integration(+ key="google_ads",+ source_type="GoogleAds",+ status="healthy",+ last_error=None,+ schema_missing=None,+ unmatched=0,+) -> IntegrationDiagnostic:+ data_source = None+ if status != "events_only":+ from products.marketing_analytics.backend.services.data_source_health import DataSourceHealthEntry++ data_source = DataSourceHealthEntry(+ source_type=source_type,+ is_native=True,+ display_name=key,+ connected=True,+ last_sync_at=None,+ last_sync_status="ok",+ last_error=last_error,+ rows_last_24h=0,+ rows_last_7d=0,+ sources_map_present=True,+ schema_columns_mapped=[],+ schema_columns_required_missing=schema_missing or [],+ required_tables=[],+ settings_url="/settings/env",+ schemas_url="/schemas/1",+ diagnosis=f"{key} diagnosis",+ fix_suggestion=None,+ )++ attribution = None+ if unmatched:+ from products.marketing_analytics.backend.services.attribution_health import AttributionHealthEntry++ attribution = AttributionHealthEntry(+ integration_key=key,+ display_name=key,+ events_with_utm_last_7d=unmatched,+ events_matched_last_7d=0,+ events_unmatched_likely_yours_last_7d=unmatched,+ last_event_with_matching_utm_at=None,+ matched_pct=0.0,+ sample_unmatched_utm_sources=[],+ )++ return IntegrationDiagnostic(+ integration_key=key,+ source_type=source_type,+ display_name=key.replace("_", " ").title(),+ overall_status=status,+ diagnosis=f"{key} diagnosis",+ data_source=data_source,+ attribution=attribution,+ )+++def _goal(goal_id="g1", name="Signup", count=1000, misconfigured=False) -> ConversionGoalSummary:+ return ConversionGoalSummary(+ id=goal_id,+ name=name,+ # What the inspector actually emits — it defaults to "EventsNode", not "events".+ kind="EventsNode",+ target_label=name,+ last_30d_count=count,+ integrated_count=count,+ events_without_utm_source=0,+ events_with_unmatched_utm_source=0,+ non_integrated_count=0,+ integrated_pct=1.0,+ is_misconfigured=misconfigured,+ misconfig_reason="references a deleted action" if misconfigured else None,+ )+++def _attribution(total=1000, matched=900) -> AttributionHealthResponse:+ return AttributionHealthResponse(+ lookback_days=90,+ integrations=[],+ total_events_with_utm=total,+ total_events_matched_to_any_integration=matched,+ total_events_unmatched=total - matched,+ sample_globally_unmatched=[],+ )+++class SetupPlanTestCase(APIBaseTest):+ """Every leaf the plan gathers is mocked; these tests are about how the plan+ composes, ranks and explains, not about the leaves' own logic."""++ def setUp(self):+ super().setUp()+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[_integration()],+ overall_status="healthy",+ summary="ok",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )+ self.attribution = _attribution()+ self.candidates = EventSuggestionsResponse(candidates=[])+ self.campaigns: list[Campaign] = []+ self.utm_events: dict[tuple[str, str], int] = {}+ self.goal_flags: dict[str, dict] = {"g1": {"counts_as_revenue": True, "counts_as_customer": True}}+ self.utm_mappings = UtmMappingSuggestionsResponse()++ # Every mock reads its attribute at call time, not at setUp time — tests+ # reassign `self.diagnostic` etc. after setUp has already run, and a captured+ # `return_value` would silently keep serving the default fixture.+ attribute_by_target = {+ "get_marketing_diagnostic": "diagnostic",+ "get_attribution_health": "attribution",+ "suggest_conversion_goals": "candidates",+ "get_campaigns_with_spend_async": "campaigns",+ "get_utm_campaign_catalogue_async": "utm_events",+ "_load_goal_flags": "goal_flags",+ "suggest_utm_mappings": "utm_mappings",+ }+ self.mocks = {}+ for target, attribute in attribute_by_target.items():+ mock = AsyncMock(side_effect=self._current(attribute))+ self.mocks[target] = mock+ patcher = patch(f"{_MODULE}.{target}", new=mock)+ patcher.start()+ self.addCleanup(patcher.stop)++ mappings_mock = AsyncMock(side_effect=lambda *args, **kwargs: NO_MAPPINGS)+ self.mocks["_load_mappings"] = mappings_mock+ mappings_patcher = patch(f"{_MODULE}._load_mappings", new=mappings_mock)+ mappings_patcher.start()+ self.addCleanup(mappings_patcher.stop)++ def _current(self, attribute: str):+ def read(*args, **kwargs):+ return getattr(self, attribute)++ return read+++class TestInvariants(SetupPlanTestCase):+ @pytest.mark.asyncio+ async def test_every_mapping_suggestion_carries_the_url_fix(self):+ # Asserted across the whole plan rather than per call site, so a new builder+ # that forgets the pairing fails here.+ self.utm_mappings = UtmMappingSuggestionsResponse(+ source_suggestions=[+ SourceMappingSuggestion(+ raw_utm_source="fb-ads",+ suggested_target="meta_ads",+ suggested_target_display_name="Meta Ads",+ reason="'fb-ads' contains a known alias of Meta Ads.",+ event_count_30d=500,+ )+ ]+ )+ self.campaigns = [+ Campaign("spring_sale_2024", "1", "google", 8200.0, 0, 0),+ *[Campaign(f"c{i}", str(i), "google", 100.0, 0, 0) for i in range(9)],+ ]+ self.utm_events = {("sprng_sale_2024", "google"): 1340}++ plan = await get_setup_plan(self.team)++ mapping_suggestions = [s for s in plan.suggestions if s.kind in MAPPING_KINDS]+ assert mapping_suggestions, "expected the fixture to produce mapping suggestions"+ for suggestion in mapping_suggestions:+ ops = [op.op for op in suggestion.also_recommended]+ assert "fix_platform_urls" in ops, f"{suggestion.id} has no URL fix"++ @pytest.mark.asyncio+ async def test_campaign_proposals_are_injected_rather_than_derived_twice(self):+ # `suggest_utm_mappings` derives its own proposals when none are passed, and doing so+ # re-reads campaigns, the UTM catalogue and team mappings — all three of which this+ # function already gathered. Leaving the argument off meant three redundant queries plus+ # a second fuzzy pass, and two independently-computed proposal sets in one response that+ # could disagree. The injection parameter exists precisely to prevent that.+ self.campaigns = [+ Campaign("spring_sale_2024", "1", "google", 8200.0, 0, 0),+ *[Campaign(f"c{i}", str(i), "google", 100.0, 0, 0) for i in range(9)],+ ]+ self.utm_events = {("sprng_sale_2024", "google"): 1340}++ await get_setup_plan(self.team)++ await_args = self.mocks["suggest_utm_mappings"].await_args+ assert await_args is not None, "suggest_utm_mappings was never awaited"+ proposals = await_args.kwargs.get("campaign_proposals")+ assert proposals is not None, "campaign_proposals was not injected"+ # The same object the plan builds its own suggestions from, not an equal-looking copy.+ assert [p.raw_utm_campaign for p in proposals.proposals] == ["sprng_sale_2024"]++ @pytest.mark.asyncio+ async def test_summary_separates_partial_capabilities_from_blocked_ones(self):+ # Counting only UNLOCKED reported "0 of 4 capabilities unlocked" for a team whose four were+ # all partial — which reads as nothing working at all.+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[+ _integration("google_ads", "GoogleAds", status="healthy"),+ _integration("meta_ads", "MetaAds", status="sync_broken"),+ ],+ overall_status="degraded",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )++ plan = await get_setup_plan(self.team)++ assert any(r.status == ReadinessStatus.PARTIAL for r in plan.readiness)+ assert "partial" in plan.summary++ def test_a_mapping_kind_cannot_be_built_without_the_url_fix(self):+ # This used to live in a helper the builders had to remember, plus a hardcoded copy of+ # the kind set here — so a new mapping kind bypassed both.+ with pytest.raises(ValidationError) as error:+ Suggestion(+ id="add_source_mapping:x",+ kind=SuggestionKind.ADD_SOURCE_MAPPING,+ severity=Severity.WARNING,+ confidence=0.9,+ title="t",+ evidence="e",+ )++ assert "fix_platform_urls" in str(error.value)++ @pytest.mark.asyncio+ async def test_a_failing_campaign_suggester_degrades_only_its_own_section(self):+ # These run outside the gather, so an unwrapped raise took the whole plan down.+ self.campaigns = [Campaign("spring_sale_2024", "1", "google", 8200.0, 0, 0)]+ self.utm_events = {("sprng_sale_2024", "google"): 1340}++ with patch(f"{_MODULE}.build_audit", side_effect=RuntimeError("bad row")):+ plan = await get_setup_plan(self.team)++ assert "campaign_suggesters" in plan.degraded+ assert not [s for s in plan.suggestions if s.kind in MAPPING_KINDS]+ # The rest of the plan survived, which is the whole point.+ assert plan.readiness++ @pytest.mark.asyncio+ async def test_output_is_byte_stable_across_runs(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[+ _integration("google_ads", "GoogleAds", status="sync_broken"),+ _integration("meta_ads", "MetaAds", status="events_only", unmatched=900),+ ],+ overall_status="broken",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )++ first = await get_setup_plan(self.team)+ second = await get_setup_plan(self.team)++ assert first.model_dump(mode="json") == second.model_dump(mode="json")++ @pytest.mark.asyncio+ async def test_suggestion_ids_are_deterministic_not_positional(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[_integration("meta_ads", "MetaAds", status="events_only", unmatched=900)],+ overall_status="degraded",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )++ plan = await get_setup_plan(self.team)++ # The frontend remembers dismissals by id, so it must describe the finding.+ assert "connect_source:meta_ads" in [s.id for s in plan.suggestions]+++class TestRanking(SetupPlanTestCase):+ @pytest.mark.asyncio+ async def test_unblocking_action_outranks_a_higher_volume_one(self):+ # Connecting the platform unblocks the goal-flag work, so it must come first+ # even though the goal suggestion carries far more event volume.+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[_integration("meta_ads", "MetaAds", status="events_only", unmatched=10)],+ overall_status="degraded",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal(count=5_000_000)]),+ )+ self.goal_flags = {"g1": {}}++ plan = await get_setup_plan(self.team)++ kinds = [s.kind for s in plan.suggestions]+ assert kinds[0] == SuggestionKind.CONNECT_SOURCE+ assert SuggestionKind.MARK_GOAL_AS_REVENUE in kinds+ assert kinds.index(SuggestionKind.CONNECT_SOURCE) < kinds.index(SuggestionKind.MARK_GOAL_AS_REVENUE)++ @pytest.mark.asyncio+ async def test_errors_outrank_warnings_at_equal_unblocking(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[+ _integration("google_ads", "GoogleAds", status="events_broken"),+ _integration("meta_ads", "MetaAds", status="schema_misconfigured", schema_missing=["cost"]),+ ],+ overall_status="degraded",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )++ plan = await get_setup_plan(self.team)++ severities = [s.severity for s in plan.suggestions]+ assert severities[0] == Severity.ERROR+++class TestDegradation(SetupPlanTestCase):+ @pytest.mark.asyncio+ async def test_diagnostic_failure_propagates(self):+ # An empty plan would read as "you're all set", which is worse than an error.+ self.mocks["get_marketing_diagnostic"].side_effect = RuntimeError("clickhouse down")++ with pytest.raises(RuntimeError):+ await get_setup_plan(self.team)++ @pytest.mark.asyncio+ async def test_leaf_failure_degrades_without_losing_the_plan(self):+ self.mocks["get_attribution_health"].side_effect = RuntimeError("timeout")+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[_integration("google_ads", "GoogleAds", status="sync_broken")],+ overall_status="broken",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )++ plan = await get_setup_plan(self.team)++ assert "attribution_health" in plan.degraded+ assert any(s.kind == SuggestionKind.FIX_SYNC for s in plan.suggestions)+ assert "Incomplete" in plan.summary++ @pytest.mark.asyncio+ async def test_campaign_query_failure_skips_only_campaign_suggestions(self):+ # A fixture that *would* produce campaign suggestions, or the absence proves nothing:+ # the plan skips the suggesters on empty input anyway.+ self.campaigns = [+ Campaign("spring_sale_2024", "1", "google", 8200.0, 0, 0),+ *[Campaign(f"c{i}", str(i), "google", 100.0, 0, 0) for i in range(9)],+ ]+ self.utm_events = {("sprng_sale_2024", "google"): 1340}+ self.mocks["get_campaigns_with_spend_async"].side_effect = RuntimeError("nope")++ plan = await get_setup_plan(self.team)++ assert "campaigns" in plan.degraded+ assert not [s for s in plan.suggestions if s.kind == SuggestionKind.ADD_CAMPAIGN_NAME_MAPPING]+++class TestReadiness(SetupPlanTestCase):+ def _readiness(self, plan, capability):+ return next(r for r in plan.readiness if r.capability == capability)++ @pytest.mark.asyncio+ async def test_cost_blocked_when_nothing_is_connected(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[_integration("google_ads", "GoogleAds", status="not_connected")],+ overall_status="no_sources",+ conversion_goals=ConversionGoalsListResponse(goals=[]),+ )++ plan = await get_setup_plan(self.team)++ assert self._readiness(plan, Capability.COST).status == ReadinessStatus.BLOCKED++ @pytest.mark.asyncio+ async def test_cost_partial_when_some_integrations_are_broken(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[+ _integration("google_ads", "GoogleAds", status="healthy"),+ _integration("meta_ads", "MetaAds", status="sync_broken"),+ ],+ overall_status="degraded",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )++ plan = await get_setup_plan(self.team)++ assert self._readiness(plan, Capability.COST).status == ReadinessStatus.PARTIAL++ @pytest.mark.asyncio+ async def test_roas_blocked_without_a_revenue_flagged_goal(self):+ # Goals exist and spend is fine, yet ROAS stays empty — what readiness is for.+ self.goal_flags = {"g1": {"counts_as_customer": True}}++ plan = await get_setup_plan(self.team)++ roas = self._readiness(plan, Capability.ROAS)+ assert roas.status == ReadinessStatus.BLOCKED+ assert "counts_as_revenue" in roas.explanation+ assert self._readiness(plan, Capability.CAC).status == ReadinessStatus.UNLOCKED++ @pytest.mark.asyncio+ async def test_readiness_links_back_to_the_blocking_suggestions(self):+ self.goal_flags = {"g1": {}}++ plan = await get_setup_plan(self.team)++ # An exact set: "non-empty and a subset" also passes when `_blockers` ignores the+ # capability and returns everything. Both are present here; only one unlocks ROAS.+ roas = self._readiness(plan, Capability.ROAS)+ assert {s.id for s in plan.suggestions} == {"mark_goal_as_revenue:any", "mark_goal_as_customer:any"}+ assert set(roas.blocked_by) == {"mark_goal_as_revenue:any"}+ assert set(self._readiness(plan, Capability.CAC).blocked_by) == {"mark_goal_as_customer:any"}++ @pytest.mark.asyncio+ async def test_roas_names_both_gaps_when_spend_is_missing_too(self):+ # Three of the five branches differ only in their explanation, so a swap would change+ # what the user is told next while every status stayed correct.+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[_integration("google_ads", "GoogleAds", status="not_connected")],+ overall_status="no_sources",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )+ self.goal_flags = {"g1": {}}++ plan = await get_setup_plan(self.team)++ roas = self._readiness(plan, Capability.ROAS)+ assert roas.status == ReadinessStatus.BLOCKED+ assert "Needs spend data and a conversion goal" in roas.explanation++ @pytest.mark.asyncio+ async def test_roas_blames_only_the_spend_when_the_goal_is_flagged(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[_integration("google_ads", "GoogleAds", status="not_connected")],+ overall_status="no_sources",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )++ plan = await get_setup_plan(self.team)++ roas = self._readiness(plan, Capability.ROAS)+ assert roas.status == ReadinessStatus.BLOCKED+ assert roas.explanation == "A goal is flagged, but there is no spend data to divide by."++ @pytest.mark.asyncio+ async def test_roas_is_partial_when_only_some_integrations_report_spend(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[+ _integration("google_ads", "GoogleAds", status="healthy"),+ _integration("meta_ads", "MetaAds", status="sync_broken"),+ ],+ overall_status="degraded",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )++ plan = await get_setup_plan(self.team)++ roas = self._readiness(plan, Capability.ROAS)+ assert roas.status == ReadinessStatus.PARTIAL+ assert roas.explanation == "Available, but only for the integrations whose spend is readable."++ @pytest.mark.asyncio+ async def test_attribution_blocked_when_no_utm_events_arrive(self):+ self.attribution = _attribution(total=0, matched=0)++ plan = await get_setup_plan(self.team)++ assert self._readiness(plan, Capability.ATTRIBUTION).status == ReadinessStatus.BLOCKED++ @pytest.mark.asyncio+ async def test_attribution_partial_when_most_events_do_not_match(self):+ self.attribution = _attribution(total=1000, matched=300)++ plan = await get_setup_plan(self.team)++ attribution = self._readiness(plan, Capability.ATTRIBUTION)+ assert attribution.status == ReadinessStatus.PARTIAL+ assert "30%" in attribution.explanation+++class TestConversionGoals(SetupPlanTestCase):+ @pytest.mark.asyncio+ async def test_names_the_best_candidate_event_when_no_goals_exist(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[_integration()],+ overall_status="healthy",+ conversion_goals=ConversionGoalsListResponse(goals=[]),+ )+ self.candidates = EventSuggestionsResponse(+ candidates=[+ CandidateEvent(+ event_name="purchase_completed",+ last_30d_count=4200,+ distinct_users_30d=3100,+ pct_with_utm_source=0.82,+ pct_with_utm_campaign=0.8,+ top_utm_sources=[("google", 2000)],+ is_already_a_goal=False,+ suggestion_score=0.9,+ suggestion_reason="high volume, well tagged",+ )+ ]+ )+ self.goal_flags = {}++ plan = await get_setup_plan(self.team)++ create = next(s for s in plan.suggestions if s.kind == SuggestionKind.CREATE_CONVERSION_GOAL)+ assert "purchase_completed" in create.evidence+ assert "4,200" in create.evidence++ @pytest.mark.asyncio+ async def test_misconfigured_goal_is_an_error(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[_integration()],+ overall_status="healthy",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal(misconfigured=True)], has_misconfigured=True),+ )++ plan = await get_setup_plan(self.team)++ fix = next(s for s in plan.suggestions if s.kind == SuggestionKind.FIX_CONVERSION_GOAL)+ assert fix.severity == Severity.ERROR+ assert "deleted action" in fix.evidence++ @pytest.mark.asyncio+ async def test_goal_flag_suggestions_are_never_batch_applied(self):+ self.goal_flags = {"g1": {}}++ plan = await get_setup_plan(self.team)++ flag_kinds = {SuggestionKind.MARK_GOAL_AS_REVENUE, SuggestionKind.MARK_GOAL_AS_CUSTOMER}+ flags = [s for s in plan.suggestions if s.kind in flag_kinds]+ assert flags+ assert all(s.safe_to_batch is False for s in flags)+++class TestIntegrationSuggestions(SetupPlanTestCase):+ @pytest.mark.asyncio+ async def test_auth_error_becomes_a_reconnect_with_a_valid_oauth_kind(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[+ _integration("snapchat_ads", "SnapchatAds", status="sync_broken", last_error="token expired")+ ],+ overall_status="broken",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )++ plan = await get_setup_plan(self.team)++ reconnect = next(s for s in plan.suggestions if s.kind == SuggestionKind.RECONNECT_OAUTH)+ # Narrowed, not indexed: only OpenOauth carries `kind`, so this also pins the op type.+ assert isinstance(reconnect.apply, OpenOauth)+ assert reconnect.apply.kind == "snapchat"++ @pytest.mark.asyncio+ async def test_non_auth_sync_error_becomes_fix_sync_not_reconnect(self):+ self.diagnostic = MarketingDiagnosticResponse(+ integrations=[+ _integration("google_ads", "GoogleAds", status="sync_broken", last_error="rate limit exceeded")+ ],+ overall_status="broken",+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),+ )++ plan = await get_setup_plan(self.team)++ assert any(s.kind == SuggestionKind.FIX_SYNC for s in plan.suggestions)+ assert not any(s.kind == SuggestionKind.RECONNECT_OAUTH for s in plan.suggestions)++ @pytest.mark.asyncio+ async def test_healthy_integration_produces_nothing(self):+ plan = await get_setup_plan(self.team)++ integration_kinds = {+ SuggestionKind.CONNECT_SOURCE,+ SuggestionKind.RECONNECT_OAUTH,+ SuggestionKind.FIX_SYNC,+ SuggestionKind.MAP_SCHEMA_COLUMNS,+ }+ assert not [s for s in plan.suggestions if s.kind in integration_kinds]diff --git a/products/marketing_analytics/backend/services/utm_audit.py b/products/marketing_analytics/backend/services/utm_audit.pyindex 9068a5c9a7cb..ce40c979cafe 100644--- a/products/marketing_analytics/backend/services/utm_audit.py+++ b/products/marketing_analytics/backend/services/utm_audit.py@@ -69,11 +69,29 @@ def run_utm_audit()mappings = load_team_mappings(team)- known_sources = build_known_sources(mappings)-campaigns = get_campaigns_with_spend(team, date_range, user=user)utm_events = get_utm_campaign_catalogue(team, date_range, user=user)+ return build_audit(campaigns, utm_events, mappings)+++# The audit is sync (it reads team config through the ORM and runs HogQL inline), but the+# async services — `marketing_diagnostic`, `setup_plan` — gather it alongside coroutines.+run_utm_audit_async = database_sync_to_async(run_utm_audit)+++def build_audit(+ campaigns: list[Campaign],+ utm_events: dict[tuple[str, str], int],+ mappings: TeamMappings,+) -> UtmAuditResponse:+ """Cross-reference already-fetched campaigns and UTM events into an audit.++ Split out of `run_utm_audit` so `setup_plan` can audit the same rows it already+ pulled for the suggesters instead of paying for both queries a second time.+ """+ known_sources = build_known_sources(mappings)+results = _cross_reference(campaigns, utm_events, mappings, known_sources) if campaigns else []all_utm = _build_all_utm_events(campaigns, utm_events, mappings)@@ -89,11 +107,6 @@ def run_utm_audit()-# The audit is sync (it reads team config through the ORM and runs HogQL inline), but the-# async services — `marketing_diagnostic`, `setup_plan` — gather it alongside coroutines.-run_utm_audit_async = database_sync_to_async(run_utm_audit)--def get_campaigns_with_spend(team: Team, date_range: QueryDateRange, *, user: User | None = None) -> list[Campaign]:"""Get all campaigns with spend from marketing integrations."""context = QueryContext(