: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
fix(dashboards): fire widget removed/filters-updated analytics from PATCH path (#63298)
Matt Puab5dbfc3c873e
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex d000cc6a3670..d2107b72768e 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -1002,6 +1002,7 @@ def _report_dashboard_tile_added(widget_properties: dict[str, Any] = {"widget_type": widget_type,"dashboard_id": dashboard.id,+ "dashboard_widget_count": _count_active_widget_tiles(dashboard),}feature_enabled = get_widget_feature_enabled(widget_type, dashboard.team)if feature_enabled is not None:@@ -1393,7 +1394,7 @@ class DashboardSerializer(DashboardMetadataSerializer):user = cast(User, self.context["request"].user)tiles = initial_data.pop("tiles", [])for tile_data in tiles:- tile, created = self._update_tiles(instance, tile_data, user)+ tile, created = self._update_tiles(instance, tile_data, user, request=self.context.get("request"))# Text and button tiles are always added via PATCH (never during initial dashboard# creation), so this update() method is the right place to fire the "tile added"# event. The `created` flag from update_or_create ensures we only fire on first@@ -1485,12 +1486,15 @@ class DashboardSerializer(DashboardMetadataSerializer):widget_data: dict[str, Any],user: User,user_access_control: UserAccessControl,+ dashboard: Dashboard,+ request: Request | None = None,) -> None:DashboardSerializer._check_widget_tile_product_access(widget, user_access_control)patch_widget_type = widget_data.get("widget_type")if patch_widget_type is not None and str(patch_widget_type) != widget.widget_type:raise serializers.ValidationError({"widget": "widget_type cannot be changed."})+ previous_widget_filters = (widget.config or {}).get("widgetFilters")if "config" in widget_data:widget.config = validate_widget_config(widget.widget_type,@@ -1504,6 +1508,21 @@ class DashboardSerializer(DashboardMetadataSerializer):widget.last_modified_at = now()widget.save()+ new_widget_filters = (widget.config or {}).get("widgetFilters")+ if "config" in widget_data and new_widget_filters != previous_widget_filters:+ report_user_action(+ user,+ "dashboard widget filters updated",+ {+ "widget_type": widget.widget_type,+ "dashboard_id": dashboard.id,+ "widget_id": str(widget.id),+ "filters_count": len(new_widget_filters) if new_widget_filters else 0,+ },+ team=dashboard.team,+ request=request,+ )+@staticmethoddef _upsert_tile(instance: Dashboard, tile_data: dict, **extra_defaults: Any) -> tuple[DashboardTile, bool]:tile_defaults = DashboardSerializer._extract_display_defaults(tile_data)@@ -1515,21 +1534,23 @@ class DashboardSerializer(DashboardMetadataSerializer):)@staticmethod- def _update_existing_tile_display_fields(instance: Dashboard, tile_data: dict) -> None:+ def _update_existing_tile_display_fields(instance: Dashboard, tile_data: dict) -> tuple[DashboardTile | None, bool]:"""Update display fields on an existing tile, or skip silently if the id is unknown.A display-only payload carries no insight/text/button_tile FK, so it cannot satisfythe ``dash_tile_exactly_one_related_object`` CHECK constraint if it falls through toan INSERT. ``update_or_create`` here used to 500 whenever the frontend posted a staletile id (cross-dashboard contamination, hard-deleted tiles, races). Never INSERT here.++ Returns the updated tile and whether this payload transitioned it to soft-deleted."""tile_id = tile_data.get("id")if tile_id is None:- return+ return None, Falsetile_defaults = DashboardSerializer._extract_display_defaults(tile_data)if not tile_defaults:- return+ return None, Falseexisting = DashboardTile.objects_including_soft_deleted.filter(id=tile_id, dashboard=instance, dashboard__team_id=instance.team_id@@ -1542,21 +1563,25 @@ class DashboardSerializer(DashboardMetadataSerializer):tile_id=tile_id,payload_fields=sorted(tile_defaults.keys()),)- return+ return None, False+ became_deleted = bool(tile_defaults.get("deleted")) and not existing.deletedfor attr, val in tile_defaults.items():setattr(existing, attr, val)# update_fields scopes the UPDATE to only the columns we changed, so concurrent writes# to other columns aren't clobbered by our stale read. save() (vs queryset.update())# keeps the post_save signal that sync_dashboard_tile listens to for cache invalidation.existing.save(update_fields=list(tile_defaults.keys()))+ return existing, became_deleted@staticmethoddef _tile_added_analytics_fields(tile: DashboardTile) -> tuple[str, str | None]:return _tile_type_and_widget_type(tile)@staticmethod- def _update_tiles(instance: Dashboard, tile_data: dict, user: User) -> tuple[DashboardTile | None, bool]:+ def _update_tiles(+ instance: Dashboard, tile_data: dict, user: User, request: Request | None = None+ ) -> tuple[DashboardTile | None, bool]:"""Returns the upserted tile and whether it was newly created, or (None, False) for display-only updates."""tile_data.pop("is_cached", None) # read only fieldtile_data.pop("order", None) # read only field@@ -1663,6 +1688,8 @@ class DashboardSerializer(DashboardMetadataSerializer):widget_data=widget_data,user=user,user_access_control=user_access_control,+ dashboard=instance,+ request=request,)except DashboardWidget.DoesNotExist:raise serializers.ValidationError({"widget": "Widget not found in this team."})@@ -1700,7 +1727,16 @@ class DashboardSerializer(DashboardMetadataSerializer):or "transparent_background" in tile_data):tile_data.pop("insight", None) # don't ever update insight tiles here- DashboardSerializer._update_existing_tile_display_fields(instance, tile_data)+ updated_tile, became_deleted = DashboardSerializer._update_existing_tile_display_fields(instance, tile_data)+ # The dashboard UI soft-deletes tiles through this PATCH path rather than the+ # delete_tile endpoint, so removal analytics must fire here too.+ if became_deleted and updated_tile is not None:+ _report_dashboard_tile_removed(+ user=user,+ dashboard=instance,+ tile=updated_tile,+ request=request,+ )return None, Falsediff --git a/products/dashboards/backend/api/test/test_dashboard_widgets.py b/products/dashboards/backend/api/test/test_dashboard_widgets.pyindex 51dcee6ed49d..7e37ecfd0415 100644--- a/products/dashboards/backend/api/test/test_dashboard_widgets.py+++ b/products/dashboards/backend/api/test/test_dashboard_widgets.py@@ -663,6 +663,7 @@ class TestDashboardWidgets(APIBaseTest):assert len(widget_added_calls) == 1assert widget_added_calls[0][0][2]["widget_type"] == "error_tracking_list"assert widget_added_calls[0][0][2]["dashboard_id"] == dashboard_id+ assert widget_added_calls[0][0][2]["dashboard_widget_count"] == 1assert "tile_id" in widget_added_calls[0][0][2]assert "widget_id" in widget_added_calls[0][0][2]@@ -700,6 +701,7 @@ class TestDashboardWidgets(APIBaseTest):assert len(widget_added_calls) == 1assert widget_added_calls[0][0][2]["widget_type"] == "error_tracking_list"assert widget_added_calls[0][0][2]["dashboard_id"] == dashboard_id+ assert widget_added_calls[0][0][2]["dashboard_widget_count"] == 1assert "tile_id" in widget_added_calls[0][0][2]assert "widget_id" in widget_added_calls[0][0][2]@@ -794,6 +796,106 @@ class TestDashboardWidgets(APIBaseTest):assert widget_removed_calls[0][0][2]["tile_id"] == tile_idassert "widget_id" in widget_removed_calls[0][0][2]+ @override_settings(IN_UNIT_TESTING=True)+ @patch("products.dashboards.backend.api.dashboard.report_user_action")+ def test_soft_delete_widget_tile_via_dashboard_patch_fires_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.patch(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}",+ {"tiles": [{"id": tile_id, "deleted": True}]},+ )+ assert response.status_code == status.HTTP_200_OK++ removed_events = [call[0][1] for call in mock_report_user_action.call_args_list]+ assert "dashboard tile removed" in removed_events+ 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++ # Re-sending the same soft-delete payload must not double-report the removal+ mock_report_user_action.reset_mock()+ response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}",+ {"tiles": [{"id": tile_id, "deleted": True}]},+ )+ assert response.status_code == status.HTTP_200_OK+ for call in mock_report_user_action.call_args_list:+ assert call[0][1] not in ("dashboard tile removed", "dashboard widget removed")++ @override_settings(IN_UNIT_TESTING=True)+ @patch("products.dashboards.backend.api.dashboard.report_user_action")+ def test_update_widget_filters_via_dashboard_patch_fires_filters_updated_event(+ 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 = dashboard_json["tiles"][0]+ tile["widget"]["config"] = {+ "limit": 10,+ "widgetFilters": {+ "qf-1": {+ "filterId": "qf-1",+ "propertyName": "$environment",+ "optionId": "opt-1",+ "operator": "exact",+ "value": "production",+ }+ },+ }+ mock_report_user_action.reset_mock()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}",+ {"tiles": [tile]},+ )+ assert response.status_code == status.HTTP_200_OK++ filters_updated_calls = [+ call for call in mock_report_user_action.call_args_list if call[0][1] == "dashboard widget filters updated"+ ]+ assert len(filters_updated_calls) == 1+ assert filters_updated_calls[0][0][2]["widget_type"] == "error_tracking_list"+ assert filters_updated_calls[0][0][2]["dashboard_id"] == dashboard_id+ assert filters_updated_calls[0][0][2]["widget_id"] == tile["widget"]["id"]+ assert filters_updated_calls[0][0][2]["filters_count"] == 1++ @override_settings(IN_UNIT_TESTING=True)+ @patch("products.dashboards.backend.api.dashboard.report_user_action")+ def test_update_widget_config_without_filters_change_does_not_fire_filters_updated_event(+ 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 = dashboard_json["tiles"][0]+ tile["widget"]["config"] = {"limit": 15}+ mock_report_user_action.reset_mock()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}",+ {"tiles": [tile]},+ )+ assert response.status_code == status.HTTP_200_OK++ for call in mock_report_user_action.call_args_list:+ assert call[0][1] != "dashboard widget filters updated"+@override_settings(IN_UNIT_TESTING=True)def test_can_batch_create_widget_tiles(self) -> None:dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})@@ -846,6 +948,28 @@ class TestDashboardWidgets(APIBaseTest):dashboard = Dashboard.objects.get(id=dashboard_id)assert dashboard.tiles.filter(widget__isnull=False).count() == 0+ @override_settings(IN_UNIT_TESTING=True)+ @patch("products.dashboards.backend.api.dashboard.report_user_action")+ def test_dashboard_widget_count_increments_with_each_add(self, mock_report_user_action) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dashboard"})+ mock_report_user_action.reset_mock()++ # First widget+ self.dashboard_api.create_widget_tile(dashboard_id, widget_type="error_tracking_list", config={"limit": 5})+ first_add = next(+ call for call in mock_report_user_action.call_args_list if call[0][1] == "dashboard widget added"+ )+ assert first_add[0][2]["dashboard_widget_count"] == 1++ mock_report_user_action.reset_mock()++ # Second widget on the same dashboard+ self.dashboard_api.create_widget_tile(dashboard_id, widget_type="session_replay_list")+ second_add = next(+ call for call in mock_report_user_action.call_args_list if call[0][1] == "dashboard widget added"+ )+ assert second_add[0][2]["dashboard_widget_count"] == 2+@override_settings(IN_UNIT_TESTING=True)@patch("products.dashboards.backend.api.dashboard.report_user_action")def test_update_widget_tile_does_not_fire_tile_added_event(self, mock_report_user_action) -> None: