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(dashboards): add an endpoint that places an existing insight (#126281)

Thomas Obermüller13f5b932d2ab
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index d662e8218993..77704902691d 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -2672,21 +2672,26 @@ class TestSaveTimeAccessBlock(APIBaseTest):
assert dashboard.deleted is True
assert not DashboardTile.objects.filter(dashboard=dashboard, insight=self.insight).exists()
- @parameterized.expand([("stored_query",), ("query_in_same_patch",)])
+ @parameterized.expand([("stored_query",), ("query_in_same_patch",), ("dashboard_add_insight",)])
def test_adding_insight_to_shared_dashboard_blocked(self, coverage: str):
self._deny_editor()
dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)
SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)
payload: dict = {"dashboards": [dashboard.id]}
- if coverage == "stored_query":
- self.insight.query = self._DENIED_QUERY
- self.insight.save()
- else:
+ if coverage == "query_in_same_patch":
# The insight isn't shared yet, so only the dashboard gate runs. It must see the
# incoming query, not the stored one that is about to be overwritten.
payload["query"] = self._DENIED_QUERY
+ else:
+ self.insight.query = self._DENIED_QUERY
+ self.insight.save()
- response = self.client.patch(f"/api/projects/{self.team.id}/insights/{self.insight.id}/", payload)
+ if coverage == "dashboard_add_insight":
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/add_insight/", {"insight_id": self.insight.id}
+ )
+ else:
+ response = self.client.patch(f"/api/projects/{self.team.id}/insights/{self.insight.id}/", payload)
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
assert "publicly shared" in str(response.json())
@@ -2698,6 +2703,21 @@ class TestSaveTimeAccessBlock(APIBaseTest):
"source": {"kind": "HogQLQuery", "query": "SELECT 1 AS one"},
}
+ def test_adding_insight_already_on_shared_dashboard_returns_its_tile(self):
+ self._deny_editor()
+ self.insight.query = self._DENIED_QUERY
+ self.insight.save()
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.user)
+ tile = DashboardTile.objects.create(dashboard=dashboard, insight=self.insight)
+ SharingConfiguration.objects.create(team=self.team, dashboard=dashboard, enabled=True)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/add_insight/", {"insight_id": self.insight.id}
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["id"] == tile.id
+
@parameterized.expand(
[
("whole_dashboard", status.HTTP_400_BAD_REQUEST),
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 12702fb44fec..46cc59fed792 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -89,6 +89,7 @@ from posthog.hogql_queries.apply_dashboard_filters import normalize_dashboard_fi
from posthog.hogql_queries.query_runner import team_configs_for_cache_key
from posthog.hogql_queries.refresh_policy import ComputeSurface
from posthog.hogql_queries.utils.caller_context import map_in_caller_context
+from posthog.models.activity_logging.activity_log import Change
from posthog.models.file_system.constants import DEFAULT_SURFACE, surface_q
from posthog.models.file_system.file_system import FileSystem, create_or_update_file, delete_file, join_path, split_path
from posthog.models.group_type_mapping import (
@@ -162,7 +163,12 @@ from products.dashboards.backend.customization import (
validated_group_keys,
without_default_settings,
)
-from products.dashboards.backend.facade.api import DashboardTileBasicSerializer, tile_ids_prefetch
+from products.dashboards.backend.facade.api import (
+ CannotAddToDashboard,
+ DashboardTileBasicSerializer,
+ add_insight_to_dashboard,
+ tile_ids_prefetch,
+)
from products.dashboards.backend.models.dashboard import (
DASHBOARD_GRID_COMPACTION_MODES,
DASHBOARD_GRID_SPACING_GAPS,
@@ -221,6 +227,8 @@ from products.product_analytics.backend.presentation.insight import (
InsightSerializer,
InsightViewSet,
get_insight_type,
+ log_and_report_insight_activity,
+ viewable_insight_or_404,
)
from products.subscriptions.backend.facade.api import dashboard_ids_with_subscriptions
@@ -826,6 +834,16 @@ class UpdateTextTileRequestSerializer(serializers.Serializer):
)
+class AddInsightToDashboardRequestSerializer(serializers.Serializer):
+ insight_id = serializers.IntegerField(
+ help_text=(
+ "ID of an existing insight to place on the dashboard. The insight must belong to the same "
+ "environment as the dashboard. Adding an insight the dashboard already shows changes nothing, and "
+ "adding one that was removed from the dashboard restores its tile."
+ ),
+ )
+
+
class DeleteTileRequestSerializer(serializers.Serializer):
tile_id = serializers.IntegerField(
required=True,
@@ -1700,10 +1718,11 @@ def _report_dashboard_tile_added(
request: Request | None = None,
widget_type: str | None = None,
tile: DashboardTile | None = None,
+ insight: Insight | None = None,
) -> None:
properties: dict[str, Any] = {
"tile_type": tile_type,
- "insight_type": None,
+ "insight_type": get_insight_type(insight) if insight is not None else None,
"dashboard_id": dashboard.id,
}
if widget_type is not None:
@@ -1743,6 +1762,48 @@ def _report_dashboard_tile_added(
)
+def _insight_dashboard_refs(insight: Insight) -> list[dict[str, Any]]:
+ """The dashboards an insight's live tiles sit on, in the shape the insight activity log records them."""
+ return [
+ {"id": dashboard_id, "name": name}
+ for dashboard_id, name in DashboardTile.objects.filter(insight=insight)
+ .order_by("dashboard_id")
+ .values_list("dashboard_id", "dashboard__name")
+ ]
+
+
+def _log_insight_dashboards_change(
+ *,
+ request: Request,
+ insight: Insight,
+ dashboards_before: list[dict[str, Any]],
+ dashboards_after: list[dict[str, Any]],
+) -> None:
+ # Same entry as a write of the insight's `dashboards` field, so the insight's history reads the same
+ # whichever endpoint placed or removed the tile.
+ user = cast(User, request.user)
+ log_and_report_insight_activity(
+ activity="updated",
+ insight=insight,
+ insight_id=insight.id,
+ insight_short_id=insight.short_id,
+ organization_id=insight.team.organization_id,
+ team_id=insight.team_id,
+ user=user,
+ was_impersonated=is_impersonated(request),
+ request=request,
+ changes=[
+ Change(
+ type="Insight",
+ action="changed",
+ field="dashboards",
+ before=dashboards_before,
+ after=dashboards_after,
+ )
+ ],
+ )
+
+
def _report_dashboard_tile_marking_changed(
*,
user: User,
@@ -3886,6 +3947,8 @@ class DashboardsViewSet(
dashboard=dashboard,
dashboard__team__project_id=self.team.project_id,
)
+ insight = tile.insight
+ insight_dashboards_before = _insight_dashboard_refs(insight) if insight is not None else []
# Collapse the vertical gap the removed tile leaves, matching the dashboard UI
# (react-grid-layout compacts upward on render but never persists it).
with transaction.atomic():
@@ -3906,9 +3969,66 @@ class DashboardsViewSet(
tile=tile,
request=request,
)
+ if insight is not None:
+ _log_insight_dashboards_change(
+ request=request,
+ insight=insight,
+ dashboards_before=insight_dashboards_before,
+ dashboards_after=[ref for ref in insight_dashboards_before if ref["id"] != dashboard.id],
+ )
return Response(status=status.HTTP_204_NO_CONTENT)
+ @validated_request(
+ request_serializer=AddInsightToDashboardRequestSerializer,
+ responses={200: DashboardTileBasicSerializer},
+ description=(
+ "Place an existing insight on this dashboard as a new tile. Requires edit access to the dashboard "
+ "and view access to the insight. Returns the tile. Adding an insight the dashboard already shows "
+ "returns its tile unchanged, and adding one that was removed from the dashboard restores its tile "
+ "with its old layout. To take an insight off a dashboard, use delete_tile."
+ ),
+ )
+ @action(methods=["POST"], detail=True, required_scopes=["dashboard:write", "insight:read"])
+ def add_insight(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ dashboard = self.get_object()
+ if dashboard.deleted:
+ raise exceptions.NotFound()
+
+ insight = viewable_insight_or_404(
+ team_id=dashboard.team_id,
+ insight_id=request.validated_data["insight_id"],
+ user_access_control=self.user_access_control,
+ )
+
+ user = cast(User, request.user)
+ insight_dashboards_before = _insight_dashboard_refs(insight)
+ try:
+ with transaction.atomic():
+ placed = add_insight_to_dashboard(
+ insight_id=insight.id,
+ insight_team_id=insight.team_id,
+ query=insight.query,
+ dashboard_id=dashboard.id,
+ user=user,
+ user_access_control=self.user_access_control,
+ )
+ except CannotAddToDashboard:
+ raise exceptions.PermissionDenied("You don't have permission to add insights to this dashboard.")
+
+ if placed.added:
+ _report_dashboard_tile_added(
+ user=user, dashboard=dashboard, tile_type="insight", insight=insight, request=request
+ )
+ _log_insight_dashboards_change(
+ request=request,
+ insight=insight,
+ dashboards_before=insight_dashboards_before,
+ dashboards_after=[*insight_dashboards_before, {"id": dashboard.id, "name": dashboard.name}],
+ )
+
+ return Response(DashboardTileBasicSerializer(DashboardTile.objects.get(pk=placed.id)).data)
+
@extend_schema(
parameters=[
OpenApiParameter(
diff --git a/products/dashboards/backend/api/test/test_dashboard_add_insight.py b/products/dashboards/backend/api/test/test_dashboard_add_insight.py
new file mode 100644
index 000000000000..af4c6f0a12d5
--- /dev/null
+++ b/products/dashboards/backend/api/test/test_dashboard_add_insight.py
@@ -0,0 +1,147 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import ANY, MagicMock, patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.api.test.dashboards import DashboardAPI
+from posthog.constants import AvailableFeature
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.dashboards.backend.models.dashboard_tile import DashboardTile
+from products.product_analytics.backend.facade.models import Insight
+
+
+class TestDashboardAddInsight(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)
+ self.dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "Growth overview"})
+ self.insight_id, _ = self.dashboard_api.create_insight({"name": "Weekly signups"})
+
+ def _add_insight(self, insight_id: int, expected_status: int = status.HTTP_200_OK) -> dict:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/{self.dashboard_id}/add_insight/",
+ {"insight_id": insight_id},
+ )
+ assert response.status_code == expected_status, response.content
+ return response.json()
+
+ def _tiles_for_insight(self, insight_id: int) -> list[DashboardTile]:
+ return list(
+ DashboardTile.objects_including_soft_deleted.filter(dashboard_id=self.dashboard_id, insight_id=insight_id)
+ )
+
+ @patch("products.dashboards.backend.api.dashboard.report_user_action")
+ def test_places_the_insight_on_the_dashboard(self, mock_report_user_action: MagicMock) -> None:
+ tile_json = self._add_insight(self.insight_id)
+
+ assert tile_json == {"id": ANY, "dashboard_id": self.dashboard_id, "deleted": None}
+ dashboard_json = self.dashboard_api.get_dashboard(self.dashboard_id)
+ assert [(tile["id"], tile["insight"]["id"]) for tile in dashboard_json["tiles"]] == [
+ (tile_json["id"], self.insight_id)
+ ]
+ mock_report_user_action.assert_any_call(
+ self.user,
+ "dashboard tile added",
+ {"tile_type": "insight", "insight_type": "trends", "dashboard_id": self.dashboard_id},
+ team=ANY,
+ request=ANY,
+ )
+
+ @parameterized.expand([("already_on_the_dashboard", False), ("removed_from_the_dashboard", True)])
+ def test_adding_again_keeps_the_one_tile(self, _name: str, remove_first: bool) -> None:
+ first_tile_id = self._add_insight(self.insight_id)["id"]
+ if remove_first:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/{self.dashboard_id}/delete_tile/",
+ {"tile_id": first_tile_id},
+ )
+ assert response.status_code == status.HTTP_204_NO_CONTENT, response.content
+
+ second_tile_id = self._add_insight(self.insight_id)["id"]
+
+ assert second_tile_id == first_tile_id
+ assert [(tile.id, bool(tile.deleted)) for tile in self._tiles_for_insight(self.insight_id)] == [
+ (first_tile_id, False)
+ ]
+
+ @patch("posthog.resource_limits.evaluator.get_limit", return_value=1)
+ @patch("posthog.resource_limits.evaluator.report_user_action")
+ def test_reports_the_insight_limit_only_when_a_tile_is_added(
+ self, mock_report_user_action: MagicMock, _mock_get_limit: MagicMock
+ ) -> None:
+ self._add_insight(self.insight_id)
+ self._add_insight(self.insight_id)
+
+ limit_hits = [call for call in mock_report_user_action.call_args_list if call.args[1] == "resource limit hit"]
+ assert [
+ (hit.args[2]["limit_key"], hit.args[2]["dashboard_id"], hit.args[2]["dashboard_name"]) for hit in limit_hits
+ ] == [("analytics.max_insights_per_dashboard", self.dashboard_id, "Growth overview")]
+
+ @parameterized.expand(
+ [
+ ("dashboard_is_view_only", "dashboard", "viewer", False),
+ ("insight_is_hidden", "insight", "none", False),
+ ("insight_is_hidden_in_a_sibling_environment", "insight", "none", True),
+ ]
+ )
+ def test_refuses_a_member_who_cannot_edit_the_dashboard_or_view_the_insight(
+ self, _name: str, resource: str, access_level: str, in_sibling_environment: bool
+ ) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+ team = self.team
+ if in_sibling_environment:
+ team = self.create_sibling_environment()
+ self.dashboard_id = Dashboard.objects.create(team=team, name="Growth overview").id
+ self.insight_id = Insight.objects.create(team=team, name="Weekly signups").id
+ resource_id = self.dashboard_id if resource == "dashboard" else self.insight_id
+ AccessControl.objects.create(
+ team=team, resource=resource, resource_id=str(resource_id), access_level=access_level
+ )
+ member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
+ self.client.force_login(member)
+
+ self._add_insight(self.insight_id, expected_status=status.HTTP_403_FORBIDDEN)
+
+ assert self._tiles_for_insight(self.insight_id) == []
+
+ @parameterized.expand([("another_organization",), ("sibling_environment",)])
+ def test_refuses_an_insight_from_another_team(self, owner: str) -> None:
+ if owner == "another_organization":
+ _, _, other_team = Organization.objects.bootstrap(None, name="Other org")
+ else:
+ other_team = self.create_sibling_environment()
+ other_insight = Insight.objects.create(team=other_team, name="Elsewhere")
+
+ self._add_insight(other_insight.id, expected_status=status.HTTP_404_NOT_FOUND)
+
+ assert self._tiles_for_insight(other_insight.id) == []
+
+ def test_refuses_a_personal_api_key_without_insight_read(self) -> None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="dashboards only",
+ user=self.user,
+ secure_value=hash_key_value(token),
+ scopes=["dashboard:write"],
+ scoped_teams=[],
+ scoped_organizations=[],
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/{self.dashboard_id}/add_insight/",
+ {"insight_id": self.insight_id},
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert response.json()["detail"] == "API key missing required scope 'insight:read'"
+ assert self._tiles_for_insight(self.insight_id) == []
diff --git a/products/dashboards/backend/facade/api.py b/products/dashboards/backend/facade/api.py
index 8ee64b8f3906..1df11d2c2cbe 100644
--- a/products/dashboards/backend/facade/api.py
+++ b/products/dashboards/backend/facade/api.py
@@ -26,6 +26,7 @@ from posthog.api.sharing_publish_gate import check_can_add_insight_to_dashboard
from posthog.helpers.dashboard_templates import create_from_template
from posthog.models.user import User
from posthog.models.user_home_settings import UserHomeSettings
+from posthog.resource_limits import LimitKey, check_count_limit
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.dashboards.backend.models.dashboard import Dashboard
@@ -70,6 +71,16 @@ class DashboardRef:
name: str | None
+@dataclass(frozen=True)
+class PlacedInsightTile:
+ """The tile that places an insight on a dashboard."""
+
+ id: int
+ dashboard_id: int
+ # Whether this call put the insight there, by creating the tile or by restoring a removed one.
+ added: bool
+
+
@dataclass(frozen=True)
class MembershipChange:
"""What one membership write changed, for the caller's analytics events and activity log."""
@@ -85,6 +96,11 @@ class DashboardTileBasicSerializer(serializers.ModelSerializer):
class Meta:
model = DashboardTile
fields = ["id", "dashboard_id", "deleted"]
+ extra_kwargs = {
+ "id": {"help_text": "ID of the dashboard tile."},
+ "dashboard_id": {"help_text": "ID of the dashboard the tile sits on."},
+ "deleted": {"help_text": "Whether the tile was removed from the dashboard."},
+ }
def _refs_in_given_order(dashboard_ids: Sequence[int]) -> tuple[DashboardRef, ...]:
@@ -284,6 +300,20 @@ def active_tile_count(dashboard_id: int) -> int:
return DashboardTile.objects.filter(dashboard_id=dashboard_id).exclude(deleted=True).count()
+def check_insight_tile_limit(*, team: "Team", dashboard_id: int, dashboard_name: str | None, user: User) -> None:
+ """Report a `resource limit hit` event when one more tile would put the dashboard at its insight limit.
+
+ The limit only notifies, so the caller places the tile either way.
+ """
+ check_count_limit(
+ team=team,
+ key=LimitKey.MAX_INSIGHTS_PER_DASHBOARD,
+ current_count=active_tile_count(dashboard_id),
+ user=user,
+ resource_properties={"dashboard_id": dashboard_id, "dashboard_name": dashboard_name or ""},
+ )
+
+
def tile_ids_prefetch(lookup: str = "dashboard_tiles") -> Prefetch:
"""Prefetch of an insight's tiles carrying only the columns a basic insight payload renders.
`lookup` is the path from the queryset's model to the insight's tiles."""
@@ -466,6 +496,89 @@ def plan_insight_tile_placement(
return InsightTilePlacement(dashboards)
+def _place_insight_tile(
+ *,
+ insight_id: int,
+ insight_team_id: int,
+ loaded_insight: "Insight | None",
+ dashboard: Dashboard,
+ query: Any,
+ user: User,
+ user_access_control: UserAccessControl | None,
+ dashboard_access: UserAccessControl | None,
+) -> tuple[DashboardTile, bool]:
+ """Put the insight on one dashboard, and report whether it was missing from it before.
+
+ `loaded_insight` is the insight row when the caller holds it, so that saving a new tile does
+ not read the row again. `dashboard_access` is `user_access_control` resolved against the
+ dashboard's own team; None skips the edit check. A removed tile is restored rather than
+ duplicated, so it keeps its layout. An insight already on the dashboard returns its tile before
+ any check, because nothing changes.
+ """
+ if dashboard.team_id != insight_team_id:
+ raise DashboardNotFound
+
+ live_tile = DashboardTile.objects.filter(insight_id=insight_id, dashboard=dashboard).first()
+ if live_tile is not None:
+ return live_tile, False
+
+ # Adding a tile is an edit of the dashboard.
+ if dashboard_access is not None and not dashboard_access.check_access_level_for_object(dashboard, "editor"):
+ raise CannotAddToDashboard(dashboard.id)
+
+ # The dashboard's public link or subscription must not expose a query the editor can't run.
+ check_can_add_insight_to_dashboard(user, dashboard, query, user_access_control)
+
+ insight_lookup: dict[str, Any] = (
+ {"insight": loaded_insight} if loaded_insight is not None else {"insight_id": insight_id}
+ )
+ tile, created = DashboardTile.objects_including_soft_deleted.get_or_create(dashboard=dashboard, **insight_lookup)
+ if tile.deleted:
+ tile.deleted = False
+ tile.save()
+ return tile, True
+ return tile, created
+
+
+def add_insight_to_dashboard(
+ *,
+ insight_id: int,
+ insight_team_id: int,
+ query: Any,
+ dashboard_id: int,
+ user: User,
+ user_access_control: UserAccessControl,
+) -> PlacedInsightTile:
+ """Place an existing insight on one dashboard, with the checks the insight API's `dashboards` field runs.
+
+ `query` is the insight's stored query, for the shared-dashboard publish gate. An insight already
+ on the dashboard keeps its tile and nothing changes. Refusals raise `CannotAddToDashboard`,
+ `DashboardNotFound` or the publish gate's ValidationError.
+
+ Run inside the caller's transaction.
+ """
+ dashboard = Dashboard.objects.filter(team_id=insight_team_id, pk=dashboard_id).first()
+ if dashboard is None:
+ raise DashboardNotFound(str(dashboard_id))
+ live_tile = DashboardTile.objects.filter(insight_id=insight_id, dashboard=dashboard).first()
+ if live_tile is not None:
+ return PlacedInsightTile(id=live_tile.id, dashboard_id=dashboard.id, added=False)
+ check_insight_tile_limit(team=dashboard.team, dashboard_id=dashboard.id, dashboard_name=dashboard.name, user=user)
+ access_by_team = _dashboard_edit_access_by_team([dashboard], user_access_control)
+ tile, added = _place_insight_tile(
+ insight_id=insight_id,
+ insight_team_id=insight_team_id,
+ # A public facade function takes no product model, so this path saves the tile by insight ID.
+ loaded_insight=None,
+ dashboard=dashboard,
+ query=query,
+ user=user,
+ user_access_control=user_access_control,
+ dashboard_access=access_by_team[dashboard.team_id],
+ )
+ return PlacedInsightTile(id=tile.id, dashboard_id=dashboard.id, added=added)
+
+
def update_insight_dashboard_membership(
*,
insight: "Insight",
@@ -504,22 +617,16 @@ def update_insight_dashboard_membership(
add_dashboards = list(Dashboard.objects.filter(id__in=ids_to_add))
add_access_by_team = _dashboard_edit_access_by_team(add_dashboards, user_access_control)
for dashboard in add_dashboards:
- if dashboard.team != insight.team:
- raise DashboardNotFound
-
- if user_access_control is not None and not add_access_by_team[dashboard.team_id].check_access_level_for_object(
- dashboard, "editor"
- ):
- raise CannotAddToDashboard(dashboard.id)
-
- # The dashboard's public link or subscription must not expose a query the editor can't run.
- check_can_add_insight_to_dashboard(user, dashboard, query, user_access_control)
-
- tile, _ = DashboardTile.objects_including_soft_deleted.get_or_create(insight=insight, dashboard=dashboard)
- if tile.deleted:
- tile.deleted = False
- tile.save()
-
+ _place_insight_tile(
+ insight_id=insight.id,
+ insight_team_id=insight.team_id,
+ loaded_insight=insight,
+ dashboard=dashboard,
+ query=query,
+ user=user,
+ user_access_control=user_access_control,
+ dashboard_access=add_access_by_team.get(dashboard.team_id),
+ )
added_dashboard_ids.append(dashboard.id)
removed_dashboard_ids: list[int] = []
@@ -556,7 +663,10 @@ __all__ = [
"DashboardTileBasicSerializer",
"InsightTilePlacement",
"MembershipChange",
+ "PlacedInsightTile",
"active_tile_count",
+ "add_insight_to_dashboard",
+ "check_insight_tile_limit",
"dashboard_exists",
"dashboard_refs",
"hide_tiles_for_insights",
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 59835381321a..80c4368240b9 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1647,6 +1647,23 @@ export interface PatchedPatchedDashboardOpenApiApi {
delete_insights?: boolean
}
+export interface AddInsightToDashboardRequestApi {
+ /** ID of an existing insight to place on the dashboard. The insight must belong to the same environment as the dashboard. Adding an insight the dashboard already shows changes nothing, and adding one that was removed from the dashboard restores its tile. */
+ insight_id: number
+}
+
+export interface DashboardTileBasicApi {
+ /** ID of the dashboard tile. */
+ readonly id: number
+ /** ID of the dashboard the tile sits on. */
+ readonly dashboard_id: number
+ /**
+ * Whether the tile was removed from the dashboard.
+ * @nullable
+ */
+ deleted?: boolean | null
+}
+
export interface CopyDashboardGroupRequestApi {
/** Dashboard id the group currently belongs to. */
fromDashboardId: number
@@ -10062,13 +10079,6 @@ export type _InsightQuerySchemaApi =
| BIVisualizationNodeApi
| HogQueryApi
-export interface DashboardTileBasicApi {
- readonly id: number
- readonly dashboard_id: number
- /** @nullable */
- deleted?: boolean | null
-}
-
/**
* Warnings attached to the query response that produced an insight's results.
*/
@@ -11365,6 +11375,18 @@ export const DashboardsDestroyFormat = {
Txt: 'txt',
} as const
+export type DashboardsAddInsightCreateParams = {
+ format?: DashboardsAddInsightCreateFormat
+}
+
+export type DashboardsAddInsightCreateFormat =
+ (typeof DashboardsAddInsightCreateFormat)[keyof typeof DashboardsAddInsightCreateFormat]
+
+export const DashboardsAddInsightCreateFormat = {
+ Json: 'json',
+ Txt: 'txt',
+} as const
+
export type DashboardsCopyGroupCreateParams = {
format?: DashboardsCopyGroupCreateFormat
}
diff --git a/products/dashboards/frontend/generated/api.ts b/products/dashboards/frontend/generated/api.ts
index 85ac02272e38..9cf05fbfbf60 100644
--- a/products/dashboards/frontend/generated/api.ts
+++ b/products/dashboards/frontend/generated/api.ts
@@ -11,6 +11,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
AddDashboardWidgetsBatchRequestOpenApiApi,
AddDashboardWidgetsBatchResponseApi,
+ AddInsightToDashboardRequestApi,
BulkUpdateTagsRequestApi,
BulkUpdateTagsResponseApi,
CopyDashboardGroupRequestApi,
@@ -24,6 +25,8 @@ import type {
DashboardTemplateApi,
DashboardTemplatesListParams,
DashboardTileApi,
+ DashboardTileBasicApi,
+ DashboardsAddInsightCreateParams,
DashboardsBulkUpdateTagsCreateParams,
DashboardsCopyGroupCreateParams,
DashboardsCopyTileCreateParams,
@@ -410,6 +413,44 @@ export const dashboardsDestroy = async (
})
}
+export const getDashboardsAddInsightCreateUrl = (
+ projectId: string,
+ id: number,
+ params?: DashboardsAddInsightCreateParams
+) => {
+ 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}/dashboards/${id}/add_insight/?${stringifiedParams}`
+ : `/api/projects/${projectId}/dashboards/${id}/add_insight/`
+}
+
+/**
+ * Place an existing insight on this dashboard as a new tile. Requires edit access to the dashboard and view access to the insight. Returns the tile. Adding an insight the dashboard already shows returns its tile unchanged, and adding one that was removed from the dashboard restores its tile with its old layout. To take an insight off a dashboard, use delete_tile.
+ */
+export const dashboardsAddInsightCreate = async (
+ projectId: string,
+ id: number,
+ addInsightToDashboardRequestApi: AddInsightToDashboardRequestApi,
+ params?: DashboardsAddInsightCreateParams,
+ options?: RequestInit
+): Promise<DashboardTileBasicApi> => {
+ return apiMutator<DashboardTileBasicApi>(getDashboardsAddInsightCreateUrl(projectId, id, params), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(addInsightToDashboardRequestApi),
+ })
+}
+
export const getDashboardsCopyGroupCreateUrl = (
projectId: string,
id: number,
diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.ts
index 30fdf7cb4696..a0c8114937fd 100644
--- a/products/dashboards/frontend/generated/api.zod.ts
+++ b/products/dashboards/frontend/generated/api.zod.ts
@@ -659,6 +659,17 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+/**
+ * Place an existing insight on this dashboard as a new tile. Requires edit access to the dashboard and view access to the insight. Returns the tile. Adding an insight the dashboard already shows returns its tile unchanged, and adding one that was removed from the dashboard restores its tile with its old layout. To take an insight off a dashboard, use delete_tile.
+ */
+export const DashboardsAddInsightCreateBody = /* @__PURE__ */ zod.object({
+ insight_id: zod
+ .number()
+ .describe(
+ 'ID of an existing insight to place on the dashboard. The insight must belong to the same environment as the dashboard. Adding an insight the dashboard already shows changes nothing, and adding one that was removed from the dashboard restores its tile.'
+ ),
+})
+
/**
* Copy a group of tiles and its settings to another dashboard.
*/
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 5509aa88403a..933ad1df680b 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -6850,7 +6850,13 @@ export namespace Schemas {
widget: DashboardPatchWidgetOpenApi;
}>;
export type DashboardTileBasic = {
+ /**
+ * ID of the dashboard tile.
+ */
id: number;
+ /**
+ * ID of the dashboard the tile sits on.
+ */
dashboard_id: number;
deleted?: (boolean | null) | undefined;
};
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 3ca898276682..5fc6a400caa8 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -7,6 +7,7 @@ from copy import deepcopy
from datetime import datetime, timedelta
from functools import lru_cache
from typing import Any, Union, cast
+from uuid import UUID
from django.conf import settings
from django.db import transaction
@@ -28,7 +29,7 @@ from pydantic import (
ValidationError as PydanticValidationError,
)
from rest_framework import request, serializers, status, viewsets
-from rest_framework.exceptions import APIException, ParseError, PermissionDenied, ValidationError
+from rest_framework.exceptions import APIException, NotFound, ParseError, PermissionDenied, ValidationError
from rest_framework.parsers import JSONParser
from rest_framework.renderers import BaseRenderer
from rest_framework.request import Request
@@ -109,7 +110,6 @@ from posthog.models.file_system.file_system import delete_files
from posthog.models.organization import Organization
from posthog.models.tagged_item import TaggedItem
from posthog.models.team.team import Team
-from posthog.models.utils import UUIDT
from posthog.permissions import (
TeamMemberStrictManagementPermission,
get_authenticator_scoped_team_ids,
@@ -127,7 +127,6 @@ from posthog.rate_limit import (
InsightExplainDailyThrottle,
)
from posthog.renderers import SafeJSONRenderer
-from posthog.resource_limits import LimitKey, check_count_limit
from posthog.schema_migrations.upgrade import upgrade
from posthog.schema_migrations.upgrade_manager import upgrade_insight
from posthog.scopes import scopes_not_covered
@@ -144,7 +143,10 @@ from posthog.utils import (
variables_override_requested_by_client,
)
-from products.access_control.backend.facade.user_access_control import access_level_satisfied_for_resource
+from products.access_control.backend.facade.user_access_control import (
+ UserAccessControl,
+ access_level_satisfied_for_resource,
+)
from products.access_control.backend.presentation.access_control import (
AccessControlViewSetMixin,
UserAccessControlSerializerMixin,
@@ -162,7 +164,7 @@ from products.dashboards.backend.facade.api import (
DashboardNotFound,
DashboardTileBasicSerializer,
InsightTilePlacement,
- active_tile_count,
+ check_insight_tile_limit,
dashboard_refs,
hide_tiles_for_insights,
insight_has_listed_tile,
@@ -237,7 +239,7 @@ def log_and_report_insight_activity(
insight: Insight,
insight_id: int,
insight_short_id: str,
- organization_id: UUIDT,
+ organization_id: UUID,
team_id: int,
user: User,
was_impersonated: bool,
@@ -278,6 +280,22 @@ def log_and_report_insight_activity(
)
+def viewable_insight_or_404(*, team_id: int, insight_id: int, user_access_control: UserAccessControl) -> Insight:
+ """The live insight of this team with this ID, for an endpoint of another product that acts on it.
+
+ Raises NotFound when the team has no such insight, and PermissionDenied when access rules hide it.
+ """
+ insight = Insight.objects.filter(team_id=team_id, pk=insight_id).first()
+ if insight is None:
+ raise NotFound()
+ # The request's access control answers only for the team in the URL, and the insight can belong to a
+ # sibling environment of the project, whose own rules decide.
+ insight_access = user_access_control.for_team_ids([insight.team_id])[insight.team_id]
+ if not insight_access.check_access_level_for_object(insight, "viewer"):
+ raise PermissionDenied("You don't have permission to view this insight.")
+ return insight
+
+
class QuerySchemaParser(JSONParser):
"""
A query schema parser that only parses the query field and validates it against the schema if it is present
@@ -756,15 +774,11 @@ class InsightSerializer(InsightBasicSerializer):
for dashboard_id in new_dashboard_ids:
if dashboard_id in existing_dashboard_ids:
continue
- check_count_limit(
+ check_insight_tile_limit(
team=team,
- key=LimitKey.MAX_INSIGHTS_PER_DASHBOARD,
- current_count=active_tile_count(dashboard_id),
+ dashboard_id=dashboard_id,
+ dashboard_name=dashboard_names.get(dashboard_id),
user=self.context["request"].user,
- resource_properties={
- "dashboard_id": dashboard_id,
- "dashboard_name": dashboard_names.get(dashboard_id) or "",
- },
)
return super().validate(attrs)
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index 9488200f4eec..7f9d7542d283 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -1583,7 +1583,8 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
]
]
- def test_adding_insight_to_dashboard_updates_activity_log(self) -> None:
+ @parameterized.expand([("insight_dashboards_field",), ("dashboard_tile_actions",)])
+ def test_adding_insight_to_dashboard_updates_activity_log(self, write_path: str) -> None:
dashboard_one_id, _ = self.dashboard_api.create_dashboard({"name": "dash 1"})
dashboard_two_id, _ = self.dashboard_api.create_dashboard({"name": "dash 2"})
@@ -1594,21 +1595,19 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
}
)
- # then remove from one of them
- self.dashboard_api.update_insight(
- insight_id,
- {
- "dashboards": [dashboard_one_id],
- },
- )
-
- # then add one
- self.dashboard_api.update_insight(
- insight_id,
- {
- "dashboards": [dashboard_one_id, dashboard_two_id],
- },
- )
+ # then remove from one of them, then add it back
+ if write_path == "insight_dashboards_field":
+ self.dashboard_api.update_insight(insight_id, {"dashboards": [dashboard_one_id]})
+ self.dashboard_api.update_insight(insight_id, {"dashboards": [dashboard_one_id, dashboard_two_id]})
+ else:
+ tile_id = next(
+ tile["id"] for tile in insight_json["dashboard_tiles"] if tile["dashboard_id"] == dashboard_two_id
+ )
+ dashboards_url = f"/api/projects/{self.team.id}/dashboards/{dashboard_two_id}"
+ response = self.client.post(f"{dashboards_url}/delete_tile/", {"tile_id": tile_id})
+ assert response.status_code == status.HTTP_204_NO_CONTENT, response.content
+ response = self.client.post(f"{dashboards_url}/add_insight/", {"insight_id": insight_id})
+ assert response.status_code == status.HTTP_200_OK, response.content
self.assert_insight_activity(
# expected activity is
@@ -1720,7 +1719,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
@patch("posthog.resource_limits.evaluator.report_user_action")
- @patch("products.product_analytics.backend.presentation.insight.active_tile_count", return_value=99)
+ @patch("products.dashboards.backend.facade.api.active_tile_count", return_value=99)
def test_insight_dashboard_limit_includes_dashboard_context(
self, _mock_active_tile_count: mock.Mock, mock_report_user_action: mock.Mock
) -> None:
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 05c765ed143e..449dbdb43470 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8724,9 +8724,14 @@ export type _InsightQuerySchemaApi =
| HogQueryApi
export interface DashboardTileBasicApi {
+ /** ID of the dashboard tile. */
readonly id: number
+ /** ID of the dashboard the tile sits on. */
readonly dashboard_id: number
- /** @nullable */
+ /**
+ * Whether the tile was removed from the dashboard.
+ * @nullable
+ */
deleted?: boolean | null
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index df1253ed3179..79a6f2bad712 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11322,9 +11322,14 @@ export namespace Schemas {
export type _InsightQuerySchema = InsightVizNode | DataTableNode | DataVisualizationNode | BIVisualizationNode | HogQuery;
export interface DashboardTileBasic {
+ /** ID of the dashboard tile. */
readonly id: number;
+ /** ID of the dashboard the tile sits on. */
readonly dashboard_id: number;
- /** @nullable */
+ /**
+ * Whether the tile was removed from the dashboard.
+ * @nullable
+ */
deleted?: boolean | null;
}
@@ -12263,6 +12268,11 @@ export namespace Schemas {
tiles: DashboardTile[];
}
+ export interface AddInsightToDashboardRequest {
+ /** ID of an existing insight to place on the dashboard. The insight must belong to the same environment as the dashboard. Adding an insight the dashboard already shows changes nothing, and adding one that was removed from the dashboard restores its tile. */
+ insight_id: number;
+ }
+
export interface AddOptOutRequest {
/**
* The recipient identifier to opt out (e.g. email address).
@@ -133770,6 +133780,18 @@ export namespace Schemas {
Txt: 'txt',
} as const;
+ export type DashboardsAddInsightCreateParams = {
+ format?: DashboardsAddInsightCreateFormat;
+ };
+
+ export type DashboardsAddInsightCreateFormat = typeof DashboardsAddInsightCreateFormat[keyof typeof DashboardsAddInsightCreateFormat];
+
+
+ export const DashboardsAddInsightCreateFormat = {
+ Json: 'json',
+ Txt: 'txt',
+ } as const;
+
export type DashboardsCopyGroupCreateParams = {
format?: DashboardsCopyGroupCreateFormat;
};