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): remove saved views from dashboard list (#106732)

Matt Puadbb8adb5b845
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 03f3673cc474..4d62a8926d30 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -135,7 +135,6 @@ rules:
|CustomPropertyValue
|DAG
|Dashboard
- |DashboardSavedView
|DashboardTemplate
|DashboardWidget
|DataColorTheme
@@ -571,7 +570,6 @@ rules:
|CustomPropertyValue
|DAG
|Dashboard
- |DashboardSavedView
|DashboardTemplate
|DashboardWidget
|DataColorTheme
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 150815f6648a..8e44393ad243 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6180,30 +6180,6 @@ snapshots:
hash: v1.k794b7964.cd0763f5b062ec767b6efa099e841b62de1f9a3a4dfdb0bf6c24f6c03ab18e91.kJlKCUFvGXQpWFE1iKqZW5d02nl2ciyHueEC_MeT0MM
products-dashboards-filter-bar--unsaved-changes-popover--light:
hash: v1.k794b7964.d76d6e64be7751440cabed822a47f9b113e3c12aa7edc1d4d087171f7a48aa5d.Evf7PgkLMcvli_EU2xrytkIty8G9Djw41eiXgsmY_KQ
- products-dashboards-saved-views-manage--default--dark:
- hash: v1.k794b7964.5a3fc6cafb3bfa5752b3707e93dd12027d95b7d5db139448c4431e84c64e5af6.uC3oT8cgBWIvwkXeqy_yiNtuoH3JxOhrSxR2bdhxzHw
- products-dashboards-saved-views-manage--default--light:
- hash: v1.k794b7964.904b2109cd3562592066930b833c34001c31579acb2f47e4aa5ba8d4a60a908d.Gv-hVuWdYVBizbiksydO37ocINir8AsH03glO4Di4fc
- products-dashboards-saved-views-picker--default--dark:
- hash: v1.k794b7964.2dc3a1c9da782f144f3fb86794d599e25c1059e29a5fac63e0ea60c37fd2fc02.7JQiCxtRWKUZodFxR9kHFDypkSac_t4lbQLAbrUFpV0
- products-dashboards-saved-views-picker--default--light:
- hash: v1.k794b7964.0acc6d10a22973391132466c371990d4977d109da092385ed548ad2440416f5a.tqKIc25c_gl4cokVmNvruSRJ9ZcV2KLPo5gQxIphCNU
- products-dashboards-saved-views-picker--loading--dark:
- hash: v1.k794b7964.ac68ab893250c0568fdcde55495d51cc605318e5840289cdcd11958db4cd171b.LhwXQQxBzBNkOLVzEqrtDFRdh-qW3up2Alf_R0tg4FQ
- products-dashboards-saved-views-picker--loading--light:
- hash: v1.k794b7964.6e89dc3c54ae50c91bebd0a0ea05d22d1947a2d52c3459ba84063bccb5848a05.8Em3rIE66mrllxUf3PVyD7jO-6trky8IBtKI0eP7oto
- products-dashboards-saved-views-picker--more-results--dark:
- hash: v1.k794b7964.2dc3a1c9da782f144f3fb86794d599e25c1059e29a5fac63e0ea60c37fd2fc02.QdrJgaVwSQBjLha1vxDX5uSMktkccvhZiENThC-u9Rw
- products-dashboards-saved-views-picker--more-results--light:
- hash: v1.k794b7964.172a8efd41450a481d100e86f49ddff26bfd1e69ff9e8f55b769680ab05f5d9c.2GozJjYRn-2e2Sg0Wo9HI1GOojCfNZ5dxEl6RFOTcUQ
- products-dashboards-saved-views-picker--read-only--dark:
- hash: v1.k794b7964.fa8fac66d037e6f747fb70380b2b1bd8f4b4dd1b477cd47c8867ce006b559adf.GvI686sjGwUmKKx9IzmOTVd2L_fIR2Z5C-c22PeJG6M
- products-dashboards-saved-views-picker--read-only--light:
- hash: v1.k794b7964.8effada2b1d9675e4e41b8349128a13df1aaf6ff7f7d9f17ceddc9e3679f3381.EXev_AfKX59mVbVsXJO_XVWjIY6fg0TTtSY1OhjBUkw
- products-dashboards-saved-views-picker--unsaved-changes--dark:
- hash: v1.k794b7964.ae4d53cf83bd85f43f482d85b46b8ea1fcbbda3c76e85c95d8ed5c69f8e7f79a.ZHe8VB25Zs01W7ob1mHEFo2fre9HgaSa_lu98ywEfKA
- products-dashboards-saved-views-picker--unsaved-changes--light:
- hash: v1.k794b7964.5b2eed8ec89ae4dc24cf99c134e2152e542dd26005cb4cf11b62c89283ba1fa3.kSoQkxAxNdC7o_qtVii8nu-mbWDhLz5XFrzl4nvApt0
products-dashboards-templates-dashboard-template-copy--default--dark:
hash: v1.k794b7964.e441fc2d991020695739b9173c39b836a71364c4f3404dcf65f174a109bc919f.xvms_5gbih7s0W9qBwflXMTvNGiKVncitN72D6PQvv4
products-dashboards-templates-dashboard-template-copy--default--light:
@@ -11557,29 +11533,29 @@ snapshots:
scenes-app-sidepanels--side-panel-activity--light:
hash: v1.k794b7964.92e0230464c1b65c62f8a84b3ddc02a97f8127281cb7fccc775fbe599d9edfa1.LK30Oro2SxWnQTaosMAkKK7EAbxhuwImwe3Eq2RrWeQ
scenes-app-sidepanels--side-panel-discussion--dark:
- hash: v1.k794b7964.77379668237153606da4214ad88ea8d67061d82b81a7c2d26199e06437d9405e.InYLBxa-_NY8tQ7ovcby5IN_d2hsQyQmpqcL4rT3WXE
+ hash: v1.k794b7964.18e2e59471989429439e73b50f456b280c43da680a9b69b70e08b802918d5c84.ZRu_ROC2ZgxukiSpGgpRtDEMfvBYqHIol6VwHYShYqI
scenes-app-sidepanels--side-panel-discussion--light:
- hash: v1.k794b7964.8df52bdeef89aaf18c083dbf46789737504984db1a23679723d438e8e5278a6a.ilpbb48KrkpZOibLP_4mb9AyWIvL-aI9zY0nnc9QUgc
+ hash: v1.k794b7964.0cd923f9987ab8ba2612c750e3d0efdbbbc272c27b836fc8e8bd1fb492287c46.YYhBtcIpD4-480nRFXbCuvRrqyRRFPuawnYnhWkEve0
scenes-app-sidepanels--side-panel-exports--dark:
- hash: v1.k794b7964.c05ce6d18e719e4e0ad3525a1564d03645a56a373f9594984f9685e6f99c662d.5-N6cm9IubDckdvrlItmOZ2EQc6e7HUAurKiRo3E8w8
+ hash: v1.k794b7964.debc055e53ce742f96ab914500f1481009ead5f98560f6f236a12742a363d148.I7rOwnzgS8Ni2tz-2zIE08UIB4C9gwDYUW-9gik0wlA
scenes-app-sidepanels--side-panel-exports--light:
- hash: v1.k794b7964.9b6ef930e271cc5423d3b0656dda8b34c639020f2a055224dce48d6b4203544a.vI1hb3lHM_6giCXMR2vP5bfoONMR8oz6Sjjx8fkCZF0
+ hash: v1.k794b7964.896d02944d015e64436d313c54ec6a3014d22d92dd20dbf4cdf400328af423d8.QSa-7v7WDVJD5ZierDLHfcUIkeCfUqAg8kxOThTpKlM
scenes-app-sidepanels--side-panel-info--dark:
hash: v1.k794b7964.eded745dc22b062535738c5dce5ba3e32ead3597bc4ca8be6edbfb60627680f9.vmhOijXx4hnqSvuh7aRGW0_OKNUk9-4dFH6Ebs4mRNI
scenes-app-sidepanels--side-panel-info--light:
hash: v1.k794b7964.7d5d05f9443f5809b23bdf08bfe9c3a48c3085826a4323d9aa3d190ee1e49505.90Nt7uDjc5Iw-q2ebtPh4pEycNoBakH9d1iJOn9iE44
scenes-app-sidepanels--side-panel-max--dark:
- hash: v1.k794b7964.4d17c357bc31e5082fe4791f6a2c568745df2a3eb317220ac25aeae4e5cdc505.E3XnvJok5QCYZKcdazTRfjvCI3LXLRYHTQdmEm4uqTk
+ hash: v1.k794b7964.cbf1e45594b0429af18929f694e4904f5f6e6fca1848a356893b61d5ae22dc5a.EUIbD43vSPUvPmgEtynAR_hDACf_hJLv9HMTSoKebSw
scenes-app-sidepanels--side-panel-max--light:
- hash: v1.k794b7964.44e3bb19b2ff3697459e5449dc1359ea10e8aa0f5cc7864a93d91a11b0fa9a35.ik9gSCL6_tFk4MzsP_zPaXYnD1gYQBZ_kRpmGBp08e8
+ hash: v1.k794b7964.1e48025febd9cbba5e857a4ecdebb70fc0e93652e5a6e698064ca8b2e1d2aa8d.5GpMKTkimVPFys0M5f6acdmDFzdyKqiGLF3xfr-Cggk
scenes-app-sidepanels--side-panel-notebooks--dark:
- hash: v1.k794b7964.6e62e6815cd0e76b7477a5bc638f00a6abc9795dde65cc49eefcb8620daa28a5.nArB3DJkr6XpVd6O9EyxnrjznlFQrs-psgbN39b1xks
+ hash: v1.k794b7964.5b9c7e5a1b63182b6e97e75907a93a77d5715d1d5a41d219647173bafb0b02f6.DsXqKoFnWAkUY8nh_OYO-tfkG47f7BYye3GDd9CI_do
scenes-app-sidepanels--side-panel-notebooks--light:
- hash: v1.k794b7964.04e991a67dc529910c7263b82bc7613da570803728185f3580fea9aa9836c134.HA4yu0bjpuGH0TVb-uYzYzge3J9BqPicleNQrmfkBnM
+ hash: v1.k794b7964.d055d1408c15215578f8532105532017d3132a8d04378b0d5825c5596cc62124.6GVeasWhjS1PR5TnIcfpz6eSZQGQ5Bek6ncqSbVcyf0
scenes-app-sidepanels--side-panel-support--dark:
- hash: v1.k794b7964.cc679c3b53adeb1bc7b9e197f98c84561ba63629d74a778baf6ea461d715084b.ZC3RRANyEzY6UYc3OkqnPys-N5X3OHONsXEyTDNXeGA
+ hash: v1.k794b7964.4bd4546990eb4ddd5acdc57a0dcca304b7ad6b3152437c90837acaa16e997521.MjSmiqQY-9ina_wEpVtcxDqhxDMCHiD9rHCujn546lQ
scenes-app-sidepanels--side-panel-support--light:
- hash: v1.k794b7964.14c7b678f90fb3b4fb13a6b985e649246a1653e8335dca068ac597ab9cf60923.MTwRKdANt9MDKDiOAM2iRk2pXN-jferTd2trX0HRJos
+ hash: v1.k794b7964.902da65fb18b9fa5f09a95a473857d594cdcc1b544522974bb6868b2c83b0fde.rbYUb-nhiDaXqudDQfw6jukLy070-yG4-6P-evFKXVg
scenes-app-signals-artefactloglist--check-lifecycle--dark:
hash: v1.k794b7964.15b3a8e1bcf9e0ce0d97471ae090a83dde50c6050508c449985c44e44d664a0c.qI_1YM1_36ezR-Q857TKtk3Aj9CCtgj5AUoDTPcOckE
scenes-app-signals-artefactloglist--check-lifecycle--light:
diff --git a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
index 924e127b2478..4a5c05c5b14c 100644
--- a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
@@ -27,7 +27,6 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { dashboardsEmptyState } from 'products/dashboards/frontend/emptyState/dashboardsEmptyState'
-import { DashboardSavedViews } from 'products/dashboards/frontend/saved-views/DashboardSavedViews'
import { DashboardsTableContainer } from './DashboardsTable'
@@ -123,8 +122,6 @@ export function Dashboards(): JSX.Element {
activeKey={currentTab}
tabs={enabledTabs}
sceneInset
- rightSlot={<DashboardSavedViews />}
- rightSlotClassName="!static !justify-start !bg-transparent"
/>
<div>{dashboardsLoading || dashboards.length > 0 || isFiltering ? <DashboardsTableContainer /> : null}</div>
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index f615ab58ecde..3a8ff9991853 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -258,7 +258,6 @@ pre_delete:posthog.storage.team_llm_gateway_policy_signal_handlers._clear_cache_
pre_delete:products.alerts.backend.activity_logging.cleanup_alert_hog_functions
pre_delete:products.alerts.backend.activity_logging.handle_alert_subscription_delete
pre_delete:products.billing_alerts.backend.team_lifecycle.rehome_billing_alerts_before_team_delete
-pre_delete:products.dashboards.backend.models.dashboard_saved_view.delete_private_views_for_deleted_user
pre_delete:products.managed_migrations.backend.activity_logging.handle_batch_import_delete
pre_delete:products.tasks.backend.models.clear_channel_repositories_on_github_integration_delete
pre_delete:products.tasks.backend.team_deletion.cancel_task_workflows_on_team_delete
diff --git a/products/dashboards/AGENTS.md b/products/dashboards/AGENTS.md
index e0926e0f3e21..c4bfcabc65b8 100644
--- a/products/dashboards/AGENTS.md
+++ b/products/dashboards/AGENTS.md
@@ -1,11 +1,11 @@
# Dashboards development guide
-This product owns dashboards, dashboard tiles, templates, saved views, and widget tiles.
+This product owns dashboards, dashboard tiles, templates, and widget tiles.
Do not treat every dashboard change as a widget change.
## Choose the change type
-- For dashboard metadata, layouts, insight tiles, text cards, button tiles, templates, or saved views, use the product models and API in this directory.
+- For dashboard metadata, layouts, insight tiles, text cards, button tiles, or templates, use the product models and API in this directory.
- For a tile with `widget_id`, read [`CONTRIBUTING.md`](./CONTRIBUTING.md). It defines widget architecture, registry parity, generated files, and validation commands.
- For dashboard creation or updates through PostHog tools, read [`building-a-dashboard`](./skills/building-a-dashboard/SKILL.md).
- For scheduled dashboard delivery, read [`managing-subscriptions`](../subscriptions/skills/managing-subscriptions/SKILL.md).
diff --git a/products/dashboards/backend/api/dashboard_saved_view.py b/products/dashboards/backend/api/dashboard_saved_view.py
deleted file mode 100644
index 445045804b47..000000000000
--- a/products/dashboards/backend/api/dashboard_saved_view.py
+++ /dev/null
@@ -1,378 +0,0 @@
-import json
-from collections.abc import Mapping
-from typing import Any, Literal, TypedDict, cast
-
-from django.db import models, transaction
-from django.db.models import QuerySet
-
-from drf_spectacular.utils import extend_schema, extend_schema_field
-from rest_framework import mixins, serializers, status, viewsets
-from rest_framework.exceptions import NotFound, PermissionDenied
-from rest_framework.pagination import CursorPagination
-from rest_framework.permissions import SAFE_METHODS, BasePermission
-from rest_framework.request import Request
-from rest_framework.response import Response
-from rest_framework.serializers import BaseSerializer
-from rest_framework.views import APIView
-
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.event_usage import report_user_action
-from posthog.helpers.trigram_search import MAX_SEARCH_LENGTH
-from posthog.models.team import Team
-from posthog.models.user import User
-
-from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl
-from products.dashboards.backend.models.dashboard import Dashboard
-from products.dashboards.backend.models.dashboard_saved_view import DashboardSavedView
-
-SAVED_VIEW_FILTER_KEYS = {"search", "createdBy", "pinned", "shared", "tags", "folder"}
-MAX_SAVED_VIEW_FILTER_BYTES = 16 * 1024
-MAX_SAVED_VIEW_FILTER_STRING_LENGTH = MAX_SEARCH_LENGTH
-MAX_SAVED_VIEW_FOLDER_LENGTH = 4000
-MAX_SAVED_VIEW_TAGS = 50
-MAX_SAVED_VIEW_TAG_LENGTH = 100
-MAX_SAVED_VIEW_CREATORS = 100
-MAX_TEAM_SAVED_VIEWS = 200
-MAX_PERSONAL_SAVED_VIEWS = 50
-
-
-class DashboardSavedViewFilters(TypedDict, total=False):
- search: str
- createdBy: list[int] | Literal["All users"]
- pinned: bool
- shared: bool
- tags: list[str]
- folder: str | None
-
-
-def saved_view_filter_properties(filters: Mapping[str, object]) -> dict[str, bool | int]:
- tags = filters.get("tags", [])
- tag_count = len(tags) if isinstance(tags, list) else 0
- has_search = bool(filters.get("search"))
- has_folder = filters.get("folder") is not None
- has_tags = tag_count > 0
- created_by = filters.get("createdBy")
- has_creator = isinstance(created_by, list) and len(created_by) > 0
- is_pinned = bool(filters.get("pinned"))
- is_shared = bool(filters.get("shared"))
-
- return {
- "has_search_filter": has_search,
- "has_folder_filter": has_folder,
- "has_tag_filter": has_tags,
- "tag_count": tag_count,
- "has_creator_filter": has_creator,
- "is_pinned": is_pinned,
- "is_shared": is_shared,
- "active_filter_count": sum([has_search, has_folder, has_tags, has_creator, is_pinned, is_shared]),
- }
-
-
-def has_saved_view_filters(filters: Mapping[str, object]) -> bool:
- return any(
- saved_view_filter_properties(filters)[property]
- for property in [
- "has_search_filter",
- "has_folder_filter",
- "has_tag_filter",
- "has_creator_filter",
- "is_pinned",
- "is_shared",
- ]
- )
-
-
-def saved_view_creator_properties(*, team_id: int, user_id: int) -> dict[str, int]:
- return {
- "saved_views_created_by_user_count": DashboardSavedView.objects.for_team(team_id)
- .filter(created_by_id=user_id)
- .count(),
- "dashboards_created_by_user_count": Dashboard.objects.filter(team_id=team_id, created_by_id=user_id).count(),
- }
-
-
-@extend_schema_field(
- {
- "oneOf": [
- {"type": "array", "items": {"type": "integer"}, "maxItems": MAX_SAVED_VIEW_CREATORS},
- {"type": "string", "enum": ["All users"]},
- ]
- }
-)
-class DashboardSavedViewCreatorsField(serializers.Field):
- def to_internal_value(self, data: object) -> list[int] | Literal["All users"]:
- if data == "All users":
- return "All users"
- if not isinstance(data, list) or any(type(creator) is not int for creator in data):
- raise serializers.ValidationError("Creators must be a list of user IDs.")
- if len(data) > MAX_SAVED_VIEW_CREATORS:
- raise serializers.ValidationError("You can select up to 100 creators.")
- creator_ids = set(cast(list[int], data))
- team = cast(Team, self.root.context["get_team"]())
- canonical_team = team.parent_team or team
- member_ids = set(
- canonical_team.organization.members.filter(pk__in=creator_ids, is_active=True).values_list("pk", flat=True)
- )
- if creator_ids != member_ids:
- raise serializers.ValidationError("Creators must be active members of this project.")
- return cast(list[int], data)
-
- def to_representation(self, value: object) -> object:
- return value
-
-
-class DashboardSavedViewFiltersSerializer(serializers.Serializer):
- search = serializers.CharField(
- required=False,
- allow_blank=True,
- max_length=MAX_SAVED_VIEW_FILTER_STRING_LENGTH,
- trim_whitespace=False,
- error_messages={"max_length": "Search must be 200 characters or fewer."},
- )
- createdBy = DashboardSavedViewCreatorsField(required=False)
- pinned = serializers.BooleanField(required=False)
- shared = serializers.BooleanField(required=False)
- tags = serializers.ListField(
- child=serializers.CharField(max_length=MAX_SAVED_VIEW_TAG_LENGTH, trim_whitespace=False),
- required=False,
- max_length=MAX_SAVED_VIEW_TAGS,
- error_messages={"max_length": "You can select up to 50 tags."},
- )
- folder = serializers.CharField(
- required=False,
- allow_null=True,
- allow_blank=True,
- max_length=MAX_SAVED_VIEW_FOLDER_LENGTH,
- trim_whitespace=False,
- error_messages={"max_length": "Folder must be 4000 characters or fewer."},
- )
-
- def to_internal_value(self, data: object) -> dict[str, object]:
- if not isinstance(data, dict):
- raise serializers.ValidationError("Filters must be an object")
- unsupported_keys = data.keys() - SAVED_VIEW_FILTER_KEYS
- if unsupported_keys:
- raise serializers.ValidationError("Filters contain unsupported fields.")
- if "search" in data and not isinstance(data["search"], str):
- raise serializers.ValidationError("Search must be a string.")
- if isinstance(data.get("search"), str) and len(cast(str, data["search"])) > MAX_SAVED_VIEW_FILTER_STRING_LENGTH:
- raise serializers.ValidationError("Search must be 200 characters or fewer.")
- if "pinned" in data and not isinstance(data["pinned"], bool):
- raise serializers.ValidationError("Pinned must be true or false.")
- if "shared" in data and not isinstance(data["shared"], bool):
- raise serializers.ValidationError("Shared must be true or false.")
- if "tags" in data and (
- not isinstance(data["tags"], list) or any(not isinstance(tag, str) for tag in data["tags"])
- ):
- raise serializers.ValidationError("Tags must be a list of strings.")
- if isinstance(data.get("tags"), list):
- tags = cast(list[str], data["tags"])
- if len(tags) > MAX_SAVED_VIEW_TAGS:
- raise serializers.ValidationError("You can select up to 50 tags.")
- if any(len(tag) > MAX_SAVED_VIEW_TAG_LENGTH for tag in tags):
- raise serializers.ValidationError("Tags must be 100 characters or fewer.")
- if "folder" in data and data["folder"] is not None and not isinstance(data["folder"], str):
- raise serializers.ValidationError("Folder must be a string or null.")
- if isinstance(data.get("folder"), str) and len(cast(str, data["folder"])) > MAX_SAVED_VIEW_FOLDER_LENGTH:
- raise serializers.ValidationError("Folder must be 4000 characters or fewer.")
- attrs = cast(dict[str, object], super().to_internal_value(data))
- if not has_saved_view_filters(attrs):
- raise serializers.ValidationError("Add at least one filter before saving a view.")
- if (
- len(json.dumps(attrs, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
- > MAX_SAVED_VIEW_FILTER_BYTES
- ):
- raise serializers.ValidationError("Saved view filters are too large.")
- return attrs
-
-
-class DashboardSavedViewWriteSerializer(serializers.ModelSerializer):
- name = serializers.CharField(max_length=200, help_text="Name shown in the dashboard list view picker.")
- filters = DashboardSavedViewFiltersSerializer(help_text="Dashboard list filters stored by this view.")
- scope = serializers.ChoiceField(
- choices=DashboardSavedView.Scope.choices,
- default=DashboardSavedView.Scope.PRIVATE,
- help_text="Whether only the creator or all team members can use this view.",
- )
-
- class Meta:
- model = DashboardSavedView
- fields = ["name", "filters", "scope"]
-
-
-class DashboardSavedViewSerializer(DashboardSavedViewWriteSerializer):
- can_change_scope = serializers.SerializerMethodField(
- help_text="Whether the current user can change this view's visibility."
- )
-
- def get_can_change_scope(self, instance: DashboardSavedView) -> bool:
- return instance.can_change_scope(cast(User, self.context["request"].user))
-
- class Meta(DashboardSavedViewWriteSerializer.Meta):
- fields = ["id", "name", "filters", "scope", "created_at", "updated_at", "created_by", "can_change_scope"]
- read_only_fields = ["id", "created_at", "updated_at", "created_by"]
-
-
-class DashboardSavedViewListQuerySerializer(serializers.Serializer):
- scope = serializers.ChoiceField(
- choices=DashboardSavedView.Scope.choices,
- required=False,
- help_text="Return saved views with this visibility scope.",
- )
-
-
-class DashboardSavedViewPagination(CursorPagination):
- page_size = 100
- page_size_query_param = "limit"
- max_page_size = 100
- ordering = ("name", "id")
-
-
-class DashboardSavedViewPermission(BasePermission):
- message = "You don't have permission to access dashboard saved views."
-
- @staticmethod
- def _saved_views_team(view: APIView) -> Team:
- viewset = cast("DashboardSavedViewViewSet", view)
- return viewset.team.parent_team or viewset.team
-
- def has_permission(self, request: Request, view: APIView) -> bool:
- team = self._saved_views_team(view)
- access_level: AccessControlLevel = "viewer" if request.method in SAFE_METHODS else "editor"
- return UserAccessControl(user=cast(User, request.user), team=team).check_access_level_for_resource(
- "dashboard", access_level
- )
-
- def has_object_permission(self, request: Request, view: APIView, obj: DashboardSavedView) -> bool:
- access_level: AccessControlLevel = "viewer" if request.method in SAFE_METHODS else "editor"
- return UserAccessControl(
- user=cast(User, request.user), team=self._saved_views_team(view)
- ).check_access_level_for_resource("dashboard", access_level)
-
-
-class DashboardSavedViewViewSet(
- TeamAndOrgViewSetMixin,
- mixins.ListModelMixin,
- mixins.CreateModelMixin,
- mixins.UpdateModelMixin,
- mixins.DestroyModelMixin,
- viewsets.GenericViewSet,
-):
- scope_object = "INTERNAL"
- permission_classes = [DashboardSavedViewPermission]
- pagination_class = DashboardSavedViewPagination
- queryset: QuerySet[DashboardSavedView] = DashboardSavedView.all_teams.all()
- serializer_class = DashboardSavedViewSerializer
-
- def get_serializer_class(self) -> type[DashboardSavedViewWriteSerializer | DashboardSavedViewSerializer]:
- if self.action == "create":
- return DashboardSavedViewWriteSerializer
- return DashboardSavedViewSerializer
-
- @extend_schema(parameters=[DashboardSavedViewListQuerySerializer])
- def list(self, request: Request, *args: object, **kwargs: object) -> Response:
- query = DashboardSavedViewListQuerySerializer(data=request.query_params)
- query.is_valid(raise_exception=True)
- return super().list(request, *args, **kwargs)
-
- @extend_schema(
- request=DashboardSavedViewWriteSerializer, responses={status.HTTP_201_CREATED: DashboardSavedViewSerializer}
- )
- def create(self, request: Request, *args: object, **kwargs: object) -> Response:
- serializer = DashboardSavedViewWriteSerializer(data=request.data, context=self.get_serializer_context())
- serializer.is_valid(raise_exception=True)
- self.perform_create(serializer)
- response_serializer = DashboardSavedViewSerializer(serializer.instance, context=self.get_serializer_context())
- return Response(response_serializer.data, status=status.HTTP_201_CREATED)
-
- def safely_get_queryset(self, queryset: QuerySet[DashboardSavedView]) -> QuerySet[DashboardSavedView]:
- queryset = queryset.filter(team_id=self.canonical_team_id).filter(
- models.Q(scope=DashboardSavedView.Scope.TEAM)
- | models.Q(scope=DashboardSavedView.Scope.PRIVATE, created_by=cast(User, self.request.user))
- )
- scope = self.request.query_params.get("scope")
- return queryset.filter(scope=scope) if scope else queryset
-
- @property
- def canonical_team_id(self) -> int:
- return self.team.parent_team_id or self.team.id
-
- def _should_skip_parents_filter(self) -> bool:
- return True
-
- def perform_create(self, serializer: BaseSerializer[Any]) -> None:
- serializer = cast(DashboardSavedViewWriteSerializer, serializer)
- scope = cast(DashboardSavedView.Scope, serializer.validated_data.get("scope", DashboardSavedView.Scope.PRIVATE))
- user = cast(User, self.request.user)
- limit = MAX_TEAM_SAVED_VIEWS if scope == DashboardSavedView.Scope.TEAM else MAX_PERSONAL_SAVED_VIEWS
- views = DashboardSavedView.objects.for_team(self.canonical_team_id).filter(scope=scope)
- if scope == DashboardSavedView.Scope.PRIVATE:
- views = views.filter(created_by=user)
-
- with transaction.atomic():
- Team.objects.select_for_update().get(pk=self.canonical_team_id)
- if views.count() >= limit:
- raise serializers.ValidationError(f"You can save up to {limit} {scope} dashboard views.")
- instance = serializer.save(team_id=self.canonical_team_id, created_by=user)
- report_user_action(
- self.request.user,
- "dashboard saved view created",
- {
- "saved_view_id": str(instance.id),
- "scope": instance.scope,
- **saved_view_filter_properties(cast(DashboardSavedViewFilters, instance.filters)),
- **saved_view_creator_properties(team_id=self.canonical_team_id, user_id=user.id),
- },
- team=self.team,
- request=self.request,
- )
-
- def perform_update(self, serializer: BaseSerializer[Any]) -> None:
- serializer = cast(DashboardSavedViewWriteSerializer, serializer)
- existing_view = cast(DashboardSavedView, serializer.instance)
- try:
- with transaction.atomic():
- locked_view = DashboardSavedView.all_teams.select_for_update().get(pk=existing_view.pk)
- scope = cast(DashboardSavedView.Scope | None, serializer.validated_data.get("scope"))
- if not locked_view.can_modify(cast(User, self.request.user)):
- raise PermissionDenied("You don't have permission to update this private saved view.")
- if (
- scope is not None
- and scope != locked_view.scope
- and not locked_view.can_change_scope(cast(User, self.request.user))
- ):
- raise PermissionDenied("Only the creator can change a shared saved view's visibility.")
- serializer.instance = locked_view
- instance = serializer.save()
- except DashboardSavedView.DoesNotExist:
- raise NotFound()
- report_user_action(
- self.request.user,
- "dashboard saved view updated",
- {
- "saved_view_id": str(instance.id),
- "scope": instance.scope,
- "changed_fields": sorted(serializer.validated_data.keys()),
- **saved_view_filter_properties(cast(DashboardSavedViewFilters, instance.filters)),
- },
- team=self.team,
- request=self.request,
- )
-
- def perform_destroy(self, instance: DashboardSavedView) -> None:
- try:
- with transaction.atomic():
- locked_view = DashboardSavedView.all_teams.select_for_update().get(pk=instance.pk)
- if not locked_view.can_modify(cast(User, self.request.user)):
- raise PermissionDenied("You don't have permission to delete this private saved view.")
- scope = locked_view.scope
- locked_view.delete()
- except DashboardSavedView.DoesNotExist:
- raise NotFound()
- report_user_action(
- self.request.user,
- "dashboard saved view deleted",
- {"saved_view_id": str(instance.id), "scope": scope},
- team=self.team,
- request=self.request,
- )
diff --git a/products/dashboards/backend/api/test/test_dashboard_saved_views.py b/products/dashboards/backend/api/test/test_dashboard_saved_views.py
deleted file mode 100644
index 7f9be7f999ec..000000000000
--- a/products/dashboards/backend/api/test/test_dashboard_saved_views.py
+++ /dev/null
@@ -1,380 +0,0 @@
-from urllib.parse import parse_qs, urlparse
-
-from posthog.test.base import APIBaseTest
-from unittest.mock import patch
-
-from parameterized import parameterized
-from rest_framework import status
-
-from posthog.models.organization import Organization, OrganizationMembership
-from posthog.models.team import Team
-from posthog.models.user import User
-
-from products.dashboards.backend.models.dashboard import Dashboard
-from products.dashboards.backend.models.dashboard_saved_view import DashboardSavedView
-
-
-class TestDashboardSavedViews(APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- self.base_url = f"/api/projects/{self.team.pk}/dashboard_saved_views/"
-
- def _payload(self, **overrides: object) -> dict[str, object]:
- payload: dict[str, object] = {
- "name": "Product dashboards",
- "filters": {"tags": ["product"], "shared": True},
- }
- payload.update(overrides)
- return payload
-
- @parameterized.expand(
- [
- ("without_filters", {}, "Add at least one filter before saving a view."),
- ("with_an_empty_creator_filter", {"createdBy": []}, "Add at least one filter before saving a view."),
- ("with_malformed_filters", {"tags": "product"}, "Tags must be a list of strings."),
- ("with_oversized_filters", {"search": "a" * 201}, "Search must be 200 characters or fewer."),
- ]
- )
- def test_rejects_saved_views_with_invalid_filters(self, _: str, filters: dict[str, object], detail: str) -> None:
- response = self.client.post(self.base_url, self._payload(filters=filters), format="json")
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["detail"] == detail
-
- def test_accepts_long_folder_paths(self) -> None:
- response = self.client.post(self.base_url, self._payload(filters={"folder": "a" * 201}), format="json")
-
- assert response.status_code == status.HTTP_201_CREATED, response.json()
-
- def test_rejects_saved_views_with_creators_outside_the_project(self) -> None:
- other_organization = Organization.objects.create(name="Other organization")
- other_user = User.objects.create_and_join(other_organization, "[email protected]", password="password")
-
- response = self.client.post(self.base_url, self._payload(filters={"createdBy": [other_user.id]}), format="json")
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["detail"] == "Creators must be active members of this project."
-
- @parameterized.expand(
- [
- ("personal", DashboardSavedView.Scope.PRIVATE, 50),
- ("team", DashboardSavedView.Scope.TEAM, 200),
- ]
- )
- def test_limits_saved_views_by_scope(self, _: str, scope: str, limit: int) -> None:
- DashboardSavedView.all_teams.bulk_create(
- [
- DashboardSavedView(
- team=self.team,
- name=f"Saved view {index}",
- filters={"pinned": True},
- scope=scope,
- created_by=self.user,
- )
- for index in range(limit)
- ]
- )
-
- response = self.client.post(self.base_url, self._payload(scope=scope), format="json")
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["detail"] == f"You can save up to {limit} {scope} dashboard views."
-
- def test_rejects_updating_a_saved_view_without_filters(self) -> None:
- response = self.client.post(self.base_url, self._payload(), format="json")
- assert response.status_code == status.HTTP_201_CREATED, response.json()
-
- response = self.client.patch(f"{self.base_url}{response.json()['id']}/", {"filters": {}}, format="json")
-
- assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["detail"] == "Add at least one filter before saving a view."
-
- def test_list_only_includes_saved_views_for_current_project(self) -> None:
- response = self.client.post(self.base_url, self._payload(), format="json")
- assert response.status_code == status.HTTP_201_CREATED, response.json()
- assert response.json()["scope"] == "private"
- assert response.json()["can_change_scope"] is True
-
- other_team = Team.objects.create(organization=self.organization, name="Other project")
- DashboardSavedView.all_teams.create(
- team=other_team,
- name="Other project view",
- filters={},
- created_by=self.user,
- )
-
- response = self.client.get(self.base_url)
-
- assert response.status_code == status.HTTP_200_OK, response.json()
- assert [view["name"] for view in response.json()["results"]] == ["Product dashboards"]
- assert response.json()["results"][0]["can_change_scope"] is True
-
- def test_list_uses_cursor_pagination(self) -> None:
- DashboardSavedView.all_teams.create(
- team=self.team,
- name="Alpha view",
- filters={"pinned": True},
- created_by=self.user,
- )
- DashboardSavedView.all_teams.create(
- team=self.team,
- name="Bravo view",
- filters={"shared": True},
- created_by=self.user,
- )
- DashboardSavedView.all_teams.create(
- team=self.team,
- name="Team view",
- filters={"shared": True},
- scope=DashboardSavedView.Scope.TEAM,
- created_by=self.user,
- )
-
- first_page = self.client.get(self.base_url, {"limit": "1", "scope": "private"})
-
- assert first_page.status_code == status.HTTP_200_OK, first_page.json()
- assert first_page.json()["next"] is not None
- assert [view["name"] for view in first_page.json()["results"]] == ["Alpha view"]
- cursor = parse_qs(urlparse(first_page.json()["next"]).query)["cursor"][0]
- second_page = self.client.get(
- self.base_url,
- {"limit": 1, "cursor": cursor, "scope": DashboardSavedView.Scope.PRIVATE},
- )
- assert second_page.status_code == status.HTTP_200_OK, second_page.json()
- assert [view["name"] for view in second_page.json()["results"]] == ["Bravo view"]
-
- team_page = self.client.get(self.base_url, {"scope": DashboardSavedView.Scope.TEAM})
- assert team_page.status_code == status.HTTP_200_OK, team_page.json()
- assert [view["name"] for view in team_page.json()["results"]] == ["Team view"]
-
- def test_child_environment_manages_parent_project_saved_views(self) -> None:
- child_team = Team.objects.create(
- organization=self.organization, parent_team=self.team, name="Child environment"
- )
- child_url = f"/api/projects/{child_team.pk}/dashboard_saved_views/"
-
- response = self.client.post(child_url, self._payload(), format="json")
- assert response.status_code == status.HTTP_201_CREATED, response.json()
- saved_view_id = response.json()["id"]
- assert DashboardSavedView.all_teams.filter(id=saved_view_id, team=self.team).exists()
-
- response = self.client.get(child_url)
-
- assert response.status_code == status.HTTP_200_OK, response.json()
- assert [view["name"] for view in response.json()["results"]] == ["Product dashboards"]
-
- response = self.client.patch(f"{child_url}{saved_view_id}/", {"name": "Updated view"}, format="json")
- assert response.status_code == status.HTTP_200_OK, response.json()
- assert response.json()["name"] == "Updated view"
-
- response = self.client.delete(f"{child_url}{saved_view_id}/")
- assert response.status_code == status.HTTP_204_NO_CONTENT
- assert not DashboardSavedView.all_teams.filter(id=saved_view_id).exists()
-
- @patch("products.dashboards.backend.api.dashboard_saved_view.UserAccessControl")
- def test_child_environment_authorizes_against_parent_project(self, user_access_control) -> None:
- user_access_control.return_value.check_access_level_for_resource.return_value = True
- child_team = Team.objects.create(
- organization=self.organization, parent_team=self.team, name="Child environment"
- )
-
- response = self.client.get(f"/api/projects/{child_team.pk}/dashboard_saved_views/")
-
- assert response.status_code == status.HTTP_200_OK, response.json()
- user_access_control.assert_called_once_with(user=self.user, team=self.team)
-
- def test_project_member_can_list_saved_views(self) -> None:
- response = self.client.post(self.base_url, self._payload(scope="team"), format="json")
- assert response.status_code == status.HTTP_201_CREATED, response.json()
-
- member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
- self.client.force_login(member)
- response = self.client.get(self.base_url)
-
- assert response.status_code == status.HTTP_200_OK, response.json()
- assert [view["name"] for view in response.json()["results"]] == ["Product dashboards"]
-
- @patch(
- "products.dashboards.backend.api.dashboard_saved_view.UserAccessControl.check_access_level_for_resource",
- return_value=False,
- )
- def test_user_without_dashboard_viewer_access_cannot_list_saved_views(self, _check_access_level) -> None:
- response = self.client.get(self.base_url)
-
- assert response.status_code == status.HTTP_403_FORBIDDEN
-
- def test_private_views_are_visible_only_to_their_creator(self) -> None:
- response = self.client.post(self.base_url, self._payload(scope="private"), format="json")
- assert response.status_code == status.HTTP_201_CREATED, response.json()
- assert response.json()["scope"] == "private"
-
- member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
- self.client.force_login(member)
- response = self.client.get(self.base_url)
-
- assert response.status_code == status.HTTP_200_OK, response.json()
- assert response.json()["results"] == []
-
- def test_deleting_a_creator_removes_only_their_private_views(self) -> None:
- creator = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
- private_view = DashboardSavedView.all_teams.create(
- team=self.team,
- name="Private view",
- filters={"pinned": True},
- scope=DashboardSavedView.Scope.PRIVATE,
- created_by=creator,
- )
- team_view = DashboardSavedView.all_teams.create(
- team=self.team,
- name="Team view",
- filters={"pinned": True},
- scope=DashboardSavedView.Scope.TEAM,
- created_by=creator,
- )
-
- creator.delete()
-
- assert not DashboardSavedView.all_teams.filter(pk=private_view.id).exists()
- assert DashboardSavedView.all_teams.filter(pk=team_view.id, created_by__isnull=True).exists()
-
- @parameterized.expand(
- [
- ("create", "post", "", {"scope": "private"}),
- ("update", "patch", "{id}/", {"name": "Renamed view"}),
- ("delete", "delete", "{id}/", None),
- ]
- )
- @patch(
- "products.dashboards.backend.api.dashboard_saved_view.UserAccessControl.check_access_level_for_resource",
- return_value=False,
- )
- def test_read_only_user_cannot_mutate_saved_views(
- self, _action: str, method: str, path: str, data: dict[str, object] | None, _check_access_level
- ) -> None:
- saved_view = DashboardSavedView.all_teams.create(
- team=self.team,
- name="Private view",
- filters={},
- scope=DashboardSavedView.Scope.PRIVATE,
- created_by=self.user,
- )
-
- request = getattr(self.client, method)
- response = request(f"{self.base_url}{path.format(id=saved_view.id)}", data, format="json")
-
- assert response.status_code == status.HTTP_403_FORBIDDEN
- assert DashboardSavedView.all_teams.filter(pk=saved_view.id).exists()
-
- @patch(
- "products.dashboards.backend.api.dashboard_saved_view.UserAccessControl.check_access_level_for_resource",
- return_value=True,
- )
- def test_only_creator_can_change_a_team_view_visibility(self, _check_access_level) -> None:
- saved_view = DashboardSavedView.all_teams.create(
- team=self.team,
- name="Team view",
- filters={},
- scope=DashboardSavedView.Scope.TEAM,
- created_by=self.user,
- )
- member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
- self.client.force_login(member)
-
- response = self.client.patch(f"{self.base_url}{saved_view.id}/", {"scope": "private"}, format="json")
-
- assert response.status_code == status.HTTP_403_FORBIDDEN
- saved_view.refresh_from_db()
- assert saved_view.scope == DashboardSavedView.Scope.TEAM
-
- @patch(
- "products.dashboards.backend.api.dashboard_saved_view.UserAccessControl.check_access_level_for_resource",
- return_value=True,
- )
- def test_dashboard_editor_cannot_update_or_delete_another_users_private_view(self, _check_access_level) -> None:
- saved_view = DashboardSavedView.all_teams.create(
- team=self.team,
- name="Private view",
- filters={"pinned": True},
- scope=DashboardSavedView.Scope.PRIVATE,
- created_by=self.user,
- )
- member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)
- self.client.force_login(member)
-
- update_response = self.client.patch(f"{self.base_url}{saved_view.id}/", {"name": "Renamed view"}, format="json")
- delete_response = self.client.delete(f"{self.base_url}{saved_view.id}/")
-
- assert update_response.status_code == status.HTTP_404_NOT_FOUND
- assert delete_response.status_code == status.HTTP_404_NOT_FOUND
- saved_view.refresh_from_db()
- assert saved_view.name == "Private view"
-
- @patch("products.dashboards.backend.api.dashboard_saved_view.report_user_action")
- def test_create_and_delete_report_saved_view_events(self, report_user_action) -> None:
- Dashboard.objects.create(team=self.team, name="First dashboard", created_by=self.user)
- Dashboard.objects.create(team=self.team, name="Second dashboard", created_by=self.user)
- response = self.client.post(self.base_url, self._payload(), format="json")
-
- assert response.status_code == status.HTTP_201_CREATED, response.json()
- saved_view = response.json()
- create_event = report_user_action.call_args
- assert create_event.args[:3] == (
- self.user,
- "dashboard saved view created",
- {
- "saved_view_id": saved_view["id"],
- "scope": "private",
- "has_search_filter": False,
- "has_folder_filter": False,
- "has_tag_filter": True,
- "tag_count": 1,
- "has_creator_filter": False,
- "is_pinned": False,
- "is_shared": True,
- "active_filter_count": 2,
- "saved_views_created_by_user_count": 1,
- "dashboards_created_by_user_count": 2,
- },
- )
- assert create_event.kwargs["team"] == self.team
- assert create_event.kwargs["request"] is not None
-
- response = self.client.delete(f"{self.base_url}{saved_view['id']}/")
-
- assert response.status_code == status.HTTP_204_NO_CONTENT
- assert [call.args[1] for call in report_user_action.call_args_list] == [
- "dashboard saved view created",
- "dashboard saved view deleted",
- ]
- assert not DashboardSavedView.all_teams.filter(pk=saved_view["id"]).exists()
-
- @patch("products.dashboards.backend.api.dashboard_saved_view.report_user_action")
- def test_update_reports_filter_shape(self, report_user_action) -> None:
- response = self.client.post(self.base_url, self._payload(), format="json")
- assert response.status_code == status.HTTP_201_CREATED, response.json()
-
- response = self.client.patch(
- f"{self.base_url}{response.json()['id']}/",
- {"filters": {"search": "dashboard", "pinned": True}},
- format="json",
- )
-
- assert response.status_code == status.HTTP_200_OK, response.json()
- update_event = report_user_action.call_args
- assert update_event.args[:3] == (
- self.user,
- "dashboard saved view updated",
- {
- "saved_view_id": response.json()["id"],
- "scope": "private",
- "changed_fields": ["filters"],
- "has_search_filter": True,
- "has_folder_filter": False,
- "has_tag_filter": False,
- "tag_count": 0,
- "has_creator_filter": False,
- "is_pinned": True,
- "is_shared": False,
- "active_filter_count": 2,
- },
- )
diff --git a/products/dashboards/backend/migrations/0022_remove_dashboardsavedview_from_state.py b/products/dashboards/backend/migrations/0022_remove_dashboardsavedview_from_state.py
new file mode 100644
index 000000000000..93b741f2f2d5
--- /dev/null
+++ b/products/dashboards/backend/migrations/0022_remove_dashboardsavedview_from_state.py
@@ -0,0 +1,14 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("dashboards", "0021_drop_dashboardtemplate_github_url_column"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[migrations.DeleteModel(name="DashboardSavedView")],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/dashboards/backend/migrations/max_migration.txt b/products/dashboards/backend/migrations/max_migration.txt
index ed2ac541b3e8..f6a6cf52470e 100644
--- a/products/dashboards/backend/migrations/max_migration.txt
+++ b/products/dashboards/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0021_drop_dashboardtemplate_github_url_column
+0022_remove_dashboardsavedview_from_state
diff --git a/products/dashboards/backend/models/__init__.py b/products/dashboards/backend/models/__init__.py
index 2204c66cf39c..20187ed53d46 100644
--- a/products/dashboards/backend/models/__init__.py
+++ b/products/dashboards/backend/models/__init__.py
@@ -1,5 +1,4 @@
from .dashboard import Dashboard
-from .dashboard_saved_view import DashboardSavedView
from .dashboard_templates import DashboardTemplate
from .dashboard_tile import ButtonTile, DashboardTile, Text
from .dashboard_widget import DashboardWidget
@@ -7,7 +6,6 @@ from .dashboard_widget import DashboardWidget
__all__ = [
"ButtonTile",
"Dashboard",
- "DashboardSavedView",
"DashboardTemplate",
"DashboardTile",
"DashboardWidget",
diff --git a/products/dashboards/backend/models/dashboard_saved_view.py b/products/dashboards/backend/models/dashboard_saved_view.py
deleted file mode 100644
index 9bd77f36c82a..000000000000
--- a/products/dashboards/backend/models/dashboard_saved_view.py
+++ /dev/null
@@ -1,55 +0,0 @@
-from typing import TYPE_CHECKING, Any
-
-from django.db import models
-from django.db.models.signals import pre_delete
-from django.dispatch import receiver
-
-from posthog.models.scoping.root_mixin import TeamScopedRootMixin
-from posthog.models.utils import UUIDModel
-
-if TYPE_CHECKING:
- from posthog.models.user import User
-
-
-class DashboardSavedView(TeamScopedRootMixin, UUIDModel):
- class Scope(models.TextChoices):
- PRIVATE = "private", "Private"
- TEAM = "team", "Team"
-
- team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
- name = models.CharField(max_length=200)
- filters = models.JSONField(default=dict)
- scope = models.CharField(max_length=20, choices=Scope, default=Scope.PRIVATE, db_default=Scope.PRIVATE)
- created_at = models.DateTimeField(auto_now_add=True)
- updated_at = models.DateTimeField(auto_now=True, null=True)
- created_by = models.ForeignKey(
- "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"
- )
- all_teams = models.Manager()
-
- def can_modify(self, user: "User") -> bool:
- return self.scope != self.Scope.PRIVATE or self.created_by_id == user.id
-
- def can_change_scope(self, user: "User") -> bool:
- return self.scope != self.Scope.TEAM or self.created_by_id == user.id
-
- class Meta(TeamScopedRootMixin.Meta):
- db_table = "posthog_dashboard_saved_view"
- ordering = ["id"]
- indexes = [
- models.Index(
- fields=["team", "id"],
- condition=models.Q(scope="team"),
- name="dash_saved_view_team_idx",
- ),
- models.Index(
- fields=["team", "created_by", "id"],
- condition=models.Q(scope="private"),
- name="dash_saved_view_private_idx",
- ),
- ]
-
-
-@receiver(pre_delete, sender="posthog.User")
-def delete_private_views_for_deleted_user(sender: type[models.Model], instance: models.Model, **kwargs: Any) -> None:
- DashboardSavedView.all_teams.filter(scope=DashboardSavedView.Scope.PRIVATE, created_by_id=instance.pk).delete()
diff --git a/products/dashboards/backend/routes.py b/products/dashboards/backend/routes.py
index ee51e05f27fe..6a95a39e604a 100644
--- a/products/dashboards/backend/routes.py
+++ b/products/dashboards/backend/routes.py
@@ -2,7 +2,7 @@ from posthog.api import sharing
from posthog.api.routing import RouterRegistry
from posthog.settings import EE_AVAILABLE
-from products.dashboards.backend.api import dashboard, dashboard_saved_view, dashboard_templates
+from products.dashboards.backend.api import dashboard, dashboard_templates
def register_routes(routers: RouterRegistry) -> None:
@@ -16,12 +16,6 @@ def register_routes(routers: RouterRegistry) -> None:
"project_dashboard_templates",
["project_id"],
)
- routers.projects.register(
- r"dashboard_saved_views",
- dashboard_saved_view.DashboardSavedViewViewSet,
- "project_dashboard_saved_views",
- ["team_id"],
- )
dashboards_router = routers.projects.register(
r"dashboards", dashboard.DashboardsViewSet, "project_dashboards", ["team_id"]
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 27092fe6c731..27f5e8ee6c6b 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -7,105 +7,6 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
-export interface DashboardSavedViewFiltersApi {
- /** @maxLength 200 */
- search?: string
- createdBy?: number[] | 'All users'
- pinned?: boolean
- shared?: boolean
- /**
- * @maxItems 50
- * @items.maxLength 100
- */
- tags?: string[]
- /**
- * @maxLength 4000
- * @nullable
- */
- folder?: string | null
-}
-
-/**
- * * `private` - Private
- * * `team` - Team
- */
-export type DashboardSavedViewScopeEnumApi =
- (typeof DashboardSavedViewScopeEnumApi)[keyof typeof DashboardSavedViewScopeEnumApi]
-
-export const DashboardSavedViewScopeEnumApi = {
- Private: 'private',
- Team: 'team',
-} as const
-
-export interface DashboardSavedViewApi {
- readonly id: string
- /**
- * Name shown in the dashboard list view picker.
- * @maxLength 200
- */
- name: string
- /** Dashboard list filters stored by this view. */
- filters: DashboardSavedViewFiltersApi
- /** Whether only the creator or all team members can use this view.
- *
- * * `private` - Private
- * * `team` - Team */
- scope?: DashboardSavedViewScopeEnumApi
- readonly created_at: string
- /** @nullable */
- readonly updated_at: string | null
- /** @nullable */
- readonly created_by: number | null
- /** Whether the current user can change this view's visibility. */
- readonly can_change_scope: boolean
-}
-
-export interface PaginatedDashboardSavedViewListApi {
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: DashboardSavedViewApi[]
-}
-
-export interface DashboardSavedViewWriteApi {
- /**
- * Name shown in the dashboard list view picker.
- * @maxLength 200
- */
- name: string
- /** Dashboard list filters stored by this view. */
- filters: DashboardSavedViewFiltersApi
- /** Whether only the creator or all team members can use this view.
- *
- * * `private` - Private
- * * `team` - Team */
- scope?: DashboardSavedViewScopeEnumApi
-}
-
-export interface PatchedDashboardSavedViewApi {
- readonly id?: string
- /**
- * Name shown in the dashboard list view picker.
- * @maxLength 200
- */
- name?: string
- /** Dashboard list filters stored by this view. */
- filters?: DashboardSavedViewFiltersApi
- /** Whether only the creator or all team members can use this view.
- *
- * * `private` - Private
- * * `team` - Team */
- scope?: DashboardSavedViewScopeEnumApi
- readonly created_at?: string
- /** @nullable */
- readonly updated_at?: string | null
- /** @nullable */
- readonly created_by?: number | null
- /** Whether the current user can change this view's visibility. */
- readonly can_change_scope?: boolean
-}
-
/**
* * `engineering` - Engineering
* * `data` - Data
@@ -10637,33 +10538,6 @@ export const ConversationsRecentTicketsWidgetTypeEnumApi = {
ConversationsRecentTickets: 'conversations_recent_tickets',
} as const
-export type DashboardSavedViewsListParams = {
- /**
- * The pagination cursor value.
- */
- cursor?: string
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * Return saved views with this visibility scope.
- *
- * * `private` - Private
- * * `team` - Team
- * @minLength 1
- */
- scope?: DashboardSavedViewsListScope
-}
-
-export type DashboardSavedViewsListScope =
- (typeof DashboardSavedViewsListScope)[keyof typeof DashboardSavedViewsListScope]
-
-export const DashboardSavedViewsListScope = {
- Private: 'private',
- Team: 'team',
-} as const
-
export type DashboardTemplatesListParams = {
/**
* Omit for all templates. When set, filter by featured flag; parsed with str_to_bool (same as other API query booleans).
diff --git a/products/dashboards/frontend/generated/api.ts b/products/dashboards/frontend/generated/api.ts
index 7674bca36749..228e0445a7ad 100644
--- a/products/dashboards/frontend/generated/api.ts
+++ b/products/dashboards/frontend/generated/api.ts
@@ -18,9 +18,6 @@ import type {
CreateTextTileRequestApi,
DashboardApi,
DashboardCollaboratorApi,
- DashboardSavedViewApi,
- DashboardSavedViewWriteApi,
- DashboardSavedViewsListParams,
DashboardSubscribeNudgeResponseApi,
DashboardTemplateApi,
DashboardTemplatesListParams,
@@ -53,10 +50,8 @@ import type {
DeleteTileRequestApi,
MoveTileRequestApi,
PaginatedDashboardBasicListApi,
- PaginatedDashboardSavedViewListApi,
PaginatedDashboardTemplateListApi,
PaginatedDataColorThemeListApi,
- PatchedDashboardSavedViewApi,
PatchedDashboardTemplateApi,
PatchedDataColorThemeApi,
PatchedMoveTileRequestApi,
@@ -87,101 +82,6 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
-export const getDashboardSavedViewsListUrl = (projectId: string, params?: DashboardSavedViewsListParams) => {
- 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}/dashboard_saved_views/?${stringifiedParams}`
- : `/api/projects/${projectId}/dashboard_saved_views/`
-}
-
-export const dashboardSavedViewsList = async (
- projectId: string,
- params?: DashboardSavedViewsListParams,
- options?: RequestInit
-): Promise<PaginatedDashboardSavedViewListApi> => {
- return apiMutator<PaginatedDashboardSavedViewListApi>(getDashboardSavedViewsListUrl(projectId, params), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getDashboardSavedViewsCreateUrl = (projectId: string) => {
- return `/api/projects/${projectId}/dashboard_saved_views/`
-}
-
-export const dashboardSavedViewsCreate = async (
- projectId: string,
- dashboardSavedViewWriteApi: DashboardSavedViewWriteApi,
- options?: RequestInit
-): Promise<DashboardSavedViewApi> => {
- return apiMutator<DashboardSavedViewApi>(getDashboardSavedViewsCreateUrl(projectId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(dashboardSavedViewWriteApi),
- })
-}
-
-export const getDashboardSavedViewsUpdateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/dashboard_saved_views/${id}/`
-}
-
-export const dashboardSavedViewsUpdate = async (
- projectId: string,
- id: string,
- dashboardSavedViewApi: NonReadonly<DashboardSavedViewApi>,
- options?: RequestInit
-): Promise<DashboardSavedViewApi> => {
- return apiMutator<DashboardSavedViewApi>(getDashboardSavedViewsUpdateUrl(projectId, id), {
- ...options,
- method: 'PUT',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(dashboardSavedViewApi),
- })
-}
-
-export const getDashboardSavedViewsPartialUpdateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/dashboard_saved_views/${id}/`
-}
-
-export const dashboardSavedViewsPartialUpdate = async (
- projectId: string,
- id: string,
- patchedDashboardSavedViewApi?: NonReadonly<PatchedDashboardSavedViewApi>,
- options?: RequestInit
-): Promise<DashboardSavedViewApi> => {
- return apiMutator<DashboardSavedViewApi>(getDashboardSavedViewsPartialUpdateUrl(projectId, id), {
- ...options,
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedDashboardSavedViewApi),
- })
-}
-
-export const getDashboardSavedViewsDestroyUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/dashboard_saved_views/${id}/`
-}
-
-export const dashboardSavedViewsDestroy = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getDashboardSavedViewsDestroyUrl(projectId, id), {
- ...options,
- method: 'DELETE',
- })
-}
-
export const getDashboardTemplatesListUrl = (projectId: string, params?: DashboardTemplatesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.ts
index f587f8be5a23..3d8cb5ab100b 100644
--- a/products/dashboards/frontend/generated/api.zod.ts
+++ b/products/dashboards/frontend/generated/api.zod.ts
@@ -9,146 +9,6 @@
*/
import * as zod from 'zod'
-export const dashboardSavedViewsCreateBodyNameMax = 200
-
-export const dashboardSavedViewsCreateBodyFiltersOneSearchMax = 200
-
-export const dashboardSavedViewsCreateBodyFiltersOneCreatedByOneMax = 100
-
-export const dashboardSavedViewsCreateBodyFiltersOneTagsItemMax = 100
-
-export const dashboardSavedViewsCreateBodyFiltersOneTagsMax = 50
-
-export const dashboardSavedViewsCreateBodyFiltersOneFolderMax = 4000
-
-export const dashboardSavedViewsCreateBodyScopeDefault = `private`
-
-export const DashboardSavedViewsCreateBody = /* @__PURE__ */ zod.object({
- name: zod
- .string()
- .max(dashboardSavedViewsCreateBodyNameMax)
- .describe('Name shown in the dashboard list view picker.'),
- filters: zod
- .object({
- search: zod.string().max(dashboardSavedViewsCreateBodyFiltersOneSearchMax).optional(),
- createdBy: zod
- .union([
- zod.array(zod.number()).max(dashboardSavedViewsCreateBodyFiltersOneCreatedByOneMax),
- zod.enum(['All users']),
- ])
- .optional(),
- pinned: zod.boolean().optional(),
- shared: zod.boolean().optional(),
- tags: zod
- .array(zod.string().max(dashboardSavedViewsCreateBodyFiltersOneTagsItemMax))
- .max(dashboardSavedViewsCreateBodyFiltersOneTagsMax)
- .optional(),
- folder: zod.string().max(dashboardSavedViewsCreateBodyFiltersOneFolderMax).nullish(),
- })
- .describe('Dashboard list filters stored by this view.'),
- scope: zod
- .enum(['private', 'team'])
- .describe('\* `private` - Private\n\* `team` - Team')
- .default(dashboardSavedViewsCreateBodyScopeDefault)
- .describe(
- 'Whether only the creator or all team members can use this view.\n\n\* `private` - Private\n\* `team` - Team'
- ),
-})
-
-export const dashboardSavedViewsUpdateBodyNameMax = 200
-
-export const dashboardSavedViewsUpdateBodyFiltersOneSearchMax = 200
-
-export const dashboardSavedViewsUpdateBodyFiltersOneCreatedByOneMax = 100
-
-export const dashboardSavedViewsUpdateBodyFiltersOneTagsItemMax = 100
-
-export const dashboardSavedViewsUpdateBodyFiltersOneTagsMax = 50
-
-export const dashboardSavedViewsUpdateBodyFiltersOneFolderMax = 4000
-
-export const dashboardSavedViewsUpdateBodyScopeDefault = `private`
-
-export const DashboardSavedViewsUpdateBody = /* @__PURE__ */ zod.object({
- name: zod
- .string()
- .max(dashboardSavedViewsUpdateBodyNameMax)
- .describe('Name shown in the dashboard list view picker.'),
- filters: zod
- .object({
- search: zod.string().max(dashboardSavedViewsUpdateBodyFiltersOneSearchMax).optional(),
- createdBy: zod
- .union([
- zod.array(zod.number()).max(dashboardSavedViewsUpdateBodyFiltersOneCreatedByOneMax),
- zod.enum(['All users']),
- ])
- .optional(),
- pinned: zod.boolean().optional(),
- shared: zod.boolean().optional(),
- tags: zod
- .array(zod.string().max(dashboardSavedViewsUpdateBodyFiltersOneTagsItemMax))
- .max(dashboardSavedViewsUpdateBodyFiltersOneTagsMax)
- .optional(),
- folder: zod.string().max(dashboardSavedViewsUpdateBodyFiltersOneFolderMax).nullish(),
- })
- .describe('Dashboard list filters stored by this view.'),
- scope: zod
- .enum(['private', 'team'])
- .describe('\* `private` - Private\n\* `team` - Team')
- .default(dashboardSavedViewsUpdateBodyScopeDefault)
- .describe(
- 'Whether only the creator or all team members can use this view.\n\n\* `private` - Private\n\* `team` - Team'
- ),
-})
-
-export const dashboardSavedViewsPartialUpdateBodyNameMax = 200
-
-export const dashboardSavedViewsPartialUpdateBodyFiltersOneSearchMax = 200
-
-export const dashboardSavedViewsPartialUpdateBodyFiltersOneCreatedByOneMax = 100
-
-export const dashboardSavedViewsPartialUpdateBodyFiltersOneTagsItemMax = 100
-
-export const dashboardSavedViewsPartialUpdateBodyFiltersOneTagsMax = 50
-
-export const dashboardSavedViewsPartialUpdateBodyFiltersOneFolderMax = 4000
-
-export const dashboardSavedViewsPartialUpdateBodyScopeDefault = `private`
-
-export const DashboardSavedViewsPartialUpdateBody = /* @__PURE__ */ zod.object({
- name: zod
- .string()
- .max(dashboardSavedViewsPartialUpdateBodyNameMax)
- .optional()
- .describe('Name shown in the dashboard list view picker.'),
- filters: zod
- .object({
- search: zod.string().max(dashboardSavedViewsPartialUpdateBodyFiltersOneSearchMax).optional(),
- createdBy: zod
- .union([
- zod.array(zod.number()).max(dashboardSavedViewsPartialUpdateBodyFiltersOneCreatedByOneMax),
- zod.enum(['All users']),
- ])
- .optional(),
- pinned: zod.boolean().optional(),
- shared: zod.boolean().optional(),
- tags: zod
- .array(zod.string().max(dashboardSavedViewsPartialUpdateBodyFiltersOneTagsItemMax))
- .max(dashboardSavedViewsPartialUpdateBodyFiltersOneTagsMax)
- .optional(),
- folder: zod.string().max(dashboardSavedViewsPartialUpdateBodyFiltersOneFolderMax).nullish(),
- })
- .optional()
- .describe('Dashboard list filters stored by this view.'),
- scope: zod
- .enum(['private', 'team'])
- .describe('\* `private` - Private\n\* `team` - Team')
- .default(dashboardSavedViewsPartialUpdateBodyScopeDefault)
- .describe(
- 'Whether only the creator or all team members can use this view.\n\n\* `private` - Private\n\* `team` - Team'
- ),
-})
-
export const dashboardTemplatesCreateBodyTemplateNameMax = 400
export const dashboardTemplatesCreateBodyDashboardDescriptionMax = 400
diff --git a/products/dashboards/frontend/saved-views/DashboardSavedViews.tsx b/products/dashboards/frontend/saved-views/DashboardSavedViews.tsx
deleted file mode 100644
index 08498bc53752..000000000000
--- a/products/dashboards/frontend/saved-views/DashboardSavedViews.tsx
+++ /dev/null
@@ -1,423 +0,0 @@
-import { deepEqual as isEqual } from 'fast-equals'
-import { useActions, useValues } from 'kea'
-import posthog from 'posthog-js'
-import { useState } from 'react'
-
-import { LemonDialog, LemonInput, LemonTag, lemonToast } from '@posthog/lemon-ui'
-
-import { ApiError } from 'lib/api-error'
-import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
-import { LemonField } from 'lib/lemon-ui/LemonField'
-import { LemonRadio } from 'lib/lemon-ui/LemonRadio'
-import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
-import { fullName } from 'lib/utils/strings'
-import {
- DEFAULT_FILTERS,
- DashboardsFilters,
- DashboardsTab,
- dashboardsLogic,
-} from 'scenes/dashboard/dashboards/dashboardsLogic'
-import { membersLogic } from 'scenes/organization/membersLogic'
-import { teamLogic } from 'scenes/teamLogic'
-
-import { AccessControlLevel, AccessControlResourceType } from '~/types'
-
-import {
- dashboardSavedViewsCreate,
- dashboardSavedViewsDestroy,
- dashboardSavedViewsPartialUpdate,
-} from '../generated/api'
-import type { PatchedDashboardSavedViewApi } from '../generated/api.schemas'
-import {
- DashboardListSavedView,
- DashboardSavedViewScope,
- DashboardSavedViewsPage,
- dashboardListSavedView,
- dashboardSavedViewsLogic,
- loadDashboardSavedViews,
-} from './dashboardSavedViewsLogic'
-import { ManageDashboardSavedViews } from './ManageDashboardSavedViews'
-import { SavedDashboardViewsPicker } from './SavedDashboardViewsPicker'
-
-function savedViewFilterProperties(filters: DashboardsFilters): Record<string, boolean | number> {
- const tagCount = filters.tags?.length ?? 0
- const hasSearch = Boolean(filters.search)
- const hasFolder = filters.folder != null
- const hasTags = tagCount > 0
- const hasCreator = Array.isArray(filters.createdBy) && filters.createdBy.length > 0
-
- return {
- has_search_filter: hasSearch,
- has_folder_filter: hasFolder,
- has_tag_filter: hasTags,
- tag_count: tagCount,
- has_creator_filter: hasCreator,
- is_pinned: filters.pinned,
- is_shared: filters.shared,
- active_filter_count: [hasSearch, hasFolder, hasTags, hasCreator, filters.pinned, filters.shared].filter(Boolean)
- .length,
- }
-}
-
-function savedViewFilters(view: DashboardListSavedView): DashboardsFilters {
- return {
- ...DEFAULT_FILTERS,
- ...view.filters,
- }
-}
-
-function SavedViewVisibilityPicker({
- initialScope,
- onChange,
-}: {
- initialScope: DashboardSavedViewScope
- onChange: (scope: DashboardSavedViewScope) => void
-}): JSX.Element {
- const [scope, setScope] = useState<DashboardSavedViewScope>(initialScope)
-
- const selectScope = (nextScope: DashboardSavedViewScope): void => {
- setScope(nextScope)
- onChange(nextScope)
- }
-
- return (
- <div className="flex items-center gap-4">
- <div className="text-xs font-semibold uppercase tracking-wide text-secondary">Visibility</div>
- <LemonRadio<DashboardSavedViewScope>
- value={scope}
- onChange={selectScope}
- orientation="horizontal"
- aria-label="View visibility"
- options={[
- {
- value: 'private',
- label: 'Private',
- },
- {
- value: 'team',
- label: 'Shared with team',
- disabledReason:
- getAccessControlDisabledReason(
- AccessControlResourceType.Dashboard,
- AccessControlLevel.Editor
- ) ?? undefined,
- },
- ]}
- />
- </div>
- )
-}
-
-export function DashboardSavedViews(): JSX.Element | null {
- const { setFilters, setSearch } = useActions(dashboardsLogic)
- const { currentTab, filters, isFiltering } = useValues(dashboardsLogic)
- const { selectableMembers } = useValues(membersLogic)
- const { currentTeamId } = useValues(teamLogic)
- const savedViewsLogic = dashboardSavedViewsLogic({ teamId: currentTeamId })
- const {
- savedViews,
- savedViewsNextCursors,
- loadMoreSavedViewsLoading,
- savedViewsLoading,
- savedViewsLoadError,
- savedViewsLoadMoreFailed,
- activeSavedViewId,
- } = useValues(savedViewsLogic)
- const {
- loadSavedViews,
- loadMoreSavedViews,
- loadMoreSavedViewsSuccess,
- savedViewCreated,
- savedViewDeleted,
- savedViewUpdated,
- setActiveSavedViewId,
- } = useActions(savedViewsLogic)
- const [updatingSavedView, setUpdatingSavedView] = useState(false)
- const activeSavedView = savedViews.find((view) => view.id === activeSavedViewId)
- const activeSavedViewHasUnsavedChanges =
- activeSavedView != null && !isEqual(filters, savedViewFilters(activeSavedView))
- const membersById = Object.fromEntries(selectableMembers().map((member) => [member.user.id, member]))
- const savedViewCreatorName = (view: DashboardListSavedView): string => {
- if (view.created_by == null) {
- return 'Unknown user'
- }
- const viewCreator = membersById[view.created_by]?.user
- return viewCreator ? fullName(viewCreator) || viewCreator.email : `User ${view.created_by}`
- }
- const savedFiltersSummary = (viewFilters: DashboardsFilters): JSX.Element => (
- <div>
- <div className="text-sm text-secondary">This view saves:</div>
- <ul className="list-disc space-y-2 pl-5 text-sm">
- {viewFilters.shared && <li>Shared dashboards</li>}
- {viewFilters.pinned && <li>Pinned dashboards</li>}
- {viewFilters.tags && viewFilters.tags.length > 0 && (
- <li>
- <div className="flex flex-wrap items-center gap-1">
- <span>Tags:</span>
- <ObjectTags tags={viewFilters.tags} staticOnly />
- </div>
- </li>
- )}
- {viewFilters.createdBy !== 'All users' && (
- <li>
- <div className="flex flex-wrap items-center gap-1">
- <span>Created by:</span>
- {viewFilters.createdBy.map((id) => {
- const member = membersById[id]
- const name = member ? fullName(member.user) || member.user.email : `User ${id}`
-
- return (
- <LemonTag
- key={id}
- size="medium"
- icon={<ProfilePicture user={member?.user} name={name} size="sm" />}
- >
- {name}
- </LemonTag>
- )
- })}
- </div>
- </li>
- )}
- {viewFilters.folder != null && <li>Folder: {viewFilters.folder || 'Project root'}</li>}
- {viewFilters.search && <li>Search: “{viewFilters.search}”</li>}
- </ul>
- </div>
- )
- const savedViewsEditDisabledReason = getAccessControlDisabledReason(
- AccessControlResourceType.Dashboard,
- AccessControlLevel.Editor
- )
-
- const saveView = (initialScope: DashboardSavedViewScope = 'private'): void => {
- if (!isFiltering) {
- lemonToast.error('Add a filter before saving a view')
- return
- }
- let scope = initialScope
- LemonDialog.openForm({
- title: 'Save as new view',
- initialValues: { name: 'My view' },
- content: (
- <div className="space-y-6">
- {savedFiltersSummary(filters)}
- <LemonField name="name">
- <LemonInput autoFocus placeholder="View name" />
- </LemonField>
- <SavedViewVisibilityPicker initialScope={scope} onChange={(value) => (scope = value)} />
- </div>
- ),
- errors: {
- name: (value) => (!value?.trim() ? 'Enter a view name' : undefined),
- },
- showErrorsOnTouch: true,
- onSubmit: async ({ name }) => {
- const trimmedName = name.trim()
- if (currentTeamId == null) {
- return
- }
- const teamId = currentTeamId
- try {
- const savedView = await dashboardSavedViewsCreate(teamId.toString(), {
- name: trimmedName,
- filters,
- scope,
- })
- if (teamId === teamLogic.values.currentTeamId) {
- savedViewCreated(dashboardListSavedView(savedView))
- setActiveSavedViewId(savedView.id)
- lemonToast.success(scope === 'private' ? 'Saved private view' : 'Saved view shared with team')
- }
- } catch (error) {
- const detail = error instanceof ApiError ? error.detail : null
- lemonToast.error(detail || 'Could not save this view. Try again.')
- throw error
- }
- },
- primaryButtonProps: {
- children: 'Save view',
- },
- shouldAwaitSubmit: true,
- width: 600,
- zIndex: '1169',
- })
- }
-
- const deleteSavedView = async (view: DashboardListSavedView): Promise<void> => {
- if (currentTeamId == null) {
- return
- }
- const teamId = currentTeamId
- try {
- await dashboardSavedViewsDestroy(teamId.toString(), view.id)
- if (teamId === teamLogic.values.currentTeamId) {
- savedViewDeleted(view.id)
- lemonToast.success('Saved view deleted')
- }
- } catch (error) {
- const detail = error instanceof ApiError ? error.detail : null
- lemonToast.error(detail || 'Could not delete this view. Try again.')
- throw error
- }
- }
-
- const updateSavedViewMetadata = async (
- view: DashboardListSavedView,
- update: Pick<PatchedDashboardSavedViewApi, 'name' | 'scope'>
- ): Promise<DashboardListSavedView> => {
- if (currentTeamId == null) {
- throw new Error('No project selected')
- }
- const teamId = currentTeamId
- try {
- const savedView = await dashboardSavedViewsPartialUpdate(teamId.toString(), view.id, update)
- const updatedView = dashboardListSavedView(savedView)
- if (teamId === teamLogic.values.currentTeamId) {
- savedViewUpdated(updatedView)
- lemonToast.success('Saved view updated')
- }
- return updatedView
- } catch (error) {
- const detail = error instanceof ApiError ? error.detail : null
- lemonToast.error(detail || 'Could not update this view. Try again.')
- throw error
- }
- }
-
- const savedFiltersDescription = (viewFilters: DashboardsFilters): string => {
- const descriptions: string[] = []
- if (viewFilters.shared) {
- descriptions.push('Shared dashboards')
- }
- if (viewFilters.pinned) {
- descriptions.push('Pinned dashboards')
- }
- if (viewFilters.tags?.length) {
- descriptions.push(`Tags: ${viewFilters.tags.join(', ')}`)
- }
- const createdBy = viewFilters.createdBy === 'All users' ? [] : viewFilters.createdBy || []
- if (createdBy.length > 0) {
- const creators = createdBy.map((id) => {
- const member = membersById[id]
- return member ? fullName(member.user) || member.user.email : `User ${id}`
- })
- descriptions.push(`Created by: ${creators.join(', ')}`)
- }
- if (viewFilters.folder != null) {
- descriptions.push(`Folder: ${viewFilters.folder || 'Project root'}`)
- }
- if (viewFilters.search) {
- descriptions.push(`Search: “${viewFilters.search}”`)
- }
- return descriptions.length > 0 ? descriptions.join(', ') : 'No filters'
- }
-
- const loadMoreSavedViewsForManagement = async (
- scope: DashboardSavedViewScope,
- cursor: string
- ): Promise<DashboardSavedViewsPage | null> => {
- if (currentTeamId == null) {
- return null
- }
- const teamId = currentTeamId
- const page = await loadDashboardSavedViews(teamId, scope, cursor)
- if (teamId !== teamLogic.values.currentTeamId) {
- return null
- }
- loadMoreSavedViewsSuccess(page)
- return page
- }
-
- const manageSavedViews = (): void => {
- LemonDialog.open({
- title: 'Manage saved views',
- content: (
- <ManageDashboardSavedViews
- views={savedViews}
- nextCursors={savedViewsNextCursors}
- editDisabledReason={savedViewsEditDisabledReason}
- onUpdate={updateSavedViewMetadata}
- onDelete={deleteSavedView}
- onLoadMore={loadMoreSavedViewsForManagement}
- renderCreator={(view) => {
- const creator = view.created_by ? membersById[view.created_by]?.user : null
- return (
- <span className="flex items-center gap-2">
- <ProfilePicture user={creator} name={savedViewCreatorName(view)} size="md" />
- <span>{savedViewCreatorName(view)}</span>
- </span>
- )
- }}
- renderFilters={savedFiltersDescription}
- />
- ),
- primaryButton: null,
- secondaryButton: { children: 'Close' },
- width: 1100,
- maxWidth: 'calc(100vw - 2rem)',
- zIndex: '1169',
- })
- }
-
- const updateSavedView = async (view: DashboardListSavedView): Promise<void> => {
- if (currentTeamId == null || updatingSavedView) {
- return
- }
- const teamId = currentTeamId
- setUpdatingSavedView(true)
- try {
- const savedView = await dashboardSavedViewsPartialUpdate(teamId.toString(), view.id, {
- filters,
- })
- if (teamId === teamLogic.values.currentTeamId) {
- savedViewUpdated(dashboardListSavedView(savedView))
- lemonToast.success('Saved view updated')
- }
- } catch (error) {
- const detail = error instanceof ApiError ? error.detail : null
- lemonToast.error(detail || 'Could not update this view. Try again.')
- } finally {
- setUpdatingSavedView(false)
- }
- }
-
- if (currentTab !== DashboardsTab.All) {
- return null
- }
-
- return (
- <SavedDashboardViewsPicker
- activeSavedView={activeSavedView}
- activeSavedViewHasUnsavedChanges={activeSavedViewHasUnsavedChanges}
- isFiltering={isFiltering}
- savedViews={savedViews}
- nextCursors={savedViewsNextCursors}
- loadingMore={loadMoreSavedViewsLoading}
- updatingSavedView={updatingSavedView}
- loading={savedViewsLoading}
- loadError={savedViewsLoadError}
- loadMoreFailed={savedViewsLoadMoreFailed}
- canEdit={!savedViewsEditDisabledReason && !savedViewsLoading}
- onSaveAsNewView={saveView}
- onSaveChanges={(view) => void updateSavedView(view)}
- onSelectView={(view) => {
- if (activeSavedViewId === view.id) {
- setActiveSavedViewId(null)
- return
- }
- posthog.capture('dashboard saved view applied', {
- scope: view.scope,
- ...savedViewFilterProperties(view.filters),
- })
- const nextFilters = savedViewFilters(view)
- setFilters({ ...nextFilters, search: '' })
- setSearch(nextFilters.search)
- setActiveSavedViewId(view.id)
- }}
- onManageViews={manageSavedViews}
- onLoadMore={loadMoreSavedViews}
- onRetryLoad={loadSavedViews}
- />
- )
-}
diff --git a/products/dashboards/frontend/saved-views/ManageDashboardSavedViews.stories.tsx b/products/dashboards/frontend/saved-views/ManageDashboardSavedViews.stories.tsx
deleted file mode 100644
index af37e1f3387a..000000000000
--- a/products/dashboards/frontend/saved-views/ManageDashboardSavedViews.stories.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/react'
-
-import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-
-import type { DashboardListSavedView } from './dashboardSavedViewsLogic'
-import { ManageDashboardSavedViews } from './ManageDashboardSavedViews'
-
-const viewNames = [
- 'Activation dashboard',
- 'Customer feedback',
- 'Daily product review',
- 'Error investigation',
- 'Experiment results',
- 'Feature adoption',
- 'Funnel review',
- 'Launch checklist',
- 'Mobile metrics',
- 'New user journeys',
- 'Onboarding review',
- 'Performance checks',
- 'Pinned dashboards',
- 'Product metrics',
- 'Retention review',
- 'Revenue dashboards',
- 'Session replay review',
- 'Support follow-up',
- 'Team planning',
- 'Weekly review',
-]
-
-const filters: DashboardListSavedView['filters'][] = [
- { search: '', createdBy: 'All users', pinned: false, shared: true, tags: ['product'], folder: null },
- { search: 'feedback', createdBy: [2], pinned: false, shared: false, tags: [], folder: null },
- { search: '', createdBy: 'All users', pinned: true, shared: false, tags: [], folder: 'Product' },
- { search: 'error', createdBy: [3], pinned: false, shared: false, tags: ['engineering'], folder: null },
- { search: '', createdBy: 'All users', pinned: false, shared: false, tags: ['experiments'], folder: 'Growth' },
- { search: 'adoption', createdBy: [4], pinned: false, shared: true, tags: [], folder: null },
- { search: '', createdBy: 'All users', pinned: false, shared: false, tags: ['product', 'growth'], folder: null },
- { search: 'launch', createdBy: [5], pinned: true, shared: false, tags: [], folder: 'Product' },
-]
-
-const creators: Record<number, { first_name: string; last_name: string; email: string }> = {
- 1: { first_name: 'You', last_name: '', email: '[email protected]' },
- 2: { first_name: 'Alex', last_name: 'Chen', email: '[email protected]' },
- 3: { first_name: 'Blair', last_name: 'Kim', email: '[email protected]' },
- 4: { first_name: 'Casey', last_name: 'Morgan', email: '[email protected]' },
- 5: { first_name: 'Devon', last_name: 'Reed', email: '[email protected]' },
-}
-
-const creatorName = (id: number): string => {
- const creator = creators[id]
- return creator ? `${creator.first_name} ${creator.last_name}`.trim() : 'Unknown user'
-}
-
-const savedViews: DashboardListSavedView[] = viewNames.map((name, index) => {
- const isPrivate = index < 8
- const createdBy = isPrivate ? 1 : (index % 4) + 2
-
- return {
- id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, '0')}`,
- name,
- scope: isPrivate ? 'private' : 'team',
- filters: filters[index % filters.length],
- created_at: `2026-08-${String(1 + index).padStart(2, '0')}T10:00:00Z`,
- updated_at: `2026-08-${String(1 + index).padStart(2, '0')}T12:00:00Z`,
- created_by: createdBy,
- can_change_scope: isPrivate || createdBy === 1,
- }
-})
-
-const meta: Meta<typeof ManageDashboardSavedViews> = {
- title: 'Products/Dashboards/Saved views/Manage',
- component: ManageDashboardSavedViews,
- parameters: {
- layout: 'padded',
- mockDate: '2026-08-26T12:00:00Z',
- },
- decorators: [
- (Story) => (
- <div className="max-w-7xl">
- <Story />
- </div>
- ),
- ],
-}
-
-export default meta
-
-type Story = StoryObj<typeof ManageDashboardSavedViews>
-
-export const Default: Story = {
- args: {
- views: savedViews,
- nextCursors: { private: null, team: null },
- editDisabledReason: null,
- onUpdate: async (view, update) => ({ ...view, ...update }),
- onDelete: async () => undefined,
- onLoadMore: async () => null,
- renderCreator: (view) => {
- const id = view.created_by ?? 0
- const creator = creators[id]
- const name = creatorName(id)
-
- return (
- <span className="flex items-center gap-2">
- <ProfilePicture user={creator} name={name} size="md" />
- <span>{name}</span>
- </span>
- )
- },
- renderFilters: (filters) => {
- const labels: string[] = []
- if (filters.shared) {
- labels.push('Shared')
- }
- if (filters.pinned) {
- labels.push('Pinned')
- }
- if (filters.tags?.length) {
- labels.push(`Tags: ${filters.tags.join(', ')}`)
- }
- if (filters.createdBy !== 'All users') {
- labels.push(`Created by: ${filters.createdBy.map(creatorName).join(', ')}`)
- }
- if (filters.folder != null) {
- labels.push(`Folder: ${filters.folder || 'Project root'}`)
- }
- if (filters.search) {
- labels.push(`Search: “${filters.search}”`)
- }
- return labels.join(', ') || 'No filters'
- },
- },
-}
diff --git a/products/dashboards/frontend/saved-views/ManageDashboardSavedViews.tsx b/products/dashboards/frontend/saved-views/ManageDashboardSavedViews.tsx
deleted file mode 100644
index 972e69586f53..000000000000
--- a/products/dashboards/frontend/saved-views/ManageDashboardSavedViews.tsx
+++ /dev/null
@@ -1,270 +0,0 @@
-import { useState } from 'react'
-
-import { IconTrash } from '@posthog/icons'
-import { LemonButton, LemonDialog, LemonInput, LemonSelect } from '@posthog/lemon-ui'
-
-import { TZLabel } from 'lib/components/TZLabel'
-import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-
-import type {
- DashboardListSavedView,
- DashboardSavedViewCursors,
- DashboardSavedViewScope,
- DashboardSavedViewsPage,
-} from './dashboardSavedViewsLogic'
-
-type SavedViewUpdate = Pick<DashboardListSavedView, 'name' | 'scope'>
-
-interface ManageDashboardSavedViewsProps {
- views: DashboardListSavedView[]
- nextCursors: DashboardSavedViewCursors
- editDisabledReason: string | null
- onUpdate: (view: DashboardListSavedView, update: Partial<SavedViewUpdate>) => Promise<DashboardListSavedView>
- onDelete: (view: DashboardListSavedView) => Promise<void>
- onLoadMore: (scope: DashboardSavedViewScope, cursor: string) => Promise<DashboardSavedViewsPage | null>
- renderCreator: (view: DashboardListSavedView) => JSX.Element | string
- renderFilters: (filters: DashboardListSavedView['filters']) => string
-}
-
-export function ManageDashboardSavedViews({
- views: initialViews,
- nextCursors: initialNextCursors,
- editDisabledReason,
- onUpdate,
- onDelete,
- onLoadMore,
- renderCreator,
- renderFilters,
-}: ManageDashboardSavedViewsProps): JSX.Element {
- const [views, setViews] = useState(initialViews)
- const [names, setNames] = useState<Record<string, string>>(() =>
- Object.fromEntries(initialViews.map((view) => [view.id, view.name]))
- )
- const [updatingIds, setUpdatingIds] = useState<string[]>([])
- const [nextCursors, setNextCursors] = useState(initialNextCursors)
- const [loadMoreFailed, setLoadMoreFailed] = useState(false)
- const [loadingMoreViews, setLoadingMoreViews] = useState(false)
-
- const setUpdating = (id: string, updating: boolean): void => {
- setUpdatingIds((ids) => (updating ? [...ids, id] : ids.filter((updatingId) => updatingId !== id)))
- }
-
- const replaceView = (updatedView: DashboardListSavedView): void => {
- setViews((currentViews) => currentViews.map((view) => (view.id === updatedView.id ? updatedView : view)))
- }
-
- const saveName = async (view: DashboardListSavedView): Promise<void> => {
- if (editDisabledReason) {
- return
- }
- const name = names[view.id].trim()
- if (!name) {
- setNames((currentNames) => ({ ...currentNames, [view.id]: view.name }))
- return
- }
- if (name === view.name || updatingIds.includes(view.id)) {
- return
- }
-
- setUpdating(view.id, true)
- try {
- const updatedView = await onUpdate(view, { name })
- replaceView(updatedView)
- } catch {
- setNames((currentNames) => ({ ...currentNames, [view.id]: view.name }))
- } finally {
- setUpdating(view.id, false)
- }
- }
-
- const saveScope = async (view: DashboardListSavedView, scope: DashboardSavedViewScope): Promise<void> => {
- if (scope === view.scope || updatingIds.includes(view.id)) {
- return
- }
-
- setUpdating(view.id, true)
- try {
- const updatedView = await onUpdate(view, { scope })
- replaceView(updatedView)
- } catch {
- return
- } finally {
- setUpdating(view.id, false)
- }
- }
-
- const deleteView = (view: DashboardListSavedView): void => {
- LemonDialog.open({
- title: `Delete saved view “${view.name}”?`,
- description:
- view.scope === 'private'
- ? 'This removes the saved view only for you.'
- : 'This removes the saved view for everyone in this project.',
- primaryButton: {
- children: 'Delete view',
- status: 'danger',
- onClick: async () => {
- setViews((currentViews) => currentViews.filter((savedView) => savedView.id !== view.id))
- try {
- await onDelete(view)
- } catch (error) {
- setViews((currentViews) => [...currentViews, view])
- throw error
- }
- },
- },
- secondaryButton: { children: 'Cancel' },
- shouldAwaitSubmit: true,
- zIndex: '1169',
- })
- }
-
- const loadMoreViews = async (): Promise<void> => {
- if (loadingMoreViews) {
- return
- }
-
- let scope: DashboardSavedViewScope | null = null
- if (nextCursors.private != null) {
- scope = 'private'
- } else if (nextCursors.team != null) {
- scope = 'team'
- }
- if (scope == null) {
- return
- }
- const cursor = nextCursors[scope]
- if (cursor == null) {
- return
- }
-
- setLoadingMoreViews(true)
- try {
- setLoadMoreFailed(false)
- const page = await onLoadMore(scope, cursor)
- if (page) {
- setViews((currentViews) => {
- const ids = new Set(currentViews.map((view) => view.id))
- return [...currentViews, ...page.views.filter((view) => !ids.has(view.id))]
- })
- setNames((currentNames) => ({
- ...currentNames,
- ...Object.fromEntries(page.views.map((view) => [view.id, view.name])),
- }))
- setNextCursors((currentCursors) => ({ ...currentCursors, [scope]: page.nextCursor }))
- }
- } catch {
- setLoadMoreFailed(true)
- } finally {
- setLoadingMoreViews(false)
- }
- }
-
- const columns: LemonTableColumns<DashboardListSavedView> = [
- {
- title: 'Name',
- key: 'name',
- width: 240,
- render: function renderName(_, view) {
- if (editDisabledReason) {
- return <span className="text-secondary">{view.name}</span>
- }
- return (
- <LemonInput
- value={names[view.id]}
- onChange={(name) => setNames((currentNames) => ({ ...currentNames, [view.id]: name }))}
- onBlur={() => void saveName(view)}
- onPressEnter={() => void saveName(view)}
- disabled={updatingIds.includes(view.id)}
- />
- )
- },
- },
- {
- title: 'Visibility',
- key: 'scope',
- width: 150,
- render: function renderScope(_, view) {
- if (editDisabledReason || !view.can_change_scope) {
- return (
- <span className="text-secondary">
- {view.scope === 'private' ? 'Private' : 'Shared with team'}
- </span>
- )
- }
- return (
- <LemonSelect<DashboardSavedViewScope>
- size="small"
- value={view.scope ?? 'team'}
- options={[
- { value: 'private', label: 'Private' },
- { value: 'team', label: 'Shared with team' },
- ]}
- onChange={(scope) => void saveScope(view, scope)}
- disabled={updatingIds.includes(view.id)}
- />
- )
- },
- },
- {
- title: 'Created by',
- key: 'created_by',
- width: 160,
- render: function renderCreatorColumn(_, view) {
- return renderCreator(view)
- },
- },
- {
- title: 'Last updated',
- key: 'updated_at',
- width: 130,
- render: function renderUpdated(_, view) {
- return <TZLabel time={view.updated_at || view.created_at} />
- },
- },
- {
- title: 'Saved filters',
- key: 'filters',
- render: function renderFiltersColumn(_, view) {
- return <span className="text-secondary">{renderFilters(view.filters)}</span>
- },
- },
- ]
- const sortedViews = [...views].sort((left, right) => {
- const scopeOrder = (view: DashboardListSavedView): number => (view.scope === 'private' ? 0 : 1)
- return scopeOrder(left) - scopeOrder(right) || left.name.localeCompare(right.name)
- })
-
- return (
- <div>
- <LemonTable
- columns={columns}
- dataSource={sortedViews}
- rowKey="id"
- size="small"
- className="max-w-full"
- emptyState="No saved views yet. Add a filter to create one."
- rowActions={(view) => (
- <LemonButton
- size="xsmall"
- type="tertiary"
- status="danger"
- icon={<IconTrash />}
- tooltip={`Delete ${view.name}`}
- aria-label={`Delete ${view.name}`}
- disabledReason={editDisabledReason}
- onClick={() => deleteView(view)}
- />
- )}
- />
- {(Object.values(nextCursors).some((cursor) => cursor !== null) || loadMoreFailed) && (
- <div className="flex flex-col items-center gap-1 border-t p-2">
- {loadMoreFailed && <div className="text-sm text-danger">Could not load more views.</div>}
- <LemonButton size="small" type="secondary" loading={loadingMoreViews} onClick={loadMoreViews}>
- {loadMoreFailed ? 'Retry loading views' : 'Load more views'}
- </LemonButton>
- </div>
- )}
- </div>
- )
-}
diff --git a/products/dashboards/frontend/saved-views/SavedDashboardViewsPicker.stories.tsx b/products/dashboards/frontend/saved-views/SavedDashboardViewsPicker.stories.tsx
deleted file mode 100644
index b0789eb442be..000000000000
--- a/products/dashboards/frontend/saved-views/SavedDashboardViewsPicker.stories.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/react'
-
-import type { DashboardListSavedView } from './dashboardSavedViewsLogic'
-import { SavedDashboardViewsPicker } from './SavedDashboardViewsPicker'
-
-const privateViewNames = [
- 'Activation dashboard',
- 'Customer feedback',
- 'Daily product review',
- 'Error investigation',
- 'Experiment results',
- 'Feature adoption',
- 'Funnel review',
- 'Launch checklist',
- 'Mobile metrics',
- 'New user journeys',
- 'Onboarding review',
- 'Product dashboards',
-]
-
-const teamViewNames = [
- 'Performance checks',
- 'Pinned dashboards',
- 'Product metrics',
- 'Retention review',
- 'Revenue dashboards',
- 'Session replay review',
- 'Support follow-up',
- 'Team metrics',
- 'Team planning',
- 'Weekly review',
- 'Workspace health',
- 'Yearly planning',
-]
-
-const savedViews: DashboardListSavedView[] = [...privateViewNames, ...teamViewNames].map((name, index) => {
- const isPrivate = index < privateViewNames.length
-
- return {
- id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, '0')}`,
- name,
- scope: isPrivate ? 'private' : 'team',
- filters: {
- search: index % 3 === 0 ? 'review' : '',
- createdBy: 'All users',
- pinned: index % 4 === 0,
- shared: index % 5 === 0,
- tags: index % 2 === 0 ? ['product'] : [],
- folder: index % 3 === 0 ? 'Product' : null,
- },
- created_at: '2026-08-20T15:30:00Z',
- updated_at: '2026-08-25T10:15:00Z',
- created_by: isPrivate ? 1 : 2,
- can_change_scope: isPrivate,
- }
-})
-
-const meta: Meta<typeof SavedDashboardViewsPicker> = {
- title: 'Products/Dashboards/Saved views/Picker',
- component: SavedDashboardViewsPicker,
- parameters: {
- layout: 'padded',
- testOptions: { snapshotTargetSelector: '.Popover' },
- },
- decorators: [
- (Story) => (
- <div className="absolute left-4 top-4">
- <Story />
- </div>
- ),
- ],
-}
-
-export default meta
-
-type Story = StoryObj<typeof SavedDashboardViewsPicker>
-
-export const Default: Story = {
- args: {
- activeSavedView: undefined,
- activeSavedViewHasUnsavedChanges: false,
- isFiltering: true,
- savedViews,
- nextCursors: { private: null, team: null },
- loadingMore: false,
- updatingSavedView: false,
- loading: false,
- loadError: false,
- loadMoreFailed: false,
- canEdit: true,
- defaultOpen: true,
- onSaveAsNewView: () => undefined,
- onSaveChanges: () => undefined,
- onSelectView: () => undefined,
- onManageViews: () => undefined,
- onLoadMore: () => undefined,
- onRetryLoad: () => undefined,
- },
-}
-
-export const Loading: Story = {
- args: {
- ...Default.args,
- activeSavedView: undefined,
- savedViews: [],
- loading: true,
- defaultOpen: true,
- },
- parameters: {
- testOptions: {
- snapshotTargetSelector: '.Popover',
- waitForLoadersToDisappear: false,
- },
- },
-}
-
-export const MoreResults: Story = {
- args: {
- ...Default.args,
- nextCursors: { private: 'next-private-page', team: null },
- },
-}
-
-export const UnsavedChanges: Story = {
- args: {
- activeSavedView: savedViews[0],
- activeSavedViewHasUnsavedChanges: true,
- isFiltering: true,
- savedViews,
- nextCursors: { private: null, team: null },
- loadingMore: false,
- updatingSavedView: false,
- loading: false,
- loadError: false,
- loadMoreFailed: false,
- canEdit: true,
- defaultOpen: true,
- onSaveAsNewView: () => undefined,
- onSaveChanges: () => undefined,
- onSelectView: () => undefined,
- onManageViews: () => undefined,
- onLoadMore: () => undefined,
- onRetryLoad: () => undefined,
- },
-}
-
-export const ReadOnly: Story = {
- args: {
- activeSavedView: savedViews[0],
- activeSavedViewHasUnsavedChanges: true,
- isFiltering: true,
- savedViews,
- nextCursors: { private: null, team: null },
- loadingMore: false,
- updatingSavedView: false,
- loading: false,
- loadError: false,
- loadMoreFailed: false,
- canEdit: false,
- defaultOpen: true,
- onSaveAsNewView: () => undefined,
- onSaveChanges: () => undefined,
- onSelectView: () => undefined,
- onManageViews: () => undefined,
- onLoadMore: () => undefined,
- onRetryLoad: () => undefined,
- },
-}
diff --git a/products/dashboards/frontend/saved-views/SavedDashboardViewsPicker.tsx b/products/dashboards/frontend/saved-views/SavedDashboardViewsPicker.tsx
deleted file mode 100644
index be3c689761fa..000000000000
--- a/products/dashboards/frontend/saved-views/SavedDashboardViewsPicker.tsx
+++ /dev/null
@@ -1,266 +0,0 @@
-import { useState } from 'react'
-
-import { IconCheck, IconChevronDown, IconPeople, IconPlus, IconUser } from '@posthog/icons'
-import { LemonButton, LemonSkeleton, LemonTag, Popover } from '@posthog/lemon-ui'
-
-import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
-
-import type {
- DashboardListSavedView,
- DashboardSavedViewCursors,
- DashboardSavedViewScope,
-} from './dashboardSavedViewsLogic'
-
-export interface SavedDashboardViewsPickerProps {
- activeSavedView: DashboardListSavedView | undefined
- activeSavedViewHasUnsavedChanges: boolean
- isFiltering: boolean
- savedViews: DashboardListSavedView[]
- nextCursors: DashboardSavedViewCursors
- loadingMore: boolean
- updatingSavedView: boolean
- loading: boolean
- loadError: boolean
- loadMoreFailed: boolean
- canEdit: boolean
- defaultOpen?: boolean
- onSaveAsNewView: () => void
- onSaveChanges: (view: DashboardListSavedView) => void
- onSelectView: (view: DashboardListSavedView) => void
- onManageViews: () => void
- onLoadMore: (scope: DashboardSavedViewScope) => void
- onRetryLoad: () => void
-}
-
-export function SavedDashboardViewsPicker({
- activeSavedView,
- activeSavedViewHasUnsavedChanges,
- isFiltering,
- savedViews,
- nextCursors,
- loadingMore,
- updatingSavedView,
- loading,
- loadError,
- loadMoreFailed,
- canEdit,
- defaultOpen = false,
- onSaveAsNewView,
- onSaveChanges,
- onSelectView,
- onManageViews,
- onLoadMore,
- onRetryLoad,
-}: SavedDashboardViewsPickerProps): JSX.Element {
- const [scope, setScope] = useState<DashboardSavedViewScope>(activeSavedView?.scope ?? 'private')
- const [visible, setVisible] = useState(defaultOpen)
- const privateSavedViews = savedViews
- .filter((view) => view.scope === 'private')
- .sort((left, right) => left.name.localeCompare(right.name))
- const teamSavedViews = savedViews
- .filter((view) => view.scope === 'team')
- .sort((left, right) => left.name.localeCompare(right.name))
- const selectedSavedViews = scope === 'private' ? privateSavedViews : teamSavedViews
- const hasMore = nextCursors[scope] !== null
- const hasSavedViews = savedViews.length > 0
- const tooltip = activeSavedView?.name || 'Saved views'
- const emptyScopeMessage = scope === 'private' ? 'No private views yet.' : 'No team views yet.'
- let triggerIcon: JSX.Element | undefined
- if (activeSavedView) {
- triggerIcon = activeSavedView.scope === 'private' ? <IconUser /> : <IconPeople />
- }
-
- const closePicker = (): void => {
- setVisible(false)
- }
-
- return (
- <Popover
- visible={visible}
- padded={false}
- onClickOutside={closePicker}
- overlay={
- <div className="flex w-72 flex-col py-1" data-attr="dashboard-saved-views-popover">
- {canEdit && activeSavedViewHasUnsavedChanges && activeSavedView && (
- <LemonButton
- fullWidth
- size="small"
- type="tertiary"
- className="h-auto justify-start rounded-none px-2 py-2 text-left"
- icon={<IconCheck className="text-primary" />}
- loading={updatingSavedView}
- onClick={() => onSaveChanges(activeSavedView)}
- >
- <span className="flex flex-col items-start gap-1">
- <span className="font-semibold text-primary">Save changes</span>
- <span className="text-xs font-normal text-secondary">
- Current filters differ from '{activeSavedView.name}'
- </span>
- </span>
- </LemonButton>
- )}
- {canEdit && isFiltering && (
- <LemonButton
- size="small"
- fullWidth
- type="tertiary"
- className="h-auto justify-start rounded-none px-2 py-2 text-left"
- icon={<IconPlus />}
- onClick={() => {
- closePicker()
- onSaveAsNewView()
- }}
- >
- <span className="flex flex-col items-start gap-1">
- <span className="font-semibold">Save as new view</span>
- <span className="text-xs font-normal text-secondary">
- Create a new view from these filters
- </span>
- </span>
- </LemonButton>
- )}
- {(activeSavedView || isFiltering) && <div className="mx-3 border-t" />}
- {loading && (
- <div className="space-y-2 px-3 py-2" role="status" aria-label="Loading saved views">
- <LemonSkeleton repeat={3} className="h-8" />
- </div>
- )}
- {!loading && loadError && (
- <LemonButton
- fullWidth
- size="small"
- type="tertiary"
- className="justify-start rounded-none px-3"
- onClick={onRetryLoad}
- >
- Could not load saved views. Retry
- </LemonButton>
- )}
- {!loading && !loadError && !hasSavedViews && !isFiltering && (
- <div className="px-3 py-2 text-sm text-secondary">Add a filter to create a saved view.</div>
- )}
- {!loading && hasSavedViews && (
- <>
- <LemonTabs<DashboardSavedViewScope>
- size="small"
- activeKey={scope}
- onChange={setScope}
- className="px-3"
- tabs={[
- {
- key: 'private',
- label: (
- <span className="flex items-center gap-1">
- Private views
- {activeSavedView?.scope === 'private' && (
- <IconCheck className="text-success" />
- )}
- </span>
- ),
- },
- {
- key: 'team',
- label: (
- <span className="flex items-center gap-1">
- Shared with team
- {activeSavedView != null && activeSavedView.scope !== 'private' && (
- <IconCheck className="text-success" />
- )}
- </span>
- ),
- },
- ]}
- />
- <div className="max-h-64 overflow-y-auto">
- {selectedSavedViews.length === 0 ? (
- <div className="px-3 py-3 text-sm text-secondary">{emptyScopeMessage}</div>
- ) : (
- selectedSavedViews.map((view) => (
- <LemonButton
- key={view.id}
- fullWidth
- size="small"
- type="tertiary"
- className="justify-start rounded-none px-3 hover:!bg-fill-secondary"
- sideIcon={
- activeSavedView?.id === view.id ? (
- <IconCheck className="text-success" />
- ) : null
- }
- onClick={() => {
- onSelectView(view)
- closePicker()
- }}
- tooltip={
- activeSavedView?.id === view.id ? 'Clear selected view' : undefined
- }
- >
- <span className="truncate">{view.name}</span>
- </LemonButton>
- ))
- )}
- {hasMore && (
- <div className="border-t p-2">
- <LemonButton
- fullWidth
- center
- size="small"
- type="secondary"
- loading={loadingMore}
- onClick={() => onLoadMore(scope)}
- data-attr="load-more-dashboard-saved-views"
- >
- {loadMoreFailed ? 'Could not load more views. Retry' : 'Load more views'}
- </LemonButton>
- </div>
- )}
- </div>
- {canEdit && (
- <div className="border-t">
- <LemonButton
- fullWidth
- size="small"
- type="tertiary"
- className="justify-start rounded-none px-3"
- onClick={() => {
- closePicker()
- onManageViews()
- }}
- >
- Manage views
- </LemonButton>
- </div>
- )}
- </>
- )}
- </div>
- }
- >
- <LemonButton
- size="small"
- type="secondary"
- data-attr="dashboard-saved-views-picker"
- icon={triggerIcon}
- sideIcon={<IconChevronDown />}
- tooltip={tooltip}
- aria-label={tooltip}
- onClick={() => {
- if (!visible && activeSavedView) {
- setScope(activeSavedView.scope ?? 'team')
- }
- setVisible(!visible)
- }}
- >
- <span className="flex items-center gap-1">
- <span>{activeSavedView?.name || 'Saved views'}</span>
- {!activeSavedView && (
- <LemonTag type="highlight" size="small">
- New
- </LemonTag>
- )}
- {canEdit && activeSavedViewHasUnsavedChanges && <span className="text-warning">Unsaved</span>}
- </span>
- </LemonButton>
- </Popover>
- )
-}
diff --git a/products/dashboards/frontend/saved-views/dashboardSavedViewsLogic.test.ts b/products/dashboards/frontend/saved-views/dashboardSavedViewsLogic.test.ts
deleted file mode 100644
index e9e3b39d502d..000000000000
--- a/products/dashboards/frontend/saved-views/dashboardSavedViewsLogic.test.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { ApiError } from 'lib/api-error'
-import { DashboardsTab, dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
-
-import { initKeaTests } from '~/test/init'
-
-import * as api from '../generated/api'
-import type { PaginatedDashboardSavedViewListApi } from '../generated/api.schemas'
-import { DashboardListSavedView, DashboardSavedViewScope, dashboardSavedViewsLogic } from './dashboardSavedViewsLogic'
-
-jest.mock('../generated/api')
-
-const dashboardSavedViewsList = jest.mocked(api.dashboardSavedViewsList)
-
-function savedView(id: string, scope: DashboardSavedViewScope): DashboardListSavedView {
- return {
- id,
- name: `View ${id}`,
- filters: {
- search: '',
- createdBy: 'All users',
- pinned: true,
- shared: false,
- tags: [],
- folder: null,
- },
- scope,
- created_at: '2026-08-27T12:00:00Z',
- updated_at: '2026-08-27T12:00:00Z',
- created_by: 1,
- can_change_scope: true,
- }
-}
-
-function page(views: DashboardListSavedView[], nextCursor: string | null): PaginatedDashboardSavedViewListApi {
- return {
- results: views,
- next: nextCursor ? `https://example.com/api/dashboard_saved_views/?cursor=${nextCursor}` : null,
- previous: null,
- }
-}
-
-describe('dashboardSavedViewsLogic', () => {
- beforeEach(() => {
- initKeaTests()
- dashboardSavedViewsList.mockReset()
- })
-
- it('tracks pagination separately for private and team views', async () => {
- dashboardSavedViewsList.mockImplementation(async (_, params) => {
- if (params?.scope === 'private') {
- return page([savedView('private-1', 'private')], null)
- }
- return page([savedView('team-1', 'team')], 'next-team-page')
- })
-
- const logic = dashboardSavedViewsLogic({ teamId: 1 })
- logic.mount()
-
- await expectLogic(logic)
- .toFinishAllListeners()
- .toMatchValues({
- savedViews: [savedView('private-1', 'private'), savedView('team-1', 'team')],
- savedViewsNextCursors: { private: null, team: 'next-team-page' },
- })
-
- expect(dashboardSavedViewsList).toHaveBeenCalledTimes(2)
- expect(dashboardSavedViewsList).toHaveBeenCalledWith('1', {
- limit: 100,
- scope: 'private',
- cursor: undefined,
- })
- expect(dashboardSavedViewsList).toHaveBeenCalledWith('1', {
- limit: 100,
- scope: 'team',
- cursor: undefined,
- })
-
- logic.unmount()
- })
-
- it('keeps pinned dashboards visible when saved views replace the Pinned tab', async () => {
- dashboardSavedViewsList.mockImplementation(async () => page([], null))
- dashboardsLogic.mount()
- dashboardsLogic.actions.setCurrentTab(DashboardsTab.Pinned)
- const logic = dashboardSavedViewsLogic({ teamId: 1 })
- logic.mount()
-
- await expectLogic(logic).toFinishAllListeners()
- expect(logic.values.currentTab).toBe(DashboardsTab.All)
- expect(logic.values.filters.pinned).toBe(true)
-
- logic.unmount()
- dashboardsLogic.unmount()
- })
-
- it('keeps loaded saved views available when loading another page fails', async () => {
- dashboardSavedViewsList.mockImplementation(async (_, params) => {
- if (params?.scope === 'private') {
- return page([savedView('private-1', 'private')], 'next-private-page')
- }
- return page([], null)
- })
- const logic = dashboardSavedViewsLogic({ teamId: 1 })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-
- logic.actions.loadMoreSavedViewsFailure('Could not load more saved views', new ApiError(undefined, 403))
-
- expectLogic(logic).toMatchValues({
- savedViews: [savedView('private-1', 'private')],
- savedViewsLoadError: false,
- savedViewsLoadMoreFailed: true,
- })
-
- logic.unmount()
- })
-
- it('unselects the active saved view when the final filter is removed', async () => {
- dashboardSavedViewsList.mockImplementation(async () => page([], null))
- const logic = dashboardSavedViewsLogic({ teamId: 1 })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- dashboardsLogic.actions.setFilters({ pinned: true, tags: ['product'] })
- logic.actions.setActiveSavedViewId('private-1')
-
- expectLogic(logic).toMatchValues({ activeSavedViewId: 'private-1' })
- await expectLogic(logic, () => dashboardsLogic.actions.setFilters({ pinned: false, tags: [] }))
- .toFinishAllListeners()
- .toMatchValues({ activeSavedViewId: null })
-
- logic.unmount()
- })
-
- it('restores the active saved view that matches persisted dashboard filters', async () => {
- dashboardSavedViewsList.mockImplementation(async (_, params) => {
- if (params?.scope === 'private') {
- return page([savedView('private-1', 'private')], null)
- }
- return page([], null)
- })
- dashboardsLogic.mount()
- dashboardsLogic.actions.setFilters({ pinned: true })
- const logic = dashboardSavedViewsLogic({ teamId: 1 })
- logic.mount()
-
- await expectLogic(logic).toFinishAllListeners().toMatchValues({ activeSavedViewId: 'private-1' })
-
- logic.unmount()
- dashboardsLogic.unmount()
- })
-})
diff --git a/products/dashboards/frontend/saved-views/dashboardSavedViewsLogic.ts b/products/dashboards/frontend/saved-views/dashboardSavedViewsLogic.ts
deleted file mode 100644
index 274c37df14d3..000000000000
--- a/products/dashboards/frontend/saved-views/dashboardSavedViewsLogic.ts
+++ /dev/null
@@ -1,297 +0,0 @@
-import { deepEqual as isEqual } from 'fast-equals'
-import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers } from 'kea'
-import posthog from 'posthog-js'
-
-import { buildUserScopedPersistenceConfig } from 'lib/logic/persistence'
-import {
- DEFAULT_FILTERS,
- DashboardsFilters,
- DashboardsTab,
- dashboardsLogic,
- hasDashboardFilters,
-} from 'scenes/dashboard/dashboards/dashboardsLogic'
-
-import * as api from 'products/dashboards/frontend/generated/api'
-import type { DashboardSavedViewApi } from 'products/dashboards/frontend/generated/api.schemas'
-
-export type DashboardSavedViewScope = NonNullable<DashboardSavedViewApi['scope']>
-export type DashboardListSavedView = Omit<DashboardSavedViewApi, 'filters' | 'scope'> & {
- filters: DashboardsFilters
- scope: DashboardSavedViewScope
-}
-
-export interface DashboardSavedViewsPage {
- views: DashboardListSavedView[]
- nextCursor: string | null
- scope: DashboardSavedViewScope
-}
-
-export type DashboardSavedViewCursors = Record<DashboardSavedViewScope, string | null>
-
-export interface DashboardSavedViewsLogicProps {
- teamId: number | null
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface dashboardSavedViewsLogicValues {
- currentTab: DashboardsTab // dashboardsLogic
- filters: DashboardsFilters // dashboardsLogic
- activeSavedViewId: string | null
- loadMoreSavedViewsLoading: boolean
- savedViews: DashboardListSavedView[]
- savedViewsLoadError: boolean
- savedViewsLoadMoreFailed: boolean
- savedViewsLoading: boolean
- savedViewsNextCursors: DashboardSavedViewCursors
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface dashboardSavedViewsLogicActions {
- setCurrentTab: (tab: DashboardsTab) => {
- tab: DashboardsTab
- } // dashboardsLogic
- setFilters: (filters: Partial<DashboardsFilters>) => {
- filters: Partial<DashboardsFilters>
- } // dashboardsLogic
- setSearch: (search: string) => {
- search: string
- } // dashboardsLogic
- loadMoreSavedViews: (scope: DashboardSavedViewScope) => {
- scope: DashboardSavedViewScope
- }
- loadMoreSavedViewsFailure: (
- message: string,
- errorObject: unknown
- ) => {
- errorObject: unknown
- message: string
- }
- loadMoreSavedViewsSuccess: (page: DashboardSavedViewsPage) => {
- page: DashboardSavedViewsPage
- }
- loadSavedViews: () => {
- value: true
- }
- loadSavedViewsFailure: (
- message: string,
- errorObject: unknown
- ) => {
- errorObject: unknown
- message: string
- }
- loadSavedViewsSuccess: (pages: DashboardSavedViewsPage[]) => {
- pages: DashboardSavedViewsPage[]
- }
- savedViewCreated: (view: DashboardListSavedView) => {
- view: DashboardListSavedView
- }
- savedViewDeleted: (id: string) => {
- id: string
- }
- savedViewUpdated: (view: DashboardListSavedView) => {
- view: DashboardListSavedView
- }
- setActiveSavedViewId: (id: string | null) => {
- id: string | null
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface dashboardSavedViewsLogicMeta {
- key: number | 'no-team'
-}
-
-export type dashboardSavedViewsLogicType = MakeLogicType<
- dashboardSavedViewsLogicValues,
- dashboardSavedViewsLogicActions,
- DashboardSavedViewsLogicProps,
- dashboardSavedViewsLogicMeta
->
-
-const emptySavedViewCursors: DashboardSavedViewCursors = { private: null, team: null }
-
-export function dashboardListSavedView(view: DashboardSavedViewApi): DashboardListSavedView {
- return {
- ...view,
- filters: { ...DEFAULT_FILTERS, ...view.filters },
- scope: view.scope ?? 'private',
- }
-}
-
-function savedViewsPage(
- response: Awaited<ReturnType<typeof api.dashboardSavedViewsList>>,
- scope: DashboardSavedViewScope
-): DashboardSavedViewsPage {
- return {
- views: response.results.map(dashboardListSavedView),
- nextCursor: response.next ? new URL(response.next).searchParams.get('cursor') : null,
- scope,
- }
-}
-
-export async function loadDashboardSavedViews(
- teamId: number,
- scope: DashboardSavedViewScope,
- cursor?: string
-): Promise<DashboardSavedViewsPage> {
- return savedViewsPage(await api.dashboardSavedViewsList(String(teamId), { limit: 100, scope, cursor }), scope)
-}
-
-export const dashboardSavedViewsLogic = kea<dashboardSavedViewsLogicType>([
- props({} as DashboardSavedViewsLogicProps),
- key((props) => props.teamId ?? 'no-team'),
- path((key) => ['products', 'dashboards', 'saved-views', 'dashboardSavedViewsLogic', key]),
- connect(() => ({
- values: [dashboardsLogic, ['currentTab', 'filters']],
- actions: [dashboardsLogic, ['setCurrentTab', 'setFilters', 'setSearch']],
- })),
- actions({
- loadSavedViews: true,
- loadSavedViewsSuccess: (pages: DashboardSavedViewsPage[]) => ({ pages }),
- loadSavedViewsFailure: (message: string, errorObject: unknown) => ({ message, errorObject }),
- loadMoreSavedViews: (scope: DashboardSavedViewScope) => ({ scope }),
- loadMoreSavedViewsSuccess: (page: DashboardSavedViewsPage) => ({ page }),
- loadMoreSavedViewsFailure: (message: string, errorObject: unknown) => ({ message, errorObject }),
- savedViewCreated: (view: DashboardListSavedView) => ({ view }),
- savedViewUpdated: (view: DashboardListSavedView) => ({ view }),
- savedViewDeleted: (id: string) => ({ id }),
- setActiveSavedViewId: (id: string | null) => ({ id }),
- }),
- reducers(() => ({
- activeSavedViewId: [
- null as string | null,
- buildUserScopedPersistenceConfig('dashboard_list_saved_view__'),
- {
- setActiveSavedViewId: (_, { id }) => id,
- savedViewDeleted: (activeSavedViewId, { id }) => {
- if (activeSavedViewId === id) {
- return null
- }
- return activeSavedViewId
- },
- },
- ],
- savedViewsNextCursors: [
- emptySavedViewCursors,
- {
- loadSavedViews: () => emptySavedViewCursors,
- loadSavedViewsSuccess: (_, { pages }) => ({
- private: pages.find((page) => page.scope === 'private')?.nextCursor ?? null,
- team: pages.find((page) => page.scope === 'team')?.nextCursor ?? null,
- }),
- loadMoreSavedViewsSuccess: (cursors, { page }) => ({
- ...cursors,
- [page.scope]: page.nextCursor,
- }),
- },
- ],
- savedViewsLoadError: [
- false,
- {
- loadSavedViews: () => false,
- loadSavedViewsFailure: () => true,
- loadSavedViewsSuccess: () => false,
- },
- ],
- savedViewsLoadMoreFailed: [
- false,
- {
- loadSavedViews: () => false,
- loadMoreSavedViews: () => false,
- loadMoreSavedViewsFailure: () => true,
- loadMoreSavedViewsSuccess: () => false,
- },
- ],
- savedViewsLoading: [
- false,
- { loadSavedViews: () => true, loadSavedViewsFailure: () => false, loadSavedViewsSuccess: () => false },
- ],
- loadMoreSavedViewsLoading: [
- false,
- {
- loadMoreSavedViews: () => true,
- loadMoreSavedViewsFailure: () => false,
- loadMoreSavedViewsSuccess: () => false,
- },
- ],
- savedViews: [
- [] as DashboardListSavedView[],
- {
- loadSavedViews: () => [],
- loadSavedViewsSuccess: (_, { pages }) => pages.flatMap((page) => page.views),
- loadMoreSavedViewsSuccess: (views, { page }) => {
- const ids = new Set(views.map((view) => view.id))
- return [...views, ...page.views.filter((view) => !ids.has(view.id))]
- },
- savedViewCreated: (views, { view }) => [...views, view],
- savedViewUpdated: (views, { view }) => views.map((item) => (item.id === view.id ? view : item)),
- savedViewDeleted: (views, { id }) => views.filter((view) => view.id !== id),
- },
- ],
- })),
- listeners(({ actions, props, values }) => ({
- loadSavedViewsSuccess: ({ pages }) => {
- const views = pages.flatMap((page) => page.views)
- if (values.activeSavedViewId && views.some((view) => view.id === values.activeSavedViewId)) {
- return
- }
- actions.setActiveSavedViewId(views.find((view) => isEqual(view.filters, values.filters))?.id ?? null)
- },
- setFilters: async (_, breakpoint) => {
- await breakpoint(0)
- if (!hasDashboardFilters(dashboardsLogic.values.filters)) {
- actions.setActiveSavedViewId(null)
- }
- },
- setSearch: async (_, breakpoint) => {
- await breakpoint(0)
- if (!hasDashboardFilters(dashboardsLogic.values.filters)) {
- actions.setActiveSavedViewId(null)
- }
- },
- loadSavedViews: async (_, breakpoint) => {
- if (props.teamId == null) {
- actions.loadSavedViewsSuccess([])
- return
- }
- try {
- const pages = await Promise.all([
- loadDashboardSavedViews(props.teamId, 'private'),
- loadDashboardSavedViews(props.teamId, 'team'),
- ])
- breakpoint()
- actions.loadSavedViewsSuccess(pages)
- } catch (error) {
- posthog.captureException(error)
- actions.loadSavedViewsFailure(
- error instanceof Error ? error.message : 'Could not load saved views',
- error
- )
- }
- },
- loadMoreSavedViews: async ({ scope }, breakpoint) => {
- const cursor = values.savedViewsNextCursors[scope]
- if (props.teamId == null || cursor == null) {
- return
- }
- try {
- const page = await loadDashboardSavedViews(props.teamId, scope, cursor)
- breakpoint()
- actions.loadMoreSavedViewsSuccess(page)
- } catch (error) {
- posthog.captureException(error)
- actions.loadMoreSavedViewsFailure(
- error instanceof Error ? error.message : 'Could not load more saved views',
- error
- )
- }
- },
- })),
- afterMount(({ actions, values }) => {
- if (values.currentTab === DashboardsTab.Pinned) {
- actions.setCurrentTab(DashboardsTab.All)
- actions.setFilters({ pinned: true })
- }
- actions.loadSavedViews()
- }),
-])
diff --git a/products/dashboards/mcp/tools.yaml b/products/dashboards/mcp/tools.yaml
index 041349441b78..356e8b39af2c 100644
--- a/products/dashboards/mcp/tools.yaml
+++ b/products/dashboards/mcp/tools.yaml
@@ -323,21 +323,6 @@ tools:
each tile's `layouts` with dashboard-update instead. This tool repacks only the tiles in `tile_order`. To
repack the whole dashboard, include every tile ID. Tiles omitted from `tile_order` keep their positions and
can overlap the repacked tiles. This tool does not set different sizes or positions for individual tiles.
- dashboard-saved-views-create:
- operation: dashboard_saved_views_create
- enabled: false
- dashboard-saved-views-destroy:
- operation: dashboard_saved_views_destroy
- enabled: false
- dashboard-saved-views-list:
- operation: dashboard_saved_views_list
- enabled: false
- dashboard-saved-views-partial-update:
- operation: dashboard_saved_views_partial_update
- enabled: false
- dashboard-saved-views-update:
- operation: dashboard_saved_views_update
- enabled: false
dashboard-templates-copy-between-projects-create:
operation: dashboard_templates_copy_between_projects_create
enabled: false
diff --git a/pyproject.toml b/pyproject.toml
index 782b096bc209..434fe3ac5139 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -762,7 +762,6 @@ ignore_imports = [
"products.cohorts.backend.routes -> products.cohorts.backend.api.staff_tools",
"products.conversations.backend.routes -> products.conversations.backend.api",
"products.dashboards.backend.routes -> products.dashboards.backend.api.dashboard",
- "products.dashboards.backend.routes -> products.dashboards.backend.api.dashboard_saved_view",
"products.dashboards.backend.routes -> products.dashboards.backend.api.dashboard_templates",
"products.early_access_features.backend.routes -> products.early_access_features.backend.api",
"products.exports.backend.routes -> products.exports.backend.api.exports",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8acc41bfdbef..552739e1b071 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25082,74 +25082,6 @@ export namespace Schemas {
widget?: DashboardPatchWidgetOpenApi;
}
- export interface DashboardSavedViewFilters {
- /** @maxLength 200 */
- search?: string;
- createdBy?: number[] | 'All users';
- pinned?: boolean;
- shared?: boolean;
- /**
- * @maxItems 50
- * @items.maxLength 100
- */
- tags?: string[];
- /**
- * @maxLength 4000
- * @nullable
- */
- folder?: string | null;
- }
-
- /**
- * * `private` - Private
- * * `team` - Team
- */
- export type DashboardSavedViewScopeEnum = typeof DashboardSavedViewScopeEnum[keyof typeof DashboardSavedViewScopeEnum];
-
-
- export const DashboardSavedViewScopeEnum = {
- Private: 'private',
- Team: 'team',
- } as const;
-
- export interface DashboardSavedView {
- readonly id: string;
- /**
- * Name shown in the dashboard list view picker.
- * @maxLength 200
- */
- name: string;
- /** Dashboard list filters stored by this view. */
- filters: DashboardSavedViewFilters;
- /** Whether only the creator or all team members can use this view.
- *
- * * `private` - Private
- * * `team` - Team */
- scope?: DashboardSavedViewScopeEnum;
- readonly created_at: string;
- /** @nullable */
- readonly updated_at: string | null;
- /** @nullable */
- readonly created_by: number | null;
- /** Whether the current user can change this view's visibility. */
- readonly can_change_scope: boolean;
- }
-
- export interface DashboardSavedViewWrite {
- /**
- * Name shown in the dashboard list view picker.
- * @maxLength 200
- */
- name: string;
- /** Dashboard list filters stored by this view. */
- filters: DashboardSavedViewFilters;
- /** Whether only the creator or all team members can use this view.
- *
- * * `private` - Private
- * * `team` - Team */
- scope?: DashboardSavedViewScopeEnum;
- }
-
export interface DashboardSubscribeNudgeResponse {
/** Whether a nudge notification was created. False when one was already sent recently for this user and dashboard, or when in-app notifications are unavailable. */
created: boolean;
@@ -63658,14 +63590,6 @@ export namespace Schemas {
results: DashboardBasic[];
}
- export interface PaginatedDashboardSavedViewList {
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: DashboardSavedView[];
- }
-
export interface PaginatedDashboardTemplateList {
count: number;
/** @nullable */
@@ -71583,29 +71507,6 @@ export namespace Schemas {
readonly updated_at?: string | null;
}
- export interface PatchedDashboardSavedView {
- readonly id?: string;
- /**
- * Name shown in the dashboard list view picker.
- * @maxLength 200
- */
- name?: string;
- /** Dashboard list filters stored by this view. */
- filters?: DashboardSavedViewFilters;
- /** Whether only the creator or all team members can use this view.
- *
- * * `private` - Private
- * * `team` - Team */
- scope?: DashboardSavedViewScopeEnum;
- readonly created_at?: string;
- /** @nullable */
- readonly updated_at?: string | null;
- /** @nullable */
- readonly created_by?: number | null;
- /** Whether the current user can change this view's visibility. */
- readonly can_change_scope?: boolean;
- }
-
export interface PatchedDashboardTemplate {
readonly id?: string;
/**
@@ -108294,33 +108195,6 @@ export namespace Schemas {
offset?: number;
};
- export type DashboardSavedViewsListParams = {
- /**
- * The pagination cursor value.
- */
- cursor?: string;
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * Return saved views with this visibility scope.
- *
- * * `private` - Private
- * * `team` - Team
- * @minLength 1
- */
- scope?: DashboardSavedViewsListScope;
- };
-
- export type DashboardSavedViewsListScope = typeof DashboardSavedViewsListScope[keyof typeof DashboardSavedViewsListScope];
-
-
- export const DashboardSavedViewsListScope = {
- Private: 'private',
- Team: 'team',
- } as const;
-
export type DashboardTemplatesListParams = {
/**
* Omit for all templates. When set, filter by featured flag; parsed with str_to_bool (same as other API query booleans).