: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(web-analytics): add heatmap capture settings api (#102556)
Jordan Mryyan977e6d9dcef7
diff --git a/posthog/models/organization.py b/posthog/models/organization.pyindex e8ee032be477..a7d7fa816850 100644--- a/posthog/models/organization.py+++ b/posthog/models/organization.py@@ -235,6 +235,7 @@ class Organization(ModelActivityMixin, UUIDTModel):)# Transient flag set by the pre_save signal to communicate active-state changes to post_save._is_active_changed: bool = False+ _has_active_subscription_changed: bool = False# Security / management settingssession_cookie_age = models.IntegerField(@@ -673,17 +674,28 @@ def organization_about_to_be_created(sender, instance: Organization, raw, using,@receiver(models.signals.pre_save, sender=Organization)-def remember_organization_is_active_change(sender, instance: Organization, **kwargs):+def remember_organization_field_changes(sender, instance: Organization, **kwargs):instance._is_active_changed = False+ instance._has_active_subscription_changed = Falseif instance._state.adding:return+ tracked_fields = {"is_active", "has_active_subscription"}update_fields = kwargs.get("update_fields")- if update_fields is not None and "is_active" not in update_fields:- return+ if update_fields is not None:+ tracked_fields &= set(update_fields)+ if not tracked_fields:+ return- previous_is_active = sender.objects.filter(pk=instance.pk).values_list("is_active", flat=True).first()- instance._is_active_changed = previous_is_active != instance.is_active+ previous = sender.objects.filter(pk=instance.pk).values("is_active", "has_active_subscription").first()+ if previous is None:+ return+ if "is_active" in tracked_fields:+ instance._is_active_changed = previous["is_active"] != instance.is_active+ if "has_active_subscription" in tracked_fields:+ instance._has_active_subscription_changed = (+ previous["has_active_subscription"] != instance.has_active_subscription+ )@receiver(post_save, sender=Organization)diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.pyindex 658ecd00ef99..96735b68878d 100644--- a/posthog/models/remote_config.py+++ b/posthog/models/remote_config.py@@ -215,6 +215,7 @@ class RemoteConfig(UUIDTModel):from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.messaging.backend.remote_config import build_push_configfrom products.surveys.backend.api.survey import get_surveys_opt_in, get_surveys_response+ from products.web_analytics.backend.remote_config import build_heatmaps_config# NOTE: It is important this is changed carefully. This is what the SDK will load in place of "decide" so the format# should be kept consistent. The JS code should be minified and the JSON should be as small as possible.@@ -281,7 +282,7 @@ class RemoteConfig(UUIDTModel):config["quotaLimited"] = ["recordings"]config["sessionRecording"] = False- config["heatmaps"] = True if team.heatmaps_opt_in else False+ config["heatmaps"] = build_heatmaps_config(team) if team.heatmaps_opt_in else False# MARK: Conversationsif team.conversations_enabled:@@ -597,6 +598,24 @@ def js_snippet_config_saved(sender, instance, created, **kwargs):transaction.on_commit(lambda: _update_team_remote_config(instance.team_id))+@receiver(post_save, sender="posthog.TeamHeatmapConfig")+def heatmap_config_saved(sender, instance, created, **kwargs):+ transaction.on_commit(lambda: _update_team_remote_config(instance.team_id))+++@receiver(post_save, sender="posthog.Organization")+def organization_subscription_saved(sender, instance, created, **kwargs):+ if created or not getattr(instance, "_has_active_subscription_changed", False):+ return+ team_ids = list(Team.objects.filter(organization_id=instance.pk, heatmaps_opt_in=True).values_list("id", flat=True))++ def rebuild_heatmaps_enabled_teams() -> None:+ for team_id in team_ids:+ _update_team_remote_config(team_id)++ transaction.on_commit(rebuild_heatmaps_enabled_teams)++@receiver(post_save, sender="posthog.Integration")@receiver(post_delete, sender="posthog.Integration")def push_integration_changed(sender, instance, **kwargs):diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.pyindex b5d63ee945a4..41b159dbdc14 100644--- a/posthog/models/test/test_remote_config.py+++ b/posthog/models/test/test_remote_config.py@@ -4,7 +4,7 @@ from typing import Anyimport pytestfrom posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchfrom django.test import override_settingsfrom django.utils import timezone@@ -134,6 +134,85 @@ class TestRemoteConfig(_RemoteConfigBase):self.sync_remote_config()assert self.remote_config.config["autocaptureExceptions"]+ def test_heatmaps_disabled_returns_false(self):+ self.team.heatmaps_opt_in = False+ self.team.save()+ self.sync_remote_config()+ assert self.remote_config.config["heatmaps"] is False++ def test_heatmaps_enabled_paid_org_defaults_to_all(self):+ self.team.organization.has_active_subscription = True+ self.team.organization.save()+ self.team.heatmaps_opt_in = True+ self.team.save()+ self.sync_remote_config()+ assert self.remote_config.config["heatmaps"] == {+ "captureMode": "all",+ "urlAllowlist": [],+ "urlAllowlistEnforced": False,+ }++ def test_heatmaps_enabled_free_org_defaults_to_allowlist(self):+ self.team.organization.has_active_subscription = False+ self.team.organization.save()+ self.team.heatmaps_opt_in = True+ self.team.save()+ self.sync_remote_config()+ assert self.remote_config.config["heatmaps"] == {+ "captureMode": "url_allowlist",+ "urlAllowlist": [],+ "urlAllowlistEnforced": False,+ }++ @override_settings(HEATMAP_URL_ALLOWLIST_ENFORCEMENT_ENABLED=True)+ def test_heatmaps_config_reflects_enforcement_and_allowlist(self):+ from posthog.models.team.team_heatmap_config import TeamHeatmapConfig++ self.team.heatmaps_opt_in = True+ self.team.save()+ TeamHeatmapConfig.objects.update_or_create(+ team=self.team, defaults={"capture_url_allowlist": ["https://example.com/pricing"]}+ )+ self.sync_remote_config()+ assert self.remote_config.config["heatmaps"] == {+ "captureMode": "url_allowlist",+ "urlAllowlist": ["https://example.com/pricing"],+ "urlAllowlistEnforced": True,+ }++ def test_heatmaps_config_clamps_downgraded_org_to_allowlist(self):+ from posthog.models.team.team_heatmap_config import TeamHeatmapConfig++ self.team.heatmaps_opt_in = True+ self.team.save()+ TeamHeatmapConfig.objects.update_or_create(+ team=self.team,+ defaults={"capture_mode": "all", "capture_url_allowlist": [f"https://example.com/{i}" for i in range(4)]},+ )+ self.team.organization.has_active_subscription = False+ self.team.organization.save()+ self.sync_remote_config()+ assert self.remote_config.config["heatmaps"] == {+ "captureMode": "url_allowlist",+ "urlAllowlist": [],+ "urlAllowlistEnforced": False,+ }++ def test_subscription_change_rebuilds_heatmaps_enabled_teams(self):+ self.team.heatmaps_opt_in = True+ self.team.save()+ with patch("posthog.models.remote_config._update_team_remote_config") as mock_rebuild:+ with self.captureOnCommitCallbacks(execute=True):+ self.organization.has_active_subscription = False+ self.organization.save()+ assert mock_rebuild.call_args_list == [call(self.team.id)]++ mock_rebuild.reset_mock()+ with self.captureOnCommitCallbacks(execute=True):+ self.organization.name = "Renamed"+ self.organization.save()+ assert not mock_rebuild.called+@parameterized.expand([("firebase", True), ("apns", True), ("slack", False)])def test_only_push_integrations_schedule_a_config_rebuild(self, kind, expects_rebuild):# Configuring push is the moment the payload has to change, and nothing else on the team isdiff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex c67c548ea51c..15cb48eb277f 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -130,7 +130,9 @@ post_save:posthog.models.organization.sync_billing_on_membership_savepost_save:posthog.models.product_intent.product_intent._invalidate_product_intents_on_savepost_save:posthog.models.remote_config.error_tracking_suppression_rule_savedpost_save:posthog.models.remote_config.feature_flag_saved+post_save:posthog.models.remote_config.heatmap_config_savedpost_save:posthog.models.remote_config.js_snippet_config_saved+post_save:posthog.models.remote_config.organization_subscription_savedpost_save:posthog.models.remote_config.product_tour_savedpost_save:posthog.models.remote_config.push_integration_changedpost_save:posthog.models.remote_config.site_app_saved@@ -258,7 +260,7 @@ pre_delete:products.tasks.backend.team_deletion.cancel_task_workflows_on_team_depre_save:posthog.models.event_ingestion_restriction_config.capture_old_restriction_typepre_save:posthog.models.organization.organization_about_to_be_createdpre_save:posthog.models.organization.organization_membership_saved-pre_save:posthog.models.organization.remember_organization_is_active_change+pre_save:posthog.models.organization.remember_organization_field_changespre_save:posthog.models.product_intent.product_intent._capture_original_team_idpre_save:posthog.models.user._pause_loops_on_user_deactivationpre_save:posthog.models.user._revoke_sessions_on_user_deactivationdiff --git a/products/web_analytics/backend/api/test/test_capture_settings.py b/products/web_analytics/backend/api/test/test_capture_settings.pynew file mode 100644index 000000000000..a4e6f50242dd--- /dev/null+++ b/products/web_analytics/backend/api/test/test_capture_settings.py@@ -0,0 +1,234 @@+import time_machine+from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from django.test import SimpleTestCase, override_settings++from parameterized import parameterized++from posthog.kafka_client.client import ClickhouseProducer+from posthog.kafka_client.topics import KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS+from posthog.models import OrganizationMembership+from posthog.models.event.util import format_clickhouse_timestamp+from posthog.models.team.team_heatmap_config import TeamHeatmapConfig++from products.web_analytics.backend.models.heatmap_capture_config_version import HeatmapCaptureConfigVersion+from products.web_analytics.backend.models.heatmap_saved import SavedHeatmap+from products.web_analytics.backend.presentation.views.capture_settings import HeatmapCaptureSettingsRequestSerializer++INSERT_HEATMAP_EVENT = """+INSERT INTO sharded_heatmaps (session_id, team_id, distinct_id, timestamp, x, y, scale_factor,+ viewport_width, viewport_height, pointer_target_fixed, current_url, type)+SELECT %(session_id)s, %(team_id)s, 'u', %(timestamp)s, 10, 20, 16, 100, 100, 1, %(current_url)s, 'click'+"""+++class TestCaptureUrlValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("example.com/pricing",),+ ("www.example.com",),+ ("/pricing",),+ ("ftp://example.com",),+ ("",),+ ]+ )+ def test_rejects_non_http_urls(self, url: str) -> None:+ serializer = HeatmapCaptureSettingsRequestSerializer(data={"url_allowlist": [url]})+ assert not serializer.is_valid()++ def test_normalizes_and_deduplicates(self) -> None:+ serializer = HeatmapCaptureSettingsRequestSerializer(+ data={"url_allowlist": [" https://example.com/b ", "https://example.com/b", "https://example.com/a/*"]}+ )+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["url_allowlist"] == ["https://example.com/a/*", "https://example.com/b"]+++class TestCaptureSettings(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ def _url(self, team_id: int | None = None) -> str:+ return f"/api/projects/{team_id or self.team.id}/heatmap_capture/settings/"++ def test_non_admin_cannot_write(self) -> None:+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ response = self.client.patch(self._url(), {"capture_mode": "all", "url_allowlist": []}, format="json")+ assert response.status_code == 403++ def test_get_returns_paid_defaults(self) -> None:+ self.organization.has_active_subscription = True+ self.organization.save()+ response = self.client.get(self._url())+ assert response.status_code == 200+ assert response.json() == {+ "capture_mode": "all",+ "url_allowlist": [],+ "enforcement_enabled": False,+ "can_capture_all_urls": True,+ "capture_url_limit": None,+ }++ def test_get_returns_free_defaults(self) -> None:+ self.organization.has_active_subscription = False+ self.organization.save()+ response = self.client.get(self._url())+ assert response.status_code == 200+ assert response.json() == {+ "capture_mode": "url_allowlist",+ "url_allowlist": [],+ "enforcement_enabled": False,+ "can_capture_all_urls": False,+ "capture_url_limit": 3,+ }++ def test_free_org_cannot_capture_all_or_exceed_limit(self) -> None:+ self.organization.has_active_subscription = False+ self.organization.save()+ assert self.client.patch(self._url(), {"capture_mode": "all"}, format="json").status_code == 400+ four = [f"https://example.com/{i}" for i in range(4)]+ assert (+ self.client.patch(+ self._url(), {"capture_mode": "url_allowlist", "url_allowlist": four}, format="json"+ ).status_code+ == 400+ )+ assert (+ self.client.patch(+ self._url(), {"capture_mode": "url_allowlist", "url_allowlist": four[:3]}, format="json"+ ).status_code+ == 200+ )++ def test_paid_org_can_capture_all(self) -> None:+ self.organization.has_active_subscription = True+ self.organization.save()+ response = self.client.patch(self._url(), {"capture_mode": "all", "url_allowlist": []}, format="json")+ assert response.status_code == 200+ assert response.json()["capture_mode"] == "all"++ def test_free_org_get_suggests_oldest_saved_heatmaps(self) -> None:+ self.organization.has_active_subscription = False+ self.organization.save()+ for i, url in enumerate(["https://ex.com/a", "https://ex.com/b", "https://ex.com/c", "https://ex.com/d"]):+ with time_machine.travel(f"2025-01-0{i + 1}", tick=False):+ SavedHeatmap.objects.create(team=self.team, url=url)+ with time_machine.travel("2025-01-05", tick=False):+ for _ in range(101):+ SavedHeatmap.objects.create(team=self.team, url="https://ex.com/a")++ body = self.client.get(self._url()).json()+ assert body["capture_mode"] == "url_allowlist"+ assert body["url_allowlist"] == ["https://ex.com/a", "https://ex.com/b", "https://ex.com/c"]+ assert HeatmapCaptureConfigVersion.objects.for_team(self.team.pk).count() == 0+ assert not TeamHeatmapConfig.objects.filter(team=self.team).exists()++ def test_downgraded_org_reads_clamped_settings(self) -> None:+ self.organization.has_active_subscription = True+ self.organization.save()+ four = [f"https://example.com/{i}" for i in range(4)]+ assert (+ self.client.patch(self._url(), {"capture_mode": "all", "url_allowlist": four}, format="json").status_code+ == 200+ )+ SavedHeatmap.objects.create(team=self.team, url="https://ex.com/a")++ self.organization.has_active_subscription = False+ self.organization.save()+ body = self.client.get(self._url()).json()+ assert body["capture_mode"] == "url_allowlist"+ assert body["url_allowlist"] == ["https://ex.com/a"]+ assert body["can_capture_all_urls"] is False++ response = self.client.patch(self._url(), {"url_allowlist": ["https://ex.com/b"]}, format="json")+ assert response.status_code == 200+ assert response.json() == {+ "capture_mode": "url_allowlist",+ "url_allowlist": ["https://ex.com/b"],+ "enforcement_enabled": False,+ "can_capture_all_urls": False,+ "capture_url_limit": 3,+ }+ config = TeamHeatmapConfig.objects.get(team=self.team)+ assert config.capture_mode == "url_allowlist"+ assert config.capture_url_allowlist == ["https://ex.com/b"]++ def test_paid_org_gets_no_suggestion(self) -> None:+ self.organization.has_active_subscription = True+ self.organization.save()+ SavedHeatmap.objects.create(team=self.team, url="https://ex.com/a")+ assert self.client.get(self._url()).json()["url_allowlist"] == []+ assert HeatmapCaptureConfigVersion.objects.for_team(self.team.pk).count() == 0++ @override_settings(HEATMAP_URL_ALLOWLIST_ENFORCEMENT_ENABLED=True)+ def test_get_reflects_enforcement_setting(self) -> None:+ assert self.client.get(self._url()).json()["enforcement_enabled"] is True++ def test_patch_saves_and_records_a_version(self) -> None:+ response = self.client.patch(+ self._url(),+ {"capture_mode": "url_allowlist", "url_allowlist": ["https://example.com/pricing"]},+ format="json",+ )+ assert response.status_code == 200+ assert response.json()["url_allowlist"] == ["https://example.com/pricing"]++ config = TeamHeatmapConfig.objects.get(team=self.team)+ assert config.capture_mode == "url_allowlist"+ assert config.capture_url_allowlist == ["https://example.com/pricing"]++ versions = HeatmapCaptureConfigVersion.objects.for_team(self.team.pk)+ assert versions.count() == 1+ version = versions.get()+ assert version.effective_to is None+ assert version.patterns == ["https://example.com/pricing"]++ def test_second_patch_soft_closes_prior_version(self) -> None:+ self.client.patch(+ self._url(), {"capture_mode": "url_allowlist", "url_allowlist": ["https://example.com/a"]}, format="json"+ )+ self.client.patch(self._url(), {"capture_mode": "all", "url_allowlist": []}, format="json")++ versions = HeatmapCaptureConfigVersion.objects.for_team(self.team.pk).order_by("effective_from")+ assert versions.count() == 2+ first, second = versions+ assert first.effective_to is not None+ assert first.patterns == ["https://example.com/a"]+ assert second.effective_to is None+ assert second.mode == "all"+ assert second.patterns == []++ def test_unchanged_patch_records_no_new_version(self) -> None:+ body = {"capture_mode": "url_allowlist", "url_allowlist": ["https://example.com/a"]}+ self.client.patch(self._url(), body, format="json")+ self.client.patch(self._url(), body, format="json")+ assert HeatmapCaptureConfigVersion.objects.for_team(self.team.pk).count() == 1+++class TestCapturePages(APIBaseTest, ClickhouseTestMixin):+ def _create_heatmap_event(self, session_id: str, current_url: str, timestamp: str) -> None:+ ClickhouseProducer().produce(+ topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS,+ sql=INSERT_HEATMAP_EVENT,+ data={+ "session_id": session_id,+ "team_id": self.team.pk,+ "timestamp": format_clickhouse_timestamp(timestamp),+ "current_url": current_url,+ },+ )++ @time_machine.travel("2025-03-31", tick=False)+ def test_pages_lists_top_urls_by_recent_volume(self) -> None:+ self._create_heatmap_event("s1", "https://example.com/pricing", "2025-03-30T09:00:00")+ self._create_heatmap_event("s2", "https://example.com/pricing", "2025-03-30T10:00:00")+ self._create_heatmap_event("s3", "https://example.com/blog", "2025-03-30T11:00:00")+ self._create_heatmap_event("s4", "https://example.com/old", "2025-01-01T09:00:00")++ pages = self.client.get(f"/api/projects/{self.team.id}/heatmap_capture/pages/").json()["pages"]+ urls = [p["url"] for p in pages]+ assert urls == ["https://example.com/pricing", "https://example.com/blog"]+ assert pages[0]["count"] == 2diff --git a/products/web_analytics/backend/capture_pages.py b/products/web_analytics/backend/capture_pages.pynew file mode 100644index 000000000000..0d16493c64ed--- /dev/null+++ b/products/web_analytics/backend/capture_pages.py@@ -0,0 +1,30 @@+from datetime import timedelta+from typing import TYPE_CHECKING, Any++from django.utils import timezone++from posthog.hogql.ast import Constant+from posthog.hogql.constants import LimitContext+from posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++if TYPE_CHECKING:+ from posthog.models import Team++TOP_HEATMAP_PAGES_LIMIT = 20+TOP_HEATMAP_PAGES_DAYS = 30+++def top_heatmap_pages(team: "Team") -> list[dict[str, Any]]:+ since = timezone.now() - timedelta(days=TOP_HEATMAP_PAGES_DAYS)+ stmt = parse_select(+ "SELECT current_url AS url, count() AS cnt FROM heatmaps "+ "WHERE timestamp >= {since} AND current_url != '' "+ "GROUP BY current_url ORDER BY cnt DESC LIMIT {limit}",+ placeholders={"since": Constant(value=since), "limit": Constant(value=TOP_HEATMAP_PAGES_LIMIT)},+ )+ result = execute_hogql_query(+ query=stmt, team=team, limit_context=LimitContext.HEATMAPS, context=HogQLContext(team_id=team.pk)+ )+ return [{"url": row[0], "count": row[1]} for row in result.results]diff --git a/products/web_analytics/backend/capture_settings.py b/products/web_analytics/backend/capture_settings.pynew file mode 100644index 000000000000..40faaf9ab9c1--- /dev/null+++ b/products/web_analytics/backend/capture_settings.py@@ -0,0 +1,131 @@+from typing import TYPE_CHECKING+from urllib.parse import urlparse++from django.db import transaction+from django.db.models import Min+from django.utils import timezone++from posthog.dataclasses import frozen+from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.models.team.extensions import get_or_create_team_extension+from posthog.models.team.team_heatmap_config import TeamHeatmapConfig++from products.web_analytics.backend.models.heatmap_capture_config_version import HeatmapCaptureConfigVersion+from products.web_analytics.backend.models.heatmap_saved import SavedHeatmap++if TYPE_CHECKING:+ from posthog.models import Team, User++HEATMAP_FREE_CAPTURE_URL_LIMIT = 3+++@frozen+class EffectiveCaptureSettings:+ capture_mode: str+ url_allowlist: list[str]+++def is_capture_all_urls_entitled(team: "Team") -> bool:+ return team.organization.has_active_subscription is not False+++def default_capture_mode(team: "Team") -> str:+ if is_capture_all_urls_entitled(team):+ return TeamHeatmapConfig.CaptureMode.ALL+ return TeamHeatmapConfig.CaptureMode.URL_ALLOWLIST+++def oldest_saved_heatmap_urls(team: "Team", limit: int = HEATMAP_FREE_CAPTURE_URL_LIMIT) -> list[str]:+ return list(+ SavedHeatmap.objects.filter(team=team, deleted=False)+ .exclude(url="")+ .values("url")+ .annotate(first_created_at=Min("created_at"))+ .order_by("first_created_at", "url")+ .values_list("url", flat=True)[:limit]+ )+++def effective_capture_settings(team: "Team", config: TeamHeatmapConfig | None) -> EffectiveCaptureSettings:+ if is_capture_all_urls_entitled(team):+ if config is None:+ return EffectiveCaptureSettings(capture_mode=TeamHeatmapConfig.CaptureMode.ALL, url_allowlist=[])+ return EffectiveCaptureSettings(+ capture_mode=config.capture_mode, url_allowlist=list(config.capture_url_allowlist)+ )++ if config is not None and config.capture_mode == TeamHeatmapConfig.CaptureMode.URL_ALLOWLIST:+ url_allowlist = list(config.capture_url_allowlist)+ else:+ url_allowlist = oldest_saved_heatmap_urls(team)+ return EffectiveCaptureSettings(+ capture_mode=TeamHeatmapConfig.CaptureMode.URL_ALLOWLIST,+ url_allowlist=url_allowlist[:HEATMAP_FREE_CAPTURE_URL_LIMIT],+ )+++def normalize_capture_url(value: str) -> str:+ url = value.strip()+ if not url:+ raise ValueError("Enter a URL, such as https://example.com/pricing.")+ parsed = urlparse(url)+ if parsed.scheme not in ("http", "https") or not parsed.netloc:+ raise ValueError("Enter a full URL that starts with http:// or https://. Use * to match any characters.")+ return url+++def save_capture_settings(+ team: "Team", capture_mode: str, url_allowlist: list[str], *, user: "User", was_impersonated: bool+) -> TeamHeatmapConfig:+ get_or_create_team_extension(team, TeamHeatmapConfig)+ with transaction.atomic():+ config = TeamHeatmapConfig.objects.select_for_update().get(team_id=team.pk)+ before_mode = config.capture_mode+ before_allowlist = config.capture_url_allowlist+ if before_mode == capture_mode and before_allowlist == url_allowlist:+ return config++ config.capture_mode = capture_mode+ config.capture_url_allowlist = url_allowlist+ config.save(update_fields=["capture_mode", "capture_url_allowlist"])++ now = timezone.now()+ versions = HeatmapCaptureConfigVersion.objects.for_team(team.pk)+ versions.filter(effective_to__isnull=True).update(effective_to=now)+ versions.create(+ team=team,+ mode=capture_mode,+ patterns=url_allowlist if capture_mode == TeamHeatmapConfig.CaptureMode.URL_ALLOWLIST else [],+ effective_from=now,+ created_by=user,+ )++ log_activity(+ organization_id=team.organization_id,+ team_id=team.pk,+ user=user,+ was_impersonated=was_impersonated,+ scope="Team",+ item_id=team.pk,+ activity="updated",+ detail=Detail(+ name=str(team.name),+ changes=[+ Change(+ type="Team",+ action="changed",+ field="heatmaps_capture_mode",+ before=before_mode,+ after=capture_mode,+ ),+ Change(+ type="Team",+ action="changed",+ field="heatmaps_capture_url_allowlist",+ before=before_allowlist,+ after=url_allowlist,+ ),+ ],+ ),+ )+ return configdiff --git a/products/web_analytics/backend/facade/capture_settings.py b/products/web_analytics/backend/facade/capture_settings.pynew file mode 100644index 000000000000..affbb62dfbbb--- /dev/null+++ b/products/web_analytics/backend/facade/capture_settings.py@@ -0,0 +1,19 @@+from products.web_analytics.backend.capture_pages import top_heatmap_pages+from products.web_analytics.backend.capture_settings import (+ HEATMAP_FREE_CAPTURE_URL_LIMIT,+ EffectiveCaptureSettings,+ effective_capture_settings,+ is_capture_all_urls_entitled,+ normalize_capture_url,+ save_capture_settings,+)++__all__ = [+ "HEATMAP_FREE_CAPTURE_URL_LIMIT",+ "EffectiveCaptureSettings",+ "effective_capture_settings",+ "is_capture_all_urls_entitled",+ "normalize_capture_url",+ "save_capture_settings",+ "top_heatmap_pages",+]diff --git a/products/web_analytics/backend/presentation/views/capture_settings.py b/products/web_analytics/backend/presentation/views/capture_settings.pynew file mode 100644index 000000000000..f14a3569d7b3--- /dev/null+++ b/products/web_analytics/backend/presentation/views/capture_settings.py@@ -0,0 +1,153 @@+from typing import cast++from django.conf import settings++from drf_spectacular.utils import extend_schema+from rest_framework import serializers, viewsets+from rest_framework.decorators import action+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.helpers.impersonation import is_impersonated+from posthog.models import Team, User+from posthog.models.team.team_heatmap_config import TeamHeatmapConfig+from posthog.permissions import TeamMemberStrictManagementPermission++from products.web_analytics.backend.facade.capture_settings import (+ HEATMAP_FREE_CAPTURE_URL_LIMIT,+ effective_capture_settings,+ is_capture_all_urls_entitled,+ normalize_capture_url,+ save_capture_settings,+ top_heatmap_pages,+)+++class HeatmapCapturePageSerializer(serializers.Serializer):+ url = serializers.CharField(help_text="A page URL that currently sends heatmap data.")+ count = serializers.IntegerField(help_text="Heatmap events captured on this page in the last 30 days.")+++class HeatmapCapturePagesSerializer(serializers.Serializer):+ pages = HeatmapCapturePageSerializer(many=True, help_text="Top pages by recent heatmap volume, most active first.")+++CAPTURE_MODE_HELP_TEXT = (+ "Whether to capture heatmap data from every page ('all') or only listed URLs ('url_allowlist')."+)+URL_ALLOWLIST_HELP_TEXT = "Full http(s) URLs that may send heatmap data. Use * to match any characters."+++class HeatmapCaptureSettingsRequestSerializer(serializers.Serializer):+ capture_mode = serializers.ChoiceField(+ choices=TeamHeatmapConfig.CaptureMode.choices, required=False, help_text=CAPTURE_MODE_HELP_TEXT+ )+ url_allowlist = serializers.ListField(+ child=serializers.CharField(max_length=2000),+ max_length=100,+ required=False,+ help_text=URL_ALLOWLIST_HELP_TEXT,+ )++ def validate_url_allowlist(self, value: list[str]) -> list[str]:+ try:+ return sorted({normalize_capture_url(url) for url in value})+ except ValueError as error:+ raise serializers.ValidationError(str(error)) from None+++class HeatmapCaptureSettingsSerializer(serializers.Serializer):+ capture_mode = serializers.ChoiceField(+ choices=TeamHeatmapConfig.CaptureMode.choices, help_text=CAPTURE_MODE_HELP_TEXT+ )+ url_allowlist = serializers.ListField(+ child=serializers.CharField(max_length=2000), help_text=URL_ALLOWLIST_HELP_TEXT+ )+ enforcement_enabled = serializers.BooleanField(+ read_only=True, help_text="Whether this installation enforces the URL allow-list for heatmap capture."+ )+ can_capture_all_urls = serializers.BooleanField(+ read_only=True, help_text="Whether this organization's plan may capture heatmaps on every page."+ )+ capture_url_limit = serializers.IntegerField(+ read_only=True,+ allow_null=True,+ help_text="How many URLs this plan may capture, or null when the plan captures all pages.",+ )+++def capture_settings_response(team: Team, config: TeamHeatmapConfig | None) -> Response:+ entitled = is_capture_all_urls_entitled(team)+ effective = effective_capture_settings(team, config)+ return Response(+ HeatmapCaptureSettingsSerializer(+ {+ "capture_mode": effective.capture_mode,+ "url_allowlist": effective.url_allowlist,+ "enforcement_enabled": settings.HEATMAP_URL_ALLOWLIST_ENFORCEMENT_ENABLED,+ "can_capture_all_urls": entitled,+ "capture_url_limit": None if entitled else HEATMAP_FREE_CAPTURE_URL_LIMIT,+ }+ ).data+ )+++class HeatmapCaptureSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ scope_object = "project"+ permission_classes = [TeamMemberStrictManagementPermission]+ serializer_class = HeatmapCaptureSettingsSerializer+ scope_object_read_actions = ["configuration", "pages"]+ scope_object_write_actions = ["update_settings"]++ @extend_schema(operation_id="heatmap_capture_settings_retrieve", responses=HeatmapCaptureSettingsSerializer)+ @action(detail=False, methods=["GET"], url_path="settings")+ def configuration(self, request: Request, **kwargs: object) -> Response:+ return capture_settings_response(self.team, TeamHeatmapConfig.objects.filter(team_id=self.team_id).first())++ @extend_schema(operation_id="heatmap_capture_pages_retrieve", responses=HeatmapCapturePagesSerializer)+ @action(detail=False, methods=["GET"], url_path="pages")+ def pages(self, request: Request, **kwargs: object) -> Response:+ return Response(HeatmapCapturePagesSerializer({"pages": top_heatmap_pages(self.team)}).data)++ @extend_schema(+ operation_id="heatmap_capture_settings_update",+ request=HeatmapCaptureSettingsRequestSerializer,+ responses=HeatmapCaptureSettingsSerializer,+ )+ @configuration.mapping.patch+ def update_settings(self, request: Request, **kwargs: object) -> Response:+ serializer = HeatmapCaptureSettingsRequestSerializer(data=request.data, partial=True)+ serializer.is_valid(raise_exception=True)+ config = TeamHeatmapConfig.objects.filter(team_id=self.team_id).first()+ if not serializer.validated_data:+ return capture_settings_response(self.team, config)++ effective = effective_capture_settings(self.team, config)+ capture_mode = serializer.validated_data.get("capture_mode", effective.capture_mode)+ url_allowlist = serializer.validated_data.get("url_allowlist", effective.url_allowlist)++ if not is_capture_all_urls_entitled(self.team):+ if capture_mode == TeamHeatmapConfig.CaptureMode.ALL:+ raise serializers.ValidationError(+ {+ "capture_mode": f"Your plan captures up to {HEATMAP_FREE_CAPTURE_URL_LIMIT} URLs. "+ "Upgrade to capture heatmaps on every page."+ }+ )+ if len(url_allowlist) > HEATMAP_FREE_CAPTURE_URL_LIMIT:+ raise serializers.ValidationError(+ {+ "url_allowlist": f"Your plan captures up to {HEATMAP_FREE_CAPTURE_URL_LIMIT} URLs. "+ "Remove some, or upgrade to capture all pages."+ }+ )++ config = save_capture_settings(+ self.team,+ capture_mode,+ url_allowlist,+ user=cast(User, request.user),+ was_impersonated=is_impersonated(request),+ )+ return capture_settings_response(self.team, config)diff --git a/products/web_analytics/backend/remote_config.py b/products/web_analytics/backend/remote_config.pynew file mode 100644index 000000000000..93911ff4370d--- /dev/null+++ b/products/web_analytics/backend/remote_config.py@@ -0,0 +1,20 @@+from typing import TYPE_CHECKING, Any++from django.conf import settings++from posthog.models.team.team_heatmap_config import TeamHeatmapConfig++from products.web_analytics.backend.capture_settings import effective_capture_settings++if TYPE_CHECKING:+ from posthog.models import Team+++def build_heatmaps_config(team: "Team") -> dict[str, Any]:+ config = TeamHeatmapConfig.objects.filter(team_id=team.pk).first()+ effective = effective_capture_settings(team, config)+ return {+ "captureMode": effective.capture_mode,+ "urlAllowlist": effective.url_allowlist,+ "urlAllowlistEnforced": settings.HEATMAP_URL_ALLOWLIST_ENFORCEMENT_ENABLED,+ }diff --git a/products/web_analytics/backend/routes.py b/products/web_analytics/backend/routes.pyindex 8487f711df5d..0f33b5b18eef 100644--- a/products/web_analytics/backend/routes.py+++ b/products/web_analytics/backend/routes.py@@ -13,6 +13,7 @@ from products.web_analytics.backend.api.web_analytics_filter_preset import WebAnfrom products.web_analytics.backend.api.web_analytics_path_cleaning_suggestions import (WebAnalyticsPathCleaningSuggestionViewSet,)+from products.web_analytics.backend.presentation.views.capture_settings import HeatmapCaptureSettingsViewSetfrom products.web_analytics.backend.presentation.views.content_autopilot import (ContentAutopilotProposalViewSet,ContentAutopilotRunViewSet,@@ -25,6 +26,9 @@ def register_routes(routers: RouterRegistry) -> None:routers.projects.register(r"heatmap_screenshot", HeatmapScreenshotSettingsViewSet, "project_heatmap_screenshot_settings", ["team_id"])+ routers.projects.register(+ r"heatmap_capture", HeatmapCaptureSettingsViewSet, "project_heatmap_capture_settings", ["team_id"]+ )routers.root.register(r"heatmap", LegacyHeatmapViewSet, basename="heatmap")routers.projects.register(r"heatmaps", HeatmapViewSet, "project_heatmaps", ["team_id"])routers.projects.register(diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex 94b9a8d99e2b..58ebdc44bfdc 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -7,6 +7,66 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+export interface HeatmapCapturePageApi {+ /** A page URL that currently sends heatmap data. */+ url: string+ /** Heatmap events captured on this page in the last 30 days. */+ count: number+}++export interface HeatmapCapturePagesApi {+ /** Top pages by recent heatmap volume, most active first. */+ pages: HeatmapCapturePageApi[]+}++/**+ * * `all` - All URLs+ * * `url_allowlist` - Only listed URLs+ */+export type TeamHeatmapConfigCaptureModeEnumApi =+ (typeof TeamHeatmapConfigCaptureModeEnumApi)[keyof typeof TeamHeatmapConfigCaptureModeEnumApi]++export const TeamHeatmapConfigCaptureModeEnumApi = {+ All: 'all',+ UrlAllowlist: 'url_allowlist',+} as const++export interface HeatmapCaptureSettingsApi {+ /** Whether to capture heatmap data from every page ('all') or only listed URLs ('url_allowlist').+ *+ * * `all` - All URLs+ * * `url_allowlist` - Only listed URLs */+ capture_mode: TeamHeatmapConfigCaptureModeEnumApi+ /**+ * Full http(s) URLs that may send heatmap data. Use * to match any characters.+ * @items.maxLength 2000+ */+ url_allowlist: string[]+ /** Whether this installation enforces the URL allow-list for heatmap capture. */+ readonly enforcement_enabled: boolean+ /** Whether this organization's plan may capture heatmaps on every page. */+ readonly can_capture_all_urls: boolean+ /**+ * How many URLs this plan may capture, or null when the plan captures all pages.+ * @nullable+ */+ readonly capture_url_limit: number | null+}++export interface PatchedHeatmapCaptureSettingsRequestApi {+ /** Whether to capture heatmap data from every page ('all') or only listed URLs ('url_allowlist').+ *+ * * `all` - All URLs+ * * `url_allowlist` - Only listed URLs */+ capture_mode?: TeamHeatmapConfigCaptureModeEnumApi+ /**+ * Full http(s) URLs that may send heatmap data. Use * to match any characters.+ * @maxItems 100+ * @items.maxLength 2000+ */+ url_allowlist?: string[]+}+export interface HeatmapScreenshotSettingsApi {/*** Exact DNS hostnames approved to receive the screenshot cookie. No URLs, wildcards, or IP addresses.diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.tsindex 9ee7a8429703..8bbebe992df2 100644--- a/products/web_analytics/frontend/generated/api.ts+++ b/products/web_analytics/frontend/generated/api.ts@@ -22,6 +22,8 @@ import type {ContentAutopilotSiteDiscoveryResponseApi,ContentAutopilotSiteProfileApi,GeneratePathCleaningSuggestionResponseApi,+ HeatmapCapturePagesApi,+ HeatmapCaptureSettingsApi,HeatmapEventsResponseApi,HeatmapPreflightRequestApi,HeatmapPreflightResponseApi,@@ -39,6 +41,7 @@ import type {PaginatedContentAutopilotSiteProfileListApi,PaginatedWebAnalyticsFilterPresetListApi,PatchedContentAutopilotSiteProfileApi,+ PatchedHeatmapCaptureSettingsRequestApi,PatchedHeatmapScreenshotSettingsRequestApi,PatchedSavedHeatmapRequestApi,PatchedWebAnalyticsFilterPresetApi,@@ -80,6 +83,51 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getHeatmapCapturePagesRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/heatmap_capture/pages/`+}++export const heatmapCapturePagesRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<HeatmapCapturePagesApi> => {+ return apiMutator<HeatmapCapturePagesApi>(getHeatmapCapturePagesRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getHeatmapCaptureSettingsRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/heatmap_capture/settings/`+}++export const heatmapCaptureSettingsRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<HeatmapCaptureSettingsApi> => {+ return apiMutator<HeatmapCaptureSettingsApi>(getHeatmapCaptureSettingsRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getHeatmapCaptureSettingsUpdateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/heatmap_capture/settings/`+}++export const heatmapCaptureSettingsUpdate = async (+ projectId: string,+ patchedHeatmapCaptureSettingsRequestApi?: PatchedHeatmapCaptureSettingsRequestApi,+ options?: RequestInit+): Promise<HeatmapCaptureSettingsApi> => {+ return apiMutator<HeatmapCaptureSettingsApi>(getHeatmapCaptureSettingsUpdateUrl(projectId), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedHeatmapCaptureSettingsRequestApi),+ })+}+export const getHeatmapScreenshotSettingsRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/heatmap_screenshot/settings/`}diff --git a/products/web_analytics/frontend/generated/api.zod.ts b/products/web_analytics/frontend/generated/api.zod.tsindex b9623fcc2944..90d806368861 100644--- a/products/web_analytics/frontend/generated/api.zod.ts+++ b/products/web_analytics/frontend/generated/api.zod.ts@@ -9,6 +9,25 @@*/import * as zod from 'zod'+export const heatmapCaptureSettingsUpdateBodyUrlAllowlistItemMax = 2000++export const heatmapCaptureSettingsUpdateBodyUrlAllowlistMax = 100++export const HeatmapCaptureSettingsUpdateBody = /* @__PURE__ */ zod.object({+ capture_mode: zod+ .enum(['all', 'url_allowlist'])+ .describe('\* `all` - All URLs\n\* `url_allowlist` - Only listed URLs')+ .optional()+ .describe(+ "Whether to capture heatmap data from every page ('all') or only listed URLs ('url_allowlist').\n\n\* `all` - All URLs\n\* `url_allowlist` - Only listed URLs"+ ),+ url_allowlist: zod+ .array(zod.string().max(heatmapCaptureSettingsUpdateBodyUrlAllowlistItemMax))+ .max(heatmapCaptureSettingsUpdateBodyUrlAllowlistMax)+ .optional()+ .describe('Full http(s) URLs that may send heatmap data. Use \* to match any characters.'),+})+export const heatmapScreenshotSettingsUpdateBodyAllowedHostnamesItemMax = 253export const heatmapScreenshotSettingsUpdateBodyAllowedHostnamesMax = 100diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yamlindex a2df7a544d79..727c39f1c70e 100644--- a/products/web_analytics/mcp/tools.yaml+++ b/products/web_analytics/mcp/tools.yaml@@ -9,6 +9,15 @@ feature: web_analyticsurl_prefix: /webui_apps: {}tools:+ heatmap-capture-pages-retrieve:+ operation: heatmap_capture_pages_retrieve+ enabled: false+ heatmap-capture-settings-retrieve:+ operation: heatmap_capture_settings_retrieve+ enabled: false+ heatmap-capture-settings-update:+ operation: heatmap_capture_settings_update+ enabled: falseheatmap-screenshot-settings-retrieve:operation: heatmap_screenshot_settings_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 44424be3ab4d..172e7a30e502 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46556,6 +46556,52 @@ export namespace Schemas {snoozed: HealthIssueCounts;}+ export interface HeatmapCapturePage {+ /** A page URL that currently sends heatmap data. */+ url: string;+ /** Heatmap events captured on this page in the last 30 days. */+ count: number;+ }++ export interface HeatmapCapturePages {+ /** Top pages by recent heatmap volume, most active first. */+ pages: HeatmapCapturePage[];+ }++ /**+ * * `all` - All URLs+ * * `url_allowlist` - Only listed URLs+ */+ export type TeamHeatmapConfigCaptureModeEnum = typeof TeamHeatmapConfigCaptureModeEnum[keyof typeof TeamHeatmapConfigCaptureModeEnum];+++ export const TeamHeatmapConfigCaptureModeEnum = {+ All: 'all',+ UrlAllowlist: 'url_allowlist',+ } as const;++ export interface HeatmapCaptureSettings {+ /** Whether to capture heatmap data from every page ('all') or only listed URLs ('url_allowlist').+ *+ * * `all` - All URLs+ * * `url_allowlist` - Only listed URLs */+ capture_mode: TeamHeatmapConfigCaptureModeEnum;+ /**+ * Full http(s) URLs that may send heatmap data. Use * to match any characters.+ * @items.maxLength 2000+ */+ url_allowlist: string[];+ /** Whether this installation enforces the URL allow-list for heatmap capture. */+ readonly enforcement_enabled: boolean;+ /** Whether this organization's plan may capture heatmaps on every page. */+ readonly can_capture_all_urls: boolean;+ /**+ * How many URLs this plan may capture, or null when the plan captures all pages.+ * @nullable+ */+ readonly capture_url_limit: number | null;+ }+export interface HeatmapEventItem {/** @nullable */session_id?: string | null;@@ -70140,6 +70186,20 @@ export namespace Schemas {readonly resolved_at?: string | null;}+ export interface PatchedHeatmapCaptureSettingsRequest {+ /** Whether to capture heatmap data from every page ('all') or only listed URLs ('url_allowlist').+ *+ * * `all` - All URLs+ * * `url_allowlist` - Only listed URLs */+ capture_mode?: TeamHeatmapConfigCaptureModeEnum;+ /**+ * Full http(s) URLs that may send heatmap data. Use * to match any characters.+ * @maxItems 100+ * @items.maxLength 2000+ */+ url_allowlist?: string[];+ }+export interface PatchedHeatmapScreenshotSettingsRequest {/*** Exact DNS hostnames approved to receive the screenshot cookie. No URLs, wildcards, or IP addresses.