:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(dashboards): capture dashboard tile removed analytics event (#62978)
Matt Pua5cc2f12aea17
diff --git a/posthog/api/test/dashboards/test_dashboard_delete_tile.py b/posthog/api/test/dashboards/test_dashboard_delete_tile.pyindex 8453c7f17fd6..49f0dc010b5e 100644--- a/posthog/api/test/dashboards/test_dashboard_delete_tile.py+++ b/posthog/api/test/dashboards/test_dashboard_delete_tile.py@@ -1,4 +1,5 @@from posthog.test.base import APIBaseTest+from unittest.mock import ANY, patchfrom django.test import override_settings@@ -54,6 +55,38 @@ class TestDashboardDeleteTile(APIBaseTest):insight_response = self.client.get(f"/api/projects/{self.team.id}/insights/{insight_id}")assert insight_response.status_code == status.HTTP_200_OK+ def _create_text_tile_for_removal(self, dashboard_id: int) -> int:+ _, dashboard_json = self.dashboard_api.create_text_tile(dashboard_id, text="hello world")+ return dashboard_json["tiles"][0]["id"]++ def _create_insight_tile_for_removal(self, dashboard_id: int) -> int:+ self.dashboard_api.create_insight({"name": "insight", "dashboards": [dashboard_id]})+ return self.dashboard_api.get_dashboard(dashboard_id)["tiles"][0]["id"]++ @parameterized.expand(+ [+ ("text", _create_text_tile_for_removal, {"tile_type": "text", "insight_type": None}),+ ("insight", _create_insight_tile_for_removal, {"tile_type": "insight", "insight_type": "trends"}),+ ]+ )+ @patch("products.dashboards.backend.api.dashboard.report_user_action")+ def test_delete_tile_fires_tile_removed_event(+ self, _name, create_tile, expected_properties, mock_report_user_action+ ) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})+ tile_id = create_tile(self, dashboard_id)+ mock_report_user_action.reset_mock()++ self._delete_tile(dashboard_id, tile_id)++ mock_report_user_action.assert_any_call(+ self.user,+ "dashboard tile removed",+ {**expected_properties, "dashboard_id": dashboard_id},+ team=ANY,+ request=ANY,+ )+def _setup_unknown_tile_id(self) -> tuple[int, int]:dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})return dashboard_id, 9_999_999diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 5c4b5413c635..d000cc6a3670 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -106,6 +106,7 @@ from products.product_analytics.backend.api.insight import (DashboardTileBasicSerializer,InsightSerializer,InsightViewSet,+ _get_insight_type,)from products.product_analytics.backend.models.insight import Insightfrom products.product_analytics.backend.models.insight_variable import InsightVariable@@ -957,6 +958,19 @@ def _check_dashboard_widget_count_limit(*, dashboard: Dashboard, user: User) ->)+def _tile_type_and_widget_type(tile: DashboardTile) -> tuple[str, str | None]:+ if tile.text_id is not None:+ return "text", None+ if tile.button_tile_id is not None:+ return "button", None+ if tile.widget_id is not None:+ widget_type = tile.widget.widget_type if tile.widget is not None else None+ return "widget", widget_type+ if tile.insight_id is not None:+ return "insight", None+ raise ValueError("Dashboard tile has no related content for analytics")++def _report_dashboard_tile_added(*,user: User,@@ -1007,6 +1021,51 @@ def _report_dashboard_tile_added()+def _report_dashboard_tile_removed(+ *,+ user: User,+ dashboard: Dashboard,+ tile: DashboardTile,+ request: Request | None = None,+) -> None:+ tile_type, widget_type = _tile_type_and_widget_type(tile)+ insight_type = _get_insight_type(tile.insight) if tile.insight is not None else None+ properties: dict[str, Any] = {+ "tile_type": tile_type,+ "insight_type": insight_type,+ "dashboard_id": dashboard.id,+ }+ if widget_type is not None:+ properties["widget_type"] = widget_type++ report_user_action(+ user,+ "dashboard tile removed",+ properties,+ team=dashboard.team,+ request=request,+ )++ if widget_type is None:+ return++ widget_properties: dict[str, Any] = {+ "widget_type": widget_type,+ "dashboard_id": dashboard.id,+ "tile_id": tile.id,+ }+ if tile.widget_id is not None:+ widget_properties["widget_id"] = str(tile.widget_id)++ report_user_action(+ user,+ "dashboard widget removed",+ widget_properties,+ team=dashboard.team,+ request=request,+ )++class DashboardSerializer(DashboardMetadataSerializer):tiles = serializers.SerializerMethodField()use_template = serializers.CharField(@@ -1494,16 +1553,7 @@ class DashboardSerializer(DashboardMetadataSerializer):@staticmethoddef _tile_added_analytics_fields(tile: DashboardTile) -> tuple[str, str | None]:- if tile.text_id is not None:- return "text", None- if tile.button_tile_id is not None:- return "button", None- if tile.widget_id is not None:- widget_type = tile.widget.widget_type if tile.widget is not None else None- return "widget", widget_type- if tile.insight_id is not None:- return "insight", None- raise ValueError("Dashboard tile has no related content for analytics")+ return _tile_type_and_widget_type(tile)@staticmethoddef _update_tiles(instance: Dashboard, tile_data: dict, user: User) -> tuple[DashboardTile | None, bool]:@@ -2399,6 +2449,13 @@ class DashboardsViewSet(["layouts"],)+ _report_dashboard_tile_removed(+ user=cast(User, request.user),+ dashboard=dashboard,+ tile=tile,+ request=request,+ )+return Response(status=status.HTTP_204_NO_CONTENT)@extend_schema(diff --git a/products/dashboards/backend/api/test/test_dashboard_widgets.py b/products/dashboards/backend/api/test/test_dashboard_widgets.pyindex 373f6d3805cc..51dcee6ed49d 100644--- a/products/dashboards/backend/api/test/test_dashboard_widgets.py+++ b/products/dashboards/backend/api/test/test_dashboard_widgets.py@@ -756,6 +756,44 @@ class TestDashboardWidgets(APIBaseTest):assert widget_added_calls[0][0][2]["widget_type"] == widget_typeassert widget_added_calls[0][0][2]["feature_enabled"] is expected+ @override_settings(IN_UNIT_TESTING=True)+ @patch("products.dashboards.backend.api.dashboard.report_user_action")+ def test_delete_widget_tile_fires_tile_removed_and_widget_removed_events(self, mock_report_user_action) -> None:+ dashboard_id, dashboard_json = self.dashboard_api.create_widget_tile(+ dashboard_id=self.dashboard_api.create_dashboard({"name": "dashboard"})[0],+ widget_type="error_tracking_list",+ config={"limit": 10},+ )+ tile_id = dashboard_json["tiles"][0]["id"]+ mock_report_user_action.reset_mock()++ response = self.client.post(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}/delete_tile",+ {"tile_id": tile_id},+ )+ assert response.status_code == status.HTTP_204_NO_CONTENT++ mock_report_user_action.assert_any_call(+ self.user,+ "dashboard tile removed",+ {+ "tile_type": "widget",+ "insight_type": None,+ "dashboard_id": dashboard_id,+ "widget_type": "error_tracking_list",+ },+ team=ANY,+ request=ANY,+ )+ widget_removed_calls = [+ call for call in mock_report_user_action.call_args_list if call[0][1] == "dashboard widget removed"+ ]+ assert len(widget_removed_calls) == 1+ assert widget_removed_calls[0][0][2]["widget_type"] == "error_tracking_list"+ assert widget_removed_calls[0][0][2]["dashboard_id"] == dashboard_id+ assert widget_removed_calls[0][0][2]["tile_id"] == tile_id+ assert "widget_id" in widget_removed_calls[0][0][2]+@override_settings(IN_UNIT_TESTING=True)def test_can_batch_create_widget_tiles(self) -> None:dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.pyindex dfc91ea46af8..b11f5b21590d 100644--- a/products/product_analytics/backend/api/insight.py+++ b/products/product_analytics/backend/api/insight.py@@ -823,8 +823,24 @@ class InsightSerializer(InsightBasicSerializer):f"You don't have permission to remove insights from dashboard: {dashboard.id}")+ # Capture the still-active tiles before soft-deleting so we report one+ # "dashboard tile removed" per tile that is actually removed.+ tiles_to_remove = list(DashboardTile.objects.filter(dashboard_id__in=ids_to_remove, insight=instance))DashboardTile.objects.filter(dashboard_id__in=ids_to_remove, insight=instance).update(deleted=True)+ for tile in tiles_to_remove:+ report_user_action(+ self.context["request"].user,+ "dashboard tile removed",+ {+ "tile_type": "insight",+ "insight_type": _get_insight_type(instance),+ "dashboard_id": tile.dashboard_id,+ },+ team=instance.team,+ request=self.context["request"],+ )+self.context["after_dashboard_changes"] = [describe_change(d) for d in dashboards if not d.deleted]@extend_schema_field(OpenApiTypes.ANY)diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.pyindex 248f9bcc6a16..8db28f0ec84e 100644--- a/products/product_analytics/backend/api/test/test_insight.py+++ b/products/product_analytics/backend/api/test/test_insight.py@@ -1496,6 +1496,24 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):request=ANY,)+ @patch("products.product_analytics.backend.api.insight.report_user_action")+ def test_removing_insight_from_dashboard_fires_tile_removed_event(self, mock_report_user_action: mock.Mock) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "test"})+ insight_id, _ = self.dashboard_api.create_insight(+ {"filters": {"insight": "STICKINESS"}, "dashboards": [dashboard_id]}+ )+ mock_report_user_action.reset_mock()++ self.dashboard_api.update_insight(insight_id, {"dashboards": []})++ mock_report_user_action.assert_any_call(+ self.user,+ "dashboard tile removed",+ {"tile_type": "insight", "insight_type": "stickiness", "dashboard_id": dashboard_id},+ team=ANY,+ request=ANY,+ )+def test_can_update_insight_dashboards_without_deleting_tiles(self) -> None:dashboard_one_id, _ = self.dashboard_api.create_dashboard({})dashboard_two_id, _ = self.dashboard_api.create_dashboard({})