Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: delete multiple insights (#68643)

Christian Raffertyff9974436998
diff --git a/frontend/src/scenes/saved-insights/SavedInsights.tsx b/frontend/src/scenes/saved-insights/SavedInsights.tsx
index a816a4698fe6..39e027754f0d 100644
--- a/frontend/src/scenes/saved-insights/SavedInsights.tsx
+++ b/frontend/src/scenes/saved-insights/SavedInsights.tsx
@@ -26,6 +26,7 @@ import {
IconHeart,
IconHeartFilled,
IconStickiness,
+ IconTrash,
IconTrends,
IconUserPaths,
IconVideoCamera,
@@ -818,10 +819,24 @@ export function NewInsightButton(): JSX.Element {
}
export function SavedInsights(): JSX.Element {
- const { loadInsights, updateFavoritedInsight, renameInsight, duplicateInsight, setSavedInsightsFilters } =
- useActions(savedInsightsLogic)
- const { insights, insightsLoading, filters, sorting, pagination, alertModalId, usingFilters } =
- useValues(savedInsightsLogic)
+ const {
+ loadInsights,
+ updateFavoritedInsight,
+ renameInsight,
+ duplicateInsight,
+ setSavedInsightsFilters,
+ bulkDeleteInsights,
+ } = useActions(savedInsightsLogic)
+ const {
+ insights,
+ insightsLoading,
+ filters,
+ sorting,
+ pagination,
+ alertModalId,
+ usingFilters,
+ bulkDeleteResponseLoading,
+ } = useValues(savedInsightsLogic)
const { currentProjectId } = useValues(projectLogic)
const summarizeInsight = useSummarizeInsight()
@@ -1113,14 +1128,44 @@ export function SavedInsights(): JSX.Element {
`Select insight ${insight.name || 'Untitled'}`,
headerAriaLabel: 'Select all insights on this page',
renderActions: (ctx) => (
- <BulkUpdateTagsButton
- resource="insights"
- selectedIds={ctx.selectedKeys}
- onSuccess={() => {
- ctx.clearSelection()
- loadInsights()
- }}
- />
+ <>
+ <BulkUpdateTagsButton
+ resource="insights"
+ selectedIds={ctx.selectedKeys}
+ onSuccess={() => {
+ ctx.clearSelection()
+ loadInsights()
+ }}
+ />
+ <LemonButton
+ type="primary"
+ status="danger"
+ size="small"
+ icon={<IconTrash />}
+ loading={bulkDeleteResponseLoading}
+ onClick={() => {
+ const count = ctx.selectedCount
+ const noun = count === 1 ? 'insight' : 'insights'
+ LemonDialog.open({
+ title: `Delete ${count} ${noun}?`,
+ description: `Are you sure you want to delete ${count} ${noun}? This action can be undone.`,
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => {
+ bulkDeleteInsights({ ids: [...ctx.selectedKeys] })
+ ctx.clearSelection()
+ },
+ },
+ secondaryButton: {
+ children: 'Cancel',
+ },
+ })
+ }}
+ >
+ Delete selected
+ </LemonButton>
+ </>
),
}}
/>
diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
index e5af3d9f74db..80d2f2b04217 100644
--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.ts
@@ -25,6 +25,11 @@ import { insightsModel } from '~/models/insightsModel'
import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'
import { Breadcrumb, InsightModel, QueryBasedInsightModel, SavedInsightsTabs } from '~/types'
+import {
+ InsightBulkDeleteResponseApi,
+ InsightBulkRestoreResponseApi,
+} from 'products/product_analytics/frontend/generated/api.schemas'
+
import { teamLogic } from '../teamLogic'
import type { savedInsightsLogicType } from './savedInsightsLogicType'
@@ -175,6 +180,26 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
return { ...values.insights, results: updatedInsights }
},
},
+ bulkDeleteResponse: [
+ null as InsightBulkDeleteResponseApi | null,
+ {
+ bulkDeleteInsights: async ({ ids }: { ids: number[] }) => {
+ return (await api.create(`api/environments/${values.currentTeamId}/insights/bulk_delete/`, {
+ ids,
+ })) as InsightBulkDeleteResponseApi
+ },
+ },
+ ],
+ bulkRestoreResponse: [
+ null as InsightBulkRestoreResponseApi | null,
+ {
+ bulkRestoreInsights: async ({ ids }: { ids: number[] }) => {
+ return (await api.create(`api/environments/${values.currentTeamId}/insights/bulk_restore/`, {
+ ids,
+ })) as InsightBulkRestoreResponseApi
+ },
+ },
+ ],
})),
reducers({
insights: {
@@ -381,6 +406,44 @@ export const savedInsightsLogic = kea<savedInsightsLogicType>([
actions.loadInsights()
}
},
+ bulkDeleteInsightsSuccess: ({ bulkDeleteResponse }) => {
+ if (!bulkDeleteResponse) {
+ return
+ }
+ const { deleted, skipped } = bulkDeleteResponse
+ const deletedIds = deleted.map((insight) => insight.id)
+ if (deletedIds.length > 0) {
+ const noun = deletedIds.length === 1 ? 'insight' : 'insights'
+ const skippedSuffix = skipped.length > 0 ? ` ${skipped.length} skipped (no permission).` : ''
+ lemonToast.info(`Deleted ${deletedIds.length} ${noun}.${skippedSuffix}`, {
+ toastId: 'bulk-delete-insights',
+ button: {
+ label: 'Undo',
+ action: () => actions.bulkRestoreInsights({ ids: deletedIds }),
+ },
+ })
+ } else if (skipped.length > 0) {
+ lemonToast.warning(`No insights deleted. ${skipped.length} skipped due to permissions.`)
+ }
+ actions.loadInsights()
+ },
+ bulkDeleteInsightsFailure: () => {
+ lemonToast.error('Failed to delete insights')
+ },
+ bulkRestoreInsightsSuccess: ({ bulkRestoreResponse }) => {
+ if (!bulkRestoreResponse) {
+ return
+ }
+ const { restored } = bulkRestoreResponse
+ if (restored.length > 0) {
+ const noun = restored.length === 1 ? 'insight' : 'insights'
+ lemonToast.success(`Restored ${restored.length} ${noun}`)
+ }
+ actions.loadInsights()
+ },
+ bulkRestoreInsightsFailure: () => {
+ lemonToast.error('Failed to restore insights')
+ },
})),
trackedActionToUrl(({ values }) => {
const changeUrl = ():
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index 97b423848188..1314f424cdfd 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -88,6 +88,8 @@ from posthog.models import Filter, User
from posthog.models.activity_logging.activity_log import (
Change,
Detail,
+ LogActivityEntry,
+ bulk_log_activity,
changes_between,
describe_change,
load_activity,
@@ -107,7 +109,11 @@ from posthog.rate_limit import (
ClickHouseSustainedRateThrottle,
)
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
-from posthog.rbac.user_access_control import UserAccessControlError, UserAccessControlSerializerMixin
+from posthog.rbac.user_access_control import (
+ UserAccessControlError,
+ UserAccessControlSerializerMixin,
+ access_level_satisfied_for_resource,
+)
from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade import upgrade
from posthog.schema_migrations.upgrade_manager import upgrade_query
@@ -965,8 +971,6 @@ class InsightSerializer(InsightBasicSerializer):
# Check if user has access to this insight when viewed in dashboard context
if self.context.get("dashboard"):
- from posthog.rbac.user_access_control import access_level_satisfied_for_resource
-
user_access_level = representation.get("user_access_level")
if user_access_level and not access_level_satisfied_for_resource("insight", user_access_level, "viewer"):
# User doesn't have sufficient access - return minimal insight data
@@ -1266,6 +1270,50 @@ class InsightViewedRequestSerializer(serializers.Serializer):
)
+INSIGHT_BULK_DELETE_MAX_IDS = 1000
+
+
+class InsightBulkDeleteRequestSerializer(serializers.Serializer):
+ ids = serializers.ListField(
+ child=serializers.IntegerField(min_value=1),
+ allow_empty=False,
+ max_length=INSIGHT_BULK_DELETE_MAX_IDS,
+ help_text=(
+ f"Insight IDs to soft-delete (or restore). At most {INSIGHT_BULK_DELETE_MAX_IDS} ids per request. "
+ "Soft-deleted insights can be brought back via the bulk_restore endpoint."
+ ),
+ )
+
+
+class InsightBulkOperationResultSerializer(serializers.Serializer):
+ id = serializers.IntegerField(help_text="ID of the insight that was soft-deleted or restored.")
+ name = serializers.CharField(
+ allow_null=True,
+ help_text="The insight's name (or derived name) at the time of the operation; null when it has neither.",
+ )
+
+
+class InsightBulkOperationSkippedSerializer(serializers.Serializer):
+ id = serializers.IntegerField(help_text="ID of the insight that was skipped.")
+ reason = serializers.CharField(
+ help_text="Human-readable reason the insight was skipped (for example, not found or no edit permission)."
+ )
+
+
+class InsightBulkDeleteResponseSerializer(serializers.Serializer):
+ deleted = InsightBulkOperationResultSerializer(many=True, help_text="Insights that were successfully soft-deleted.")
+ skipped = InsightBulkOperationSkippedSerializer(
+ many=True, help_text="Insights that were not deleted, with the reason for each."
+ )
+
+
+class InsightBulkRestoreResponseSerializer(serializers.Serializer):
+ restored = InsightBulkOperationResultSerializer(many=True, help_text="Insights that were successfully restored.")
+ skipped = InsightBulkOperationSkippedSerializer(
+ many=True, help_text="Insights that were not restored, with the reason for each."
+ )
+
+
@extend_schema(extensions={"x-product": ProductKey.PRODUCT_ANALYTICS})
@extend_schema_view(
list=extend_schema(
@@ -2182,6 +2230,159 @@ When set, the specified dashboard's filters and date range override will be appl
return Response(status=status.HTTP_201_CREATED)
+ # `Sequence` rather than `list` here: this viewset defines a `list` method that shadows the builtin `list`
+ # in the class namespace, so `list[...]` in this signature breaks both at class-definition time and for mypy.
+ def _bulk_filter_editable_insights(
+ self, ids: Sequence[int], *, deleted: bool
+ ) -> tuple[Sequence[Insight], Sequence[dict[str, Any]]]:
+ """Resolve `ids` to insights in this project with the given `deleted` state, split into the ones
+ the requester may edit and `skipped` entries (not found, or missing edit permission)."""
+ # objects_including_soft_deleted so the restore path (deleted=True) can find soft-deleted insights;
+ # the default manager excludes them.
+ insights = list(
+ Insight.objects_including_soft_deleted.filter(
+ id__in=ids, team__project_id=self.team.project_id, deleted=deleted
+ )
+ )
+ found_ids = {insight.id for insight in insights}
+ skipped: list[dict[str, Any]] = [
+ {"id": missing_id, "reason": "Insight not found"} for missing_id in ids if missing_id not in found_ids
+ ]
+
+ if not insights or not self.user_access_control:
+ return insights, skipped
+
+ self.user_access_control.preload_object_access_controls(cast(list, insights))
+ editable: list[Insight] = []
+ for insight in insights:
+ user_access_level = self.user_access_control.get_user_access_level(insight)
+ if user_access_level and access_level_satisfied_for_resource("insight", user_access_level, "editor"):
+ editable.append(insight)
+ else:
+ skipped.append({"id": insight.id, "reason": "You don't have permission to edit this insight"})
+ return editable, skipped
+
+ @validated_request(
+ request_serializer=InsightBulkDeleteRequestSerializer,
+ responses={200: OpenApiResponse(response=InsightBulkDeleteResponseSerializer)},
+ description=(
+ "Soft-delete insights in bulk by ID. Mirrors the single-insight delete: sets deleted=True, "
+ "soft-deletes the insights' dashboard tiles, and removes their linked alerts. Insights the "
+ "requester cannot edit are skipped and reported in `skipped`. Reversible via the bulk_restore endpoint."
+ ),
+ )
+ @action(methods=["POST"], detail=False, required_scopes=["insight:write"])
+ def bulk_delete(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ ids: list[int] = request.validated_data["ids"]
+ insights, skipped = self._bulk_filter_editable_insights(ids, deleted=False)
+
+ deleted: list[dict[str, Any]] = []
+ if insights:
+ current_user = cast(User, request.user)
+ was_impersonated = is_impersonated(request)
+ organization_id = current_user.current_organization_id
+ insight_ids = [insight.id for insight in insights]
+
+ with transaction.atomic():
+ Insight.objects_including_soft_deleted.filter(
+ id__in=insight_ids, team__project_id=self.team.project_id
+ ).update(deleted=True, last_modified_at=now(), last_modified_by=current_user)
+ # Match InsightSerializer.update: hide the insights' tiles and remove linked alerts. Alerts are
+ # deleted one at a time (not a queryset .delete()) so ModelActivityMixin.delete logs each removal.
+ DashboardTile.objects_including_soft_deleted.filter(insight_id__in=insight_ids).update(deleted=True)
+ for alert in AlertConfiguration.objects.filter(insight_id__in=insight_ids):
+ alert.delete()
+
+ activity_log_entries: list[LogActivityEntry] = []
+ for insight in insights:
+ insight_name = insight.name or insight.derived_name
+ deleted.append({"id": insight.id, "name": insight_name})
+ # The experiments feature creates unnamed insights; the single-delete path skips logging those.
+ if insight_name:
+ activity_log_entries.append(
+ LogActivityEntry(
+ organization_id=organization_id,
+ team_id=self.team_id,
+ user=current_user,
+ was_impersonated=was_impersonated,
+ item_id=insight.id,
+ scope="Insight",
+ activity="deleted",
+ detail=Detail(name=insight_name, short_id=insight.short_id),
+ )
+ )
+ bulk_log_activity(activity_log_entries)
+
+ self.user_permissions.reset_insights_dashboard_cached_results()
+
+ return Response({"deleted": deleted, "skipped": skipped})
+
+ @validated_request(
+ request_serializer=InsightBulkDeleteRequestSerializer,
+ responses={200: OpenApiResponse(response=InsightBulkRestoreResponseSerializer)},
+ description=(
+ "Restore soft-deleted insights in bulk by ID — the inverse of bulk_delete. Sets deleted=False and "
+ "re-activates the insights' dashboard tiles on dashboards that still exist. Linked alerts are not "
+ "restored (they are removed on delete). Insights the requester cannot edit are reported in `skipped`."
+ ),
+ )
+ @action(methods=["POST"], detail=False, required_scopes=["insight:write"])
+ def bulk_restore(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ ids: list[int] = request.validated_data["ids"]
+ insights, skipped = self._bulk_filter_editable_insights(ids, deleted=True)
+
+ restored: list[dict[str, Any]] = []
+ if insights:
+ current_user = cast(User, request.user)
+ was_impersonated = is_impersonated(request)
+ organization_id = current_user.current_organization_id
+ insight_ids = [insight.id for insight in insights]
+
+ with transaction.atomic():
+ Insight.objects_including_soft_deleted.filter(
+ id__in=insight_ids, team__project_id=self.team.project_id
+ ).update(deleted=False, last_modified_at=now(), last_modified_by=current_user)
+ # Re-activate tiles linking these insights to live dashboards, but only ones the requester may
+ # edit — mirrors the per-dashboard CAN_EDIT check in InsightSerializer._update_insight_dashboards
+ # so a restore can't force an insight back onto a dashboard the user can only view. Tiles removed
+ # before the bulk delete may also reappear; acceptable for the immediate-undo case this backs.
+ candidate_tiles = DashboardTile.objects_including_soft_deleted.filter(
+ insight_id__in=insight_ids, deleted=True, dashboard__deleted=False
+ ).select_related("dashboard")
+ restorable_tile_ids = [
+ tile.id
+ for tile in candidate_tiles
+ if self.user_permissions.dashboard(tile.dashboard).effective_privilege_level
+ == Dashboard.PrivilegeLevel.CAN_EDIT
+ ]
+ if restorable_tile_ids:
+ DashboardTile.objects_including_soft_deleted.filter(id__in=restorable_tile_ids).update(
+ deleted=False
+ )
+
+ activity_log_entries: list[LogActivityEntry] = []
+ for insight in insights:
+ insight_name = insight.name or insight.derived_name
+ restored.append({"id": insight.id, "name": insight_name})
+ if insight_name:
+ activity_log_entries.append(
+ LogActivityEntry(
+ organization_id=organization_id,
+ team_id=self.team_id,
+ user=current_user,
+ was_impersonated=was_impersonated,
+ item_id=insight.id,
+ scope="Insight",
+ activity="restored",
+ detail=Detail(name=insight_name, short_id=insight.short_id),
+ )
+ )
+ bulk_log_activity(activity_log_entries)
+
+ self.user_permissions.reset_insights_dashboard_cached_results()
+
+ return Response({"restored": restored, "skipped": skipped})
+
@extend_schema(
operation_id="insights_all_activity_retrieve",
parameters=[
diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.py
index f5f9923432cd..8ad4d0906f43 100644
--- a/products/product_analytics/backend/api/test/test_insight.py
+++ b/products/product_analytics/backend/api/test/test_insight.py
@@ -17,7 +17,7 @@ from posthog.test.base import (
)
from unittest import mock
from unittest.case import skip
-from unittest.mock import ANY, patch
+from unittest.mock import ANY, PropertyMock, patch
from django.test import override_settings
from django.utils import timezone
@@ -56,6 +56,7 @@ from posthog.models.project import Project
from posthog.test.db_context_capturing import capture_db_queries
from posthog.test.persons import create_person
+from products.alerts.backend.models.alert import AlertConfiguration
from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile, Text
@@ -4986,3 +4987,110 @@ class TestInsightErrorHandling(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn(error_message, str(response.json()))
+
+
+class TestInsightBulkDelete(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
+ def _create_insight(self, name: str = "My insight") -> Insight:
+ return Insight.objects.create(team=self.team, name=name, saved=True, created_by=self.user)
+
+ def _bulk_delete(self, ids: list[int]) -> Any:
+ return self.client.post(f"/api/environments/{self.team.id}/insights/bulk_delete/", {"ids": ids}, format="json")
+
+ def _bulk_restore(self, ids: list[int]) -> Any:
+ return self.client.post(f"/api/environments/{self.team.id}/insights/bulk_restore/", {"ids": ids}, format="json")
+
+ def test_bulk_delete_soft_deletes_insights(self) -> None:
+ one = self._create_insight("one")
+ two = self._create_insight("two")
+
+ response = self._bulk_delete([one.id, two.id])
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ body = response.json()
+ self.assertEqual({item["id"] for item in body["deleted"]}, {one.id, two.id})
+ self.assertEqual(body["skipped"], [])
+ self.assertTrue(Insight.objects_including_soft_deleted.get(id=one.id).deleted)
+ self.assertTrue(Insight.objects_including_soft_deleted.get(id=two.id).deleted)
+
+ def test_bulk_delete_hides_dashboard_tiles_and_removes_alerts(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, name="Dashboard")
+ insight = self._create_insight()
+ tile = DashboardTile.objects.create(insight=insight, dashboard=dashboard)
+ alert = AlertConfiguration.objects.create(team=self.team, insight=insight, name="alert")
+
+ response = self._bulk_delete([insight.id])
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertTrue(DashboardTile.objects_including_soft_deleted.get(id=tile.id).deleted)
+ self.assertFalse(AlertConfiguration.objects.filter(id=alert.id).exists())
+
+ def test_bulk_delete_reports_unknown_ids_as_skipped(self) -> None:
+ insight = self._create_insight()
+
+ response = self._bulk_delete([insight.id, 9_999_999])
+
+ body = response.json()
+ self.assertEqual([item["id"] for item in body["deleted"]], [insight.id])
+ self.assertEqual(body["skipped"], [{"id": 9_999_999, "reason": "Insight not found"}])
+
+ def test_bulk_delete_skips_insights_without_edit_access(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
+ editable = self._create_insight("editable")
+ restricted = self._create_insight("restricted")
+ AccessControl.objects.create(resource="insight", resource_id=restricted.id, team=self.team, access_level="none")
+
+ self.client.force_login(member)
+ response = self._bulk_delete([editable.id, restricted.id])
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ body = response.json()
+ self.assertEqual([item["id"] for item in body["deleted"]], [editable.id])
+ self.assertEqual([item["id"] for item in body["skipped"]], [restricted.id])
+ self.assertTrue(Insight.objects_including_soft_deleted.get(id=editable.id).deleted)
+ self.assertFalse(Insight.objects_including_soft_deleted.get(id=restricted.id).deleted)
+
+ def test_bulk_delete_rejects_empty_ids(self) -> None:
+ response = self._bulk_delete([])
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_bulk_restore_restores_insights_and_tiles(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, name="Dashboard")
+ insight = self._create_insight()
+ tile = DashboardTile.objects.create(insight=insight, dashboard=dashboard)
+
+ self.assertEqual(self._bulk_delete([insight.id]).status_code, status.HTTP_200_OK)
+ self.assertTrue(Insight.objects_including_soft_deleted.get(id=insight.id).deleted)
+ self.assertTrue(DashboardTile.objects_including_soft_deleted.get(id=tile.id).deleted)
+
+ response = self._bulk_restore([insight.id])
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual([item["id"] for item in response.json()["restored"]], [insight.id])
+ self.assertFalse(Insight.objects_including_soft_deleted.get(id=insight.id).deleted)
+ self.assertFalse(DashboardTile.objects_including_soft_deleted.get(id=tile.id).deleted)
+
+ def test_bulk_restore_skips_tiles_on_dashboards_the_user_cannot_edit(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, name="Dashboard")
+ insight = self._create_insight()
+ tile = DashboardTile.objects.create(insight=insight, dashboard=dashboard)
+ self.assertEqual(self._bulk_delete([insight.id]).status_code, status.HTTP_200_OK)
+
+ # Simulate the requester only having view access to the dashboard the insight sits on.
+ with patch(
+ "posthog.user_permissions.UserDashboardPermissions.effective_privilege_level",
+ new_callable=PropertyMock,
+ return_value=Dashboard.PrivilegeLevel.CAN_VIEW,
+ ):
+ response = self._bulk_restore([insight.id])
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual([item["id"] for item in response.json()["restored"]], [insight.id])
+ self.assertFalse(Insight.objects_including_soft_deleted.get(id=insight.id).deleted)
+ # The insight comes back, but its tile on a dashboard the user can only view stays hidden.
+ self.assertTrue(DashboardTile.objects_including_soft_deleted.get(id=tile.id).deleted)
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 42bfa6a7f30a..cc2c163d4c2f 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -7663,6 +7663,46 @@ export interface ActivityLogPaginatedResponseApi {
total_count: number
}
+export interface InsightBulkDeleteRequestApi {
+ /**
+ * Insight IDs to soft-delete (or restore). At most 1000 ids per request. Soft-deleted insights can be brought back via the bulk_restore endpoint.
+ * @maxItems 1000
+ * @items.minimum 1
+ */
+ ids: number[]
+}
+
+export interface InsightBulkOperationResultApi {
+ /** ID of the insight that was soft-deleted or restored. */
+ id: number
+ /**
+ * The insight's name (or derived name) at the time of the operation; null when it has neither.
+ * @nullable
+ */
+ name: string | null
+}
+
+export interface InsightBulkOperationSkippedApi {
+ /** ID of the insight that was skipped. */
+ id: number
+ /** Human-readable reason the insight was skipped (for example, not found or no edit permission). */
+ reason: string
+}
+
+export interface InsightBulkDeleteResponseApi {
+ /** Insights that were successfully soft-deleted. */
+ deleted: InsightBulkOperationResultApi[]
+ /** Insights that were not deleted, with the reason for each. */
+ skipped: InsightBulkOperationSkippedApi[]
+}
+
+export interface InsightBulkRestoreResponseApi {
+ /** Insights that were successfully restored. */
+ restored: InsightBulkOperationResultApi[]
+ /** Insights that were not restored, with the reason for each. */
+ skipped: InsightBulkOperationSkippedApi[]
+}
+
/**
* * `add` - add
* * `remove` - remove
@@ -8134,6 +8174,30 @@ export const InsightsAllActivityRetrieveFormat = {
Json: 'json',
} as const
+export type InsightsBulkDeleteCreateParams = {
+ format?: InsightsBulkDeleteCreateFormat
+}
+
+export type InsightsBulkDeleteCreateFormat =
+ (typeof InsightsBulkDeleteCreateFormat)[keyof typeof InsightsBulkDeleteCreateFormat]
+
+export const InsightsBulkDeleteCreateFormat = {
+ Csv: 'csv',
+ Json: 'json',
+} as const
+
+export type InsightsBulkRestoreCreateParams = {
+ format?: InsightsBulkRestoreCreateFormat
+}
+
+export type InsightsBulkRestoreCreateFormat =
+ (typeof InsightsBulkRestoreCreateFormat)[keyof typeof InsightsBulkRestoreCreateFormat]
+
+export const InsightsBulkRestoreCreateFormat = {
+ Csv: 'csv',
+ Json: 'json',
+} as const
+
export type InsightsBulkUpdateTagsCreateParams = {
format?: InsightsBulkUpdateTagsCreateFormat
}
diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.ts
index f78bf0b84d91..d77e1569e481 100644
--- a/products/product_analytics/frontend/generated/api.ts
+++ b/products/product_analytics/frontend/generated/api.ts
@@ -21,10 +21,15 @@ import type {
ElementsStatsRetrieveParams,
ElementsValuesListParams,
InsightApi,
+ InsightBulkDeleteRequestApi,
+ InsightBulkDeleteResponseApi,
+ InsightBulkRestoreResponseApi,
InsightViewedRequestApi,
InsightsActivityRetrieveParams,
InsightsAllActivityRetrieveParams,
InsightsAnalyzeRetrieveParams,
+ InsightsBulkDeleteCreateParams,
+ InsightsBulkRestoreCreateParams,
InsightsBulkUpdateTagsCreateParams,
InsightsCancelCreateParams,
InsightsCreateParams,
@@ -746,6 +751,72 @@ export const insightsAllActivityRetrieve = async (
})
}
+export const getInsightsBulkDeleteCreateUrl = (projectId: string, params?: InsightsBulkDeleteCreateParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/insights/bulk_delete/?${stringifiedParams}`
+ : `/api/projects/${projectId}/insights/bulk_delete/`
+}
+
+/**
+ * Soft-delete insights in bulk by ID. Mirrors the single-insight delete: sets deleted=True, soft-deletes the insights' dashboard tiles, and removes their linked alerts. Insights the requester cannot edit are skipped and reported in `skipped`. Reversible via the bulk_restore endpoint.
+ */
+export const insightsBulkDeleteCreate = async (
+ projectId: string,
+ insightBulkDeleteRequestApi: InsightBulkDeleteRequestApi,
+ params?: InsightsBulkDeleteCreateParams,
+ options?: RequestInit
+): Promise<InsightBulkDeleteResponseApi> => {
+ return apiMutator<InsightBulkDeleteResponseApi>(getInsightsBulkDeleteCreateUrl(projectId, params), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(insightBulkDeleteRequestApi),
+ })
+}
+
+export const getInsightsBulkRestoreCreateUrl = (projectId: string, params?: InsightsBulkRestoreCreateParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/insights/bulk_restore/?${stringifiedParams}`
+ : `/api/projects/${projectId}/insights/bulk_restore/`
+}
+
+/**
+ * Restore soft-deleted insights in bulk by ID — the inverse of bulk_delete. Sets deleted=False and re-activates the insights' dashboard tiles on dashboards that still exist. Linked alerts are not restored (they are removed on delete). Insights the requester cannot edit are reported in `skipped`.
+ */
+export const insightsBulkRestoreCreate = async (
+ projectId: string,
+ insightBulkDeleteRequestApi: InsightBulkDeleteRequestApi,
+ params?: InsightsBulkRestoreCreateParams,
+ options?: RequestInit
+): Promise<InsightBulkRestoreResponseApi> => {
+ return apiMutator<InsightBulkRestoreResponseApi>(getInsightsBulkRestoreCreateUrl(projectId, params), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(insightBulkDeleteRequestApi),
+ })
+}
+
export const getInsightsBulkUpdateTagsCreateUrl = (projectId: string, params?: InsightsBulkUpdateTagsCreateParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.ts
index 6cb33d9cd3cd..f62e0b1d0b7c 100644
--- a/products/product_analytics/frontend/generated/api.zod.ts
+++ b/products/product_analytics/frontend/generated/api.zod.ts
@@ -239,6 +239,36 @@ export const InsightsSuggestionsCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+/**
+ * Soft-delete insights in bulk by ID. Mirrors the single-insight delete: sets deleted=True, soft-deletes the insights' dashboard tiles, and removes their linked alerts. Insights the requester cannot edit are skipped and reported in `skipped`. Reversible via the bulk_restore endpoint.
+ */
+
+export const insightsBulkDeleteCreateBodyIdsMax = 1000
+
+export const InsightsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({
+ ids: zod
+ .array(zod.number().min(1))
+ .max(insightsBulkDeleteCreateBodyIdsMax)
+ .describe(
+ 'Insight IDs to soft-delete (or restore). At most 1000 ids per request. Soft-deleted insights can be brought back via the bulk_restore endpoint.'
+ ),
+})
+
+/**
+ * Restore soft-deleted insights in bulk by ID — the inverse of bulk_delete. Sets deleted=False and re-activates the insights' dashboard tiles on dashboards that still exist. Linked alerts are not restored (they are removed on delete). Insights the requester cannot edit are reported in `skipped`.
+ */
+
+export const insightsBulkRestoreCreateBodyIdsMax = 1000
+
+export const InsightsBulkRestoreCreateBody = /* @__PURE__ */ zod.object({
+ ids: zod
+ .array(zod.number().min(1))
+ .max(insightsBulkRestoreCreateBodyIdsMax)
+ .describe(
+ 'Insight IDs to soft-delete (or restore). At most 1000 ids per request. Soft-deleted insights can be brought back via the bulk_restore endpoint.'
+ ),
+})
+
/**
* Bulk update tags on multiple objects.
*
diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yaml
index d658849ae9e9..309d825d7973 100644
--- a/products/product_analytics/mcp/tools.yaml
+++ b/products/product_analytics/mcp/tools.yaml
@@ -242,6 +242,12 @@ tools:
insights-analyze-retrieve:
operation: insights_analyze_retrieve
enabled: false
+ insights-bulk-delete-create:
+ operation: insights_bulk_delete_create
+ enabled: false
+ insights-bulk-restore-create:
+ operation: insights_bulk_restore_create
+ enabled: false
insights-bulk-update-tags-create:
operation: insights_bulk_update_tags_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7046f4bdcee8..670df602dd24 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27805,6 +27805,46 @@ export namespace Schemas {
id_jag_allowed_clients?: string[];
}
+ export interface InsightBulkDeleteRequest {
+ /**
+ * Insight IDs to soft-delete (or restore). At most 1000 ids per request. Soft-deleted insights can be brought back via the bulk_restore endpoint.
+ * @maxItems 1000
+ * @items.minimum 1
+ */
+ ids: number[];
+ }
+
+ export interface InsightBulkOperationResult {
+ /** ID of the insight that was soft-deleted or restored. */
+ id: number;
+ /**
+ * The insight's name (or derived name) at the time of the operation; null when it has neither.
+ * @nullable
+ */
+ name: string | null;
+ }
+
+ export interface InsightBulkOperationSkipped {
+ /** ID of the insight that was skipped. */
+ id: number;
+ /** Human-readable reason the insight was skipped (for example, not found or no edit permission). */
+ reason: string;
+ }
+
+ export interface InsightBulkDeleteResponse {
+ /** Insights that were successfully soft-deleted. */
+ deleted: InsightBulkOperationResult[];
+ /** Insights that were not deleted, with the reason for each. */
+ skipped: InsightBulkOperationSkipped[];
+ }
+
+ export interface InsightBulkRestoreResponse {
+ /** Insights that were successfully restored. */
+ restored: InsightBulkOperationResult[];
+ /** Insights that were not restored, with the reason for each. */
+ skipped: InsightBulkOperationSkipped[];
+ }
+
/**
* * `trends` - trends
* * `funnel` - funnel
@@ -58920,6 +58960,30 @@ export namespace Schemas {
Json: 'json',
} as const;
+ export type EnvironmentsInsightsBulkDeleteCreateParams = {
+ format?: EnvironmentsInsightsBulkDeleteCreateFormat;
+ };
+
+ export type EnvironmentsInsightsBulkDeleteCreateFormat = typeof EnvironmentsInsightsBulkDeleteCreateFormat[keyof typeof EnvironmentsInsightsBulkDeleteCreateFormat];
+
+
+ export const EnvironmentsInsightsBulkDeleteCreateFormat = {
+ Csv: 'csv',
+ Json: 'json',
+ } as const;
+
+ export type EnvironmentsInsightsBulkRestoreCreateParams = {
+ format?: EnvironmentsInsightsBulkRestoreCreateFormat;
+ };
+
+ export type EnvironmentsInsightsBulkRestoreCreateFormat = typeof EnvironmentsInsightsBulkRestoreCreateFormat[keyof typeof EnvironmentsInsightsBulkRestoreCreateFormat];
+
+
+ export const EnvironmentsInsightsBulkRestoreCreateFormat = {
+ Csv: 'csv',
+ Json: 'json',
+ } as const;
+
export type EnvironmentsInsightsBulkUpdateTagsCreateParams = {
format?: EnvironmentsInsightsBulkUpdateTagsCreateFormat;
};
@@ -65802,6 +65866,30 @@ export namespace Schemas {
Json: 'json',
} as const;
+ export type InsightsBulkDeleteCreateParams = {
+ format?: InsightsBulkDeleteCreateFormat;
+ };
+
+ export type InsightsBulkDeleteCreateFormat = typeof InsightsBulkDeleteCreateFormat[keyof typeof InsightsBulkDeleteCreateFormat];
+
+
+ export const InsightsBulkDeleteCreateFormat = {
+ Csv: 'csv',
+ Json: 'json',
+ } as const;
+
+ export type InsightsBulkRestoreCreateParams = {
+ format?: InsightsBulkRestoreCreateFormat;
+ };
+
+ export type InsightsBulkRestoreCreateFormat = typeof InsightsBulkRestoreCreateFormat[keyof typeof InsightsBulkRestoreCreateFormat];
+
+
+ export const InsightsBulkRestoreCreateFormat = {
+ Csv: 'csv',
+ Json: 'json',
+ } as const;
+
export type InsightsBulkUpdateTagsCreateParams = {
format?: InsightsBulkUpdateTagsCreateFormat;
};