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.

chore(web_analytics): move models to product app (#59223)

Julian Beze67541390b6a
diff --git a/livestream/bot/generate_definitions.py b/livestream/bot/generate_definitions.py
index 01e2fd20ea17..f870146e2098 100644
--- a/livestream/bot/generate_definitions.py
+++ b/livestream/bot/generate_definitions.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Generate bot definitions JSON for the Go livestream service.
-Reads from posthog/hogql_queries/web_analytics/bot_definitions.py (single source of truth)
+Reads from products/web_analytics/backend/hogql_queries/bot_definitions.py (single source of truth)
and writes livestream/bot/definitions.json.
Run from repo root:
@@ -17,7 +17,7 @@ from pathlib import Path
repo_root = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(repo_root))
-from posthog.hogql_queries.web_analytics.bot_definitions import BOT_DEFINITIONS # noqa: E402
+from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS # noqa: E402
entries = [
{
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index 034ae42aca0c..0a5704fb173a 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -128,11 +128,17 @@ from products.visual_review.backend.presentation.views import (
RunViewSet as VisualReviewRunViewSet,
SnapshotViewSet as VisualReviewSnapshotViewSet,
)
+from products.web_analytics.backend.api.heatmaps_api import (
+ HeatmapScreenshotViewSet,
+ HeatmapViewSet,
+ LegacyHeatmapViewSet,
+ SavedHeatmapViewSet,
+)
+from products.web_analytics.backend.api.web_analytics_filter_preset import WebAnalyticsFilterPresetViewSet
from ee.api.session_summaries import SessionGroupSummaryViewSet
from ee.api.vercel import vercel_installation, vercel_product, vercel_proxy, vercel_resource
-from ..heatmaps.heatmaps_api import HeatmapScreenshotViewSet, HeatmapViewSet, LegacyHeatmapViewSet, SavedHeatmapViewSet
from ..session_recordings.session_recording_api import SessionRecordingViewSet
from ..session_recordings.session_recording_external_reference_api import SessionRecordingExternalReferenceViewSet
from ..session_recordings.session_recording_playlist_api import SessionRecordingPlaylistViewSet
@@ -199,7 +205,6 @@ from .file_system import file_system, file_system_shortcut, persisted_folder, us
from .llm_prompt import LLMPromptViewSet
from .oauth import OrganizationOAuthApplicationViewSet
from .session import SessionViewSet
-from .web_analytics_filter_preset import WebAnalyticsFilterPresetViewSet
@decorators.api_view(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"])
diff --git a/posthog/hogql/database/schema/sessions_v1.py b/posthog/hogql/database/schema/sessions_v1.py
index 7f49b319310f..080b0801eb55 100644
--- a/posthog/hogql/database/schema/sessions_v1.py
+++ b/posthog/hogql/database/schema/sessions_v1.py
@@ -464,7 +464,7 @@ def get_lazy_session_table_properties_v1(search: Optional[str]):
return results
-# NOTE: Keep the AD IDs in sync with `posthog.hogql_queries.web_analytics.session_attribution_explorer_query_runner.py`
+# NOTE: Keep the AD IDs in sync with `products.web_analytics.backend.hogql_queries.session_attribution_explorer_query_runner.py`
SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP = {
"$entry_referring_domain": "finalizeAggregation(initial_referring_domain)",
"$entry_utm_source": "finalizeAggregation(initial_utm_source)",
diff --git a/posthog/hogql/database/schema/sessions_v2.py b/posthog/hogql/database/schema/sessions_v2.py
index 1e94869ff043..6f7d3a3edb60 100644
--- a/posthog/hogql/database/schema/sessions_v2.py
+++ b/posthog/hogql/database/schema/sessions_v2.py
@@ -602,7 +602,7 @@ def get_lazy_session_table_properties_v2(search: Optional[str]):
return results
-# NOTE: Keep the AD IDs in sync with `posthog.hogql_queries.web_analytics.session_attribution_explorer_query_runner.py`
+# NOTE: Keep the AD IDs in sync with `products.web_analytics.backend.hogql_queries.session_attribution_explorer_query_runner.py`
SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP = {
"$entry_referring_domain": "finalizeAggregation(initial_referring_domain)",
"$entry_utm_source": "finalizeAggregation(initial_utm_source)",
diff --git a/posthog/hogql/database/schema/sessions_v3.py b/posthog/hogql/database/schema/sessions_v3.py
index adaae084fa11..345b8e76380e 100644
--- a/posthog/hogql/database/schema/sessions_v3.py
+++ b/posthog/hogql/database/schema/sessions_v3.py
@@ -527,7 +527,7 @@ def get_lazy_session_table_properties_v3(search: Optional[str]):
return results
-# NOTE: Keep the AD IDs in sync with `posthog.hogql_queries.web_analytics.session_attribution_explorer_query_runner.py`
+# NOTE: Keep the AD IDs in sync with `products.web_analytics.backend.hogql_queries.session_attribution_explorer_query_runner.py`
SESSION_PROPERTY_TO_RAW_SESSIONS_EXPR_MAP = {
"$entry_referring_domain": "finalizeAggregation(entry_referring_domain)",
"$entry_utm_source": "finalizeAggregation(entry_utm_source)",
diff --git a/posthog/hogql/functions/test/test_traffic_type_functions.py b/posthog/hogql/functions/test/test_traffic_type_functions.py
index 7c607dfdf2b5..7658e75b4cb1 100644
--- a/posthog/hogql/functions/test/test_traffic_type_functions.py
+++ b/posthog/hogql/functions/test/test_traffic_type_functions.py
@@ -9,7 +9,7 @@ from posthog.hogql.functions.traffic_type import (
is_bot,
)
-from posthog.hogql_queries.web_analytics.bot_definitions import BOT_DEFINITIONS
+from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
class TestTrafficTypeFunctions:
diff --git a/posthog/hogql/functions/test/test_traffic_type_real_ua.py b/posthog/hogql/functions/test/test_traffic_type_real_ua.py
index 27936e800fb7..3859e21ec16c 100644
--- a/posthog/hogql/functions/test/test_traffic_type_real_ua.py
+++ b/posthog/hogql/functions/test/test_traffic_type_real_ua.py
@@ -6,8 +6,8 @@ from posthog.test.base import BaseTest, _create_event, flush_persons_and_events
from posthog.hogql.query import execute_hogql_query
-from posthog.hogql_queries.web_analytics.bot_definitions import BOT_DEFINITIONS
-from posthog.hogql_queries.web_analytics.bot_ua_fixtures import (
+from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
+from products.web_analytics.backend.hogql_queries.bot_ua_fixtures import (
BOT_USER_AGENTS,
CATEGORY_TO_TRAFFIC_CATEGORY,
CATEGORY_TO_TRAFFIC_TYPE,
diff --git a/posthog/hogql/functions/traffic_type.py b/posthog/hogql/functions/traffic_type.py
index 0da0061b343b..7940da25127b 100644
--- a/posthog/hogql/functions/traffic_type.py
+++ b/posthog/hogql/functions/traffic_type.py
@@ -13,13 +13,13 @@ runners) to provide maximum flexibility during development. This allows usage in
- Any future features that leverage HogQL expressions
Bot definitions (patterns, categories, names) live in
-posthog.hogql_queries.web_analytics.bot_definitions so that changes to
+products.web_analytics.backend.hogql_queries.bot_definitions so that changes to
bot data do not require a HogQL review.
"""
from posthog.hogql import ast
-from posthog.hogql_queries.web_analytics.bot_definitions import BOT_DEFINITIONS
+from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
def _build_bot_array_lookup(
diff --git a/posthog/hogql/transforms/preaggregated_table_transformation.py b/posthog/hogql/transforms/preaggregated_table_transformation.py
index a4c6dc992552..3503c7773b67 100644
--- a/posthog/hogql/transforms/preaggregated_table_transformation.py
+++ b/posthog/hogql/transforms/preaggregated_table_transformation.py
@@ -36,7 +36,7 @@ from posthog.hogql.helpers.timestamp_visitor import (
)
from posthog.hogql.visitor import CloningVisitor
-from posthog.hogql_queries.web_analytics.pre_aggregated.properties import (
+from products.web_analytics.backend.hogql_queries.pre_aggregated.properties import (
EVENT_PROPERTY_TO_FIELD,
SESSION_PROPERTY_TO_FIELD,
)
diff --git a/posthog/hogql/transforms/test/test_preaggregated_table_transformation.py b/posthog/hogql/transforms/test/test_preaggregated_table_transformation.py
index f00a83005a1b..924b376f0e65 100644
--- a/posthog/hogql/transforms/test/test_preaggregated_table_transformation.py
+++ b/posthog/hogql/transforms/test/test_preaggregated_table_transformation.py
@@ -21,11 +21,12 @@ from posthog.hogql.transforms.preaggregated_table_transformation import (
from posthog.clickhouse.client import sync_execute
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
-from posthog.hogql_queries.web_analytics.pre_aggregated.properties import (
+from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
+
+from products.web_analytics.backend.hogql_queries.pre_aggregated.properties import (
EVENT_PROPERTY_TO_FIELD,
SESSION_PROPERTY_TO_FIELD,
)
-from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
class TestPreaggregatedTableTransformation(BaseTest, QueryMatchingTest):
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 4a4890d20c05..272d1e664e70 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -529,7 +529,7 @@ def get_query_runner(
limit_context=limit_context,
)
if kind == "WebOverviewQuery":
- from .web_analytics.web_overview import WebOverviewQueryRunner
+ from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
return WebOverviewQueryRunner(
query=query,
@@ -540,7 +540,7 @@ def get_query_runner(
)
if kind == "WebStatsTableQuery":
- from .web_analytics.stats_table import WebStatsTableQueryRunner
+ from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
return WebStatsTableQueryRunner(
query=query,
@@ -551,7 +551,7 @@ def get_query_runner(
)
if kind == "WebGoalsQuery":
- from .web_analytics.web_goals import WebGoalsQueryRunner
+ from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner
return WebGoalsQueryRunner(
query=query,
@@ -562,7 +562,7 @@ def get_query_runner(
)
if kind == "WebNotableChangesQuery":
- from .web_analytics.notable_changes import WebNotableChangesQueryRunner
+ from products.web_analytics.backend.hogql_queries.notable_changes import WebNotableChangesQueryRunner
return WebNotableChangesQueryRunner(
query=query,
@@ -573,7 +573,7 @@ def get_query_runner(
)
if kind == "WebTrendsQuery":
- from .web_analytics.web_trends_query_runner import WebTrendsQueryRunner
+ from products.web_analytics.backend.hogql_queries.web_trends_query_runner import WebTrendsQueryRunner
return WebTrendsQueryRunner(
query=query,
@@ -584,7 +584,7 @@ def get_query_runner(
)
if kind == "WebExternalClicksTableQuery":
- from .web_analytics.external_clicks import WebExternalClicksTableQueryRunner
+ from products.web_analytics.backend.hogql_queries.external_clicks import WebExternalClicksTableQueryRunner
return WebExternalClicksTableQueryRunner(
query=query,
@@ -595,7 +595,9 @@ def get_query_runner(
)
if kind == "WebVitalsPathBreakdownQuery":
- from .web_analytics.web_vitals_path_breakdown import WebVitalsPathBreakdownQueryRunner
+ from products.web_analytics.backend.hogql_queries.web_vitals_path_breakdown import (
+ WebVitalsPathBreakdownQueryRunner,
+ )
return WebVitalsPathBreakdownQueryRunner(
query=query,
@@ -603,7 +605,7 @@ def get_query_runner(
)
if kind == "WebPageURLSearchQuery":
- from .web_analytics.page_url_search_query_runner import PageUrlSearchQueryRunner
+ from products.web_analytics.backend.hogql_queries.page_url_search_query_runner import PageUrlSearchQueryRunner
return PageUrlSearchQueryRunner(
query=query,
@@ -614,7 +616,9 @@ def get_query_runner(
)
if kind == "SessionAttributionExplorerQuery":
- from .web_analytics.session_attribution_explorer_query_runner import SessionAttributionExplorerQueryRunner
+ from products.web_analytics.backend.hogql_queries.session_attribution_explorer_query_runner import (
+ SessionAttributionExplorerQueryRunner,
+ )
return SessionAttributionExplorerQueryRunner(
query=query,
diff --git a/posthog/management/commands/generate_bot_demo_data.py b/posthog/management/commands/generate_bot_demo_data.py
index fdf5944a7b68..b79a5af1ba62 100644
--- a/posthog/management/commands/generate_bot_demo_data.py
+++ b/posthog/management/commands/generate_bot_demo_data.py
@@ -14,10 +14,11 @@ from posthog.demo.products.hedgebox.taxonomy import (
URL_PRICING,
URL_SIGNUP,
)
-from posthog.hogql_queries.web_analytics.bot_ua_fixtures import BOT_USER_AGENTS
from posthog.models import Team
from posthog.models.event.util import create_event
+from products.web_analytics.backend.hogql_queries.bot_ua_fixtures import BOT_USER_AGENTS
+
# Crawl patterns per bot category - bots visit different pages based on their purpose
CRAWL_PATTERNS: dict[str, list[str]] = {
"ai_crawler": [
diff --git a/posthog/migrations/1176_migrate_web_analytics_models.py b/posthog/migrations/1176_migrate_web_analytics_models.py
new file mode 100644
index 000000000000..cae1fcea5841
--- /dev/null
+++ b/posthog/migrations/1176_migrate_web_analytics_models.py
@@ -0,0 +1,88 @@
+# Generated by Django 5.2.14 on 2026-05-20 15:31
+
+from django.db import migrations
+
+MODELS_TO_MOVE = ("savedheatmap", "heatmapsnapshot", "webanalyticsfilterpreset")
+
+
+def _move_content_types(apps, schema_editor, from_label, to_label):
+ """Move ContentTypes between apps, handling duplicates idempotently.
+
+ If the target (app_label, model) already exists (e.g., Django auto-created
+ it before migration ran, or a prior failed attempt), merges permissions
+ onto the target and deletes the source to avoid unique constraint violations.
+
+ Uses schema_editor.connection.alias for multi-DB safety.
+ """
+ db_alias = schema_editor.connection.alias
+ ContentType = apps.get_model("contenttypes", "ContentType")
+ Permission = apps.get_model("auth", "Permission")
+
+ for model_name in MODELS_TO_MOVE:
+ source = ContentType.objects.using(db_alias).filter(app_label=from_label, model=model_name).first()
+ target = ContentType.objects.using(db_alias).filter(app_label=to_label, model=model_name).first()
+
+ if source and target:
+ Permission.objects.using(db_alias).filter(content_type=source).update(content_type=target)
+ source.delete(using=db_alias)
+ elif source:
+ source.app_label = to_label
+ source.save(using=db_alias)
+
+
+def update_content_types(apps, schema_editor):
+ _move_content_types(apps, schema_editor, "posthog", "web_analytics")
+
+
+def reverse_content_types(apps, schema_editor):
+ _move_content_types(apps, schema_editor, "web_analytics", "posthog")
+
+
+class Migration(migrations.Migration):
+ dependencies = [("posthog", "1175_drop_alertconfiguration_is_calculating_column")]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AlterUniqueTogether(
+ name="savedheatmap",
+ unique_together=None,
+ ),
+ migrations.RemoveField(
+ model_name="savedheatmap",
+ name="created_by",
+ ),
+ migrations.RemoveField(
+ model_name="savedheatmap",
+ name="team",
+ ),
+ migrations.AlterUniqueTogether(
+ name="webanalyticsfilterpreset",
+ unique_together=None,
+ ),
+ migrations.RemoveField(
+ model_name="webanalyticsfilterpreset",
+ name="created_by",
+ ),
+ migrations.RemoveField(
+ model_name="webanalyticsfilterpreset",
+ name="last_modified_by",
+ ),
+ migrations.RemoveField(
+ model_name="webanalyticsfilterpreset",
+ name="team",
+ ),
+ migrations.DeleteModel(
+ name="HeatmapSnapshot",
+ ),
+ migrations.DeleteModel(
+ name="SavedHeatmap",
+ ),
+ migrations.DeleteModel(
+ name="WebAnalyticsFilterPreset",
+ ),
+ ],
+ database_operations=[],
+ ),
+ migrations.RunPython(update_content_types, reverse_content_types),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 8581b368b8b6..3f671bfe9ff6 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1175_drop_alertconfiguration_is_calculating_column
+1176_migrate_web_analytics_models
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 9735516f90dc..c18c3bff237d 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -47,7 +47,6 @@ from .filters import Filter, RetentionFilter
from .group import Group
from .group_usage_metric import GroupUsageMetric
from .group_type_mapping import GroupTypeMapping
-from .heatmap_saved import SavedHeatmap, HeatmapSnapshot
from .host_definition import HostDefinition
from .hog_flow import HogFlow
from .hog_functions import HogFunction
@@ -97,7 +96,6 @@ from .repo_routing_rule import RepoRoutingRule
from .user_repo_preference import UserRepoPreference
from .user_scene_personalisation import UserScenePersonalisation
from .user_home_settings import UserHomeSettings
-from .web_analytics_filter_preset import WebAnalyticsFilterPreset
from .oauth import (
CIMDVerificationToken,
OAuthAccessToken,
@@ -160,7 +158,6 @@ __all__ = [
"Group",
"GroupUsageMetric",
"GroupTypeMapping",
- "HeatmapSnapshot",
"HealthIssue",
"HogFlow",
"HogFunction",
@@ -213,7 +210,6 @@ __all__ = [
"RemoteConfig",
"ResourceTransfer",
"EventSchema",
- "SavedHeatmap",
"SchemaPropertyGroup",
"SchemaPropertyGroupProperty",
"SessionRecording",
@@ -240,7 +236,6 @@ __all__ = [
"UserIntegration",
"UserPushToken",
"ScheduledChange",
- "WebAnalyticsFilterPreset",
"Comment",
# Deprecated models here for backwards compatibility
"Prompt",
diff --git a/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py b/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py
index 69389fc4c4fa..5d21e9ffb493 100644
--- a/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py
+++ b/posthog/models/web_preaggregated/test_web_pre_aggregated_timezones.py
@@ -6,20 +6,23 @@ from parameterized import parameterized
from posthog.schema import DateRange, HogQLQueryModifiers, WebStatsBreakdown, WebStatsTableQuery
from posthog.clickhouse.client.execute import sync_execute
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
-from posthog.hogql_queries.web_analytics.test.test_web_stats_table import FloatAwareTestCase
-from posthog.hogql_queries.web_analytics.test.web_preaggregated_test_base import WebAnalyticsPreAggregatedTestBase
from posthog.models import Person, Team
from posthog.models.utils import uuid7
from posthog.models.web_preaggregated.sql import WEB_BOUNCES_INSERT_SQL, WEB_STATS_INSERT_SQL
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.test.test_web_stats_table import FloatAwareTestCase
+from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_base import (
+ WebAnalyticsPreAggregatedTestBase,
+)
+
@snapshot_clickhouse_queries
class TestTimezonePreAggregatedIntegration(WebAnalyticsPreAggregatedTestBase, FloatAwareTestCase):
def setUp(self):
super().setUp()
patcher = patch(
- "posthog.hogql_queries.web_analytics.stats_table.is_web_analytics_events_prefilter_team",
+ "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
return_value=False,
)
patcher.start()
diff --git a/posthog/models/web_preaggregated/test_web_preaggregated_sql.py b/posthog/models/web_preaggregated/test_web_preaggregated_sql.py
index 6c4edc61e1f7..62621b56e88e 100644
--- a/posthog/models/web_preaggregated/test_web_preaggregated_sql.py
+++ b/posthog/models/web_preaggregated/test_web_preaggregated_sql.py
@@ -3,7 +3,6 @@ from freezegun import freeze_time
from posthog.test.base import _create_event, _create_person
from posthog.clickhouse.client.execute import sync_execute
-from posthog.hogql_queries.web_analytics.test.web_preaggregated_test_base import WebAnalyticsPreAggregatedTestBase
from posthog.models.utils import uuid7
from posthog.models.web_preaggregated.sql import (
DROP_PARTITION_SQL,
@@ -20,6 +19,10 @@ from posthog.models.web_preaggregated.sql import (
get_web_stats_insert_columns,
)
+from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_base import (
+ WebAnalyticsPreAggregatedTestBase,
+)
+
class TestPartitionDropSQL:
def test_drop_partition_daily_format(self):
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 12a3ecf682f2..a4f5900838a8 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -75,6 +75,7 @@ PRODUCTS_APPS = [
"products.warehouse_sources_queue.backend.apps.WarehouseSourcesQueueConfig",
"products.business_knowledge.backend.apps.BusinessKnowledgeConfig",
"products.deployments.backend.apps.DeploymentsConfig",
+ "products.web_analytics.backend.apps.WebAnalyticsConfig",
"products.warehouse_sources.backend.apps.WarehouseSourcesConfig",
"products.data_tools.backend.apps.DataToolsConfig",
"products.alerts.backend.apps.AlertsConfig",
diff --git a/posthog/tasks/__init__.py b/posthog/tasks/__init__.py
index a70a2bc3f9e9..a60088f9741a 100644
--- a/posthog/tasks/__init__.py
+++ b/posthog/tasks/__init__.py
@@ -11,7 +11,6 @@ from . import (
exporter,
feature_flags,
health_checks,
- heatmap_screenshot,
hog_flows,
hog_functions,
integrations,
@@ -42,7 +41,6 @@ __all__ = [
"exporter",
"feature_flags",
"health_checks",
- "heatmap_screenshot",
"hog_flows",
"hog_functions",
"integrations",
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 4359bb7f7f66..da563b1f6d09 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -66,7 +66,6 @@
'posthog.tasks.feature_flags.update_team_flags_cache',
'posthog.tasks.feature_flags.update_team_service_flags_cache',
'posthog.tasks.health_checks.evaluate_health_check_for_team',
- 'posthog.tasks.heatmap_screenshot.generate_heatmap_screenshot',
'posthog.tasks.hog_flows.refresh_affected_hog_flows',
'posthog.tasks.hog_functions.refresh_affected_hog_functions',
'posthog.tasks.hog_functions.sync_hog_function_templates_task',
diff --git a/posthog/test/base.py b/posthog/test/base.py
index ed307448531f..893794ee4b2d 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -1913,7 +1913,7 @@ def snapshot_hogql_queries(fn_or_class):
# Add patches for modules that import execute_hogql_query directly
try:
- from posthog.hogql_queries.web_analytics import web_overview
+ from products.web_analytics.backend.hogql_queries import web_overview
if hasattr(web_overview, "execute_hogql_query"):
patches.append(patch.object(web_overview, "execute_hogql_query", capture_module_execute))
@@ -1921,7 +1921,7 @@ def snapshot_hogql_queries(fn_or_class):
pass
try:
- from posthog.hogql_queries.web_analytics import stats_table
+ from products.web_analytics.backend.hogql_queries import stats_table
if hasattr(stats_table, "execute_hogql_query"):
patches.append(patch.object(stats_table, "execute_hogql_query", capture_module_execute))
diff --git a/products/ruff.toml b/products/ruff.toml
index 61aca47632ed..62795c9e794b 100644
--- a/products/ruff.toml
+++ b/products/ruff.toml
@@ -42,6 +42,7 @@ extend-select = ["ANN001", "ANN201", "ANN202", "ANN204"]
"surveys/backend/**" = ["ANN"]
"tasks/backend/**" = ["ANN"]
"visual_review/backend/**" = ["ANN"]
+"web_analytics/backend/**" = ["ANN"]
"warehouse_sources/backend/**" = ["ANN"]
"workflows/backend/**" = ["ANN"]
diff --git a/products/web_analytics/backend/api/__init__.py b/products/web_analytics/backend/api/__init__.py
new file mode 100644
index 000000000000..67ac57c93ea0
--- /dev/null
+++ b/products/web_analytics/backend/api/__init__.py
@@ -0,0 +1,3 @@
+from .api import WebAnalyticsViewSet
+
+__all__ = ["WebAnalyticsViewSet"]
diff --git a/products/web_analytics/backend/api.py b/products/web_analytics/backend/api/api.py
similarity index 100%
rename from products/web_analytics/backend/api.py
rename to products/web_analytics/backend/api/api.py
diff --git a/posthog/heatmaps/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.py
similarity index 99%
rename from posthog/heatmaps/heatmaps_api.py
rename to products/web_analytics/backend/api/heatmaps_api.py
index b753edb51037..238b1021c32a 100644
--- a/posthog/heatmaps/heatmaps_api.py
+++ b/products/web_analytics/backend/api/heatmaps_api.py
@@ -25,10 +25,8 @@ from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
from posthog.auth import ExportRendererAuthentication
from posthog.clickhouse.query_tagging import Feature, tag_queries
-from posthog.heatmaps.heatmaps_utils import DEFAULT_TARGET_WIDTHS
from posthog.models import User
from posthog.models.activity_logging.activity_log import Detail, log_activity
-from posthog.models.heatmap_saved import HeatmapSnapshot, SavedHeatmap
from posthog.rate_limit import (
AIBurstRateThrottle,
AISustainedRateThrottle,
@@ -36,9 +34,12 @@ from posthog.rate_limit import (
ClickHouseSustainedRateThrottle,
)
from posthog.security.url_validation import is_url_allowed
-from posthog.tasks.heatmap_screenshot import generate_heatmap_screenshot
from posthog.utils import relative_date_parse_with_delta_mapping
+from products.web_analytics.backend.api.heatmaps_utils import DEFAULT_TARGET_WIDTHS
+from products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmap
+from products.web_analytics.backend.tasks.heatmap_screenshot import generate_heatmap_screenshot
+
STALE_PROCESSING_THRESHOLD = timedelta(minutes=10)
DEFAULT_QUERY = """
diff --git a/posthog/heatmaps/heatmaps_utils.py b/products/web_analytics/backend/api/heatmaps_utils.py
similarity index 100%
rename from posthog/heatmaps/heatmaps_utils.py
rename to products/web_analytics/backend/api/heatmaps_utils.py
diff --git a/posthog/api/web_analytics_filter_preset.py b/products/web_analytics/backend/api/web_analytics_filter_preset.py
similarity index 98%
rename from posthog/api/web_analytics_filter_preset.py
rename to products/web_analytics/backend/api/web_analytics_filter_preset.py
index e4c454a66043..559cc6b5abe2 100644
--- a/posthog/api/web_analytics_filter_preset.py
+++ b/products/web_analytics/backend/api/web_analytics_filter_preset.py
@@ -13,7 +13,8 @@ from posthog.api.shared import UserBasicSerializer
from posthog.models import User
from posthog.models.activity_logging.activity_log import Change, Detail, changes_between, log_activity
from posthog.models.utils import UUIDT
-from posthog.models.web_analytics_filter_preset import WebAnalyticsFilterPreset
+
+from products.web_analytics.backend.models import WebAnalyticsFilterPreset
def log_preset_activity(
diff --git a/products/web_analytics/backend/apps.py b/products/web_analytics/backend/apps.py
new file mode 100644
index 000000000000..8ac1189359d9
--- /dev/null
+++ b/products/web_analytics/backend/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class WebAnalyticsConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.web_analytics.backend"
+ label = "web_analytics"
diff --git a/posthog/hogql_queries/web_analytics/__init__.py b/products/web_analytics/backend/hogql_queries/__init__.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/__init__.py
rename to products/web_analytics/backend/hogql_queries/__init__.py
diff --git a/posthog/hogql_queries/web_analytics/bot_definitions.py b/products/web_analytics/backend/hogql_queries/bot_definitions.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/bot_definitions.py
rename to products/web_analytics/backend/hogql_queries/bot_definitions.py
diff --git a/posthog/hogql_queries/web_analytics/bot_ua_fixtures.py b/products/web_analytics/backend/hogql_queries/bot_ua_fixtures.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/bot_ua_fixtures.py
rename to products/web_analytics/backend/hogql_queries/bot_ua_fixtures.py
diff --git a/posthog/hogql_queries/web_analytics/ctes.py b/products/web_analytics/backend/hogql_queries/ctes.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/ctes.py
rename to products/web_analytics/backend/hogql_queries/ctes.py
diff --git a/posthog/hogql_queries/web_analytics/events_prefilter.py b/products/web_analytics/backend/hogql_queries/events_prefilter.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/events_prefilter.py
rename to products/web_analytics/backend/hogql_queries/events_prefilter.py
diff --git a/posthog/hogql_queries/web_analytics/external/__init__.py b/products/web_analytics/backend/hogql_queries/external/__init__.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/external/__init__.py
rename to products/web_analytics/backend/hogql_queries/external/__init__.py
diff --git a/posthog/hogql_queries/web_analytics/external/summary_query_runner.py b/products/web_analytics/backend/hogql_queries/external/summary_query_runner.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/external/summary_query_runner.py
rename to products/web_analytics/backend/hogql_queries/external/summary_query_runner.py
diff --git a/posthog/hogql_queries/web_analytics/external/test/__init__.py b/products/web_analytics/backend/hogql_queries/external/test/__init__.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/external/test/__init__.py
rename to products/web_analytics/backend/hogql_queries/external/test/__init__.py
diff --git a/posthog/hogql_queries/web_analytics/external/test/test_summary_query_runner.py b/products/web_analytics/backend/hogql_queries/external/test/test_summary_query_runner.py
similarity index 94%
rename from posthog/hogql_queries/web_analytics/external/test/test_summary_query_runner.py
rename to products/web_analytics/backend/hogql_queries/external/test/test_summary_query_runner.py
index 3baafd43fb53..75455779845e 100644
--- a/posthog/hogql_queries/web_analytics/external/test/test_summary_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/external/test/test_summary_query_runner.py
@@ -9,7 +9,7 @@ from posthog.hogql.database.schema.web_analytics_s3 import (
create_s3_web_stats_table,
)
-from posthog.hogql_queries.web_analytics.external.summary_query_runner import (
+from products.web_analytics.backend.hogql_queries.external.summary_query_runner import (
QueryResult,
WebAnalyticsExternalSummaryQueryRunner,
)
@@ -23,7 +23,7 @@ class TestWebAnalyticsExternalSummaryQueryRunner(APIBaseTest):
properties=[],
)
- @patch("posthog.hogql_queries.web_analytics.external.summary_query_runner.chdb")
+ @patch("products.web_analytics.backend.hogql_queries.external.summary_query_runner.chdb")
def test_calculate_success(self, mock_chdb):
self.team.organization.is_platform = True
self.team.organization.save()
@@ -43,7 +43,7 @@ class TestWebAnalyticsExternalSummaryQueryRunner(APIBaseTest):
assert response.data["bounce_rate"] == 0.5 # 25/50
assert mock_chdb.query.call_count == 2
- @patch("posthog.hogql_queries.web_analytics.external.summary_query_runner.chdb")
+ @patch("products.web_analytics.backend.hogql_queries.external.summary_query_runner.chdb")
def test_calculate_platform_access_required(self, mock_chdb):
self.team.organization.is_platform = False
self.team.organization.save()
@@ -56,7 +56,7 @@ class TestWebAnalyticsExternalSummaryQueryRunner(APIBaseTest):
assert response.error.code == "platform_access_required"
assert mock_chdb.query.call_count == 0
- @patch("posthog.hogql_queries.web_analytics.external.summary_query_runner.chdb")
+ @patch("products.web_analytics.backend.hogql_queries.external.summary_query_runner.chdb")
def test_calculate_query_execution_failed(self, mock_chdb):
self.team.organization.is_platform = True
self.team.organization.save()
@@ -70,7 +70,7 @@ class TestWebAnalyticsExternalSummaryQueryRunner(APIBaseTest):
assert response.error is not None
assert response.error.code == "query_execution_failed"
- @patch("posthog.hogql_queries.web_analytics.external.summary_query_runner.chdb")
+ @patch("products.web_analytics.backend.hogql_queries.external.summary_query_runner.chdb")
def test_calculate_empty_results(self, mock_chdb):
self.team.organization.is_platform = True
self.team.organization.save()
@@ -86,7 +86,7 @@ class TestWebAnalyticsExternalSummaryQueryRunner(APIBaseTest):
assert response.data["total_pageviews"] == 0
assert response.data["bounce_rate"] == 0.0
- @patch("posthog.hogql_queries.web_analytics.external.summary_query_runner.chdb")
+ @patch("products.web_analytics.backend.hogql_queries.external.summary_query_runner.chdb")
def test_bounce_rate_calculation_edge_cases(self, mock_chdb):
self.team.organization.is_platform = True
self.team.organization.save()
@@ -114,7 +114,7 @@ class TestWebAnalyticsExternalSummaryQueryRunner(APIBaseTest):
runner = WebAnalyticsExternalSummaryQueryRunner(query=self.query, team=self.team)
assert runner.can_use_s3_tables is False
- @patch("posthog.hogql_queries.web_analytics.external.summary_query_runner.build_function_call")
+ @patch("products.web_analytics.backend.hogql_queries.external.summary_query_runner.build_function_call")
def test_build_s3_table_functions(self, mock_build_function_call):
mock_build_function_call.return_value = "s3('url', 'format', 'structure')"
diff --git a/posthog/hogql_queries/web_analytics/external_clicks.py b/products/web_analytics/backend/hogql_queries/external_clicks.py
similarity index 97%
rename from posthog/hogql_queries/web_analytics/external_clicks.py
rename to products/web_analytics/backend/hogql_queries/external_clicks.py
index 7bbd99c7b5fc..0ebc203f9e46 100644
--- a/posthog/hogql_queries/web_analytics/external_clicks.py
+++ b/products/web_analytics/backend/hogql_queries/external_clicks.py
@@ -15,7 +15,8 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.property import property_to_expr
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
-from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner, map_columns
+
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner, map_columns
class WebExternalClicksTableQueryRunner(WebAnalyticsQueryRunner[WebExternalClicksTableQueryResponse]):
diff --git a/posthog/hogql_queries/web_analytics/metrics.py b/products/web_analytics/backend/hogql_queries/metrics.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/metrics.py
rename to products/web_analytics/backend/hogql_queries/metrics.py
diff --git a/posthog/hogql_queries/web_analytics/notable_changes.py b/products/web_analytics/backend/hogql_queries/notable_changes.py
similarity index 97%
rename from posthog/hogql_queries/web_analytics/notable_changes.py
rename to products/web_analytics/backend/hogql_queries/notable_changes.py
index 0725279f1bd8..188d4e0aaf5d 100644
--- a/posthog/hogql_queries/web_analytics/notable_changes.py
+++ b/products/web_analytics/backend/hogql_queries/notable_changes.py
@@ -16,9 +16,11 @@ from posthog.hogql.database.schema.channel_type import wrap_with_null_if_empty
from posthog.hogql.property import property_to_expr
from posthog.hogql.query import execute_hogql_query
-from posthog.hogql_queries.web_analytics.pre_aggregated.properties import STATS_TABLE_SUPPORTED_FILTERS
-from posthog.hogql_queries.web_analytics.pre_aggregated.query_builder import WebAnalyticsPreAggregatedQueryBuilder
-from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner
+from products.web_analytics.backend.hogql_queries.pre_aggregated.properties import STATS_TABLE_SUPPORTED_FILTERS
+from products.web_analytics.backend.hogql_queries.pre_aggregated.query_builder import (
+ WebAnalyticsPreAggregatedQueryBuilder,
+)
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner
logger = structlog.get_logger(__name__)
diff --git a/posthog/hogql_queries/web_analytics/page_url_search_query_runner.py b/products/web_analytics/backend/hogql_queries/page_url_search_query_runner.py
similarity index 96%
rename from posthog/hogql_queries/web_analytics/page_url_search_query_runner.py
rename to products/web_analytics/backend/hogql_queries/page_url_search_query_runner.py
index 39dc386fb8f2..a76032222e2e 100644
--- a/posthog/hogql_queries/web_analytics/page_url_search_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/page_url_search_query_runner.py
@@ -9,7 +9,7 @@ from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.query import execute_hogql_query
-from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner
PAGE_URL_SEARCH_DEFAULT_LIMIT = 100
diff --git a/posthog/hogql_queries/web_analytics/pre_aggregated/properties.py b/products/web_analytics/backend/hogql_queries/pre_aggregated/properties.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/pre_aggregated/properties.py
rename to products/web_analytics/backend/hogql_queries/pre_aggregated/properties.py
diff --git a/posthog/hogql_queries/web_analytics/pre_aggregated/property_transformer.py b/products/web_analytics/backend/hogql_queries/pre_aggregated/property_transformer.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/pre_aggregated/property_transformer.py
rename to products/web_analytics/backend/hogql_queries/pre_aggregated/property_transformer.py
diff --git a/posthog/hogql_queries/web_analytics/pre_aggregated/query_builder.py b/products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/pre_aggregated/query_builder.py
rename to products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.py
index dceb73a84e87..ee737283f774 100644
--- a/posthog/hogql_queries/web_analytics/pre_aggregated/query_builder.py
+++ b/products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.py
@@ -5,7 +5,7 @@ from posthog.hogql import ast
from posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_expr
from posthog.hogql.property import property_to_expr
-from posthog.hogql_queries.web_analytics.pre_aggregated.property_transformer import (
+from products.web_analytics.backend.hogql_queries.pre_aggregated.property_transformer import (
ChannelTypeReplacer,
PreAggregatedPropertyTransformer,
)
diff --git a/posthog/hogql_queries/web_analytics/query_constants/__init__.py b/products/web_analytics/backend/hogql_queries/query_constants/__init__.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/query_constants/__init__.py
rename to products/web_analytics/backend/hogql_queries/query_constants/__init__.py
diff --git a/posthog/hogql_queries/web_analytics/query_constants/stats_table_queries.py b/products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/query_constants/stats_table_queries.py
rename to products/web_analytics/backend/hogql_queries/query_constants/stats_table_queries.py
diff --git a/posthog/hogql_queries/web_analytics/session_attribution_explorer_query_runner.py b/products/web_analytics/backend/hogql_queries/session_attribution_explorer_query_runner.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/session_attribution_explorer_query_runner.py
rename to products/web_analytics/backend/hogql_queries/session_attribution_explorer_query_runner.py
diff --git a/posthog/hogql_queries/web_analytics/stats_table.py b/products/web_analytics/backend/hogql_queries/stats_table.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/stats_table.py
rename to products/web_analytics/backend/hogql_queries/stats_table.py
index 0110cba227e5..126ded3dc7bb 100644
--- a/posthog/hogql_queries/web_analytics/stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table.py
@@ -26,9 +26,11 @@ from posthog.hogql.property import (
)
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
-from posthog.hogql_queries.web_analytics.events_prefilter import PrefilterHogQLHasMorePaginator
-from posthog.hogql_queries.web_analytics.stats_table_pre_aggregated import StatsTablePreAggregatedQueryBuilder
-from posthog.hogql_queries.web_analytics.stats_table_strategies import (
+from posthog.settings.data_stores import is_web_analytics_events_prefilter_team
+
+from products.web_analytics.backend.hogql_queries.events_prefilter import PrefilterHogQLHasMorePaginator
+from products.web_analytics.backend.hogql_queries.stats_table_pre_aggregated import StatsTablePreAggregatedQueryBuilder
+from products.web_analytics.backend.hogql_queries.stats_table_strategies import (
ChannelTypeStrategy,
FrustrationMetricsStrategy,
PathBounceAvgTimeStrategy,
@@ -36,8 +38,7 @@ from posthog.hogql_queries.web_analytics.stats_table_strategies import (
SimpleBreakdownStrategy,
StatsTableQueryStrategy,
)
-from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner, map_columns
-from posthog.settings.data_stores import is_web_analytics_events_prefilter_team
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner, map_columns
BREAKDOWN_NULL_DISPLAY = "(none)"
BREAKDOWN_REFERRER_PREFIX = "referrer:"
diff --git a/posthog/hogql_queries/web_analytics/stats_table_pre_aggregated.py b/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/stats_table_pre_aggregated.py
rename to products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py
index 89f1ae0c67f2..cc46e8056a91 100644
--- a/posthog/hogql_queries/web_analytics/stats_table_pre_aggregated.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py
@@ -11,11 +11,13 @@ from posthog.hogql.database.schema.channel_type import (
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.property import property_to_expr
-from posthog.hogql_queries.web_analytics.pre_aggregated.properties import STATS_TABLE_SUPPORTED_FILTERS
-from posthog.hogql_queries.web_analytics.pre_aggregated.query_builder import WebAnalyticsPreAggregatedQueryBuilder
+from products.web_analytics.backend.hogql_queries.pre_aggregated.properties import STATS_TABLE_SUPPORTED_FILTERS
+from products.web_analytics.backend.hogql_queries.pre_aggregated.query_builder import (
+ WebAnalyticsPreAggregatedQueryBuilder,
+)
if TYPE_CHECKING:
- from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
+ from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
WEB_ANALYTICS_STATS_TABLE_PRE_AGGREGATED_SUPPORTED_BREAKDOWNS = [
diff --git a/posthog/hogql_queries/web_analytics/stats_table_strategies.py b/products/web_analytics/backend/hogql_queries/stats_table_strategies.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/stats_table_strategies.py
rename to products/web_analytics/backend/hogql_queries/stats_table_strategies.py
index 4d02cf44d623..21c0fb5d5b0a 100644
--- a/posthog/hogql_queries/web_analytics/stats_table_strategies.py
+++ b/products/web_analytics/backend/hogql_queries/stats_table_strategies.py
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING
from posthog.hogql import ast
from posthog.hogql.parser import parse_expr, parse_select
-from posthog.hogql_queries.web_analytics.query_constants.stats_table_queries import (
+from products.web_analytics.backend.hogql_queries.query_constants.stats_table_queries import (
FRUSTRATION_METRICS_INNER_QUERY,
MAIN_INNER_QUERY,
PATH_BOUNCE_AND_AVG_TIME_QUERY,
@@ -14,7 +14,7 @@ from posthog.hogql_queries.web_analytics.query_constants.stats_table_queries imp
)
if TYPE_CHECKING:
- from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
+ from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
class StatsTableQueryStrategy(ABC):
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_active_hours_heatmap_query_runner.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_active_hours_heatmap_query_runner.ambr
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_active_hours_heatmap_query_runner.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_active_hours_heatmap_query_runner.ambr
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_external_clicks_table.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_external_clicks_table.ambr
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_external_clicks_table.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_external_clicks_table.ambr
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_notable_changes.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_notable_changes.ambr
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_notable_changes.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_notable_changes.ambr
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_sample_web_analytics_queries.hogql.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_sample_web_analytics_queries.hogql.ambr
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_sample_web_analytics_queries.hogql.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_sample_web_analytics_queries.hogql.ambr
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_session_attribution_explorer_query_runner.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_session_attribution_explorer_query_runner.ambr
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_session_attribution_explorer_query_runner.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_session_attribution_explorer_query_runner.ambr
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_traffic_type_snapshot.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_traffic_type_snapshot.ambr
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_traffic_type_snapshot.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_traffic_type_snapshot.ambr
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_goals.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.ambr
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_goals.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_goals.ambr
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_overview.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_overview.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_overview.ambr
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_pre_aggregated.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_pre_aggregated.ambr
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_pre_aggregated.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_pre_aggregated.ambr
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr
similarity index 89%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr
index 285b25a44433..0dc038be377d 100644
--- a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
+++ b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_stats_table.ambr
@@ -247,115 +247,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestWebStatsTableQueryRunner.test_avg_time_on_multiple_routes_and_users.2
- '''
- SELECT counts.breakdown_value AS `context.columns.breakdown_value`,
- tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,
- tuple(counts.views, counts.previous_views) AS `context.columns.views`,
- tuple(coalesce(time_on_page.avg_time_on_page, 0), coalesce(time_on_page.previous_avg_time_on_page, 0)) AS `context.columns.avg_time_on_page`,
- tuple(coalesce(bounce.bounce_rate, 0), coalesce(bounce.previous_bounce_rate, 0)) AS `context.columns.bounce_rate`,
- divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`
- FROM
- (SELECT breakdown_value AS breakdown_value,
- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,
- uniqIf(filtered_person_id, 0) AS previous_visitors,
- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,
- sumIf(filtered_pageview_count, 0) AS previous_views
- FROM
- (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,
- count() AS filtered_pageview_count,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.person_id,
- events.properties,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS counts
- LEFT JOIN
- (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,
- quantileIf(0.9)(least(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', ''), 'Float64'), 86400),
- and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS avg_time_on_page,
- quantileIf(0.9)(least(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', ''), 'Float64'), 86400),
- 0) AS previous_avg_time_on_page
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.properties,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$pageleave'), equals(events.event, '$screen')), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_pathname'), ''), 'null'), '^"|"$', '')), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', '')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)
- LEFT JOIN
- (SELECT breakdown_value AS breakdown_value,
- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,
- avgIf(is_bounce, 0) AS previous_bounce_rate
- FROM
- (SELECT events__session.`$entry_pathname` AS breakdown_value,
- any(events__session.`$is_bounce`) AS is_bounce,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,
- toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)
- WHERE isNotNull(counts.breakdown_value)
- ORDER BY `context.columns.visitors` DESC,
- `context.columns.views` DESC,
- `context.columns.breakdown_value` ASC
- LIMIT 101
- OFFSET 0 SETTINGS readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
# name: TestWebStatsTableQueryRunner.test_avg_time_on_page_multiple_users
'''
@@ -455,96 +346,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestWebStatsTableQueryRunner.test_avg_time_on_page_multiple_users.2
- '''
- SELECT counts.breakdown_value AS `context.columns.breakdown_value`,
- tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,
- tuple(counts.views, counts.previous_views) AS `context.columns.views`,
- tuple(coalesce(time_on_page.avg_time_on_page, 0), coalesce(time_on_page.previous_avg_time_on_page, 0)) AS `context.columns.avg_time_on_page`,
- tuple(coalesce(bounce.bounce_rate, 0), coalesce(bounce.previous_bounce_rate, 0)) AS `context.columns.bounce_rate`,
- divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`
- FROM
- (SELECT breakdown_value AS breakdown_value,
- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,
- uniqIf(filtered_person_id, 0) AS previous_visitors,
- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,
- sumIf(filtered_pageview_count, 0) AS previous_views
- FROM
- (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,
- count() AS filtered_pageview_count,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.person_id,
- events.properties,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS counts
- LEFT JOIN
- (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,
- quantileIf(0.9)(least(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', ''), 'Float64'), 86400),
- and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS avg_time_on_page,
- quantileIf(0.9)(least(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', ''), 'Float64'), 86400),
- 0) AS previous_avg_time_on_page
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.properties,
- events.timestamp
- FROM events
- LEFT JOIN
- (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,
- toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- WHERE and(equals(events.team_id, 99999), and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1))
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)
- WHERE isNotNull(counts.breakdown_value)
- ORDER BY `context.columns.visitors` DESC,
- `context.columns.views` DESC,
- `context.columns.breakdown_value` ASC
- LIMIT 101
- OFFSET 0 SETTINGS readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
# name: TestWebStatsTableQueryRunner.test_avg_time_on_page_one_user
'''
@@ -644,115 +445,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestWebStatsTableQueryRunner.test_avg_time_on_page_one_user.2
- '''
- SELECT counts.breakdown_value AS `context.columns.breakdown_value`,
- tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,
- tuple(counts.views, counts.previous_views) AS `context.columns.views`,
- tuple(coalesce(time_on_page.avg_time_on_page, 0), coalesce(time_on_page.previous_avg_time_on_page, 0)) AS `context.columns.avg_time_on_page`,
- tuple(coalesce(bounce.bounce_rate, 0), coalesce(bounce.previous_bounce_rate, 0)) AS `context.columns.bounce_rate`,
- divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`
- FROM
- (SELECT breakdown_value AS breakdown_value,
- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,
- uniqIf(filtered_person_id, 0) AS previous_visitors,
- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,
- sumIf(filtered_pageview_count, 0) AS previous_views
- FROM
- (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,
- count() AS filtered_pageview_count,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.person_id,
- events.properties,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS counts
- LEFT JOIN
- (SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,
- quantileIf(0.9)(least(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', ''), 'Float64'), 86400),
- and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))))) AS avg_time_on_page,
- quantileIf(0.9)(least(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', ''), 'Float64'), 86400),
- 0) AS previous_avg_time_on_page
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.properties,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$pageleave'), equals(events.event, '$screen')), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_pathname'), ''), 'null'), '^"|"$', '')), isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$prev_pageview_duration'), ''), 'null'), '^"|"$', '')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY breakdown_value) AS time_on_page ON equals(counts.breakdown_value, time_on_page.breakdown_value)
- LEFT JOIN
- (SELECT breakdown_value AS breakdown_value,
- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,
- avgIf(is_bounce, 0) AS previous_bounce_rate
- FROM
- (SELECT events__session.`$entry_pathname` AS breakdown_value,
- any(events__session.`$is_bounce`) AS is_bounce,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,
- toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)
- WHERE isNotNull(counts.breakdown_value)
- ORDER BY `context.columns.visitors` DESC,
- `context.columns.views` DESC,
- `context.columns.breakdown_value` ASC
- LIMIT 101
- OFFSET 0 SETTINGS readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate
'''
@@ -842,17 +534,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestWebStatsTableQueryRunner.test_bounce_rate.2
- '''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
- '''
-# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_one_user
'''
@@ -942,98 +623,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestWebStatsTableQueryRunner.test_bounce_rate_one_user.2
- '''
- SELECT counts.breakdown_value AS `context.columns.breakdown_value`,
- tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,
- tuple(counts.views, counts.previous_views) AS `context.columns.views`,
- tuple(bounce.bounce_rate, bounce.previous_bounce_rate) AS `context.columns.bounce_rate`,
- divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`
- FROM
- (SELECT breakdown_value AS breakdown_value,
- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,
- uniqIf(filtered_person_id, 0) AS previous_visitors,
- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,
- sumIf(filtered_pageview_count, 0) AS previous_views
- FROM
- (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,
- count() AS filtered_pageview_count,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.person_id,
- events.properties,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS counts
- LEFT JOIN
- (SELECT breakdown_value AS breakdown_value,
- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,
- avgIf(is_bounce, 0) AS previous_bounce_rate
- FROM
- (SELECT events__session.`$entry_pathname` AS breakdown_value,
- any(events__session.`$is_bounce`) AS is_bounce,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,
- toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)
- WHERE isNotNull(counts.breakdown_value)
- ORDER BY `context.columns.visitors` DESC,
- `context.columns.views` DESC,
- `context.columns.breakdown_value` ASC
- LIMIT 101
- OFFSET 0 SETTINGS readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_path_cleaning
'''
@@ -1123,98 +712,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestWebStatsTableQueryRunner.test_bounce_rate_path_cleaning.2
- '''
- SELECT counts.breakdown_value AS `context.columns.breakdown_value`,
- tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,
- tuple(counts.views, counts.previous_views) AS `context.columns.views`,
- tuple(bounce.bounce_rate, bounce.previous_bounce_rate) AS `context.columns.bounce_rate`,
- divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`
- FROM
- (SELECT breakdown_value AS breakdown_value,
- uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,
- uniqIf(filtered_person_id, 0) AS previous_visitors,
- sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,
- sumIf(filtered_pageview_count, 0) AS previous_views
- FROM
- (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,
- count() AS filtered_pageview_count,
- replaceRegexpAll(replaceRegexpAll(replaceRegexpAll(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', ''), '\\/a\\/\\d+', '/a/:id'), '\\/b\\/\\d+', '/b/:id'), '\\/c\\/\\d+', '/c/:id') AS breakdown_value,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.person_id,
- events.properties,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS counts
- LEFT JOIN
- (SELECT breakdown_value AS breakdown_value,
- avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,
- avgIf(is_bounce, 0) AS previous_bounce_rate
- FROM
- (SELECT replaceRegexpAll(replaceRegexpAll(replaceRegexpAll(events__session.`$entry_pathname`, '\\/a\\/\\d+', '/a/:id'), '\\/b\\/\\d+', '/b/:id'), '\\/c\\/\\d+', '/c/:id') AS breakdown_value,
- any(events__session.`$is_bounce`) AS is_bounce,
- events__session.session_id AS session_id,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,
- toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- WHERE and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)
- WHERE isNotNull(counts.breakdown_value)
- ORDER BY `context.columns.visitors` DESC,
- `context.columns.views` DESC,
- `context.columns.breakdown_value` ASC
- LIMIT 101
- OFFSET 0 SETTINGS readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_with_multiple_pathname_filters
'''
@@ -2078,65 +1575,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate.2
- '''
- SELECT breakdown_value AS `context.columns.breakdown_value`,
- tuple(uniq(filtered_person_id), NULL) AS `context.columns.visitors`,
- tuple(sum(filtered_pageview_count), NULL) AS `context.columns.views`,
- tuple(avg(is_bounce), NULL) AS `context.columns.bounce_rate`,
- divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`
- FROM
- (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,
- count() AS filtered_pageview_count,
- events__session.`$entry_pathname` AS breakdown_value,
- events__session.session_id AS session_id,
- any(events__session.`$is_bounce`) AS is_bounce,
- min(events__session.`$start_timestamp`) AS start_timestamp
- FROM
- (SELECT events.`$session_id_uuid`,
- events.distinct_id,
- events.event,
- events.person_id,
- events.timestamp
- FROM events
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2023-12-01'), lessOrEquals(toDate(events.timestamp), '2023-12-16'))) AS events
- LEFT JOIN
- (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,
- toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,
- min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
- LEFT OUTER JOIN
- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), 1)
- GROUP BY session_id,
- breakdown_value)
- GROUP BY `context.columns.breakdown_value`
- HAVING isNotNull(`context.columns.breakdown_value`)
- ORDER BY `context.columns.visitors` DESC,
- `context.columns.views` DESC,
- `context.columns.breakdown_value` ASC
- LIMIT 101
- OFFSET 0 SETTINGS readonly=2,
- max_execution_time=60,
- allow_experimental_object_type=1,
- max_ast_elements=4000000,
- max_expanded_ast_elements=4000000,
- max_bytes_before_external_group_by=0,
- transform_null_in=1,
- optimize_min_equality_disjunction_chain_length=4294967295,
- allow_experimental_join_condition=1,
- use_hive_partitioning=0
- '''
-# ---
# name: TestWebStatsTableQueryRunner.test_entry_bounce_rate_one_user
'''
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_vitals_path_breakdown.ambr b/products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_vitals_path_breakdown.ambr
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_vitals_path_breakdown.ambr
rename to products/web_analytics/backend/hogql_queries/test/__snapshots__/test_web_vitals_path_breakdown.ambr
diff --git a/posthog/hogql_queries/web_analytics/test/test_bot_definitions.py b/products/web_analytics/backend/hogql_queries/test/test_bot_definitions.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_bot_definitions.py
rename to products/web_analytics/backend/hogql_queries/test/test_bot_definitions.py
index 85892f7fd4b1..7e38cef4c415 100644
--- a/posthog/hogql_queries/web_analytics/test/test_bot_definitions.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_bot_definitions.py
@@ -1,6 +1,6 @@
import pytest
-from posthog.hogql_queries.web_analytics.bot_definitions import BOT_DEFINITIONS
+from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
class TestBotDefinitionsDataStructure:
diff --git a/posthog/hogql_queries/web_analytics/test/test_events_prefilter.py b/products/web_analytics/backend/hogql_queries/test/test_events_prefilter.py
similarity index 91%
rename from posthog/hogql_queries/web_analytics/test/test_events_prefilter.py
rename to products/web_analytics/backend/hogql_queries/test/test_events_prefilter.py
index a28a9ca9fdf0..0b87d063ed25 100644
--- a/posthog/hogql_queries/web_analytics/test/test_events_prefilter.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_events_prefilter.py
@@ -10,7 +10,7 @@ from posthog.schema import (
WebStatsTableQuery,
)
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
class TestEventsPrefilterTransformer(ClickhouseTestMixin, APIBaseTest):
@@ -22,7 +22,7 @@ class TestEventsPrefilterTransformer(ClickhouseTestMixin, APIBaseTest):
**query_kwargs,
)
with patch(
- "posthog.hogql_queries.web_analytics.stats_table.is_web_analytics_events_prefilter_team",
+ "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
return_value=True,
):
runner = WebStatsTableQueryRunner(team=self.team, query=query)
@@ -54,7 +54,7 @@ class TestEventsPrefilterTransformer(ClickhouseTestMixin, APIBaseTest):
includeBounceRate=True,
)
with patch(
- "posthog.hogql_queries.web_analytics.stats_table.is_web_analytics_events_prefilter_team",
+ "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
return_value=True,
):
runner = WebStatsTableQueryRunner(team=self.team, query=query)
@@ -78,7 +78,7 @@ class TestEventsPrefilterTransformer(ClickhouseTestMixin, APIBaseTest):
includeBounceRate=True,
)
with patch(
- "posthog.hogql_queries.web_analytics.stats_table.is_web_analytics_events_prefilter_team",
+ "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
return_value=True,
):
runner = WebStatsTableQueryRunner(team=self.team, query=query)
@@ -96,7 +96,7 @@ class TestEventsPrefilterTransformer(ClickhouseTestMixin, APIBaseTest):
includeBounceRate=True,
)
with patch(
- "posthog.hogql_queries.web_analytics.stats_table.is_web_analytics_events_prefilter_team",
+ "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
return_value=False,
):
runner = WebStatsTableQueryRunner(team=self.team, query=query)
@@ -113,7 +113,7 @@ class TestEventsPrefilterTransformer(ClickhouseTestMixin, APIBaseTest):
breakdownBy=WebStatsBreakdown.DEVICE_TYPE,
)
with patch(
- "posthog.hogql_queries.web_analytics.stats_table.is_web_analytics_events_prefilter_team",
+ "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
return_value=True,
):
runner = WebStatsTableQueryRunner(team=self.team, query=query)
diff --git a/posthog/hogql_queries/web_analytics/test/test_external_clicks_table.py b/products/web_analytics/backend/hogql_queries/test/test_external_clicks_table.py
similarity index 99%
rename from posthog/hogql_queries/web_analytics/test/test_external_clicks_table.py
rename to products/web_analytics/backend/hogql_queries/test/test_external_clicks_table.py
index fab51892cd48..d2efb334834a 100644
--- a/posthog/hogql_queries/web_analytics/test/test_external_clicks_table.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_external_clicks_table.py
@@ -18,9 +18,10 @@ from posthog.schema import (
WebExternalClicksTableQuery,
)
-from posthog.hogql_queries.web_analytics.external_clicks import WebExternalClicksTableQueryRunner
from posthog.models.utils import uuid7
+from products.web_analytics.backend.hogql_queries.external_clicks import WebExternalClicksTableQueryRunner
+
@snapshot_clickhouse_queries
class TestExternalClicksTableQueryRunner(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql_queries/web_analytics/test/test_notable_changes.py b/products/web_analytics/backend/hogql_queries/test/test_notable_changes.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_notable_changes.py
rename to products/web_analytics/backend/hogql_queries/test/test_notable_changes.py
index d691fbd2bdf1..acc41d7e887b 100644
--- a/posthog/hogql_queries/web_analytics/test/test_notable_changes.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_notable_changes.py
@@ -3,9 +3,10 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, s
from posthog.schema import CompareFilter, DateRange, HogQLQueryModifiers, WebNotableChangesQuery
-from posthog.hogql_queries.web_analytics.notable_changes import WebNotableChangesQueryRunner
from posthog.models.utils import uuid7
+from products.web_analytics.backend.hogql_queries.notable_changes import WebNotableChangesQueryRunner
+
@snapshot_clickhouse_queries
class TestWebNotableChangesQueryRunner(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql_queries/web_analytics/test/test_page_reports_avg_time.py b/products/web_analytics/backend/hogql_queries/test/test_page_reports_avg_time.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/test_page_reports_avg_time.py
rename to products/web_analytics/backend/hogql_queries/test/test_page_reports_avg_time.py
diff --git a/posthog/hogql_queries/web_analytics/test/test_page_url_search_query_runner.py b/products/web_analytics/backend/hogql_queries/test/test_page_url_search_query_runner.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_page_url_search_query_runner.py
rename to products/web_analytics/backend/hogql_queries/test/test_page_url_search_query_runner.py
index b8250c2dbd4a..880ee8ed554c 100644
--- a/posthog/hogql_queries/web_analytics/test/test_page_url_search_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_page_url_search_query_runner.py
@@ -3,9 +3,10 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _
from posthog.schema import DateRange, WebPageURLSearchQuery
-from posthog.hogql_queries.web_analytics.page_url_search_query_runner import PageUrlSearchQueryRunner
from posthog.models.utils import uuid7
+from products.web_analytics.backend.hogql_queries.page_url_search_query_runner import PageUrlSearchQueryRunner
+
class TestPageUrlSearchQueryRunner(ClickhouseTestMixin, APIBaseTest):
QUERY_TIMESTAMP = "2025-01-29"
diff --git a/posthog/hogql_queries/web_analytics/test/test_sample_web_analytics_queries.py b/products/web_analytics/backend/hogql_queries/test/test_sample_web_analytics_queries.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_sample_web_analytics_queries.py
rename to products/web_analytics/backend/hogql_queries/test/test_sample_web_analytics_queries.py
index ba759277231f..345f3b4678a1 100644
--- a/posthog/hogql_queries/web_analytics/test/test_sample_web_analytics_queries.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_sample_web_analytics_queries.py
@@ -38,8 +38,9 @@ from posthog.schema import (
)
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
+
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
@snapshot_hogql_queries
diff --git a/posthog/hogql_queries/web_analytics/test/test_session_attribution_explorer_query_runner.py b/products/web_analytics/backend/hogql_queries/test/test_session_attribution_explorer_query_runner.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_session_attribution_explorer_query_runner.py
rename to products/web_analytics/backend/hogql_queries/test/test_session_attribution_explorer_query_runner.py
index f114b1651846..b8b2444c98ae 100644
--- a/posthog/hogql_queries/web_analytics/test/test_session_attribution_explorer_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_session_attribution_explorer_query_runner.py
@@ -15,10 +15,11 @@ from posthog.schema import (
from posthog.hogql.constants import LimitContext
-from posthog.hogql_queries.web_analytics.session_attribution_explorer_query_runner import (
+from posthog.models.utils import uuid7
+
+from products.web_analytics.backend.hogql_queries.session_attribution_explorer_query_runner import (
SessionAttributionExplorerQueryRunner,
)
-from posthog.models.utils import uuid7
@snapshot_clickhouse_queries
diff --git a/posthog/hogql_queries/web_analytics/test/test_traffic_type_snapshot.py b/products/web_analytics/backend/hogql_queries/test/test_traffic_type_snapshot.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/test_traffic_type_snapshot.py
rename to products/web_analytics/backend/hogql_queries/test/test_traffic_type_snapshot.py
diff --git a/posthog/hogql_queries/web_analytics/test/test_trends_pre_aggregated_query_builder.py b/products/web_analytics/backend/hogql_queries/test/test_trends_pre_aggregated_query_builder.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_trends_pre_aggregated_query_builder.py
rename to products/web_analytics/backend/hogql_queries/test/test_trends_pre_aggregated_query_builder.py
index 1081a6fc1c56..2f960b695f02 100644
--- a/posthog/hogql_queries/web_analytics/test/test_trends_pre_aggregated_query_builder.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_trends_pre_aggregated_query_builder.py
@@ -10,7 +10,9 @@ from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.printer import prepare_and_print_ast
-from posthog.hogql_queries.web_analytics.trends_pre_aggregated_query_builder import TrendsPreAggregatedQueryBuilder
+from products.web_analytics.backend.hogql_queries.trends_pre_aggregated_query_builder import (
+ TrendsPreAggregatedQueryBuilder,
+)
class TestTrendsPreAggregatedQueryBuilder(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_analytics_cohort_filter.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_web_analytics_cohort_filter.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py
index 15074c4f47e3..787759d7411f 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_analytics_cohort_filter.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_cohort_filter.py
@@ -13,13 +13,13 @@ from posthog.schema import (
WebStatsTableQuery,
)
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
-from posthog.hogql_queries.web_analytics.web_goals import WebGoalsQueryRunner
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
from posthog.models import Cohort
from posthog.models.utils import uuid7
from products.actions.backend.models.action import Action
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
class TestWebAnalyticsCohortFilter(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_analytics_metrics.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
similarity index 87%
rename from posthog/hogql_queries/web_analytics/test/test_web_analytics_metrics.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
index ba8c6cf6c7c9..87ac060dcda4 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_analytics_metrics.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
@@ -7,12 +7,12 @@ from parameterized import parameterized
from posthog.schema import WebStatsBreakdown
-from posthog.hogql_queries.web_analytics.metrics import (
+from products.web_analytics.backend.hogql_queries.metrics import (
WEB_ANALYTICS_QUERY_COUNTER,
WEB_ANALYTICS_QUERY_DURATION,
WEB_ANALYTICS_QUERY_ERRORS,
)
-from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner
def _make_runner(
@@ -135,7 +135,8 @@ class TestWebAnalyticsMetrics(TestCase):
],
)
@patch(
- "posthog.hogql_queries.web_analytics.web_analytics_query_runner.get_query_tag_value", return_value="user_123"
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.get_query_tag_value",
+ return_value="user_123",
)
def test_successful_query_emits_correct_labels(
self, _name, query_kind, breakdown, conversion_goal, expected_labels, query_strategy, _mock_tag
@@ -156,7 +157,9 @@ class TestWebAnalyticsMetrics(TestCase):
label_filter = {**expected_labels, "used_preaggregated": "true"}
assert _get_counter_value(WEB_ANALYTICS_QUERY_COUNTER, label_filter) == 1.0
- @patch("posthog.hogql_queries.web_analytics.web_analytics_query_runner.get_query_tag_value", return_value=None)
+ @patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.get_query_tag_value", return_value=None
+ )
def test_error_query_increments_error_counter(self, _mock_tag):
runner = _make_runner(
query_kind="WebStatsTableQuery",
@@ -184,7 +187,8 @@ class TestWebAnalyticsMetrics(TestCase):
assert _get_counter_value(WEB_ANALYTICS_QUERY_COUNTER, counter_filter) == 1.0
@patch(
- "posthog.hogql_queries.web_analytics.web_analytics_query_runner.get_query_tag_value", return_value="user_456"
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.get_query_tag_value",
+ return_value="user_456",
)
def test_canonical_log_line_emitted(self, _mock_tag):
runner = _make_runner(query_kind="WebOverviewQuery", breakdown=None, properties=["fake_prop"])
@@ -194,7 +198,7 @@ class TestWebAnalyticsMetrics(TestCase):
with (
patch.object(WebAnalyticsQueryRunner.__mro__[1], "calculate", return_value=fake_response),
- patch("posthog.hogql_queries.web_analytics.web_analytics_query_runner.logger") as mock_logger,
+ patch("products.web_analytics.backend.hogql_queries.web_analytics_query_runner.logger") as mock_logger,
):
WebAnalyticsQueryRunner.calculate(runner)
@@ -215,7 +219,9 @@ class TestWebAnalyticsMetrics(TestCase):
assert kw["date_from"] == "2024-01-01"
assert kw["date_to"] == "2024-01-07"
- @patch("posthog.hogql_queries.web_analytics.web_analytics_query_runner.get_query_tag_value", return_value=None)
+ @patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.get_query_tag_value", return_value=None
+ )
def test_stats_table_log_line_includes_query_strategy(self, _mock_tag):
runner = _make_runner(query_kind="WebStatsTableQuery", breakdown=WebStatsBreakdown.PAGE)
cast(MagicMock, runner.query_strategy).return_value = "stats_table_path_bounce"
@@ -226,7 +232,7 @@ class TestWebAnalyticsMetrics(TestCase):
with (
patch.object(WebAnalyticsQueryRunner.__mro__[1], "calculate", return_value=fake_response),
- patch("posthog.hogql_queries.web_analytics.web_analytics_query_runner.logger") as mock_logger,
+ patch("products.web_analytics.backend.hogql_queries.web_analytics_query_runner.logger") as mock_logger,
):
WebAnalyticsQueryRunner.calculate(runner)
@@ -234,7 +240,9 @@ class TestWebAnalyticsMetrics(TestCase):
assert mock_logger.info.call_args[1]["clickhouse_query_type"] == "stats_table_path_bounce_query"
@parameterized.expand([(b.name, b) for b in WebStatsBreakdown])
- @patch("posthog.hogql_queries.web_analytics.web_analytics_query_runner.get_query_tag_value", return_value=None)
+ @patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.get_query_tag_value", return_value=None
+ )
def test_all_breakdown_values_produce_valid_labels(self, _name, breakdown, _mock_tag):
runner = _make_runner(breakdown=breakdown)
fake_response = MagicMock()
@@ -246,7 +254,9 @@ class TestWebAnalyticsMetrics(TestCase):
label_filter = {"breakdown": breakdown.value}
assert _get_counter_value(WEB_ANALYTICS_QUERY_COUNTER, label_filter) >= 1.0
- @patch("posthog.hogql_queries.web_analytics.web_analytics_query_runner.get_query_tag_value", return_value=None)
+ @patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.get_query_tag_value", return_value=None
+ )
def test_preaggregated_none_maps_to_unknown(self, _mock_tag):
runner = _make_runner()
fake_response = MagicMock()
@@ -263,7 +273,9 @@ class TestWebAnalyticsMetrics(TestCase):
== 1.0
)
- @patch("posthog.hogql_queries.web_analytics.web_analytics_query_runner.get_query_tag_value", return_value=None)
+ @patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.get_query_tag_value", return_value=None
+ )
def test_response_missing_preaggregated_attr_maps_to_unknown(self, _mock_tag):
runner = _make_runner()
fake_response = MagicMock(spec=[]) # empty spec = no attributes
@@ -279,7 +291,9 @@ class TestWebAnalyticsMetrics(TestCase):
== 1.0
)
- @patch("posthog.hogql_queries.web_analytics.web_analytics_query_runner.get_query_tag_value", return_value=None)
+ @patch(
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.get_query_tag_value", return_value=None
+ )
def test_strategy_resolution_failure_still_emits_error_metrics(self, _mock_tag):
runner = _make_runner(query_kind="WebStatsTableQuery", breakdown=WebStatsBreakdown.PAGE)
cast(MagicMock, runner.query_strategy).side_effect = RuntimeError("strategy boom")
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py
similarity index 95%
rename from posthog/hogql_queries/web_analytics/test/test_web_analytics_query_runner.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py
index a9459963780e..679940d8f269 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_query_runner.py
@@ -25,9 +25,10 @@ from posthog.schema import (
)
from posthog.clickhouse.query_tagging import tag_queries
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
-from posthog.hogql_queries.web_analytics.web_analytics_query_runner import _sample_rate_from_count
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
+
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import _sample_rate_from_count
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
@snapshot_clickhouse_queries
@@ -229,7 +230,7 @@ class TestWebAnalyticsBreakdownTagging(ClickhouseTestMixin, APIBaseTest):
runner = WebStatsTableQueryRunner(team=self.team, query=query)
with mock.patch(
- "posthog.hogql_queries.web_analytics.web_analytics_query_runner.tag_queries",
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.tag_queries",
wraps=tag_queries,
) as spy:
runner.calculate()
@@ -246,7 +247,7 @@ class TestWebAnalyticsBreakdownTagging(ClickhouseTestMixin, APIBaseTest):
runner = WebOverviewQueryRunner(team=self.team, query=query)
with mock.patch(
- "posthog.hogql_queries.web_analytics.web_analytics_query_runner.tag_queries",
+ "products.web_analytics.backend.hogql_queries.web_analytics_query_runner.tag_queries",
wraps=tag_queries,
) as spy:
runner.calculate()
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_analytics_rbac.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_rbac.py
similarity index 96%
rename from posthog/hogql_queries/web_analytics/test/test_web_analytics_rbac.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_analytics_rbac.py
index 831475044bab..4801c1e34396 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_analytics_rbac.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_rbac.py
@@ -3,9 +3,10 @@ from posthog.test.base import APIBaseTest
from posthog.schema import DateRange, WebOverviewQuery
from posthog.constants import AvailableFeature
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
from posthog.rbac.user_access_control import UserAccessControlError
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
+
try:
from ee.models.rbac.access_control import AccessControl
except ImportError:
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_bounces_pre_aggregated.py b/products/web_analytics/backend/hogql_queries/test/test_web_bounces_pre_aggregated.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_web_bounces_pre_aggregated.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_bounces_pre_aggregated.py
index 18e5a594c233..65f7aed09961 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_bounces_pre_aggregated.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_bounces_pre_aggregated.py
@@ -4,11 +4,14 @@ from posthog.test.base import _create_event, _create_person, flush_persons_and_e
from posthog.schema import DateRange, HogQLQueryModifiers, SessionTableVersion, WebOverviewQuery
from posthog.clickhouse.client.execute import sync_execute
-from posthog.hogql_queries.web_analytics.test.web_preaggregated_test_base import WebAnalyticsPreAggregatedTestBase
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
from posthog.models.utils import uuid7
from posthog.models.web_preaggregated.sql import WEB_BOUNCES_INSERT_SQL
+from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_base import (
+ WebAnalyticsPreAggregatedTestBase,
+)
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
+
class TestWebBouncesPreAggregated(WebAnalyticsPreAggregatedTestBase):
def _setup_test_data(self):
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_goals.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals.py
similarity index 99%
rename from posthog/hogql_queries/web_analytics/test/test_web_goals.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_goals.py
index 9bbf661d93b8..5b536a8773da 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_goals.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals.py
@@ -22,12 +22,12 @@ from posthog.schema import (
from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.clickhouse.client import sync_execute
-from posthog.hogql_queries.web_analytics.web_goals import WebGoalsQueryRunner
from posthog.models import Cohort, Element, Person
from posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLE
from posthog.models.utils import uuid7
from products.actions.backend.models.action import Action
+from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner
@snapshot_clickhouse_queries
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_overview.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
similarity index 99%
rename from posthog/hogql_queries/web_analytics/test/test_web_overview.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_overview.py
index 77bdf2b72a7b..b6c99f87dc9d 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_overview.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview.py
@@ -33,13 +33,15 @@ from posthog.hogql.context import HogQLContext
from posthog.hogql.printer import prepare_and_print_ast
from posthog.clickhouse.client.execute import sync_execute
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
-from posthog.hogql_queries.web_analytics.web_overview_pre_aggregated import WebOverviewPreAggregatedQueryBuilder
from posthog.models import Cohort, Element
from posthog.models.utils import uuid7
from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME
from products.actions.backend.models.action import Action
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
+from products.web_analytics.backend.hogql_queries.web_overview_pre_aggregated import (
+ WebOverviewPreAggregatedQueryBuilder,
+)
@snapshot_clickhouse_queries
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_overview_dashboard_filters.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_dashboard_filters.py
similarity index 96%
rename from posthog/hogql_queries/web_analytics/test/test_web_overview_dashboard_filters.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_overview_dashboard_filters.py
index 4dd5d7fd0507..9dc318ad18c7 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_overview_dashboard_filters.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_dashboard_filters.py
@@ -3,9 +3,10 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _
from posthog.schema import DashboardFilter, DateRange, EventPropertyFilter, WebOverviewQuery
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
from posthog.models.utils import uuid7
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
+
class TestWebOverviewDashboardFilters(ClickhouseTestMixin, APIBaseTest):
def test_dashboard_filter_applies_when_no_existing_properties(self):
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
similarity index 97%
rename from posthog/hogql_queries/web_analytics/test/test_web_overview_lazy_precompute.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
index b9f6ca81232f..aa3aa1031539 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
@@ -20,11 +20,11 @@ from posthog.schema import (
WebOverviewQuery,
)
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
from posthog.models.utils import uuid7
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
@override_settings(IN_UNIT_TESTING=True)
@@ -38,7 +38,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# team. Outside this context manager the default `posthoganalytics.feature_enabled`
# returns False (no API key in tests), which models a flag-disabled org.
return patch(
- "posthog.hogql_queries.web_analytics.web_overview_lazy_precompute.posthoganalytics.feature_enabled",
+ "products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute.posthoganalytics.feature_enabled",
return_value=True,
)
@@ -471,12 +471,14 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
return LazyComputationResult(ready=True, job_ids=[uuid.uuid4()])
return LazyComputationResult(ready=False, job_ids=[uuid.uuid4()])
- from posthog.hogql_queries.web_analytics.web_overview_lazy_precompute import execute_lazy_precomputed_read
+ from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (
+ execute_lazy_precomputed_read,
+ )
with (
self._enable_lazy(),
patch(
- "posthog.hogql_queries.web_analytics.web_overview_lazy_precompute.ensure_web_overview_precomputed",
+ "products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute.ensure_web_overview_precomputed",
side_effect=fake_ensure,
),
):
@@ -570,12 +572,14 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
def test_falls_back_when_current_period_not_ready(self):
# Symmetric to the previous test: if the current-period precompute
# hasn't reached READY, the read would scan empty buckets. Fall back.
- from posthog.hogql_queries.web_analytics.web_overview_lazy_precompute import execute_lazy_precomputed_read
+ from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (
+ execute_lazy_precomputed_read,
+ )
with (
self._enable_lazy(),
patch(
- "posthog.hogql_queries.web_analytics.web_overview_lazy_precompute.ensure_web_overview_precomputed",
+ "products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute.ensure_web_overview_precomputed",
return_value=LazyComputationResult(ready=False, job_ids=[uuid.uuid4()]),
),
):
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_overview_state_aggregations.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_state_aggregations.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_web_overview_state_aggregations.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_overview_state_aggregations.py
index eee12b92b2cf..0ebf592288de 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_overview_state_aggregations.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_state_aggregations.py
@@ -14,9 +14,10 @@ from posthog.hogql.transforms.state_aggregations import (
)
from posthog.clickhouse.client.execute import sync_execute
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
from posthog.models.utils import uuid7
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
+
class TestWebOverviewStateTransform(ClickhouseTestMixin, APIBaseTest):
"""Test that web overview queries work correctly with state transformations."""
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_stats_pre_aggregated.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated.py
similarity index 99%
rename from posthog/hogql_queries/web_analytics/test/test_web_stats_pre_aggregated.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated.py
index 6f40011bf282..93eedcfa548f 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_stats_pre_aggregated.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated.py
@@ -16,14 +16,17 @@ from posthog.schema import (
)
from posthog.clickhouse.client.execute import sync_execute
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
-from posthog.hogql_queries.web_analytics.stats_table_pre_aggregated import (
+from posthog.models.utils import uuid7
+from posthog.models.web_preaggregated.sql import WEB_BOUNCES_INSERT_SQL, WEB_STATS_INSERT_SQL
+
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.stats_table_pre_aggregated import (
WEB_ANALYTICS_STATS_TABLE_PRE_AGGREGATED_SUPPORTED_BREAKDOWNS,
StatsTablePreAggregatedQueryBuilder,
)
-from posthog.hogql_queries.web_analytics.test.web_preaggregated_test_base import WebAnalyticsPreAggregatedTestBase
-from posthog.models.utils import uuid7
-from posthog.models.web_preaggregated.sql import WEB_BOUNCES_INSERT_SQL, WEB_STATS_INSERT_SQL
+from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_base import (
+ WebAnalyticsPreAggregatedTestBase,
+)
@snapshot_clickhouse_queries
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_stats_pre_aggregated_channel_types.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated_channel_types.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_web_stats_pre_aggregated_channel_types.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated_channel_types.py
index 6f555231f6f8..0b8230bdf1f8 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_stats_pre_aggregated_channel_types.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_pre_aggregated_channel_types.py
@@ -6,11 +6,14 @@ from posthog.schema import DateRange, HogQLQueryModifiers, SessionPropertyFilter
from posthog.hogql.database.schema.channel_type import DEFAULT_CHANNEL_TYPES
from posthog.clickhouse.client.execute import sync_execute
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
-from posthog.hogql_queries.web_analytics.test.web_preaggregated_test_base import WebAnalyticsPreAggregatedTestBase
from posthog.models.utils import uuid7
from posthog.models.web_preaggregated.sql import WEB_STATS_INSERT_SQL
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_base import (
+ WebAnalyticsPreAggregatedTestBase,
+)
+
class TestWebStatsPreAggregatedChannelTypes(WebAnalyticsPreAggregatedTestBase):
def _setup_test_data(self):
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_stats_table.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
similarity index 99%
rename from posthog/hogql_queries/web_analytics/test/test_web_stats_table.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
index e8fa13b5bb88..cd040281d3c5 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_stats_table.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table.py
@@ -35,11 +35,11 @@ from posthog.schema import (
WebStatsTableQuery,
)
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
from posthog.models import Cohort, Element
from posthog.models.utils import uuid7
from products.actions.backend.models.action import Action
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
nan_value = float("nan")
@@ -84,7 +84,7 @@ class TestWebStatsTableQueryRunner(ClickhouseTestMixin, APIBaseTest, FloatAwareT
def setUp(self):
super().setUp()
patcher = patch(
- "posthog.hogql_queries.web_analytics.stats_table.is_web_analytics_events_prefilter_team",
+ "products.web_analytics.backend.hogql_queries.stats_table.is_web_analytics_events_prefilter_team",
return_value=False,
)
patcher.start()
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_stats_table_pre_aggregated_conversions.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py
similarity index 96%
rename from posthog/hogql_queries/web_analytics/test/test_web_stats_table_pre_aggregated_conversions.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py
index 8548ba7fd68c..e43c4e9d26f4 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_stats_table_pre_aggregated_conversions.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_table_pre_aggregated_conversions.py
@@ -11,12 +11,14 @@ from posthog.schema import (
)
from posthog.clickhouse.client.execute import sync_execute
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
-from posthog.hogql_queries.web_analytics.test.web_preaggregated_test_base import WebAnalyticsPreAggregatedTestBase
from posthog.models.utils import uuid7
from posthog.models.web_preaggregated.sql import WEB_STATS_INSERT_SQL
from products.actions.backend.models.action import Action
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.test.web_preaggregated_test_base import (
+ WebAnalyticsPreAggregatedTestBase,
+)
class TestWebStatsTablePreAggregatedConversions(WebAnalyticsPreAggregatedTestBase):
@@ -141,7 +143,9 @@ class TestWebStatsTablePreAggregatedConversions(WebAnalyticsPreAggregatedTestBas
def test_conversion_goal_with_preaggregated_tables_bounce_style(self):
"""Test conversion goals using bounce-rate-style query pattern (alternative implementation)"""
- from posthog.hogql_queries.web_analytics.stats_table_pre_aggregated import StatsTablePreAggregatedQueryBuilder
+ from products.web_analytics.backend.hogql_queries.stats_table_pre_aggregated import (
+ StatsTablePreAggregatedQueryBuilder,
+ )
# Enable bounce-style query for this test
original_flag = StatsTablePreAggregatedQueryBuilder.USE_BOUNCE_STYLE_CONVERSION_QUERY
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_traffic_type.py b/products/web_analytics/backend/hogql_queries/test/test_web_traffic_type.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_web_traffic_type.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_traffic_type.py
index 1b12f53ef41a..4c91e47ae0ac 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_traffic_type.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_traffic_type.py
@@ -2,7 +2,7 @@ import pytest
from posthog.hogql import ast
-from posthog.hogql_queries.web_analytics.traffic_type import (
+from products.web_analytics.backend.hogql_queries.traffic_type import (
get_bot_name_expr,
get_bot_type_expr,
get_traffic_category_expr,
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_trends_query_runner.py b/products/web_analytics/backend/hogql_queries/test/test_web_trends_query_runner.py
similarity index 97%
rename from posthog/hogql_queries/web_analytics/test/test_web_trends_query_runner.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_trends_query_runner.py
index 22acba5bc4eb..67321fecf941 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_trends_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_trends_query_runner.py
@@ -3,7 +3,7 @@ from unittest.mock import MagicMock, patch
from posthog.schema import HogQLQueryModifiers, IntervalType, WebTrendsMetric, WebTrendsQuery
-from posthog.hogql_queries.web_analytics.web_trends_query_runner import WebTrendsQueryRunner
+from products.web_analytics.backend.hogql_queries.web_trends_query_runner import WebTrendsQueryRunner
class TestWebTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
diff --git a/posthog/hogql_queries/web_analytics/test/test_web_vitals_path_breakdown.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/test/test_web_vitals_path_breakdown.py
rename to products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.py
index 1266362b4144..921183c380e1 100644
--- a/posthog/hogql_queries/web_analytics/test/test_web_vitals_path_breakdown.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_path_breakdown.py
@@ -18,7 +18,7 @@ from posthog.schema import (
WebVitalsPathBreakdownResultItem,
)
-from posthog.hogql_queries.web_analytics.web_vitals_path_breakdown import WebVitalsPathBreakdownQueryRunner
+from products.web_analytics.backend.hogql_queries.web_vitals_path_breakdown import WebVitalsPathBreakdownQueryRunner
@snapshot_clickhouse_queries
diff --git a/posthog/hogql_queries/web_analytics/test/web_preaggregated_test_base.py b/products/web_analytics/backend/hogql_queries/test/web_preaggregated_test_base.py
similarity index 100%
rename from posthog/hogql_queries/web_analytics/test/web_preaggregated_test_base.py
rename to products/web_analytics/backend/hogql_queries/test/web_preaggregated_test_base.py
diff --git a/posthog/hogql_queries/web_analytics/test_web_analytics_tables_version.py b/products/web_analytics/backend/hogql_queries/test_web_analytics_tables_version.py
similarity index 94%
rename from posthog/hogql_queries/web_analytics/test_web_analytics_tables_version.py
rename to products/web_analytics/backend/hogql_queries/test_web_analytics_tables_version.py
index c29fd2cdf030..fde0103dc0d9 100644
--- a/posthog/hogql_queries/web_analytics/test_web_analytics_tables_version.py
+++ b/products/web_analytics/backend/hogql_queries/test_web_analytics_tables_version.py
@@ -10,9 +10,9 @@ from posthog.schema import (
WebTrendsQuery,
)
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
-from posthog.hogql_queries.web_analytics.web_trends_query_runner import WebTrendsQueryRunner
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
+from products.web_analytics.backend.hogql_queries.web_trends_query_runner import WebTrendsQueryRunner
class TestWebAnalyticsTablesVersion(APIBaseTest):
diff --git a/posthog/hogql_queries/web_analytics/traffic_type.py b/products/web_analytics/backend/hogql_queries/traffic_type.py
similarity index 97%
rename from posthog/hogql_queries/web_analytics/traffic_type.py
rename to products/web_analytics/backend/hogql_queries/traffic_type.py
index e66aa9b0dc90..d8cbe8966ea7 100644
--- a/posthog/hogql_queries/web_analytics/traffic_type.py
+++ b/products/web_analytics/backend/hogql_queries/traffic_type.py
@@ -21,7 +21,7 @@ from posthog.hogql.functions.traffic_type import (
is_bot as _is_bot,
)
-from posthog.hogql_queries.web_analytics.bot_definitions import BOT_DEFINITIONS
+from products.web_analytics.backend.hogql_queries.bot_definitions import BOT_DEFINITIONS
__all__ = [
"BOT_DEFINITIONS",
diff --git a/posthog/hogql_queries/web_analytics/trends_pre_aggregated_query_builder.py b/products/web_analytics/backend/hogql_queries/trends_pre_aggregated_query_builder.py
similarity index 95%
rename from posthog/hogql_queries/web_analytics/trends_pre_aggregated_query_builder.py
rename to products/web_analytics/backend/hogql_queries/trends_pre_aggregated_query_builder.py
index 4d57f2ca1ee3..f6786ef7dfe4 100644
--- a/posthog/hogql_queries/web_analytics/trends_pre_aggregated_query_builder.py
+++ b/products/web_analytics/backend/hogql_queries/trends_pre_aggregated_query_builder.py
@@ -4,8 +4,12 @@ from posthog.schema import IntervalType, WebTrendsMetric
from posthog.hogql import ast
-from posthog.hogql_queries.web_analytics.pre_aggregated.properties import WEB_ANALYTICS_TRENDS_SUPPORTED_FILTERS
-from posthog.hogql_queries.web_analytics.pre_aggregated.query_builder import WebAnalyticsPreAggregatedQueryBuilder
+from products.web_analytics.backend.hogql_queries.pre_aggregated.properties import (
+ WEB_ANALYTICS_TRENDS_SUPPORTED_FILTERS,
+)
+from products.web_analytics.backend.hogql_queries.pre_aggregated.query_builder import (
+ WebAnalyticsPreAggregatedQueryBuilder,
+)
WEB_ANALYTICS_TRENDS_PRE_AGGREGATED_SUPPORTED_METRICS = [
WebTrendsMetric.UNIQUE_USERS,
diff --git a/posthog/hogql_queries/web_analytics/web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
similarity index 99%
rename from posthog/hogql_queries/web_analytics/web_analytics_query_runner.py
rename to products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
index 844af91de0d7..f2af3623085b 100644
--- a/posthog/hogql_queries/web_analytics/web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
@@ -40,18 +40,18 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryResponseProtocol, A
from posthog.hogql_queries.utils.query_compare_to_date_range import QueryCompareToDateRange
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
-from posthog.hogql_queries.web_analytics.metrics import (
- WEB_ANALYTICS_QUERY_COUNTER,
- WEB_ANALYTICS_QUERY_DURATION,
- WEB_ANALYTICS_QUERY_ERRORS,
-)
-from posthog.hogql_queries.web_analytics.traffic_type import get_traffic_category_expr, get_traffic_type_expr
from posthog.models import User
from posthog.models.filters.mixins.utils import cached_property
from posthog.rbac.user_access_control import UserAccessControl
from posthog.utils import generate_cache_key, get_safe_cache
from products.actions.backend.models.action import Action
+from products.web_analytics.backend.hogql_queries.metrics import (
+ WEB_ANALYTICS_QUERY_COUNTER,
+ WEB_ANALYTICS_QUERY_DURATION,
+ WEB_ANALYTICS_QUERY_ERRORS,
+)
+from products.web_analytics.backend.hogql_queries.traffic_type import get_traffic_category_expr, get_traffic_type_expr
logger = structlog.get_logger(__name__)
diff --git a/posthog/hogql_queries/web_analytics/web_goals.py b/products/web_analytics/backend/hogql_queries/web_goals.py
similarity index 98%
rename from posthog/hogql_queries/web_analytics/web_goals.py
rename to products/web_analytics/backend/hogql_queries/web_goals.py
index 0e989f98549d..fffa4106df5e 100644
--- a/posthog/hogql_queries/web_analytics/web_goals.py
+++ b/products/web_analytics/backend/hogql_queries/web_goals.py
@@ -8,9 +8,8 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.property import action_to_expr, get_property_type, property_to_expr
from posthog.hogql.query import execute_hogql_query
-from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner
-
from products.actions.backend.models.action import Action
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner
# Returns an array `seq` split into chunks of size `size`
# Example:
diff --git a/posthog/hogql_queries/web_analytics/web_overview.py b/products/web_analytics/backend/hogql_queries/web_overview.py
similarity index 97%
rename from posthog/hogql_queries/web_analytics/web_overview.py
rename to products/web_analytics/backend/hogql_queries/web_overview.py
index 0957043a0712..f7c82512b025 100644
--- a/posthog/hogql_queries/web_analytics/web_overview.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview.py
@@ -15,13 +15,16 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.property import property_to_expr
from posthog.hogql.query import execute_hogql_query
-from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner
-from posthog.hogql_queries.web_analytics.web_overview_lazy_precompute import (
+from posthog.models.filters.mixins.utils import cached_property
+
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner
+from products.web_analytics.backend.hogql_queries.web_overview_lazy_precompute import (
can_use_lazy_precompute,
execute_lazy_precomputed_read,
)
-from posthog.hogql_queries.web_analytics.web_overview_pre_aggregated import WebOverviewPreAggregatedQueryBuilder
-from posthog.models.filters.mixins.utils import cached_property
+from products.web_analytics.backend.hogql_queries.web_overview_pre_aggregated import (
+ WebOverviewPreAggregatedQueryBuilder,
+)
logger = structlog.get_logger(__name__)
diff --git a/posthog/hogql_queries/web_analytics/web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
similarity index 99%
rename from posthog/hogql_queries/web_analytics/web_overview_lazy_precompute.py
rename to products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
index 6ae2e2205981..d50600ed457d 100644
--- a/posthog/hogql_queries/web_analytics/web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
@@ -25,7 +25,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
)
if TYPE_CHECKING:
- from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
+ from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
logger = structlog.get_logger(__name__)
diff --git a/posthog/hogql_queries/web_analytics/web_overview_pre_aggregated.py b/products/web_analytics/backend/hogql_queries/web_overview_pre_aggregated.py
similarity index 96%
rename from posthog/hogql_queries/web_analytics/web_overview_pre_aggregated.py
rename to products/web_analytics/backend/hogql_queries/web_overview_pre_aggregated.py
index 239d675e20fb..f9480e2875cd 100644
--- a/posthog/hogql_queries/web_analytics/web_overview_pre_aggregated.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview_pre_aggregated.py
@@ -4,11 +4,13 @@ from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.property import property_to_expr
-from posthog.hogql_queries.web_analytics.pre_aggregated.properties import WEB_OVERVIEW_SUPPORTED_PROPERTIES
-from posthog.hogql_queries.web_analytics.pre_aggregated.query_builder import WebAnalyticsPreAggregatedQueryBuilder
+from products.web_analytics.backend.hogql_queries.pre_aggregated.properties import WEB_OVERVIEW_SUPPORTED_PROPERTIES
+from products.web_analytics.backend.hogql_queries.pre_aggregated.query_builder import (
+ WebAnalyticsPreAggregatedQueryBuilder,
+)
if TYPE_CHECKING:
- from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
+ from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
class WebOverviewPreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder):
diff --git a/posthog/hogql_queries/web_analytics/web_trends_query_runner.py b/products/web_analytics/backend/hogql_queries/web_trends_query_runner.py
similarity index 93%
rename from posthog/hogql_queries/web_analytics/web_trends_query_runner.py
rename to products/web_analytics/backend/hogql_queries/web_trends_query_runner.py
index 527361c5cd76..cf6e09763cd9 100644
--- a/posthog/hogql_queries/web_analytics/web_trends_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/web_trends_query_runner.py
@@ -9,10 +9,13 @@ from posthog.hogql.context import HogQLContext
from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
-from posthog.hogql_queries.web_analytics.trends_pre_aggregated_query_builder import TrendsPreAggregatedQueryBuilder
-from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner
from posthog.models.filters.mixins.utils import cached_property
+from products.web_analytics.backend.hogql_queries.trends_pre_aggregated_query_builder import (
+ TrendsPreAggregatedQueryBuilder,
+)
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner
+
class WebTrendsQueryRunner(WebAnalyticsQueryRunner[WebTrendsQueryResponse]):
query: WebTrendsQuery
diff --git a/posthog/hogql_queries/web_analytics/web_vitals_path_breakdown.py b/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py
similarity index 97%
rename from posthog/hogql_queries/web_analytics/web_vitals_path_breakdown.py
rename to products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py
index 6f1a6d1cfae9..67ace8ebd62d 100644
--- a/posthog/hogql_queries/web_analytics/web_vitals_path_breakdown.py
+++ b/products/web_analytics/backend/hogql_queries/web_vitals_path_breakdown.py
@@ -12,9 +12,10 @@ from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.property import get_property_type, property_to_expr
from posthog.hogql.query import execute_hogql_query
-from posthog.hogql_queries.web_analytics.web_analytics_query_runner import WebAnalyticsQueryRunner
from posthog.queries.trends.util import PROPERTY_MATH_FUNCTIONS
+from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner
+
class WebVitalsPathBreakdownQueryRunner(WebAnalyticsQueryRunner[WebVitalsPathBreakdownQueryResponse]):
query: WebVitalsPathBreakdownQuery
diff --git a/products/web_analytics/backend/migrations/0001_initial.py b/products/web_analytics/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..60953f256845
--- /dev/null
+++ b/products/web_analytics/backend/migrations/0001_initial.py
@@ -0,0 +1,226 @@
+# Generated by Django 5.2.14 on 2026-05-20 15:31
+
+import django.utils.timezone
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.utils
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ ("posthog", "1176_migrate_web_analytics_models"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.CreateModel(
+ name="SavedHeatmap",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "short_id",
+ models.CharField(
+ blank=True,
+ default=posthog.utils.generate_short_id,
+ max_length=12,
+ ),
+ ),
+ ("name", models.CharField(blank=True, max_length=400, null=True)),
+ ("url", models.URLField(max_length=2000)),
+ (
+ "data_url",
+ models.URLField(
+ blank=True,
+ help_text="URL for fetching heatmap data",
+ max_length=2000,
+ null=True,
+ ),
+ ),
+ ("target_widths", models.JSONField(default=list)),
+ (
+ "type",
+ models.CharField(
+ choices=[
+ ("screenshot", "Screenshot"),
+ ("iframe", "Iframe"),
+ ("recording", "Recording"),
+ ],
+ default="screenshot",
+ max_length=20,
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("processing", "Processing"),
+ ("completed", "Completed"),
+ ("failed", "Failed"),
+ ],
+ default="processing",
+ max_length=20,
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("exception", models.TextField(blank=True, null=True)),
+ ("deleted", models.BooleanField(default=False)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_heatmapsaved",
+ },
+ ),
+ migrations.CreateModel(
+ name="HeatmapSnapshot",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("width", models.IntegerField()),
+ ("content", models.BinaryField(null=True)),
+ (
+ "content_location",
+ models.TextField(blank=True, max_length=1000, null=True),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "heatmap",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="snapshots",
+ to="web_analytics.savedheatmap",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_heatmapsnapshot",
+ },
+ ),
+ migrations.CreateModel(
+ name="WebAnalyticsFilterPreset",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "short_id",
+ models.CharField(
+ blank=True,
+ default=posthog.utils.generate_short_id,
+ max_length=12,
+ ),
+ ),
+ ("name", models.CharField(max_length=400)),
+ ("description", models.TextField(blank=True)),
+ ("pinned", models.BooleanField(default=False)),
+ ("deleted", models.BooleanField(default=False)),
+ ("filters", models.JSONField(default=dict)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "last_modified_at",
+ models.DateTimeField(default=django.utils.timezone.now),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "last_modified_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="modified_web_analytics_filter_presets",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_webanalyticsfilterpreset",
+ },
+ ),
+ migrations.AddIndex(
+ model_name="savedheatmap",
+ index=models.Index(fields=["team", "url"], name="posthog_hea_team_id_7540ce_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="savedheatmap",
+ index=models.Index(fields=["status"], name="posthog_hea_status_851064_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="savedheatmap",
+ index=models.Index(fields=["deleted"], name="posthog_hea_deleted_9942b0_idx"),
+ ),
+ migrations.AlterUniqueTogether(
+ name="savedheatmap",
+ unique_together={("team", "short_id")},
+ ),
+ migrations.AddIndex(
+ model_name="heatmapsnapshot",
+ index=models.Index(fields=["heatmap", "width"], name="posthog_hea_heatmap_9543e8_idx"),
+ ),
+ migrations.AlterUniqueTogether(
+ name="heatmapsnapshot",
+ unique_together={("heatmap", "width")},
+ ),
+ migrations.AddIndex(
+ model_name="webanalyticsfilterpreset",
+ index=models.Index(fields=["deleted", "-last_modified_at"], name="wa_preset_del_mod_idx"),
+ ),
+ migrations.AlterUniqueTogether(
+ name="webanalyticsfilterpreset",
+ unique_together={("team", "short_id")},
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/web_analytics/backend/migrations/__init__.py b/products/web_analytics/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/web_analytics/backend/migrations/max_migration.txt b/products/web_analytics/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..cbab66dde92a
--- /dev/null
+++ b/products/web_analytics/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_initial
diff --git a/products/web_analytics/backend/models/__init__.py b/products/web_analytics/backend/models/__init__.py
new file mode 100644
index 000000000000..292a036d20d4
--- /dev/null
+++ b/products/web_analytics/backend/models/__init__.py
@@ -0,0 +1,8 @@
+from .heatmap_saved import HeatmapSnapshot, SavedHeatmap
+from .web_analytics_filter_preset import WebAnalyticsFilterPreset
+
+__all__ = [
+ "HeatmapSnapshot",
+ "SavedHeatmap",
+ "WebAnalyticsFilterPreset",
+]
diff --git a/posthog/models/heatmap_saved.py b/products/web_analytics/backend/models/heatmap_saved.py
similarity index 92%
rename from posthog/models/heatmap_saved.py
rename to products/web_analytics/backend/models/heatmap_saved.py
index 8ab8eefcf4d2..cf05922c807e 100644
--- a/posthog/models/heatmap_saved.py
+++ b/products/web_analytics/backend/models/heatmap_saved.py
@@ -17,7 +17,7 @@ class SavedHeatmap(UUIDTModel):
short_id = models.CharField(max_length=12, blank=True, default=generate_short_id)
name = models.CharField(max_length=400, null=True, blank=True)
- team = models.ForeignKey("Team", on_delete=models.CASCADE)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
url = models.URLField(max_length=2000)
data_url = models.URLField(max_length=2000, null=True, blank=True, help_text="URL for fetching heatmap data")
# Planned widths to generate for screenshot-type heatmaps
@@ -30,7 +30,7 @@ class SavedHeatmap(UUIDTModel):
# Metadata
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
- created_by = models.ForeignKey("User", on_delete=models.SET_NULL, null=True, blank=True)
+ created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True)
# Error handling
exception = models.TextField(null=True, blank=True)
@@ -74,6 +74,7 @@ class HeatmapSnapshot(UUIDModel):
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
+ db_table = "posthog_heatmapsnapshot"
unique_together = ("heatmap", "width")
indexes = [
models.Index(fields=["heatmap", "width"]),
diff --git a/posthog/models/web_analytics_filter_preset.py b/products/web_analytics/backend/models/web_analytics_filter_preset.py
similarity index 81%
rename from posthog/models/web_analytics_filter_preset.py
rename to products/web_analytics/backend/models/web_analytics_filter_preset.py
index d877b6765855..2d458c51eddc 100644
--- a/posthog/models/web_analytics_filter_preset.py
+++ b/products/web_analytics/backend/models/web_analytics_filter_preset.py
@@ -9,15 +9,15 @@ class WebAnalyticsFilterPreset(UUIDModel):
short_id = models.CharField(max_length=12, blank=True, default=generate_short_id)
name = models.CharField(max_length=400)
description = models.TextField(blank=True)
- team = models.ForeignKey("Team", on_delete=models.CASCADE)
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
pinned = models.BooleanField(default=False)
deleted = models.BooleanField(default=False)
filters = models.JSONField(default=dict)
created_at = models.DateTimeField(auto_now_add=True, blank=True)
- created_by = models.ForeignKey("User", on_delete=models.SET_NULL, null=True, blank=True)
+ created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True)
last_modified_at = models.DateTimeField(default=timezone.now)
last_modified_by = models.ForeignKey(
- "User",
+ "posthog.User",
on_delete=models.SET_NULL,
null=True,
blank=True,
@@ -27,6 +27,7 @@ class WebAnalyticsFilterPreset(UUIDModel):
LAST_MODIFIED_FIELDS = {"name", "description", "filters"}
class Meta:
+ db_table = "posthog_webanalyticsfilterpreset"
unique_together = ("team", "short_id")
indexes = [
models.Index(fields=["deleted", "-last_modified_at"], name="wa_preset_del_mod_idx"),
diff --git a/products/web_analytics/backend/tasks/__init__.py b/products/web_analytics/backend/tasks/__init__.py
new file mode 100644
index 000000000000..ac23eb99ada3
--- /dev/null
+++ b/products/web_analytics/backend/tasks/__init__.py
@@ -0,0 +1,3 @@
+from . import heatmap_screenshot
+
+__all__ = ["heatmap_screenshot"]
diff --git a/posthog/tasks/heatmap_screenshot.py b/products/web_analytics/backend/tasks/heatmap_screenshot.py
similarity index 98%
rename from posthog/tasks/heatmap_screenshot.py
rename to products/web_analytics/backend/tasks/heatmap_screenshot.py
index d60064ec69b5..81b58d51a93e 100644
--- a/posthog/tasks/heatmap_screenshot.py
+++ b/products/web_analytics/backend/tasks/heatmap_screenshot.py
@@ -11,11 +11,12 @@ from playwright.sync_api import (
)
from posthog.exceptions_capture import capture_exception
-from posthog.heatmaps.heatmaps_utils import DEFAULT_TARGET_WIDTHS
-from posthog.models.heatmap_saved import HeatmapSnapshot, SavedHeatmap
from posthog.security.url_validation import is_url_allowed, should_block_url
from posthog.tasks.utils import CeleryQueue
+from products.web_analytics.backend.api.heatmaps_utils import DEFAULT_TARGET_WIDTHS
+from products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmap
+
logger = structlog.get_logger(__name__)
TMP_DIR = "/tmp"
diff --git a/products/web_analytics/backend/tasks/test/__init__.py b/products/web_analytics/backend/tasks/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/tasks/test/test_heatmap_screenshot.py b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py
similarity index 88%
rename from posthog/tasks/test/test_heatmap_screenshot.py
rename to products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py
index 064858b24f42..104574df77a9 100644
--- a/posthog/tasks/test/test_heatmap_screenshot.py
+++ b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py
@@ -1,12 +1,12 @@
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
-from posthog.models.heatmap_saved import HeatmapSnapshot, SavedHeatmap
-from posthog.tasks.heatmap_screenshot import generate_heatmap_screenshot
+from products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmap
+from products.web_analytics.backend.tasks.heatmap_screenshot import generate_heatmap_screenshot
class TestHeatmapScreenshotTask(APIBaseTest):
- @patch("posthog.tasks.heatmap_screenshot.sync_playwright")
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.sync_playwright")
def test_generates_multiple_width_snapshots_and_marks_completed(self, mock_sync_playwright: MagicMock) -> None:
# Arrange Playwright mocks
mock_p = MagicMock()
@@ -50,7 +50,7 @@ class TestHeatmapScreenshotTask(APIBaseTest):
# Ensure we cleaned up the browser
mock_browser.close.assert_called_once()
- @patch("posthog.tasks.heatmap_screenshot.sync_playwright")
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.sync_playwright")
def test_failure_marks_failed_and_records_exception(self, mock_sync_playwright: MagicMock) -> None:
# Arrange: make playwright crash when entering context
mock_sync_playwright.return_value.__enter__.side_effect = RuntimeError("boom")
diff --git a/posthog/heatmaps/test/__snapshots__/test_heatmaps_api.ambr b/products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr
similarity index 100%
rename from posthog/heatmaps/test/__snapshots__/test_heatmaps_api.ambr
rename to products/web_analytics/backend/test/__snapshots__/test_heatmaps_api.ambr
diff --git a/posthog/heatmaps/test/test_heatmap_screenshots.py b/products/web_analytics/backend/test/test_heatmap_screenshots.py
similarity index 94%
rename from posthog/heatmaps/test/test_heatmap_screenshots.py
rename to products/web_analytics/backend/test/test_heatmap_screenshots.py
index e814aa6ce259..763ea47598e8 100644
--- a/posthog/heatmaps/test/test_heatmap_screenshots.py
+++ b/products/web_analytics/backend/test/test_heatmap_screenshots.py
@@ -8,7 +8,9 @@ from django.utils import timezone
from rest_framework.test import APIClient
from posthog.jwt import PosthogJwtAudience, encode_jwt
-from posthog.models import HeatmapSnapshot, SavedHeatmap, Team
+from posthog.models import Team
+
+from products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmap
class TestHeatmapsAPI(APIBaseTest):
@@ -17,7 +19,7 @@ class TestHeatmapsAPI(APIBaseTest):
self.client = APIClient()
self.client.force_authenticate(user=self.user)
- @patch("posthog.tasks.heatmap_screenshot.generate_heatmap_screenshot.delay")
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.generate_heatmap_screenshot.delay")
def test_generate_creates_saved_with_target_widths(self, mock_task):
resp = self.client.post(
f"/api/environments/{self.team.id}/saved/",
@@ -113,7 +115,7 @@ class TestHeatmapsAPI(APIBaseTest):
self.assertEqual(r["Content-Type"], "image/jpeg")
self.assertEqual(r.content, b"jpegdata1024")
- @patch("posthog.heatmaps.heatmaps_api.generate_heatmap_screenshot")
+ @patch("products.web_analytics.backend.api.heatmaps_api.generate_heatmap_screenshot")
def test_retrieve_auto_recovers_stale_processing_heatmap(self, mock_task):
saved = SavedHeatmap.objects.create(
team=self.team,
@@ -137,7 +139,7 @@ class TestHeatmapsAPI(APIBaseTest):
# Old snapshots were cleaned up
self.assertEqual(HeatmapSnapshot.objects.filter(heatmap=saved).count(), 0)
- @patch("posthog.heatmaps.heatmaps_api.generate_heatmap_screenshot")
+ @patch("products.web_analytics.backend.api.heatmaps_api.generate_heatmap_screenshot")
def test_retrieve_does_not_recover_recent_processing_heatmap(self, mock_task):
saved = SavedHeatmap.objects.create(
team=self.team,
@@ -153,7 +155,7 @@ class TestHeatmapsAPI(APIBaseTest):
# Task was NOT re-enqueued (still within threshold)
mock_task.delay.assert_not_called()
- @patch("posthog.heatmaps.heatmaps_api.generate_heatmap_screenshot")
+ @patch("products.web_analytics.backend.api.heatmaps_api.generate_heatmap_screenshot")
def test_regenerate_endpoint_re_enqueues_task(self, mock_task):
saved = SavedHeatmap.objects.create(
team=self.team,
diff --git a/posthog/heatmaps/test/test_heatmaps_api.py b/products/web_analytics/backend/test/test_heatmaps_api.py
similarity index 100%
rename from posthog/heatmaps/test/test_heatmaps_api.py
rename to products/web_analytics/backend/test/test_heatmaps_api.py
diff --git a/products/web_analytics/backend/weekly_digest.py b/products/web_analytics/backend/weekly_digest.py
index 5e39bdc0e6bc..0ca764ef9e7a 100644
--- a/products/web_analytics/backend/weekly_digest.py
+++ b/products/web_analytics/backend/weekly_digest.py
@@ -15,13 +15,14 @@ from posthog.schema import (
)
from posthog.clickhouse.query_tagging import tag_queries
-from posthog.hogql_queries.web_analytics.stats_table import WebStatsTableQueryRunner
-from posthog.hogql_queries.web_analytics.web_goals import NoActionsError, WebGoalsQueryRunner
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
from posthog.models import Team
from posthog.models.user import User
from posthog.tasks.email_utils import compute_week_over_week_change
+from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
+from products.web_analytics.backend.hogql_queries.web_goals import NoActionsError, WebGoalsQueryRunner
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
+
logger = structlog.get_logger(__name__)
diff --git a/products/web_analytics/dags/web_preaggregated_asset_checks.py b/products/web_analytics/dags/web_preaggregated_asset_checks.py
index 044d83515f53..382d2750ed11 100644
--- a/products/web_analytics/dags/web_preaggregated_asset_checks.py
+++ b/products/web_analytics/dags/web_preaggregated_asset_checks.py
@@ -20,10 +20,10 @@ from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.escape import substitute_params
from posthog.clickhouse.query_tagging import DagsterTags, get_query_tags, tags_context
from posthog.dags.common import dagster_tags
-from posthog.hogql_queries.web_analytics.web_overview import WebOverviewQueryRunner
from posthog.models import Team
from posthog.settings.base_variables import DEBUG
+from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
from products.web_analytics.dags.web_preaggregated_utils import TEAM_ID_FOR_WEB_ANALYTICS_ASSET_CHECKS
logger = structlog.get_logger(__name__)
diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.ts
index c7212f4918f8..ba860feec91b 100644
--- a/products/web_analytics/frontend/generated/api.schemas.ts
+++ b/products/web_analytics/frontend/generated/api.schemas.ts
@@ -108,6 +108,219 @@ export interface WeeklyDigestResponseApi {
dashboard_url: string
}
+/**
+ * * `engineering` - Engineering
+ * `data` - Data
+ * `product` - Product Management
+ * `founder` - Founder
+ * `leadership` - Leadership
+ * `marketing` - Marketing
+ * `sales` - Sales / Success
+ * `other` - Other
+ */
+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
+
+export const RoleAtOrganizationEnumApi = {
+ Engineering: 'engineering',
+ Data: 'data',
+ Product: 'product',
+ Founder: 'founder',
+ Leadership: 'leadership',
+ Marketing: 'marketing',
+ Sales: 'sales',
+ Other: 'other',
+} as const
+
+export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
+
+export const BlankEnumApi = {
+ '': '',
+} as const
+
+/**
+ * @nullable
+ */
+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null
+
+export interface UserBasicApi {
+ readonly id: number
+ readonly uuid: string
+ /**
+ * @maxLength 200
+ * @nullable
+ */
+ distinct_id?: string | null
+ /** @maxLength 150 */
+ first_name?: string
+ /** @maxLength 150 */
+ last_name?: string
+ /** @maxLength 254 */
+ email: string
+ /** @nullable */
+ is_email_verified?: boolean | null
+ /** @nullable */
+ readonly hedgehog_config: UserBasicApiHedgehogConfig
+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
+}
+
+export interface WebAnalyticsFilterPresetApi {
+ readonly id: string
+ readonly short_id: string
+ /** @maxLength 400 */
+ name: string
+ description?: string
+ pinned?: boolean
+ readonly created_at: string
+ readonly created_by: UserBasicApi
+ deleted?: boolean
+ filters?: unknown
+ readonly last_modified_at: string
+ readonly last_modified_by: UserBasicApi
+}
+
+export interface PaginatedWebAnalyticsFilterPresetListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: WebAnalyticsFilterPresetApi[]
+}
+
+export interface PatchedWebAnalyticsFilterPresetApi {
+ readonly id?: string
+ readonly short_id?: string
+ /** @maxLength 400 */
+ name?: string
+ description?: string
+ pinned?: boolean
+ readonly created_at?: string
+ readonly created_by?: UserBasicApi
+ deleted?: boolean
+ filters?: unknown
+ readonly last_modified_at?: string
+ readonly last_modified_by?: UserBasicApi
+}
+
+export interface HeatmapResponseItemApi {
+ count: number
+ pointer_y: number
+ pointer_relative_x: number
+ pointer_target_fixed: boolean
+}
+
+export interface HeatmapsResponseApi {
+ results: HeatmapResponseItemApi[]
+}
+
+export interface PaginatedHeatmapsResponseListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: HeatmapsResponseApi[]
+}
+
+/**
+ * * `screenshot` - Screenshot
+ * `iframe` - Iframe
+ * `recording` - Recording
+ */
+export type HeatmapScreenshotResponseTypeEnumApi =
+ (typeof HeatmapScreenshotResponseTypeEnumApi)[keyof typeof HeatmapScreenshotResponseTypeEnumApi]
+
+export const HeatmapScreenshotResponseTypeEnumApi = {
+ Screenshot: 'screenshot',
+ Iframe: 'iframe',
+ Recording: 'recording',
+} as const
+
+/**
+ * * `processing` - Processing
+ * `completed` - Completed
+ * `failed` - Failed
+ */
+export type HeatmapScreenshotResponseStatusEnumApi =
+ (typeof HeatmapScreenshotResponseStatusEnumApi)[keyof typeof HeatmapScreenshotResponseStatusEnumApi]
+
+export const HeatmapScreenshotResponseStatusEnumApi = {
+ Processing: 'processing',
+ Completed: 'completed',
+ Failed: 'failed',
+} as const
+
+export type HeatmapScreenshotResponseApiSnapshotsItem = { [key: string]: unknown }
+
+export interface HeatmapScreenshotResponseApi {
+ readonly id: string
+ readonly short_id: string
+ /**
+ * @maxLength 400
+ * @nullable
+ */
+ name?: string | null
+ /** @maxLength 2000 */
+ url: string
+ /**
+ * URL for fetching heatmap data
+ * @maxLength 2000
+ * @nullable
+ */
+ data_url?: string | null
+ target_widths?: unknown
+ type?: HeatmapScreenshotResponseTypeEnumApi
+ readonly status: HeatmapScreenshotResponseStatusEnumApi
+ readonly has_content: boolean
+ readonly snapshots: readonly HeatmapScreenshotResponseApiSnapshotsItem[]
+ deleted?: boolean
+ readonly created_by: UserBasicApi
+ readonly created_at: string
+ readonly updated_at: string
+ /** @nullable */
+ readonly exception: string | null
+}
+
+export interface PaginatedHeatmapScreenshotResponseListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: HeatmapScreenshotResponseApi[]
+}
+
+export type PatchedHeatmapScreenshotResponseApiSnapshotsItem = { [key: string]: unknown }
+
+export interface PatchedHeatmapScreenshotResponseApi {
+ readonly id?: string
+ readonly short_id?: string
+ /**
+ * @maxLength 400
+ * @nullable
+ */
+ name?: string | null
+ /** @maxLength 2000 */
+ url?: string
+ /**
+ * URL for fetching heatmap data
+ * @maxLength 2000
+ * @nullable
+ */
+ data_url?: string | null
+ target_widths?: unknown
+ type?: HeatmapScreenshotResponseTypeEnumApi
+ readonly status?: HeatmapScreenshotResponseStatusEnumApi
+ readonly has_content?: boolean
+ readonly snapshots?: readonly PatchedHeatmapScreenshotResponseApiSnapshotsItem[]
+ deleted?: boolean
+ readonly created_by?: UserBasicApi
+ readonly created_at?: string
+ readonly updated_at?: string
+ /** @nullable */
+ readonly exception?: string | null
+}
+
export type WebAnalyticsWeeklyDigestParams = {
/**
* When true (default), include period-over-period change for each metric comparing against the prior equal-length period. Set to false to skip the comparison query (faster).
@@ -118,3 +331,38 @@ export type WebAnalyticsWeeklyDigestParams = {
*/
days?: number
}
+
+export type WebAnalyticsFilterPresetsListParams = {
+ created_by?: number
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ short_id?: string
+}
+
+export type HeatmapsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type SavedListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.ts
index 4246d8a1af36..1eda8262da31 100644
--- a/products/web_analytics/frontend/generated/api.ts
+++ b/products/web_analytics/frontend/generated/api.ts
@@ -8,7 +8,37 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
-import type { WebAnalyticsWeeklyDigestParams, WeeklyDigestResponseApi } from './api.schemas'
+import type {
+ HeatmapScreenshotResponseApi,
+ HeatmapsListParams,
+ PaginatedHeatmapScreenshotResponseListApi,
+ PaginatedHeatmapsResponseListApi,
+ PaginatedWebAnalyticsFilterPresetListApi,
+ PatchedHeatmapScreenshotResponseApi,
+ PatchedWebAnalyticsFilterPresetApi,
+ SavedListParams,
+ WebAnalyticsFilterPresetApi,
+ WebAnalyticsFilterPresetsListParams,
+ WebAnalyticsWeeklyDigestParams,
+ WeeklyDigestResponseApi,
+} from './api.schemas'
+
+// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
+
+type WritableKeys<T> = {
+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
+}[keyof T]
+
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
+
+type Writable<T> = Pick<T, WritableKeys<T>>
+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
+ ? {
+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
+ }
+ : DistributeReadOnlyOverUnions<T>
export const getWebAnalyticsWeeklyDigestUrl = (projectId: string, params?: WebAnalyticsWeeklyDigestParams) => {
const normalizedParams = new URLSearchParams()
@@ -40,3 +70,269 @@ export const webAnalyticsWeeklyDigest = async (
method: 'GET',
})
}
+
+export const getWebAnalyticsFilterPresetsListUrl = (
+ projectId: string,
+ params?: WebAnalyticsFilterPresetsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/environments/${projectId}/web_analytics_filter_presets/?${stringifiedParams}`
+ : `/api/environments/${projectId}/web_analytics_filter_presets/`
+}
+
+export const webAnalyticsFilterPresetsList = async (
+ projectId: string,
+ params?: WebAnalyticsFilterPresetsListParams,
+ options?: RequestInit
+): Promise<PaginatedWebAnalyticsFilterPresetListApi> => {
+ return apiMutator<PaginatedWebAnalyticsFilterPresetListApi>(
+ getWebAnalyticsFilterPresetsListUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getWebAnalyticsFilterPresetsCreateUrl = (projectId: string) => {
+ return `/api/environments/${projectId}/web_analytics_filter_presets/`
+}
+
+export const webAnalyticsFilterPresetsCreate = async (
+ projectId: string,
+ webAnalyticsFilterPresetApi: NonReadonly<WebAnalyticsFilterPresetApi>,
+ options?: RequestInit
+): Promise<WebAnalyticsFilterPresetApi> => {
+ return apiMutator<WebAnalyticsFilterPresetApi>(getWebAnalyticsFilterPresetsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(webAnalyticsFilterPresetApi),
+ })
+}
+
+export const getWebAnalyticsFilterPresetsRetrieveUrl = (projectId: string, shortId: string) => {
+ return `/api/environments/${projectId}/web_analytics_filter_presets/${shortId}/`
+}
+
+export const webAnalyticsFilterPresetsRetrieve = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<WebAnalyticsFilterPresetApi> => {
+ return apiMutator<WebAnalyticsFilterPresetApi>(getWebAnalyticsFilterPresetsRetrieveUrl(projectId, shortId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getWebAnalyticsFilterPresetsUpdateUrl = (projectId: string, shortId: string) => {
+ return `/api/environments/${projectId}/web_analytics_filter_presets/${shortId}/`
+}
+
+export const webAnalyticsFilterPresetsUpdate = async (
+ projectId: string,
+ shortId: string,
+ webAnalyticsFilterPresetApi: NonReadonly<WebAnalyticsFilterPresetApi>,
+ options?: RequestInit
+): Promise<WebAnalyticsFilterPresetApi> => {
+ return apiMutator<WebAnalyticsFilterPresetApi>(getWebAnalyticsFilterPresetsUpdateUrl(projectId, shortId), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(webAnalyticsFilterPresetApi),
+ })
+}
+
+export const getWebAnalyticsFilterPresetsPartialUpdateUrl = (projectId: string, shortId: string) => {
+ return `/api/environments/${projectId}/web_analytics_filter_presets/${shortId}/`
+}
+
+export const webAnalyticsFilterPresetsPartialUpdate = async (
+ projectId: string,
+ shortId: string,
+ patchedWebAnalyticsFilterPresetApi?: NonReadonly<PatchedWebAnalyticsFilterPresetApi>,
+ options?: RequestInit
+): Promise<WebAnalyticsFilterPresetApi> => {
+ return apiMutator<WebAnalyticsFilterPresetApi>(getWebAnalyticsFilterPresetsPartialUpdateUrl(projectId, shortId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedWebAnalyticsFilterPresetApi),
+ })
+}
+
+export const getWebAnalyticsFilterPresetsDestroyUrl = (projectId: string, shortId: string) => {
+ return `/api/environments/${projectId}/web_analytics_filter_presets/${shortId}/`
+}
+
+/**
+ * Hard delete of this model is not allowed. Use a patch API call to set "deleted" to true
+ */
+export const webAnalyticsFilterPresetsDestroy = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<unknown> => {
+ return apiMutator<unknown>(getWebAnalyticsFilterPresetsDestroyUrl(projectId, shortId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getHeatmapsListUrl = (projectId: string, params?: HeatmapsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/heatmaps/?${stringifiedParams}`
+ : `/api/projects/${projectId}/heatmaps/`
+}
+
+export const heatmapsList = async (
+ projectId: string,
+ params?: HeatmapsListParams,
+ options?: RequestInit
+): Promise<PaginatedHeatmapsResponseListApi> => {
+ return apiMutator<PaginatedHeatmapsResponseListApi>(getHeatmapsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getHeatmapsEventsRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/heatmaps/events/`
+}
+
+export const heatmapsEventsRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getHeatmapsEventsRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSavedListUrl = (projectId: string, params?: SavedListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/saved/?${stringifiedParams}`
+ : `/api/projects/${projectId}/saved/`
+}
+
+export const savedList = async (
+ projectId: string,
+ params?: SavedListParams,
+ options?: RequestInit
+): Promise<PaginatedHeatmapScreenshotResponseListApi> => {
+ return apiMutator<PaginatedHeatmapScreenshotResponseListApi>(getSavedListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSavedCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/saved/`
+}
+
+export const savedCreate = async (
+ projectId: string,
+ heatmapScreenshotResponseApi: NonReadonly<HeatmapScreenshotResponseApi>,
+ options?: RequestInit
+): Promise<HeatmapScreenshotResponseApi> => {
+ return apiMutator<HeatmapScreenshotResponseApi>(getSavedCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(heatmapScreenshotResponseApi),
+ })
+}
+
+export const getSavedRetrieveUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/saved/${shortId}/`
+}
+
+export const savedRetrieve = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<HeatmapScreenshotResponseApi> => {
+ return apiMutator<HeatmapScreenshotResponseApi>(getSavedRetrieveUrl(projectId, shortId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSavedPartialUpdateUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/saved/${shortId}/`
+}
+
+export const savedPartialUpdate = async (
+ projectId: string,
+ shortId: string,
+ patchedHeatmapScreenshotResponseApi?: NonReadonly<PatchedHeatmapScreenshotResponseApi>,
+ options?: RequestInit
+): Promise<HeatmapScreenshotResponseApi> => {
+ return apiMutator<HeatmapScreenshotResponseApi>(getSavedPartialUpdateUrl(projectId, shortId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedHeatmapScreenshotResponseApi),
+ })
+}
+
+export const getSavedDestroyUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/saved/${shortId}/`
+}
+
+/**
+ * Hard delete of this model is not allowed. Use a patch API call to set "deleted" to true
+ */
+export const savedDestroy = async (projectId: string, shortId: string, options?: RequestInit): Promise<unknown> => {
+ return apiMutator<unknown>(getSavedDestroyUrl(projectId, shortId), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getSavedRegenerateCreateUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/saved/${shortId}/regenerate/`
+}
+
+export const savedRegenerateCreate = async (
+ projectId: string,
+ shortId: string,
+ heatmapScreenshotResponseApi: NonReadonly<HeatmapScreenshotResponseApi>,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getSavedRegenerateCreateUrl(projectId, shortId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(heatmapScreenshotResponseApi),
+ })
+}
diff --git a/products/web_analytics/frontend/generated/api.zod.ts b/products/web_analytics/frontend/generated/api.zod.ts
index e8a15d4e1b52..964e69037552 100644
--- a/products/web_analytics/frontend/generated/api.zod.ts
+++ b/products/web_analytics/frontend/generated/api.zod.ts
@@ -7,3 +7,88 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+import * as zod from 'zod'
+
+export const webAnalyticsFilterPresetsCreateBodyNameMax = 400
+
+export const WebAnalyticsFilterPresetsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(webAnalyticsFilterPresetsCreateBodyNameMax),
+ description: zod.string().optional(),
+ pinned: zod.boolean().optional(),
+ deleted: zod.boolean().optional(),
+ filters: zod.unknown().optional(),
+})
+
+export const webAnalyticsFilterPresetsUpdateBodyNameMax = 400
+
+export const WebAnalyticsFilterPresetsUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(webAnalyticsFilterPresetsUpdateBodyNameMax),
+ description: zod.string().optional(),
+ pinned: zod.boolean().optional(),
+ deleted: zod.boolean().optional(),
+ filters: zod.unknown().optional(),
+})
+
+export const webAnalyticsFilterPresetsPartialUpdateBodyNameMax = 400
+
+export const WebAnalyticsFilterPresetsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(webAnalyticsFilterPresetsPartialUpdateBodyNameMax).optional(),
+ description: zod.string().optional(),
+ pinned: zod.boolean().optional(),
+ deleted: zod.boolean().optional(),
+ filters: zod.unknown().optional(),
+})
+
+export const savedCreateBodyNameMax = 400
+
+export const savedCreateBodyUrlMax = 2000
+
+export const savedCreateBodyDataUrlMax = 2000
+
+export const SavedCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(savedCreateBodyNameMax).nullish(),
+ url: zod.url().max(savedCreateBodyUrlMax),
+ data_url: zod.url().max(savedCreateBodyDataUrlMax).nullish().describe('URL for fetching heatmap data'),
+ target_widths: zod.unknown().optional(),
+ type: zod
+ .enum(['screenshot', 'iframe', 'recording'])
+ .optional()
+ .describe('\* `screenshot` - Screenshot\n\* `iframe` - Iframe\n\* `recording` - Recording'),
+ deleted: zod.boolean().optional(),
+})
+
+export const savedPartialUpdateBodyNameMax = 400
+
+export const savedPartialUpdateBodyUrlMax = 2000
+
+export const savedPartialUpdateBodyDataUrlMax = 2000
+
+export const SavedPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(savedPartialUpdateBodyNameMax).nullish(),
+ url: zod.url().max(savedPartialUpdateBodyUrlMax).optional(),
+ data_url: zod.url().max(savedPartialUpdateBodyDataUrlMax).nullish().describe('URL for fetching heatmap data'),
+ target_widths: zod.unknown().optional(),
+ type: zod
+ .enum(['screenshot', 'iframe', 'recording'])
+ .optional()
+ .describe('\* `screenshot` - Screenshot\n\* `iframe` - Iframe\n\* `recording` - Recording'),
+ deleted: zod.boolean().optional(),
+})
+
+export const savedRegenerateCreateBodyNameMax = 400
+
+export const savedRegenerateCreateBodyUrlMax = 2000
+
+export const savedRegenerateCreateBodyDataUrlMax = 2000
+
+export const SavedRegenerateCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(savedRegenerateCreateBodyNameMax).nullish(),
+ url: zod.url().max(savedRegenerateCreateBodyUrlMax),
+ data_url: zod.url().max(savedRegenerateCreateBodyDataUrlMax).nullish().describe('URL for fetching heatmap data'),
+ target_widths: zod.unknown().optional(),
+ type: zod
+ .enum(['screenshot', 'iframe', 'recording'])
+ .optional()
+ .describe('\* `screenshot` - Screenshot\n\* `iframe` - Iframe\n\* `recording` - Recording'),
+ deleted: zod.boolean().optional(),
+})
diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yaml
index 06d584becb8f..95cdd4966155 100644
--- a/products/web_analytics/mcp/tools.yaml
+++ b/products/web_analytics/mcp/tools.yaml
@@ -9,6 +9,48 @@ feature: web_analytics
url_prefix: /web
ui_apps: {}
tools:
+ heatmaps-events-retrieve:
+ operation: heatmaps_events_retrieve
+ enabled: false
+ heatmaps-list:
+ operation: heatmaps_list
+ enabled: false
+ saved-create:
+ operation: saved_create
+ enabled: false
+ saved-destroy:
+ operation: saved_destroy
+ enabled: false
+ saved-list:
+ operation: saved_list
+ enabled: false
+ saved-partial-update:
+ operation: saved_partial_update
+ enabled: false
+ saved-regenerate-create:
+ operation: saved_regenerate_create
+ enabled: false
+ saved-retrieve:
+ operation: saved_retrieve
+ enabled: false
+ web-analytics-filter-presets-create:
+ operation: web_analytics_filter_presets_create
+ enabled: false
+ web-analytics-filter-presets-destroy:
+ operation: web_analytics_filter_presets_destroy
+ enabled: false
+ web-analytics-filter-presets-list:
+ operation: web_analytics_filter_presets_list
+ enabled: false
+ web-analytics-filter-presets-partial-update:
+ operation: web_analytics_filter_presets_partial_update
+ enabled: false
+ web-analytics-filter-presets-retrieve:
+ operation: web_analytics_filter_presets_retrieve
+ enabled: false
+ web-analytics-filter-presets-update:
+ operation: web_analytics_filter_presets_update
+ enabled: false
web-analytics-weekly-digest:
operation: web_analytics_weekly_digest
enabled: true
diff --git a/tach.toml b/tach.toml
index 0263e67c8a8b..76da02121894 100644
--- a/tach.toml
+++ b/tach.toml
@@ -540,6 +540,7 @@ depends_on = [
"ee",
"posthog",
"products.actions",
+ "products.analytics_platform",
]
layer = "modules"