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 demo data generator command (#74054)

Javier Bahamondesae3e6d33b94b
diff --git a/products/marketing_analytics/backend/demo/config.py b/products/marketing_analytics/backend/demo/config.py
new file mode 100644
index 000000000000..1fcd4c135bb8
--- /dev/null
+++ b/products/marketing_analytics/backend/demo/config.py
@@ -0,0 +1,154 @@
+"""Team configuration for the demo world: conversion goals, mappings, flags."""
+
+from posthog.models import Team, User
+
+from products.actions.backend.models.action import Action
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.marketing_analytics.backend.demo.warehouse import STRIPE_INVOICES_TABLE
+from products.marketing_analytics.backend.demo.world import EVENT_DEMO_BOOKED, EVENT_PURCHASE, EVENT_SIGNUP
+
+MARKETING_FEATURE_FLAGS = (
+ "marketing-analytics",
+ "marketing-analytics-utm-audit",
+ "marketing-analytics-drill-down",
+ "marketing-analytics-extended-drill-down",
+ "marketing-analytics-multi-touch-attribution",
+ "marketing-analytics-ai",
+ "advance-marketing-analytics-settings",
+)
+
+_DEFAULT_SCHEMA_MAP = {
+ "utm_campaign_name": "utm_campaign",
+ "utm_source_name": "utm_source",
+ "timestamp_field": "timestamp",
+ "distinct_id_field": "distinct_id",
+}
+
+
+def _ensure_demo_action(team: Team) -> Action:
+ action = Action.objects.filter(team=team, name="Demo booked (marketing demo)", deleted=False).first()
+ if action:
+ return action
+ return Action.objects.create(
+ team=team,
+ name="Demo booked (marketing demo)",
+ steps_json=[{"event": EVENT_DEMO_BOOKED}],
+ )
+
+
+def build_conversion_goals(team: Team) -> list[dict]:
+ action = _ensure_demo_action(team)
+ return [
+ {
+ "kind": "EventsNode",
+ "event": EVENT_SIGNUP,
+ "conversion_goal_id": "cg_signups",
+ "name": EVENT_SIGNUP,
+ "conversion_goal_name": "Sign ups",
+ "math": "dau",
+ "schema_map": _DEFAULT_SCHEMA_MAP,
+ },
+ {
+ "kind": "EventsNode",
+ "event": EVENT_PURCHASE,
+ "conversion_goal_id": "cg_purchases",
+ "name": EVENT_PURCHASE,
+ "conversion_goal_name": "Purchase revenue",
+ "math": "sum",
+ "math_property": "revenue",
+ "counts_as_customer": True,
+ "counts_as_revenue": True,
+ "schema_map": _DEFAULT_SCHEMA_MAP,
+ },
+ {
+ "kind": "ActionsNode",
+ "id": action.pk,
+ "conversion_goal_id": "cg_demos",
+ "name": "Demo booked (marketing demo)",
+ "conversion_goal_name": "Demos booked",
+ "math": "total",
+ "schema_map": _DEFAULT_SCHEMA_MAP,
+ },
+ {
+ "kind": "DataWarehouseNode",
+ "id": STRIPE_INVOICES_TABLE,
+ "table_name": STRIPE_INVOICES_TABLE,
+ "conversion_goal_id": "cg_invoices",
+ "name": STRIPE_INVOICES_TABLE,
+ "conversion_goal_name": "Paid invoices",
+ "math": "sum",
+ "math_property": "amount",
+ "counts_as_customer": True,
+ "counts_as_revenue": True,
+ "timestamp_field": "created_at",
+ "distinct_id_field": "distinct_id",
+ "id_field": "id",
+ "schema_map": {
+ "utm_campaign_name": "utm_campaign",
+ "utm_source_name": "utm_source",
+ "timestamp_field": "created_at",
+ "distinct_id_field": "distinct_id",
+ },
+ },
+ # Deliberately broken goals: exercise is_misconfigured in the inspector
+ # and the dashboard's validation warnings.
+ {
+ "kind": "ActionsNode",
+ "id": 999999,
+ "conversion_goal_id": "cg_ghost_action",
+ "name": "Ghost action",
+ "conversion_goal_name": "Ghost action (broken)",
+ "math": "total",
+ "schema_map": _DEFAULT_SCHEMA_MAP,
+ },
+ {
+ "kind": "EventsNode",
+ "event": None,
+ "conversion_goal_id": "cg_all_events",
+ "name": "All events",
+ "conversion_goal_name": "All events (misconfigured)",
+ "math": "total",
+ "schema_map": _DEFAULT_SCHEMA_MAP,
+ },
+ ]
+
+
+def apply_marketing_config(team: Team, *, bigquery_sources_map: dict[str, dict[str, str]]) -> None:
+ config = team.marketing_analytics_config
+ config.conversion_goals = build_conversion_goals(team)
+ config.sources_map = bigquery_sources_map
+ config.campaign_name_mappings = {
+ "GoogleAds": {"Spring Sale 2026": ["spring_sale_2026", "spring-sale-2026"]},
+ }
+ config.custom_source_mappings = {"GoogleAds": ["partner_blog"]}
+ config.campaign_field_preferences = {"BingAds": {"match_field": "campaign_id"}}
+ # 30 days: keeps the goals inspector non-approximate and lets the
+ # out-of-window journey actually fall outside the window within 60 days.
+ config.attribution_window_days = 30
+ config.attribution_mode = "last_touch"
+ config.save()
+
+
+def enable_feature_flags(team: Team, user: User) -> list[str]:
+ """Enable the marketing flags at 100% on the target team and on the local
+ self-capture team (the one whose flags the local PostHog UI evaluates)."""
+ teams = {team.pk: team}
+ self_capture_team = Team.objects.filter(api_token="phc_localposthogprojecttoken").first()
+ if self_capture_team:
+ teams[self_capture_team.pk] = self_capture_team
+ enabled = []
+ for target in teams.values():
+ for key in MARKETING_FEATURE_FLAGS:
+ FeatureFlag.objects.update_or_create(
+ team=target,
+ key=key,
+ defaults={
+ "name": key,
+ "active": True,
+ "deleted": False,
+ "created_by": user,
+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},
+ },
+ )
+ enabled.append(f"{target.pk}:{key}")
+ return enabled
diff --git a/products/marketing_analytics/backend/demo/events.py b/products/marketing_analytics/backend/demo/events.py
new file mode 100644
index 000000000000..ebf5c7a0a3f5
--- /dev/null
+++ b/products/marketing_analytics/backend/demo/events.py
@@ -0,0 +1,400 @@
+"""Deterministic event generation for the marketing demo world.
+
+Everything is derived from a seeded RNG so re-runs with the same seed produce
+the same world. Events are written straight to ClickHouse via the Kafka
+producer (`create_event`), which accepts historical timestamps.
+"""
+
+import uuid
+import datetime as dt
+from dataclasses import dataclass, field
+from random import Random
+from urllib.parse import urlencode
+
+from posthog.models import Team
+from posthog.models.event.util import create_event
+from posthog.models.utils import uuid7
+
+from products.marketing_analytics.backend.demo.world import (
+ CAMPAIGNS,
+ EVENT_DEMO_BOOKED,
+ EVENT_PAGEVIEW,
+ EVENT_PURCHASE,
+ EVENT_SIGNUP,
+ FREE_CHANNELS,
+ SITE_URL,
+ DemoCampaign,
+ DemoFreeChannel,
+)
+
+PERSON_NAMESPACE = uuid.UUID("aa8e9c34-0d7a-46bc-b78b-1a4c5c6f7d01")
+
+
+@dataclass
+class InvoiceRow:
+ invoice_id: str
+ distinct_id: str
+ created_at: dt.datetime
+ amount: float
+ utm_campaign: str
+ utm_source: str
+
+
+@dataclass
+class GenerationResult:
+ events_written: int = 0
+ invoices: list[InvoiceRow] = field(default_factory=list)
+
+
+class MarketingEventGenerator:
+ def __init__(self, team: Team, *, seed: str, days_past: int, scale: float, now: dt.datetime):
+ self.team = team
+ self.rng = Random(seed)
+ self.days_past = days_past
+ self.scale = scale
+ self.now = now
+ self.result = GenerationResult()
+ self._person_counter = 0
+
+ def generate(self) -> GenerationResult:
+ for day_offset in range(self.days_past, 0, -1):
+ day = self.now - dt.timedelta(days=day_offset)
+ for campaign in CAMPAIGNS:
+ self._generate_campaign_day(campaign, day)
+ for channel in FREE_CHANNELS:
+ self._generate_free_channel_day(channel, day)
+ self._generate_edge_cases(day)
+ self._generate_journeys()
+ return self.result
+
+ # --- daily traffic ---
+
+ def _generate_campaign_day(self, campaign: DemoCampaign, day: dt.datetime) -> None:
+ for _ in range(self._daily_volume(campaign.daily_sessions, day)):
+ distinct_id, person_uuid = self._new_person()
+ ts = self._time_in_day(day)
+ utm_source = self._pick_variant(campaign.utm_source, campaign.utm_source_variants)
+ utm_campaign = self._pick_variant(
+ campaign.utm_campaign or campaign.name.lower(), campaign.utm_campaign_variants
+ )
+ properties: dict = {
+ "utm_source": utm_source,
+ "utm_medium": campaign.utm_medium,
+ "utm_campaign": utm_campaign,
+ "utm_content": self.rng.choice(["hero_cta", "pricing_card", "footer_link"]),
+ "$referring_domain": campaign.referring_domain or "$direct",
+ }
+ if campaign.click_id_property:
+ properties[campaign.click_id_property] = uuid.uuid5(PERSON_NAMESPACE, f"click-{distinct_id}").hex
+ session_id = self._pageview(distinct_id, person_uuid, ts, properties)
+ self._maybe_convert(
+ distinct_id,
+ person_uuid,
+ ts,
+ campaign.signup_rate,
+ campaign.purchase_rate,
+ utm_campaign,
+ utm_source,
+ session_id=session_id,
+ )
+
+ def _generate_free_channel_day(self, channel: DemoFreeChannel, day: dt.datetime) -> None:
+ for _ in range(self._daily_volume(channel.daily_sessions, day)):
+ distinct_id, person_uuid = self._new_person()
+ ts = self._time_in_day(day)
+ properties: dict = {"$referring_domain": channel.referring_domain}
+ utm_source = self._pick_variant(channel.utm_source, channel.utm_source_variants)
+ if utm_source:
+ properties["utm_source"] = utm_source
+ if channel.utm_medium:
+ properties["utm_medium"] = channel.utm_medium
+ if channel.utm_campaign:
+ properties["utm_campaign"] = channel.utm_campaign
+ session_id = self._pageview(distinct_id, person_uuid, ts, properties)
+ self._maybe_convert(
+ distinct_id,
+ person_uuid,
+ ts,
+ channel.signup_rate,
+ channel.purchase_rate,
+ channel.utm_campaign or "",
+ utm_source or "",
+ session_id=session_id,
+ )
+
+ def _generate_edge_cases(self, day: dt.datetime) -> None:
+ # Purchases whose utm_source matches no integration: feeds the
+ # "Non-integrated conversions" table and the unmatched goal split.
+ if day.weekday() in (1, 4):
+ distinct_id, person_uuid = self._new_person()
+ ts = self._time_in_day(day)
+ self._purchase(
+ distinct_id,
+ person_uuid,
+ ts,
+ amount=round(self.rng.uniform(40, 120), 2),
+ utm_campaign="mystery_blast",
+ utm_source="some_unknown_source",
+ )
+ # Purchases with no UTMs and no prior pageview: organic fallback + "without UTM" split.
+ if day.weekday() == 2:
+ distinct_id, person_uuid = self._new_person()
+ ts = self._time_in_day(day)
+ self._purchase(distinct_id, person_uuid, ts, amount=round(self.rng.uniform(30, 90), 2))
+
+ # --- multi-touch journeys ---
+
+ def _generate_journeys(self) -> None:
+ week_starts = [self.now - dt.timedelta(days=offset) for offset in range(self.days_past, 6, -7)]
+ for week_start in week_starts:
+ self._journey_paid_social_to_search(week_start)
+ self._journey_organic_email_search(week_start)
+ self._journey_ai_to_direct(week_start)
+ self._journey_same_timestamp_touches(week_start)
+ self._journey_out_of_window()
+
+ def _journey_paid_social_to_search(self, start: dt.datetime) -> None:
+ distinct_id, person_uuid = self._new_person()
+ t0 = self._time_in_day(start)
+ self._pageview(
+ distinct_id,
+ person_uuid,
+ t0,
+ {
+ "utm_source": "facebook",
+ "utm_medium": "paid-social",
+ "utm_campaign": "prospecting_feed",
+ "$referring_domain": "facebook.com",
+ },
+ )
+ t1 = self._time_in_day(start + dt.timedelta(days=2))
+ self._pageview(
+ distinct_id,
+ person_uuid,
+ t1,
+ {
+ "utm_source": "google",
+ "utm_medium": "cpc",
+ "utm_campaign": "brand_search",
+ "$referring_domain": "google.com",
+ },
+ )
+ self._signup(distinct_id, person_uuid, t1 + dt.timedelta(minutes=9))
+ self._purchase(
+ distinct_id,
+ person_uuid,
+ self._time_in_day(start + dt.timedelta(days=3)),
+ amount=round(self.rng.uniform(180, 320), 2),
+ utm_campaign="",
+ utm_source="",
+ )
+
+ def _journey_organic_email_search(self, start: dt.datetime) -> None:
+ distinct_id, person_uuid = self._new_person()
+ self._pageview(distinct_id, person_uuid, self._time_in_day(start), {"$referring_domain": "google.com"})
+ self._pageview(
+ distinct_id,
+ person_uuid,
+ self._time_in_day(start + dt.timedelta(days=3)),
+ {
+ "utm_source": "newsletter",
+ "utm_medium": "email",
+ "utm_campaign": "weekly_digest",
+ "$referring_domain": "$direct",
+ },
+ )
+ t2 = self._time_in_day(start + dt.timedelta(days=5))
+ self._pageview(
+ distinct_id,
+ person_uuid,
+ t2,
+ {
+ "utm_source": "google",
+ "utm_medium": "cpc",
+ "utm_campaign": "spring_sale_2026",
+ "$referring_domain": "google.com",
+ },
+ )
+ self._signup(distinct_id, person_uuid, t2 + dt.timedelta(minutes=4))
+ self._purchase(
+ distinct_id,
+ person_uuid,
+ self._time_in_day(start + dt.timedelta(days=6)),
+ amount=round(self.rng.uniform(90, 210), 2),
+ )
+
+ def _journey_ai_to_direct(self, start: dt.datetime) -> None:
+ distinct_id, person_uuid = self._new_person()
+ self._pageview(distinct_id, person_uuid, self._time_in_day(start), {"$referring_domain": "chatgpt.com"})
+ t1 = self._time_in_day(start + dt.timedelta(days=2))
+ self._pageview(distinct_id, person_uuid, t1, {"$referring_domain": "$direct"})
+ self._signup(distinct_id, person_uuid, t1 + dt.timedelta(minutes=6))
+
+ def _journey_same_timestamp_touches(self, start: dt.datetime) -> None:
+ # Two touchpoints sharing an exact timestamp: exercises tie-breaking in
+ # last-touch and weight normalization in multi-touch modes.
+ distinct_id, person_uuid = self._new_person()
+ ts = self._time_in_day(start + dt.timedelta(days=1))
+ for campaign, source in (("brand_search", "google"), ("prospecting_feed", "facebook")):
+ self._pageview(
+ distinct_id,
+ person_uuid,
+ ts,
+ {"utm_source": source, "utm_medium": "cpc", "utm_campaign": campaign, "$referring_domain": "$direct"},
+ )
+ self._signup(distinct_id, person_uuid, ts + dt.timedelta(hours=1))
+
+ def _journey_out_of_window(self) -> None:
+ # Touchpoint > attribution window (30d) before the conversion: the
+ # conversion must fall back to organic/organic.
+ if self.days_past < 40:
+ return
+ distinct_id, person_uuid = self._new_person()
+ touch_ts = self.now - dt.timedelta(days=self.days_past - 1)
+ self._pageview(
+ distinct_id,
+ person_uuid,
+ touch_ts,
+ {
+ "utm_source": "google",
+ "utm_medium": "cpc",
+ "utm_campaign": "brand_search",
+ "$referring_domain": "google.com",
+ },
+ )
+ self._purchase(
+ distinct_id,
+ person_uuid,
+ touch_ts + dt.timedelta(days=38),
+ amount=150.0,
+ )
+
+ # --- primitives ---
+
+ def _daily_volume(self, base: int, day: dt.datetime) -> int:
+ if base <= 0:
+ return 0
+ weekday_factor = 0.7 if day.weekday() >= 5 else 1.0
+ jitter = self.rng.uniform(0.8, 1.2)
+ return max(1, round(base * self.scale * weekday_factor * jitter))
+
+ def _time_in_day(self, day: dt.datetime) -> dt.datetime:
+ return day.replace(hour=0, minute=0, second=0, microsecond=0) + dt.timedelta(
+ seconds=self.rng.randint(6 * 3600, 22 * 3600)
+ )
+
+ def _new_person(self) -> tuple[str, uuid.UUID]:
+ self._person_counter += 1
+ distinct_id = f"mkt-demo-{self._person_counter}"
+ return distinct_id, uuid.uuid5(PERSON_NAMESPACE, distinct_id)
+
+ def _pick_variant(self, base: str | None, variants: dict[str, float]) -> str | None:
+ if base is None:
+ return None
+ roll = self.rng.random()
+ cumulative = 0.0
+ for variant, share in variants.items():
+ cumulative += share
+ if roll < cumulative:
+ return variant
+ return base
+
+ def _maybe_convert(
+ self,
+ distinct_id: str,
+ person_uuid: uuid.UUID,
+ ts: dt.datetime,
+ signup_rate: float,
+ purchase_rate: float,
+ utm_campaign: str | None,
+ utm_source: str | None,
+ session_id: str | None = None,
+ ) -> None:
+ if self.rng.random() < signup_rate:
+ self._signup(
+ distinct_id, person_uuid, ts + dt.timedelta(minutes=self.rng.randint(2, 25)), session_id=session_id
+ )
+ if self.rng.random() < 0.04:
+ self._emit(
+ distinct_id,
+ person_uuid,
+ EVENT_DEMO_BOOKED,
+ ts + dt.timedelta(hours=self.rng.randint(1, 8)),
+ {"plan": self.rng.choice(["scale", "enterprise"])},
+ )
+ if self.rng.random() < purchase_rate:
+ self._purchase(
+ distinct_id,
+ person_uuid,
+ ts + dt.timedelta(hours=self.rng.randint(1, 20)),
+ amount=round(self.rng.uniform(50, 400), 2),
+ utm_campaign=utm_campaign,
+ utm_source=utm_source,
+ )
+
+ def _pageview(self, distinct_id: str, person_uuid: uuid.UUID, ts: dt.datetime, properties: dict) -> str:
+ utm_params = {k: v for k, v in properties.items() if k.startswith("utm_") and v}
+ url = SITE_URL + ("/?" + urlencode(utm_params) if utm_params else "/")
+ session_id = self._new_session_id(ts)
+ self._emit(
+ distinct_id, person_uuid, EVENT_PAGEVIEW, ts, {**properties, "$current_url": url}, session_id=session_id
+ )
+ return session_id
+
+ def _signup(self, distinct_id: str, person_uuid: uuid.UUID, ts: dt.datetime, session_id: str | None = None) -> None:
+ self._emit(distinct_id, person_uuid, EVENT_SIGNUP, ts, {}, session_id=session_id)
+
+ def _purchase(
+ self,
+ distinct_id: str,
+ person_uuid: uuid.UUID,
+ ts: dt.datetime,
+ *,
+ amount: float,
+ utm_campaign: str | None = None,
+ utm_source: str | None = None,
+ ) -> None:
+ properties: dict = {"revenue": amount, "currency": "USD"}
+ if utm_campaign:
+ properties["utm_campaign"] = utm_campaign
+ if utm_source:
+ properties["utm_source"] = utm_source
+ self._emit(distinct_id, person_uuid, EVENT_PURCHASE, ts, properties)
+ # A slice of purchases also lands in the fake Stripe invoices warehouse
+ # table, backing the DataWarehouseNode conversion goal.
+ if self.rng.random() < 0.6:
+ self.result.invoices.append(
+ InvoiceRow(
+ invoice_id=f"in_{uuid.uuid5(PERSON_NAMESPACE, f'{distinct_id}-{ts.isoformat()}').hex[:16]}",
+ distinct_id=distinct_id,
+ created_at=ts,
+ amount=amount,
+ utm_campaign=utm_campaign or "",
+ utm_source=utm_source or "",
+ )
+ )
+
+ def _new_session_id(self, ts: dt.datetime) -> str:
+ return str(uuid7(unix_ms_time=int(ts.timestamp() * 1000), random=self.rng))
+
+ def _emit(
+ self,
+ distinct_id: str,
+ person_uuid: uuid.UUID,
+ event: str,
+ ts: dt.datetime,
+ properties: dict,
+ session_id: str | None = None,
+ ) -> None:
+ create_event(
+ event_uuid=uuid7(unix_ms_time=int(ts.timestamp() * 1000), random=self.rng),
+ event=event,
+ team=self.team,
+ distinct_id=distinct_id,
+ timestamp=ts,
+ properties={"$session_id": session_id or self._new_session_id(ts), **properties},
+ person_id=person_uuid,
+ person_properties={"email": f"{distinct_id}@example.com"},
+ person_created_at=ts,
+ )
+ self.result.events_written += 1
diff --git a/products/marketing_analytics/backend/demo/health.py b/products/marketing_analytics/backend/demo/health.py
new file mode 100644
index 000000000000..838efcc78c88
--- /dev/null
+++ b/products/marketing_analytics/backend/demo/health.py
@@ -0,0 +1,116 @@
+"""Postgres fixtures that stage every Integration health / diagnose state.
+
+Source health is computed purely from ExternalDataSource / ExternalDataSchema /
+ExternalDataJob rows, so each platform below is staged into a different
+`last_sync_status`. TikTok is deliberately not created: its traffic makes the
+diagnose service report `events_only`.
+"""
+
+import datetime as dt
+
+from django.utils import timezone
+
+from posthog.models import Team
+
+from products.warehouse_sources.backend.facade.models import (
+ DataWarehouseTable,
+ ExternalDataJob,
+ ExternalDataSchema,
+ ExternalDataSource,
+)
+
+# platform -> (schema names, staged state). Only data-preserving states are used
+# (ok / stale / error / tables_disabled) so every platform still shows cost data
+# in the dashboard while the health surfaces stay non-trivial.
+PLATFORM_STATES: dict[str, tuple[tuple[str, ...], str]] = {
+ "GoogleAds": (("campaign", "campaign_overview_stats", "ad_group", "ad_group_stats", "ad", "ad_stats"), "ok"),
+ "MetaAds": (("campaigns", "campaign_stats"), "ok"),
+ "LinkedinAds": (("campaign_groups", "campaign_group_stats"), "ok"),
+ "RedditAds": (("campaigns", "campaign_report"), "ok"),
+ "PinterestAds": (("campaigns", "campaign_analytics"), "ok"),
+ "BingAds": (("campaigns", "campaign_performance_report"), "stale"),
+ "SnapchatAds": (("campaigns", "campaign_stats_daily"), "error"),
+ "TikTokAds": (("campaigns", "campaign_report"), "tables_disabled"),
+}
+
+
+def _create_job(
+ source: ExternalDataSource,
+ *,
+ status: str,
+ age: dt.timedelta,
+ rows_synced: int | None = None,
+ latest_error: str | None = None,
+) -> None:
+ now = timezone.now()
+ job = ExternalDataJob.objects.create(
+ team=source.team,
+ pipeline=source,
+ status=status,
+ rows_synced=rows_synced,
+ latest_error=latest_error,
+ finished_at=now - age,
+ )
+ ExternalDataJob.objects.filter(id=job.id).update(created_at=now - age)
+
+
+def create_sources(team: Team) -> dict[str, ExternalDataSource]:
+ """Create one ExternalDataSource per staged platform (replacing previous demo runs)."""
+ sources: dict[str, ExternalDataSource] = {}
+ for platform in PLATFORM_STATES:
+ # Only retire previous demo fixtures - never a real integration the team may have.
+ ExternalDataSource.objects.filter(
+ team=team, source_type=platform, deleted=False, source_id__startswith="marketing-demo-"
+ ).update(deleted=True)
+ sources[platform] = ExternalDataSource.objects.create(
+ team=team,
+ source_id=f"marketing-demo-{platform.lower()}",
+ connection_id=f"marketing-demo-{platform.lower()}",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=platform,
+ prefix="",
+ )
+ return sources
+
+
+def stage_schemas_and_jobs(
+ team: Team,
+ sources: dict[str, ExternalDataSource],
+ table_by_platform_schema: dict[tuple[str, str], DataWarehouseTable | None],
+) -> None:
+ now = timezone.now()
+ for platform, (schema_names, state) in PLATFORM_STATES.items():
+ source = sources[platform]
+ for schema_name in schema_names:
+ schema_status: str | None = ExternalDataSchema.Status.COMPLETED
+ should_sync = True
+ if state == "tables_failed" and schema_name == schema_names[-1]:
+ schema_status = ExternalDataSchema.Status.FAILED
+ if state == "tables_disabled" and schema_name == schema_names[-1]:
+ should_sync = False
+ if state == "never":
+ schema_status = None
+ ExternalDataSchema.objects.create(
+ team=team,
+ source=source,
+ name=schema_name,
+ table=table_by_platform_schema.get((platform, schema_name)),
+ should_sync=should_sync,
+ status=schema_status,
+ last_synced_at=None if state == "never" else now - dt.timedelta(hours=1),
+ )
+ if state == "ok":
+ _create_job(source, status=ExternalDataJob.Status.COMPLETED, age=dt.timedelta(hours=1), rows_synced=5000)
+ elif state == "stale":
+ _create_job(source, status=ExternalDataJob.Status.COMPLETED, age=dt.timedelta(hours=30), rows_synced=4200)
+ elif state == "error":
+ _create_job(source, status=ExternalDataJob.Status.COMPLETED, age=dt.timedelta(days=3), rows_synced=3100)
+ _create_job(
+ source,
+ status=ExternalDataJob.Status.FAILED,
+ age=dt.timedelta(hours=1),
+ latest_error="Authentication failed: refresh token expired",
+ )
+ elif state in ("tables_missing", "tables_failed", "tables_disabled"):
+ _create_job(source, status=ExternalDataJob.Status.COMPLETED, age=dt.timedelta(hours=2), rows_synced=900)
+ # "never": no jobs at all
diff --git a/products/marketing_analytics/backend/demo/warehouse.py b/products/marketing_analytics/backend/demo/warehouse.py
new file mode 100644
index 000000000000..cd6eee2c27d4
--- /dev/null
+++ b/products/marketing_analytics/backend/demo/warehouse.py
@@ -0,0 +1,609 @@
+"""Cost tables for the demo world: CSV generation + warehouse registration.
+
+Native tables use each platform's real column names (micros for Google, JSON
+action arrays for Meta, unified entity+stats report for Bing) so the production
+adapters read them unmodified. Table names follow the `{sourcetype}_{schema}`
+convention the adapter factory autodetects.
+"""
+
+import csv
+import json
+import datetime as dt
+from dataclasses import dataclass
+from pathlib import Path
+from random import Random
+
+from posthog.models import Team
+
+from products.marketing_analytics.backend.demo.events import InvoiceRow
+from products.marketing_analytics.backend.demo.world import CAMPAIGNS, DemoCampaign
+from products.warehouse_sources.backend.facade.models import (
+ DataWarehouseCredential,
+ DataWarehouseTable,
+ ExternalDataSource,
+)
+from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
+
+DEMO_BUCKET = "marketing_demo"
+
+CLP_PER_USD = 950
+
+BIGQUERY_ADS_TABLE = "demo_partner_ads"
+STRIPE_INVOICES_TABLE = "demo_stripe_invoices"
+
+
+@dataclass
+class RegisteredTable:
+ name: str
+ table: DataWarehouseTable
+
+
+def _daily_stats(campaign: DemoCampaign, day: dt.date, rng: Random) -> tuple[float, int, int, int, float]:
+ jitter = rng.uniform(0.75, 1.25)
+ cost = round(campaign.daily_cost * jitter, 2)
+ impressions = max(1, round(campaign.daily_impressions * jitter))
+ clicks = max(0, round(campaign.daily_clicks * jitter))
+ conversions = round(clicks * campaign.reported_conversion_rate)
+ value = round(conversions * campaign.reported_value_per_conversion * rng.uniform(0.8, 1.2), 2)
+ return cost, impressions, clicks, conversions, value
+
+
+def _write_csv(path: Path, header: list[str], rows: list[list]) -> None:
+ with path.open("w", newline="") as f:
+ writer = csv.writer(f)
+ writer.writerow(header)
+ writer.writerows(rows)
+
+
+class CostTableBuilder:
+ def __init__(self, *, seed: str, days_past: int, now: dt.datetime, out_dir: Path):
+ self.rng = Random(f"{seed}-warehouse")
+ self.days = [(now - dt.timedelta(days=offset)).date() for offset in range(days_past, 0, -1)]
+ self.out_dir = out_dir
+
+ def _campaigns(self, platform: str) -> list[DemoCampaign]:
+ return [c for c in CAMPAIGNS if c.platform == platform and c.daily_cost > 0]
+
+ def build_google(self) -> dict[str, Path]:
+ campaigns = self._campaigns("GoogleAds")
+ entity_rows = [[c.campaign_id, c.name, "ENABLED"] for c in campaigns]
+ stats_rows: list[list] = []
+ ad_group_rows: list[list] = []
+ ad_group_stats_rows: list[list] = []
+ ad_rows: list[list] = []
+ ad_stats_rows: list[list] = []
+ for c in campaigns:
+ for day in self.days:
+ cost, impressions, clicks, conversions, value = _daily_stats(c, day, self.rng)
+ stats_rows.append(
+ [c.campaign_id, str(day), impressions, clicks, round(cost * 1_000_000), conversions, value, "USD"]
+ )
+ if c.ad_groups:
+ share = 1 / len(c.ad_groups)
+ for group in c.ad_groups:
+ ad_group_stats_rows.append(
+ [
+ group.ad_group_id,
+ str(day),
+ round(impressions * share),
+ round(clicks * share),
+ round(cost * share * 1_000_000),
+ round(conversions * share),
+ round(value * share, 2),
+ "USD",
+ ]
+ )
+ ad_share = share / len(group.ads)
+ for ad in group.ads:
+ ad_stats_rows.append(
+ [
+ ad.ad_id,
+ str(day),
+ round(impressions * ad_share),
+ round(clicks * ad_share),
+ round(cost * ad_share * 1_000_000),
+ round(conversions * ad_share),
+ round(value * ad_share, 2),
+ "USD",
+ ]
+ )
+ for group in c.ad_groups:
+ ad_group_rows.append([group.ad_group_id, group.name, c.campaign_id])
+ for ad in group.ads:
+ ad_rows.append([ad.ad_id, ad.name, group.ad_group_id, c.campaign_id])
+
+ stats_header = [
+ "segments_date",
+ "metrics_impressions",
+ "metrics_clicks",
+ "metrics_cost_micros",
+ "metrics_conversions",
+ "metrics_conversions_value",
+ "customer_currency_code",
+ ]
+ paths = {
+ "campaign": self.out_dir / "googleads_campaign.csv",
+ "campaign_overview_stats": self.out_dir / "googleads_campaign_overview_stats.csv",
+ "ad_group": self.out_dir / "googleads_ad_group.csv",
+ "ad_group_stats": self.out_dir / "googleads_ad_group_stats.csv",
+ "ad": self.out_dir / "googleads_ad.csv",
+ "ad_stats": self.out_dir / "googleads_ad_stats.csv",
+ }
+ _write_csv(paths["campaign"], ["campaign_id", "campaign_name", "campaign_status"], entity_rows)
+ _write_csv(paths["campaign_overview_stats"], ["campaign_id", *stats_header], stats_rows)
+ _write_csv(paths["ad_group"], ["ad_group_id", "ad_group_name", "campaign_id"], ad_group_rows)
+ _write_csv(paths["ad_group_stats"], ["ad_group_id", *stats_header], ad_group_stats_rows)
+ _write_csv(paths["ad"], ["ad_group_ad_ad_id", "ad_group_ad_ad_name", "ad_group_id", "campaign_id"], ad_rows)
+ _write_csv(paths["ad_stats"], ["ad_group_ad_ad_id", *stats_header], ad_stats_rows)
+ return paths
+
+ def build_meta(self) -> dict[str, Path]:
+ campaigns = self._campaigns("MetaAds")
+ entity_rows = [[c.campaign_id, c.name, "ACTIVE"] for c in campaigns]
+ stats_rows: list[list] = []
+ for c in campaigns:
+ for day in self.days:
+ cost, impressions, clicks, conversions, value = _daily_stats(c, day, self.rng)
+ actions = json.dumps([{"action_type": "purchase", "value": str(conversions)}])
+ action_values = json.dumps([{"action_type": "purchase", "value": str(value)}])
+ stats_rows.append(
+ [c.campaign_id, str(day), str(day), impressions, clicks, cost, "USD", actions, action_values]
+ )
+ paths = {
+ "campaigns": self.out_dir / "metaads_campaigns.csv",
+ "campaign_stats": self.out_dir / "metaads_campaign_stats.csv",
+ }
+ _write_csv(paths["campaigns"], ["id", "name", "status"], entity_rows)
+ _write_csv(
+ paths["campaign_stats"],
+ [
+ "campaign_id",
+ "date_start",
+ "date_stop",
+ "impressions",
+ "clicks",
+ "spend",
+ "account_currency",
+ "actions",
+ "action_values",
+ ],
+ stats_rows,
+ )
+ return paths
+
+ def build_bing(self) -> dict[str, Path]:
+ campaigns = self._campaigns("BingAds")
+ entity_rows = [[c.campaign_id, c.name, "Active"] for c in campaigns]
+ stats_rows: list[list] = []
+ for c in campaigns:
+ for day in self.days:
+ cost, impressions, clicks, conversions, value = _daily_stats(c, day, self.rng)
+ stats_rows.append(
+ [c.campaign_id, c.name, str(day), impressions, clicks, cost, conversions, value, "USD"]
+ )
+ paths = {
+ "campaigns": self.out_dir / "bingads_campaigns.csv",
+ "campaign_performance_report": self.out_dir / "bingads_campaign_performance_report.csv",
+ }
+ _write_csv(paths["campaigns"], ["id", "name", "status"], entity_rows)
+ _write_csv(
+ paths["campaign_performance_report"],
+ [
+ "campaign_id",
+ "campaign_name",
+ "time_period",
+ "impressions",
+ "clicks",
+ "spend",
+ "conversions",
+ "revenue",
+ "currency_code",
+ ],
+ stats_rows,
+ )
+ return paths
+
+ def build_linkedin(self) -> dict[str, Path]:
+ campaigns = self._campaigns("LinkedinAds")
+ entity_rows = [[c.campaign_id, c.name, "ACTIVE"] for c in campaigns]
+ stats_rows: list[list] = []
+ for c in campaigns:
+ for day in self.days:
+ cost, impressions, clicks, conversions, value = _daily_stats(c, day, self.rng)
+ stats_rows.append([c.campaign_id, str(day), impressions, clicks, cost, conversions, value, "USD"])
+ paths = {
+ "campaign_groups": self.out_dir / "linkedinads_campaign_groups.csv",
+ "campaign_group_stats": self.out_dir / "linkedinads_campaign_group_stats.csv",
+ }
+ _write_csv(paths["campaign_groups"], ["id", "name", "status"], entity_rows)
+ _write_csv(
+ paths["campaign_group_stats"],
+ [
+ "campaign_group_id",
+ "date_start",
+ "impressions",
+ "clicks",
+ "cost_in_usd",
+ "external_website_conversions",
+ "conversion_value_in_local_currency",
+ "currency",
+ ],
+ stats_rows,
+ )
+ return paths
+
+ def build_reddit(self) -> dict[str, Path]:
+ campaigns = self._campaigns("RedditAds")
+ entity_rows = [[c.campaign_id, c.name, "ACTIVE"] for c in campaigns]
+ stats_rows: list[list] = []
+ for c in campaigns:
+ for day in self.days:
+ cost, impressions, clicks, conversions, value = _daily_stats(c, day, self.rng)
+ stats_rows.append(
+ [
+ c.campaign_id,
+ str(day),
+ impressions,
+ clicks,
+ round(cost * 1_000_000), # micros
+ conversions,
+ round(value * 100), # cents
+ 0,
+ "USD",
+ ]
+ )
+ paths = {
+ "campaigns": self.out_dir / "redditads_campaigns.csv",
+ "campaign_report": self.out_dir / "redditads_campaign_report.csv",
+ }
+ _write_csv(paths["campaigns"], ["id", "name", "status"], entity_rows)
+ _write_csv(
+ paths["campaign_report"],
+ [
+ "campaign_id",
+ "date",
+ "impressions",
+ "clicks",
+ "spend",
+ "key_conversion_total_count",
+ "conversion_purchase_total_value",
+ "conversion_signup_total_value",
+ "currency",
+ ],
+ stats_rows,
+ )
+ return paths
+
+ def build_pinterest(self) -> dict[str, Path]:
+ campaigns = self._campaigns("PinterestAds")
+ entity_rows = [[c.campaign_id, c.name, "ACTIVE"] for c in campaigns]
+ stats_rows: list[list] = []
+ for c in campaigns:
+ for day in self.days:
+ cost, impressions, clicks, conversions, value = _daily_stats(c, day, self.rng)
+ stats_rows.append(
+ [
+ c.campaign_id,
+ str(day),
+ impressions,
+ clicks,
+ cost, # spend_in_dollar: plain dollars
+ conversions,
+ round(value * 1_000_000), # micro-dollars
+ "USD",
+ ]
+ )
+ paths = {
+ "campaigns": self.out_dir / "pinterestads_campaigns.csv",
+ "campaign_analytics": self.out_dir / "pinterestads_campaign_analytics.csv",
+ }
+ _write_csv(paths["campaigns"], ["id", "name", "status"], entity_rows)
+ _write_csv(
+ paths["campaign_analytics"],
+ [
+ "campaign_id",
+ "date",
+ "total_impression",
+ "total_clickthrough",
+ "spend_in_dollar",
+ "total_conversions",
+ "total_checkout_value_in_micro_dollar",
+ "currency",
+ ],
+ stats_rows,
+ )
+ return paths
+
+ def build_snapchat(self) -> dict[str, Path]:
+ campaigns = self._campaigns("SnapchatAds")
+ entity_rows = [[c.campaign_id, c.name, "ACTIVE"] for c in campaigns]
+ stats_rows: list[list] = []
+ for c in campaigns:
+ for day in self.days:
+ cost, impressions, clicks, conversions, value = _daily_stats(c, day, self.rng)
+ stats_rows.append(
+ [
+ c.campaign_id,
+ str(day),
+ impressions,
+ clicks, # "swipes" is Snapchat's click metric
+ round(cost * 1_000_000), # micros
+ conversions,
+ value,
+ "USD",
+ ]
+ )
+ paths = {
+ "campaigns": self.out_dir / "snapchatads_campaigns.csv",
+ "campaign_stats_daily": self.out_dir / "snapchatads_campaign_stats_daily.csv",
+ }
+ _write_csv(paths["campaigns"], ["id", "name", "status"], entity_rows)
+ _write_csv(
+ paths["campaign_stats_daily"],
+ [
+ "id",
+ "start_time",
+ "impressions",
+ "swipes",
+ "spend",
+ "conversion_purchases",
+ "conversion_purchases_value",
+ "currency",
+ ],
+ stats_rows,
+ )
+ return paths
+
+ def build_tiktok(self) -> dict[str, Path]:
+ campaigns = self._campaigns("TikTokAds")
+ entity_rows = [[c.campaign_id, c.name, "CAMPAIGN_STATUS_ENABLE"] for c in campaigns]
+ stats_rows: list[list] = []
+ for c in campaigns:
+ for day in self.days:
+ cost, impressions, clicks, conversions, value = _daily_stats(c, day, self.rng)
+ stats_rows.append(
+ [
+ c.campaign_id,
+ f"{day} 00:00:00",
+ impressions,
+ clicks,
+ round(cost * CLP_PER_USD, 2),
+ conversions,
+ round(value * CLP_PER_USD, 2),
+ "CLP",
+ ]
+ )
+ paths = {
+ "campaigns": self.out_dir / "tiktokads_campaigns.csv",
+ "campaign_report": self.out_dir / "tiktokads_campaign_report.csv",
+ }
+ _write_csv(paths["campaigns"], ["campaign_id", "campaign_name", "operation_status"], entity_rows)
+ _write_csv(
+ paths["campaign_report"],
+ [
+ "campaign_id",
+ "stat_time_day",
+ "impressions",
+ "clicks",
+ "spend",
+ "conversion",
+ "total_complete_payment_rate",
+ "currency",
+ ],
+ stats_rows,
+ )
+ return paths
+
+ def build_bigquery_ads(self) -> Path:
+ campaigns = self._campaigns("BigQuery")
+ rows: list[list] = []
+ for c in campaigns:
+ for day in self.days:
+ cost, impressions, clicks, _conversions, _value = _daily_stats(c, day, self.rng)
+ rows.append([c.campaign_id, c.name, str(day), cost, clicks, impressions])
+ path = self.out_dir / f"{BIGQUERY_ADS_TABLE}.csv"
+ _write_csv(path, ["campaign_id", "campaign_name", "date", "cost", "clicks", "impressions"], rows)
+ return path
+
+ def build_stripe_invoices(self, invoices: list[InvoiceRow]) -> Path:
+ rows = [
+ [
+ inv.invoice_id,
+ inv.distinct_id,
+ inv.created_at.strftime("%Y-%m-%d %H:%M:%S"),
+ inv.amount,
+ inv.utm_campaign,
+ inv.utm_source,
+ ]
+ for inv in invoices
+ ]
+ path = self.out_dir / f"{STRIPE_INVOICES_TABLE}.csv"
+ _write_csv(path, ["id", "distinct_id", "created_at", "amount", "utm_campaign", "utm_source"], rows)
+ return path
+
+
+STRING = "String"
+FLOAT = "Float64"
+
+GOOGLE_COLUMNS: dict[str, dict[str, str]] = {
+ "campaign": {"campaign_id": STRING, "campaign_name": STRING, "campaign_status": STRING},
+ "campaign_overview_stats": {
+ "campaign_id": STRING,
+ "segments_date": STRING,
+ "metrics_impressions": FLOAT,
+ "metrics_clicks": FLOAT,
+ "metrics_cost_micros": FLOAT,
+ "metrics_conversions": FLOAT,
+ "metrics_conversions_value": FLOAT,
+ "customer_currency_code": STRING,
+ },
+ "ad_group": {"ad_group_id": STRING, "ad_group_name": STRING, "campaign_id": STRING},
+ "ad": {"ad_group_ad_ad_id": STRING, "ad_group_ad_ad_name": STRING, "ad_group_id": STRING, "campaign_id": STRING},
+}
+GOOGLE_COLUMNS["ad_group_stats"] = {**GOOGLE_COLUMNS["campaign_overview_stats"], "ad_group_id": STRING}
+del GOOGLE_COLUMNS["ad_group_stats"]["campaign_id"]
+GOOGLE_COLUMNS["ad_stats"] = {**GOOGLE_COLUMNS["campaign_overview_stats"], "ad_group_ad_ad_id": STRING}
+del GOOGLE_COLUMNS["ad_stats"]["campaign_id"]
+
+META_COLUMNS: dict[str, dict[str, str]] = {
+ "campaigns": {"id": STRING, "name": STRING, "status": STRING},
+ "campaign_stats": {
+ "campaign_id": STRING,
+ "date_start": STRING,
+ "date_stop": STRING,
+ "impressions": FLOAT,
+ "clicks": FLOAT,
+ "spend": FLOAT,
+ "account_currency": STRING,
+ "actions": STRING,
+ "action_values": STRING,
+ },
+}
+
+BING_COLUMNS: dict[str, dict[str, str]] = {
+ "campaigns": {"id": STRING, "name": STRING, "status": STRING},
+ "campaign_performance_report": {
+ "campaign_id": STRING,
+ "campaign_name": STRING,
+ "time_period": STRING,
+ "impressions": FLOAT,
+ "clicks": FLOAT,
+ "spend": FLOAT,
+ "conversions": FLOAT,
+ "revenue": FLOAT,
+ "currency_code": STRING,
+ },
+}
+
+LINKEDIN_COLUMNS: dict[str, dict[str, str]] = {
+ "campaign_groups": {"id": STRING, "name": STRING, "status": STRING},
+ "campaign_group_stats": {
+ "campaign_group_id": STRING,
+ "date_start": STRING,
+ "impressions": FLOAT,
+ "clicks": FLOAT,
+ "cost_in_usd": FLOAT,
+ "external_website_conversions": FLOAT,
+ "conversion_value_in_local_currency": FLOAT,
+ "currency": STRING,
+ },
+}
+
+REDDIT_COLUMNS: dict[str, dict[str, str]] = {
+ "campaigns": {"id": STRING, "name": STRING, "status": STRING},
+ "campaign_report": {
+ "campaign_id": STRING,
+ "date": STRING,
+ "impressions": FLOAT,
+ "clicks": FLOAT,
+ "spend": FLOAT,
+ "key_conversion_total_count": FLOAT,
+ "conversion_purchase_total_value": FLOAT,
+ "conversion_signup_total_value": FLOAT,
+ "currency": STRING,
+ },
+}
+
+PINTEREST_COLUMNS: dict[str, dict[str, str]] = {
+ "campaigns": {"id": STRING, "name": STRING, "status": STRING},
+ "campaign_analytics": {
+ "campaign_id": STRING,
+ "date": STRING,
+ "total_impression": FLOAT,
+ "total_clickthrough": FLOAT,
+ "spend_in_dollar": FLOAT,
+ "total_conversions": FLOAT,
+ "total_checkout_value_in_micro_dollar": FLOAT,
+ "currency": STRING,
+ },
+}
+
+SNAPCHAT_COLUMNS: dict[str, dict[str, str]] = {
+ "campaigns": {"id": STRING, "name": STRING, "status": STRING},
+ "campaign_stats_daily": {
+ "id": STRING,
+ "start_time": STRING,
+ "impressions": FLOAT,
+ "swipes": FLOAT,
+ "spend": FLOAT,
+ "conversion_purchases": FLOAT,
+ "conversion_purchases_value": FLOAT,
+ "currency": STRING,
+ },
+}
+
+TIKTOK_COLUMNS: dict[str, dict[str, str]] = {
+ "campaigns": {"campaign_id": STRING, "campaign_name": STRING, "operation_status": STRING},
+ "campaign_report": {
+ "campaign_id": STRING,
+ "stat_time_day": STRING,
+ "impressions": FLOAT,
+ "clicks": FLOAT,
+ "spend": FLOAT,
+ "conversion": FLOAT,
+ "total_complete_payment_rate": FLOAT,
+ "currency": STRING,
+ },
+}
+
+# platform -> (builder method name, table name prefix, columns per schema)
+NATIVE_SPECS: dict[str, tuple[str, str, dict[str, dict[str, str]]]] = {
+ "GoogleAds": ("build_google", "googleads", GOOGLE_COLUMNS),
+ "MetaAds": ("build_meta", "metaads", META_COLUMNS),
+ "BingAds": ("build_bing", "bingads", BING_COLUMNS),
+ "LinkedinAds": ("build_linkedin", "linkedinads", LINKEDIN_COLUMNS),
+ "RedditAds": ("build_reddit", "redditads", REDDIT_COLUMNS),
+ "PinterestAds": ("build_pinterest", "pinterestads", PINTEREST_COLUMNS),
+ "SnapchatAds": ("build_snapchat", "snapchatads", SNAPCHAT_COLUMNS),
+ "TikTokAds": ("build_tiktok", "tiktokads", TIKTOK_COLUMNS),
+}
+
+BIGQUERY_ADS_COLUMNS = {
+ "campaign_id": STRING,
+ "campaign_name": STRING,
+ "date": STRING,
+ "cost": FLOAT,
+ "clicks": FLOAT,
+ "impressions": FLOAT,
+}
+
+STRIPE_INVOICES_COLUMNS = {
+ "id": STRING,
+ "distinct_id": STRING,
+ "created_at": STRING,
+ "amount": FLOAT,
+ "utm_campaign": STRING,
+ "utm_source": STRING,
+}
+
+
+def register_table(
+ team: Team,
+ *,
+ csv_path: Path,
+ table_name: str,
+ columns: dict[str, str],
+ source: ExternalDataSource | None,
+ credential: DataWarehouseCredential | None,
+) -> RegisteredTable:
+ existing = DataWarehouseTable.objects.filter(team=team, name=table_name, deleted=False).first()
+ if existing:
+ existing_source = existing.external_data_source
+ if existing_source is not None and not (existing_source.source_id or "").startswith("marketing-demo"):
+ raise ValueError(
+ f"Table '{table_name}' belongs to a real integration on this team - "
+ "run the demo seeder against a dedicated project instead"
+ )
+ existing.deleted = True
+ existing.save()
+ table, _source, _credential, _df, _cleanup = create_data_warehouse_table_from_csv(
+ csv_path,
+ table_name,
+ columns,
+ DEMO_BUCKET,
+ team,
+ source=source,
+ credential=credential,
+ source_prefix="",
+ )
+ return RegisteredTable(name=table_name, table=table)
diff --git a/products/marketing_analytics/backend/demo/world.py b/products/marketing_analytics/backend/demo/world.py
new file mode 100644
index 000000000000..76bfdd0aad7e
--- /dev/null
+++ b/products/marketing_analytics/backend/demo/world.py
@@ -0,0 +1,579 @@
+"""Static catalog of the demo marketing world.
+
+Every campaign and channel here exists to exercise a specific dashboard or
+Integration health state; the `scenario` field documents which one.
+"""
+
+from dataclasses import dataclass, field
+
+
+@dataclass(frozen=True)
+class DemoAd:
+ ad_id: str
+ name: str
+
+
+@dataclass(frozen=True)
+class DemoAdGroup:
+ ad_group_id: str
+ name: str
+ ads: tuple[DemoAd, ...]
+
+
+@dataclass(frozen=True)
+class DemoCampaign:
+ platform: str # ExternalDataSource.source_type, e.g. "GoogleAds"
+ campaign_id: str
+ name: str
+ daily_cost: float
+ daily_impressions: int
+ daily_clicks: int
+ daily_sessions: int # $pageviews generated per day; 0 => no traffic (not_linked)
+ utm_source: str | None
+ utm_campaign: str | None # value events carry; None => use name.lower()
+ utm_medium: str = "cpc"
+ referring_domain: str = ""
+ click_id_property: str | None = None # $gclid / $fbclid
+ signup_rate: float = 0.0
+ purchase_rate: float = 0.0
+ reported_conversion_rate: float = 0.02 # of clicks
+ reported_value_per_conversion: float = 90.0
+ utm_source_variants: dict[str, float] = field(default_factory=dict) # variant -> share
+ utm_campaign_variants: dict[str, float] = field(default_factory=dict)
+ ad_groups: tuple[DemoAdGroup, ...] = ()
+ scenario: str = ""
+
+
+@dataclass(frozen=True)
+class DemoFreeChannel:
+ key: str
+ daily_sessions: int
+ referring_domain: str
+ utm_source: str | None = None
+ utm_medium: str | None = None
+ utm_campaign: str | None = None
+ signup_rate: float = 0.03
+ purchase_rate: float = 0.008
+ utm_source_variants: dict[str, float] = field(default_factory=dict)
+ scenario: str = ""
+
+
+def _google_hierarchy() -> tuple[DemoAdGroup, ...]:
+ return (
+ DemoAdGroup(
+ "20001",
+ "brand-exact",
+ (DemoAd("30001", "hero_v1"), DemoAd("30002", "hero_v2")),
+ ),
+ DemoAdGroup(
+ "20002",
+ "brand-broad",
+ (DemoAd("30003", "lifestyle"), DemoAd("30004", "testimonial")),
+ ),
+ )
+
+
+CAMPAIGNS: tuple[DemoCampaign, ...] = (
+ # --- Google Ads (source healthy, full campaign > ad group > ad hierarchy) ---
+ DemoCampaign(
+ platform="GoogleAds",
+ campaign_id="10001",
+ name="brand_search",
+ daily_cost=120.0,
+ daily_impressions=2600,
+ daily_clicks=140,
+ daily_sessions=60,
+ utm_source="google",
+ utm_campaign="brand_search",
+ referring_domain="google.com",
+ click_id_property="$gclid",
+ signup_rate=0.12,
+ purchase_rate=0.035,
+ reported_conversion_rate=0.05,
+ reported_value_per_conversion=140.0,
+ # ~10% of clicks arrive with a capitalized source: demonstrates the
+ # case-sensitive source split on the conversions side.
+ utm_source_variants={"Google": 0.1},
+ ad_groups=_google_hierarchy(),
+ scenario="healthy hero campaign, good ROAS, drill-down to ad level",
+ ),
+ DemoCampaign(
+ platform="GoogleAds",
+ campaign_id="10002",
+ name="generic_search",
+ daily_cost=260.0,
+ daily_impressions=6100,
+ daily_clicks=210,
+ daily_sessions=45,
+ utm_source="google",
+ utm_campaign="generic_search",
+ referring_domain="google.com",
+ click_id_property="$gclid",
+ signup_rate=0.015,
+ purchase_rate=0.002,
+ reported_conversion_rate=0.01,
+ reported_value_per_conversion=45.0,
+ ad_groups=(
+ DemoAdGroup("20003", "generic-broad", (DemoAd("30005", "explainer_30s"), DemoAd("30006", "pricing_card"))),
+ ),
+ scenario="high spend, ROAS < 1 (wasted-spend story)",
+ ),
+ DemoCampaign(
+ platform="GoogleAds",
+ campaign_id="10003",
+ name="summer_promo_2026",
+ daily_cost=45.0,
+ daily_impressions=1900,
+ daily_clicks=70,
+ daily_sessions=0,
+ utm_source=None,
+ utm_campaign=None,
+ scenario="spend but zero tagged pageviews -> UTM audit NOT_LINKED",
+ ),
+ DemoCampaign(
+ platform="GoogleAds",
+ campaign_id="10004",
+ name="Spring Sale 2026",
+ daily_cost=85.0,
+ daily_impressions=2100,
+ daily_clicks=95,
+ daily_sessions=35,
+ utm_source="google",
+ utm_campaign="spring_sale_2026",
+ referring_domain="google.com",
+ click_id_property="$gclid",
+ signup_rate=0.08,
+ purchase_rate=0.02,
+ utm_campaign_variants={"spring-sale-2026": 0.4},
+ scenario="dirty utm_campaign variants resolved via campaign_name_mappings",
+ ),
+ DemoCampaign(
+ platform="GoogleAds",
+ campaign_id="10005",
+ name="mixed_promo",
+ daily_cost=55.0,
+ daily_impressions=1500,
+ daily_clicks=60,
+ daily_sessions=25,
+ utm_source="google",
+ utm_campaign="mixed_promo",
+ referring_domain="google.com",
+ signup_rate=0.06,
+ purchase_rate=0.015,
+ scenario="same campaign name as a Meta campaign; only google-tagged events",
+ ),
+ # --- Meta Ads (source stale: last sync > 24h ago) ---
+ DemoCampaign(
+ platform="MetaAds",
+ campaign_id="120330000000000001",
+ name="prospecting_feed",
+ daily_cost=90.0,
+ daily_impressions=11000,
+ daily_clicks=180,
+ daily_sessions=55,
+ utm_source="meta",
+ utm_campaign="prospecting_feed",
+ utm_medium="paid-social",
+ referring_domain="facebook.com",
+ click_id_property="$fbclid",
+ signup_rate=0.05,
+ purchase_rate=0.012,
+ # The UTM audit only exact-matches the primary source (default aliases
+ # are not applied there), so the base stays "meta"; the variants still
+ # exercise facebook/fb -> meta normalization on the conversions side.
+ utm_source_variants={"facebook": 0.25, "fb": 0.15},
+ scenario="alias sources (meta/facebook/fb) all resolve to meta",
+ ),
+ DemoCampaign(
+ platform="MetaAds",
+ campaign_id="120330000000000002",
+ name="stories_reels",
+ daily_cost=70.0,
+ daily_impressions=9000,
+ daily_clicks=150,
+ daily_sessions=40,
+ utm_source="ig",
+ utm_campaign="stories_reels",
+ utm_medium="paid-social",
+ referring_domain="instagram.com",
+ signup_rate=0.04,
+ purchase_rate=0.008,
+ scenario="'ig' is not a Meta alias -> UTM audit UNKNOWN_SOURCE + mapping suggestion flow",
+ ),
+ DemoCampaign(
+ platform="MetaAds",
+ campaign_id="120330000000000003",
+ name="mixed_promo",
+ daily_cost=40.0,
+ daily_impressions=5200,
+ daily_clicks=80,
+ daily_sessions=0,
+ utm_source=None,
+ utm_campaign=None,
+ utm_medium="paid-social",
+ scenario="same name as the Google campaign that owns the events -> NAME_COLLISION",
+ ),
+ # --- Bing Ads (source in error state; matched by campaign_id via field preferences) ---
+ DemoCampaign(
+ platform="BingAds",
+ campaign_id="90001",
+ name="bing_brand",
+ daily_cost=35.0,
+ daily_impressions=900,
+ daily_clicks=45,
+ daily_sessions=18,
+ utm_source="bing",
+ utm_campaign="90001",
+ referring_domain="bing.com",
+ signup_rate=0.09,
+ purchase_rate=0.02,
+ scenario="matches by campaign_id (campaign_field_preferences)",
+ ),
+ DemoCampaign(
+ platform="BingAds",
+ campaign_id="90002",
+ name="shared_campaign",
+ daily_cost=25.0,
+ daily_impressions=700,
+ daily_clicks=30,
+ daily_sessions=12,
+ utm_source="google",
+ utm_campaign="90002",
+ referring_domain="google.com",
+ signup_rate=0.03,
+ purchase_rate=0.005,
+ scenario="events tagged with a source claimed by Google -> NO_TAGGED_EVENTS",
+ ),
+ # --- LinkedIn Ads (campaign_groups hierarchy naming, cost_in_usd column) ---
+ DemoCampaign(
+ platform="LinkedinAds",
+ campaign_id="501",
+ name="li_abm_exec",
+ daily_cost=110.0,
+ daily_impressions=1400,
+ daily_clicks=40,
+ daily_sessions=16,
+ utm_source="linkedin",
+ utm_campaign="li_abm_exec",
+ utm_medium="paid-social",
+ referring_domain="linkedin.com",
+ signup_rate=0.1,
+ purchase_rate=0.03,
+ reported_value_per_conversion=350.0,
+ utm_source_variants={"li": 0.2},
+ scenario="high-value B2B campaign; 'li' alias variant",
+ ),
+ DemoCampaign(
+ platform="LinkedinAds",
+ campaign_id="502",
+ name="li_retargeting",
+ daily_cost=45.0,
+ daily_impressions=800,
+ daily_clicks=18,
+ daily_sessions=8,
+ utm_source="linkedin",
+ utm_campaign="li_retargeting",
+ utm_medium="paid-social",
+ referring_domain="linkedin.com",
+ signup_rate=0.12,
+ purchase_rate=0.04,
+ scenario="LinkedIn retargeting",
+ ),
+ # --- Reddit Ads (spend in micros, conversion values in cents) ---
+ DemoCampaign(
+ platform="RedditAds",
+ campaign_id="60001",
+ name="reddit_devs",
+ daily_cost=28.0,
+ daily_impressions=5200,
+ daily_clicks=120,
+ daily_sessions=20,
+ utm_source="reddit",
+ utm_campaign="reddit_devs",
+ utm_medium="paid-social",
+ referring_domain="reddit.com",
+ signup_rate=0.06,
+ purchase_rate=0.01,
+ scenario="Reddit: micros + cents formats",
+ ),
+ # --- Pinterest Ads (total_impression / spend_in_dollar columns) ---
+ DemoCampaign(
+ platform="PinterestAds",
+ campaign_id="2001",
+ name="pin_inspiration",
+ daily_cost=22.0,
+ daily_impressions=8800,
+ daily_clicks=95,
+ daily_sessions=14,
+ utm_source="pinterest",
+ utm_campaign="pin_inspiration",
+ utm_medium="paid-social",
+ referring_domain="pinterest.com",
+ signup_rate=0.04,
+ purchase_rate=0.012,
+ scenario="Pinterest: dollar spend + micro-dollar checkout value",
+ ),
+ # --- Snapchat Ads (swipes as clicks, spend in micros; source in error state) ---
+ DemoCampaign(
+ platform="SnapchatAds",
+ campaign_id="80001",
+ name="snap_gen_z",
+ daily_cost=38.0,
+ daily_impressions=15500,
+ daily_clicks=210,
+ daily_sessions=17,
+ utm_source="snapchat",
+ utm_campaign="snap_gen_z",
+ utm_medium="paid-social",
+ referring_domain="snapchat.com",
+ signup_rate=0.03,
+ purchase_rate=0.006,
+ scenario="Snapchat: swipes column + micros",
+ ),
+ # --- TikTok Ads (report in CLP: exercises currency conversion; stats schema disabled) ---
+ DemoCampaign(
+ platform="TikTokAds",
+ campaign_id="70001",
+ name="tt_launch",
+ daily_cost=42.0, # USD equivalent; written to the report in CLP
+ daily_impressions=12800,
+ daily_clicks=260,
+ daily_sessions=30,
+ utm_source="tiktok",
+ utm_campaign="tt_launch",
+ utm_medium="paid-social",
+ referring_domain="tiktok.com",
+ signup_rate=0.03,
+ purchase_rate=0.006,
+ # 'tik-tok' normalizes to the tiktok alias in attribution health, but not
+ # in the UTM audit (different normalization rules) - both on purpose.
+ utm_source_variants={"tik-tok": 0.3},
+ scenario="TikTok: CLP currency conversion + near-miss 'tik-tok' variant",
+ ),
+ # --- External BigQuery cost table (sources_map + const: source + EUR currency) ---
+ DemoCampaign(
+ platform="BigQuery",
+ campaign_id="partner-1",
+ name="partner_newsletter_boost",
+ daily_cost=30.0, # EUR: exercises convertCurrency against team base currency
+ daily_impressions=2500,
+ daily_clicks=65,
+ daily_sessions=22,
+ utm_source="demo_partner",
+ utm_campaign="partner_newsletter_boost",
+ utm_medium="paid",
+ referring_domain="partner.example.com",
+ signup_rate=0.07,
+ purchase_rate=0.018,
+ scenario="self-managed style table via sources_map, const: source, EUR costs",
+ ),
+)
+
+
+FREE_CHANNELS: tuple[DemoFreeChannel, ...] = (
+ DemoFreeChannel(
+ key="organic_search",
+ daily_sessions=80,
+ referring_domain="google.com",
+ signup_rate=0.05,
+ purchase_rate=0.012,
+ scenario="Organic Search: no UTMs, no cost -> null ROAS/CPC",
+ ),
+ DemoFreeChannel(
+ key="direct",
+ daily_sessions=50,
+ referring_domain="$direct",
+ signup_rate=0.06,
+ purchase_rate=0.02,
+ scenario="Direct",
+ ),
+ DemoFreeChannel(
+ key="email",
+ daily_sessions=30,
+ referring_domain="$direct",
+ utm_source="newsletter",
+ utm_medium="email",
+ utm_campaign="weekly_digest",
+ signup_rate=0.09,
+ purchase_rate=0.025,
+ utm_source_variants={"newsltr": 0.2},
+ scenario="Email + a near-miss source with no known alias token (audit 'unmapped')",
+ ),
+ DemoFreeChannel(
+ key="organic_social",
+ daily_sessions=26,
+ referring_domain="facebook.com",
+ signup_rate=0.03,
+ purchase_rate=0.006,
+ scenario="Organic Social: social referrer, no UTMs, no paid signals",
+ ),
+ DemoFreeChannel(
+ key="organic_social_x",
+ daily_sessions=12,
+ referring_domain="twitter.com",
+ signup_rate=0.025,
+ purchase_rate=0.004,
+ scenario="Organic Social (X)",
+ ),
+ DemoFreeChannel(
+ key="organic_video",
+ daily_sessions=20,
+ referring_domain="youtube.com",
+ signup_rate=0.04,
+ purchase_rate=0.008,
+ scenario="Organic Video",
+ ),
+ DemoFreeChannel(
+ key="affiliate",
+ daily_sessions=9,
+ referring_domain="partners.example.com",
+ utm_source="partner_tier1",
+ utm_medium="affiliate",
+ utm_campaign="affiliate_program",
+ signup_rate=0.08,
+ purchase_rate=0.025,
+ scenario="Affiliate channel via utm_medium=affiliate",
+ ),
+ DemoFreeChannel(
+ key="push",
+ daily_sessions=11,
+ referring_domain="$direct",
+ utm_source="onesignal",
+ utm_medium="push",
+ utm_campaign="winback_push",
+ signup_rate=0.02,
+ purchase_rate=0.015,
+ scenario="Push channel via utm_medium=push",
+ ),
+ DemoFreeChannel(
+ key="sms",
+ daily_sessions=6,
+ referring_domain="$direct",
+ utm_source="twilio",
+ utm_medium="sms",
+ utm_campaign="flash_sale_sms",
+ signup_rate=0.05,
+ purchase_rate=0.03,
+ scenario="SMS channel via utm_medium=sms",
+ ),
+ DemoFreeChannel(
+ key="referral_ph",
+ daily_sessions=15,
+ referring_domain="producthunt.com",
+ signup_rate=0.1,
+ purchase_rate=0.02,
+ scenario="Referral",
+ ),
+ DemoFreeChannel(
+ key="referral_hn",
+ daily_sessions=10,
+ referring_domain="news.ycombinator.com",
+ signup_rate=0.07,
+ purchase_rate=0.01,
+ scenario="Referral",
+ ),
+ DemoFreeChannel(
+ key="ai_chatgpt",
+ daily_sessions=18,
+ referring_domain="chatgpt.com",
+ signup_rate=0.11,
+ purchase_rate=0.03,
+ scenario="AI channel via referrer, no paid signals",
+ ),
+ DemoFreeChannel(
+ key="ai_claude",
+ daily_sessions=8,
+ referring_domain="claude.ai",
+ signup_rate=0.14,
+ purchase_rate=0.04,
+ scenario="AI channel",
+ ),
+ DemoFreeChannel(
+ key="ai_perplexity",
+ daily_sessions=6,
+ referring_domain="perplexity.ai",
+ signup_rate=0.08,
+ purchase_rate=0.02,
+ scenario="AI channel",
+ ),
+ DemoFreeChannel(
+ key="ai_gemini",
+ daily_sessions=4,
+ referring_domain="gemini.google.com",
+ signup_rate=0.06,
+ purchase_rate=0.012,
+ scenario="AI channel",
+ ),
+ DemoFreeChannel(
+ key="ai_copilot",
+ daily_sessions=3,
+ referring_domain="copilot.microsoft.com",
+ signup_rate=0.05,
+ purchase_rate=0.01,
+ scenario="AI channel",
+ ),
+ DemoFreeChannel(
+ key="ai_grok",
+ daily_sessions=3,
+ referring_domain="grok.com",
+ signup_rate=0.06,
+ purchase_rate=0.012,
+ scenario="AI channel",
+ ),
+ DemoFreeChannel(
+ key="ai_deepseek",
+ daily_sessions=2,
+ referring_domain="deepseek.com",
+ signup_rate=0.05,
+ purchase_rate=0.008,
+ scenario="AI channel",
+ ),
+ DemoFreeChannel(
+ key="ai_meta",
+ daily_sessions=2,
+ referring_domain="meta.ai",
+ signup_rate=0.04,
+ purchase_rate=0.006,
+ scenario="AI channel",
+ ),
+ DemoFreeChannel(
+ key="ai_mistral",
+ daily_sessions=2,
+ referring_domain="chat.mistral.ai",
+ signup_rate=0.05,
+ purchase_rate=0.008,
+ scenario="AI channel",
+ ),
+ DemoFreeChannel(
+ key="ai_chatgpt_utm",
+ daily_sessions=4,
+ referring_domain="chatgpt.com",
+ utm_source="chatgpt",
+ utm_medium="referral",
+ utm_campaign="ai_recommendation",
+ signup_rate=0.1,
+ purchase_rate=0.025,
+ scenario="AI channel reached via utm_source=chatgpt (not just referrer)",
+ ),
+)
+
+# Sources with cost rows written to the warehouse (must stay in sync with health.py).
+NATIVE_PLATFORMS_WITH_DATA: tuple[str, ...] = (
+ "GoogleAds",
+ "MetaAds",
+ "BingAds",
+ "LinkedinAds",
+ "RedditAds",
+ "PinterestAds",
+ "SnapchatAds",
+ "TikTokAds",
+)
+
+BIGQUERY_SOURCE_LABEL = "demo_partner"
+
+EVENT_SIGNUP = "user signed up"
+EVENT_PURCHASE = "purchase completed"
+EVENT_DEMO_BOOKED = "demo booked"
+EVENT_PAGEVIEW = "$pageview"
+
+SITE_URL = "https://demo.posthog.dev"
diff --git a/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.py b/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.py
new file mode 100644
index 000000000000..6725b2a95975
--- /dev/null
+++ b/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.py
@@ -0,0 +1,205 @@
+"""Generate demo data for the Marketing analytics dashboard.
+
+Creates a self-contained marketing world in the target project:
+
+- $pageviews with correct, near-miss, and wrong UTMs across paid platforms,
+ organic, direct, email, referral, and AI-assistant traffic
+- conversion events (sign ups, purchases with revenue, demo bookings) with
+ single- and multi-touch journeys, including out-of-window fallbacks
+- cost tables in the warehouse using each platform's real column formats
+ (Google micros + full ad hierarchy, Meta JSON actions, Bing unified report,
+ plus a BigQuery-style table mapped via sources_map with EUR costs)
+- ExternalDataSource/Schema/Job fixtures staging every Integration health
+ state (ok, stale, error, never, tables missing/failed/disabled)
+- team marketing config: conversion goals (healthy and deliberately broken),
+ campaign name mappings, custom source mappings, field preferences
+- the marketing feature flags at 100% rollout
+
+Run against a dedicated local project: re-runs soft-delete and recreate the
+demo sources/tables, but events accumulate.
+
+Usage:
+ DEBUG=1 python manage.py generate_marketing_demo_data --team-id 2
+ DEBUG=1 python manage.py generate_marketing_demo_data --team-id 2 --days-past 90 --scale 0.5
+ DEBUG=1 python manage.py generate_marketing_demo_data --team-id 2 --dry-run
+"""
+
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+from django.utils import timezone
+
+from posthog.models import Team
+from posthog.settings import OBJECT_STORAGE_ACCESS_KEY_ID, OBJECT_STORAGE_SECRET_ACCESS_KEY
+
+from products.marketing_analytics.backend.demo import (
+ config as demo_config,
+ health,
+ warehouse,
+)
+from products.marketing_analytics.backend.demo.events import MarketingEventGenerator
+from products.marketing_analytics.backend.demo.world import CAMPAIGNS, FREE_CHANNELS
+from products.warehouse_sources.backend.facade.models import (
+ DataWarehouseTable,
+ ExternalDataSource,
+ get_or_create_datawarehouse_credential,
+)
+
+
+class Command(BaseCommand):
+ help = "Generate marketing analytics demo data (events, cost tables, health fixtures, config)."
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--team-id", type=int, required=True, help="Team (project) to seed into.")
+ parser.add_argument("--seed", type=str, default="marketing-demo", help="Deterministic RNG seed.")
+ parser.add_argument("--days-past", type=int, default=60, help="Days of history to generate (default: 60).")
+ parser.add_argument("--scale", type=float, default=1.0, help="Traffic volume multiplier (default: 1.0).")
+ parser.add_argument("--dry-run", action="store_true", help="Print the plan without writing anything.")
+ parser.add_argument("--skip-events", action="store_true", help="Skip event generation (config/tables only).")
+ parser.add_argument("--skip-flags", action="store_true", help="Skip enabling feature flags.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ # Local-dev only: this seeder persists the deployment's OBJECT_STORAGE_*
+ # key pair into a tenant-owned warehouse credential, which must never
+ # happen against production object storage.
+ if not settings.DEBUG:
+ raise CommandError("This command is only for local development (requires DEBUG=1)")
+ try:
+ team = Team.objects.get(pk=options["team_id"])
+ except Team.DoesNotExist:
+ raise CommandError(f"Team {options['team_id']} does not exist")
+ user = team.organization.members.first()
+ if user is None:
+ raise CommandError(f"Team {team.pk} has no organization members")
+
+ if not OBJECT_STORAGE_ACCESS_KEY_ID or not OBJECT_STORAGE_SECRET_ACCESS_KEY:
+ raise CommandError("Object storage credentials are not configured (OBJECT_STORAGE_* settings)")
+
+ days_past: int = options["days_past"]
+ scale: float = options["scale"]
+ now = timezone.now()
+
+ if options["dry_run"]:
+ self._print_plan(days_past, scale)
+ return
+
+ generator = MarketingEventGenerator(team, seed=options["seed"], days_past=days_past, scale=scale, now=now)
+ if options["skip_events"]:
+ self.stdout.write("Skipping event generation.")
+ else:
+ self.stdout.write(f"Generating events for {days_past} days (scale {scale})...")
+ generator.generate()
+ self.stdout.write(self.style.SUCCESS(f"Wrote {generator.result.events_written} events to ClickHouse."))
+
+ with tempfile.TemporaryDirectory(prefix="marketing-demo-") as tmp:
+ out_dir = Path(tmp)
+ builder = warehouse.CostTableBuilder(seed=options["seed"], days_past=days_past, now=now, out_dir=out_dir)
+
+ self.stdout.write("Creating warehouse sources and staging Integration health states...")
+ sources = health.create_sources(team)
+ credential = get_or_create_datawarehouse_credential(
+ team_id=team.pk,
+ access_key=OBJECT_STORAGE_ACCESS_KEY_ID,
+ access_secret=OBJECT_STORAGE_SECRET_ACCESS_KEY,
+ )
+
+ self.stdout.write("Uploading cost tables for all native platforms...")
+ table_map: dict[tuple[str, str], Any] = {}
+ for platform, (builder_method, prefix, columns_by_schema) in warehouse.NATIVE_SPECS.items():
+ for schema_name, csv_path in getattr(builder, builder_method)().items():
+ registered = warehouse.register_table(
+ team,
+ csv_path=csv_path,
+ table_name=f"{prefix}_{schema_name}",
+ columns=columns_by_schema[schema_name],
+ source=sources[platform],
+ credential=credential,
+ )
+ table_map[(platform, schema_name)] = registered.table
+
+ health.stage_schemas_and_jobs(team, sources, table_map)
+
+ self.stdout.write("Uploading BigQuery-style ads table + Stripe-style invoices table...")
+ ExternalDataSource.objects.filter(
+ team=team, source_type="BigQuery", source_id="marketing-demo-bigquery"
+ ).update(deleted=True)
+ bigquery_source = ExternalDataSource.objects.create(
+ team=team,
+ source_id="marketing-demo-bigquery",
+ connection_id="marketing-demo-bigquery",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type="BigQuery",
+ prefix="",
+ )
+ ads_table = warehouse.register_table(
+ team,
+ csv_path=builder.build_bigquery_ads(),
+ table_name=warehouse.BIGQUERY_ADS_TABLE,
+ columns=warehouse.BIGQUERY_ADS_COLUMNS,
+ source=bigquery_source,
+ credential=credential,
+ )
+ # On --skip-events there are no fresh invoices; keep an existing
+ # populated table instead of overwriting it with an empty one.
+ invoices_table = None
+ if options["skip_events"]:
+ existing_invoices = DataWarehouseTable.objects.filter(
+ team=team, name=warehouse.STRIPE_INVOICES_TABLE, deleted=False
+ ).first()
+ if existing_invoices:
+ invoices_table = warehouse.RegisteredTable(
+ name=warehouse.STRIPE_INVOICES_TABLE, table=existing_invoices
+ )
+ if invoices_table is None:
+ invoices_table = warehouse.register_table(
+ team,
+ csv_path=builder.build_stripe_invoices(generator.result.invoices),
+ table_name=warehouse.STRIPE_INVOICES_TABLE,
+ columns=warehouse.STRIPE_INVOICES_COLUMNS,
+ source=bigquery_source,
+ credential=credential,
+ )
+ self.stdout.write(
+ f"Registered {len(table_map) + 2} warehouse tables "
+ f"({ads_table.name}, {invoices_table.name}, and native cost tables)."
+ )
+
+ bigquery_sources_map = {
+ str(ads_table.table.id): {
+ "id": "campaign_id",
+ "campaign": "campaign_name",
+ "source": "const:demo_partner",
+ "date": "date",
+ "cost": "cost",
+ "clicks": "clicks",
+ "impressions": "impressions",
+ "currency": "const:EUR",
+ }
+ }
+ self.stdout.write("Applying marketing analytics config (goals, mappings, attribution)...")
+ demo_config.apply_marketing_config(team, bigquery_sources_map=bigquery_sources_map)
+
+ if not options["skip_flags"]:
+ enabled = demo_config.enable_feature_flags(team, user)
+ self.stdout.write(f"Enabled {len(enabled)} feature flags.")
+
+ self.stdout.write(self.style.SUCCESS("Done. Open /marketing in the target project."))
+ self.stdout.write(
+ "Kafka delivery is async: give ClickHouse a minute before expecting all events in the dashboard."
+ )
+
+ def _print_plan(self, days_past: int, scale: float) -> None:
+ daily_sessions = sum(c.daily_sessions for c in CAMPAIGNS) + sum(c.daily_sessions for c in FREE_CHANNELS)
+ self.stdout.write(f"Would generate ~{round(daily_sessions * scale)} sessions/day for {days_past} days:")
+ for campaign in CAMPAIGNS:
+ self.stdout.write(f" [{campaign.platform}] {campaign.name}: {campaign.scenario or 'traffic'}")
+ for channel in FREE_CHANNELS:
+ self.stdout.write(f" [free] {channel.key}: {channel.scenario or 'traffic'}")
+ native_tables = sum(len(columns) for _method, _prefix, columns in warehouse.NATIVE_SPECS.values())
+ self.stdout.write(
+ f"Plus: health fixtures for {len(warehouse.NATIVE_SPECS)} platforms, "
+ f"{native_tables + 2} warehouse tables, 6 conversion goals, flags."
+ )
diff --git a/tach.toml b/tach.toml
index a45cbbead852..e12ad6a25225 100644
--- a/tach.toml
+++ b/tach.toml
@@ -698,6 +698,7 @@ depends_on = [
"products.access_control",
"products.actions",
"products.analytics_platform", "products.warehouse_sources",
+ "products.feature_flags",
]
layer = "modules"