:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(dashboards): add saved filter views (#90231)
Matt Pua1801e49a2486
diff --git a/.agents/skills/managing-dashboards/SKILL.md b/.agents/skills/managing-dashboards/SKILL.mdindex 75bb3e60cdd7..e46e493c5243 100644--- a/.agents/skills/managing-dashboards/SKILL.md+++ b/.agents/skills/managing-dashboards/SKILL.md@@ -42,7 +42,7 @@ Do this before implementation for a new dashboard feature. Skip it for a narrow1. State the user problem, intended actor, and explicit non-goals.2. State the feature action and its default behavior.-3. State the state owner: dashboard, tile, request, user, or URL.+3. State where the feature stores its state: dashboard, tile, request, user, URL, or a separate team-scoped resource.4. State the availability, read permission, and mutation permission.5. State behavior for new rows, existing rows, and invalid or absent state.6. State the acceptance criteria for allowed, denied, shared, and failure paths.@@ -67,6 +67,7 @@ State these decisions before implementation.8. Define cache, refresh, query, and failure behavior.9. If templates apply, define scope, portability, copy semantics, and later edits.10. Define lifecycle, API, streaming, quota, audit, and project-tree effects.+11. For a new API, add MCP tools for its supported operations. Exclude an operation only with a documented reason. Record required scopes.Use this checklist as a design gate. Read the linked reference when an item applies.@@ -89,6 +90,7 @@ Use this checklist as a design gate. Read the linked reference when an item appl5. Keep query work bounded. Do not turn dashboard load into unbounded tile queries or concurrent requests.6. Keep grid updates stable during drag, resize, and tile refresh. Avoid a full grid relayout for each tile result.7. Add observability when a change creates a new loading, query, cache, access, or refresh path.+8. For list-only state, render controls only where that state applies.## 5. Test the boundary, not only the happy path@@ -102,6 +104,7 @@ Cover each affected boundary.- Narrow layout, wide layout, drag, resize, insertion, duplication, and persisted layout reload.- Template scope, permissions, variable substitution, and project-specific references.- API schema and generated types after serializer changes.+- Paginated list ordering, each page, and client continuation when the UI loads every result.- Filter and variable precedence, shared-token behavior, and quick-filter validation.- Soft-delete, restore, move, copy, and project-transfer behavior.- Streaming completion, disconnect, and individual tile failure behavior.diff --git a/.agents/skills/managing-dashboards/references/backend-contracts-and-operations.md b/.agents/skills/managing-dashboards/references/backend-contracts-and-operations.mdindex 061ac66e3729..9791bbb92213 100644--- a/.agents/skills/managing-dashboards/references/backend-contracts-and-operations.md+++ b/.agents/skills/managing-dashboards/references/backend-contracts-and-operations.md@@ -34,14 +34,19 @@ Dashboard list behavior is a separate contract from dashboard detail.- Product-created unlisted dashboards need stable lookup data and concurrent-create protection.- Keep product-created dashboards out of normal lists unless the product explicitly exposes them.+### Persisted list state++- Store persisted list configuration separately from dashboard metadata.+- Persist only values that reconstruct the list. Do not persist temporary UI state.+## API, schema, and MCP contracts-Dashboard behavior has REST and generated frontend consumers. It also has MCP consumers when the changed API operation is enabled in `products/dashboards/mcp/tools.yaml`.+Dashboard behavior has REST, generated frontend, and MCP consumers.1. Add serializer schema annotations for every new request or response field.2. Run `hogli build:openapi` after API contract changes.-3. Update `products/dashboards/mcp/tools.yaml` only when the changed operation is MCP-enabled or becomes MCP-enabled.-4. Regenerate MCP code only when the OpenAPI operation or tool definition changes.+3. Define MCP operations in `products/dashboards/mcp/tools.yaml`. Include required scopes and destructive annotations.+4. Regenerate MCP code when the OpenAPI operation or tool definition changes.5. Check required API scopes. Dashboard reads, writes, and query execution use different scopes.6. Keep one-off filter and variable overrides non-persistent unless the endpoint explicitly persists them.7. Keep shared-token rules. Shared requests ignore dashboard filter and variable overrides.@@ -69,6 +74,7 @@ Check limits before you add a path that creates, loads, or runs dashboard work.- Dashboard creation uses `LimitKey.MAX_DASHBOARDS_PER_TEAM`.- Public and embedded access must not bypass quotas or product access checks.+- Use paginated loading by default. Load all rows only when the result is bounded and the feature requires it.- Bound request payloads, tile IDs, filter sizes, and pagination before they reach query execution.Read `manage-dashboard-widgets` for widget-specific limits, gates, and throttles.@@ -86,12 +92,13 @@ Dashboard changes are product events and audit events.## Backend test matrix-| Change | Test boundary |-| ------------------------ | -------------------------------------------------------------------------------- |-| Persisted model field | Migration, serializer, OpenAPI, generated types, and MCP schema |-| Create or delete | Team quota, soft delete, activity log, file-system sync, and restore |-| Move, copy, or duplicate | Source and destination access, transaction rollback, and tile uniqueness |-| Read endpoint | REST and stream behavior, shared sanitization, cache policy, and error payload |-| Query endpoint | Scope, throttle, access method, cache outcome, cancellation, and partial failure |-| Template or transfer | Old payload, source-specific reference, target team, and excluded derived fields |-| Subscription path | Permission, duplicate delivery, cache loss, and notification failure |+| Change | Test boundary |+| ------------------------ | ----------------------------------------------------------------------------------- |+| Persisted model field | Migration, serializer, OpenAPI, generated types, and MCP schema |+| Persisted list state | Applicable payload, stable pagination, list placement, permission, and MCP decision |+| Create or delete | Team quota, soft delete, activity log, file-system sync, and restore |+| Move, copy, or duplicate | Source and destination access, transaction rollback, and tile uniqueness |+| Read endpoint | REST and stream behavior, shared sanitization, cache policy, and error payload |+| Query endpoint | Scope, throttle, access method, cache outcome, cancellation, and partial failure |+| Template or transfer | Old payload, source-specific reference, target team, and excluded derived fields |+| Subscription path | Permission, duplicate delivery, cache loss, and notification failure |diff --git a/.agents/skills/managing-dashboards/references/data-models-and-collaboration.md b/.agents/skills/managing-dashboards/references/data-models-and-collaboration.mdindex 9ab9a4fa4ced..82cc85ba758f 100644--- a/.agents/skills/managing-dashboards/references/data-models-and-collaboration.md+++ b/.agents/skills/managing-dashboards/references/data-models-and-collaboration.md@@ -13,6 +13,8 @@ Define the rollout before you add the model or field.5. Define rollback behavior after new rows contain the state.6. Use `django-migrations` for model and migration changes.+When a new model references `Team` or `User`, check the hot-table foreign-key rules in `django-migrations`. A new table usually needs `db_constraint=False`.+## Relation lifecycleFor each new relation, define one behavior for every operation.diff --git a/.agents/skills/managing-dashboards/references/feature-lifecycle-and-rollout.md b/.agents/skills/managing-dashboards/references/feature-lifecycle-and-rollout.mdindex 4b71b4011cbc..5a7cb7bb32ea 100644--- a/.agents/skills/managing-dashboards/references/feature-lifecycle-and-rollout.md+++ b/.agents/skills/managing-dashboards/references/feature-lifecycle-and-rollout.md@@ -16,6 +16,8 @@ For a new dashboard feature, record these decisions before you select implementaDo not use a feature flag as a substitute for a permission check.+For persisted list state, store only the state the list can apply. Do not store transient navigation or popover state.+## Lifecycle matrixFor persisted feature state, mark each operation as `preserve`, `copy`, `reset`, `omit`, or `not applicable`.@@ -48,6 +50,8 @@ If the feature needs a gate, define:Check both the backend and frontend gate. The backend must reject a mutation that the frontend hides.+If the rollout is organization-scoped, evaluate the flag without a user identity. Do not let user-specific targeting split the organization.+## Acceptance criteria and test layersWrite acceptance criteria before you write tests.diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 4f7ba4039a14..aa32471c088b 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -119,6 +119,7 @@ rules:|CustomPropertyValue|DAG|Dashboard+ |DashboardSavedView|DashboardTemplate|DashboardWidget|DataColorTheme@@ -501,6 +502,7 @@ rules:|CustomPropertyValue|DAG|Dashboard+ |DashboardSavedView|DashboardTemplate|DashboardWidget|DataColorThemediff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 76556d0c5682..c011c3c9f461 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5240,6 +5240,30 @@ snapshots:hash: v1.k794b7964.e0388f165831a8b73632873a43ccc0668057db62a62e84c8bd19ad28d14bb011.c66ZeT4g4B2NMURw6V91iBT-AUnw7Tf6EtiY5Vr_-cYproducts-dashboards-dashboard-widgets-widgetcard--locked--light:hash: v1.k794b7964.5b137c02f2365806484425bc25fe4c896fc99edbac07caff03503ed3222da251._dt53kAV0UsgvHveL2zwjSHjc2D-p2LO9mZunqv7f5c+ 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-mbWDhLz5XFrzl4nvApt0products-dashboards-templates-dashboard-template-copy--default--dark:hash: v1.k794b7964.e441fc2d991020695739b9173c39b836a71364c4f3404dcf65f174a109bc919f.xvms_5gbih7s0W9qBwflXMTvNGiKVncitN72D6PQvv4products-dashboards-templates-dashboard-template-copy--default--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex c53cf39be833..47eaee47f03e 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -298,6 +298,7 @@ export const FEATURE_FLAGS = {DASHBOARD_CUSTOMIZATION: 'dashboard-customization', // owner: @MattPua #team-analytics-platformDASHBOARD_EXPORT_NUDGE: 'dashboard-export-nudge', // owner: #team-analytics-platform multivariate=control,test, nudges people who just exported a dashboard toward a recurring subscriptionDASHBOARD_LAYOUT_DISCARD_PROMPT: 'dashboard-layout-discard-prompt', // owner: @cory.s #team-analytics-platform+ DASHBOARD_SAVED_VIEWS: 'dashboard-saved-views', // owner: #team-analytics-platform, target organizations for saved dashboard-list viewsDASHBOARD_TEMPLATE_CHOOSER_EXPERIMENT: 'dashboard-template-chooser-experiment', // owner: @mattp #team-analytics-platform multivariate=control,simple,newDASHBOARD_WIDGETS: 'dashboard-widgets', // owner: @mattp #team-analytics-platformDATA_MODELING_BACKEND_V2: 'data-modeling-backend-v2', // owner: #team-data-modelingdiff --git a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsxindex cbd939d579e5..9a6df7d18ba4 100644--- a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx+++ b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx@@ -16,6 +16,7 @@ import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'import { NewDashboardModal } from 'scenes/dashboard/NewDashboardModal'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'+import { teamLogic } from 'scenes/teamLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'@@ -24,6 +25,8 @@ 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 { dashboardSavedViewsLogic } from 'products/dashboards/frontend/saved-views/dashboardSavedViewsLogic'import { DashboardsTableContainer } from './DashboardsTable'@@ -39,14 +42,15 @@ export function Dashboards(): JSX.Element {const { setCurrentTab } = useActions(dashboardsLogic)const { dashboards, currentTab, isFiltering } = useValues(dashboardsLogic)const { showNewDashboardModal } = useActions(newDashboardLogic)-+ const { currentTeamId } = useValues(teamLogic)+ const { dashboardSavedViewsEnabled } = useValues(dashboardSavedViewsLogic({ teamId: currentTeamId }))const enabledTabs: LemonTab<DashboardsTab>[] = [{key: DashboardsTab.All,label: 'All dashboards',},{ key: DashboardsTab.Yours, label: 'My dashboards' },- { key: DashboardsTab.Pinned, label: 'Pinned' },+ ...(dashboardSavedViewsEnabled ? [] : [{ key: DashboardsTab.Pinned, label: 'Pinned' }]),{key: DashboardsTab.Templates,label: 'Templates',@@ -94,10 +98,14 @@ export function Dashboards(): JSX.Element {}/><LemonTabs+ onChange={(newKey) => {+ setCurrentTab(newKey)+ }}activeKey={currentTab}- onChange={(newKey) => setCurrentTab(newKey)}tabs={enabledTabs}sceneInset+ rightSlot={<DashboardSavedViews />}+ rightSlotClassName="!static !justify-start !bg-transparent"/><div>diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsxindex dd7b9bce74c5..3ca5a52df5a0 100644--- a/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx@@ -1,5 +1,4 @@import { useActions, useValues } from 'kea'-import { useDebouncedCallback } from 'use-debounce'import { IconChevronDown, IconFolder, IconPin, IconPinFilled, IconShare, IconX } from '@posthog/icons'import { LemonInput, Popover } from '@posthog/lemon-ui'@@ -17,11 +16,6 @@ export function DashboardsFiltersBar({ extraActions }: DashboardsFiltersBarPropsconst { setFilters, setTagSearch, setShowTagPopover, setSearch } = useActions(dashboardsLogic)const createdByIds = filters.createdBy === 'All users' ? [] : filters.createdBy-- const debouncedSetSearch = useDebouncedCallback((value: string) => {- setSearch(value)- }, 300)-const handleTagToggle = (tag: string): void => {const selected = new Set(filters.tags || [])if (selected.has(tag)) {@@ -34,15 +28,7 @@ export function DashboardsFiltersBar({ extraActions }: DashboardsFiltersBarPropsreturn (<div className="flex justify-between gap-2 flex-wrap mb-4">- <LemonInput- type="search"- placeholder="Search for dashboards"- onChange={(value) => {- setFilters({ search: value })- debouncedSetSearch(value)- }}- value={filters.search}- />+ <LemonInput type="search" placeholder="Search for dashboards" onChange={setSearch} value={filters.search} /><div className="flex items-center gap-2 flex-wrap"><div className="flex items-center gap-2 flex-wrap"><span>Filter to:</span>@@ -164,7 +150,11 @@ export function DashboardsFiltersBar({ extraActions }: DashboardsFiltersBarProps{currentTab !== DashboardsTab.Yours && (<MemberSelectMultiplePopovervalue={createdByIds}- onChange={(ids) => setFilters({ createdBy: ids.length > 0 ? ids : 'All users' })}+ onChange={(ids) =>+ setFilters({+ createdBy: ids.length > 0 ? ids : 'All users',+ })+ }/>)}{extraActions}diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.tsindex a4e58d25b059..725f72192810 100644--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts@@ -519,6 +519,19 @@ describe('dashboardsLogic', () => {})})+ it('normalizes the legacy pinned tab while preserving its filter', async () => {+ logic.unmount()+ router.actions.push(urls.dashboards(), { tab: DashboardsTab.Pinned })+ logic = dashboardsLogic({ tabId: '1' })+ logic.mount()++ await expectLogic(logic).toMatchValues({+ currentTab: DashboardsTab.All,+ filters: expect.objectContaining({ pinned: true }),+ })+ expect(router.values.searchParams['tab']).toBeUndefined()+ })+it('restores both search and tags from the URL and fetches with the restored tags', async () => {let lastRequestUrl: URL | null = nulluseMocks({diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.tsindex 9f442290a374..560520df7e74 100644--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts@@ -52,6 +52,17 @@ export const DEFAULT_FILTERS: DashboardsFilters = {folder: null,}+export function hasDashboardFilters(filters: DashboardsFilters): boolean {+ return Boolean(+ filters.search ||+ filters.pinned ||+ filters.shared ||+ (filters.createdBy !== 'All users' && filters.createdBy.length > 0) ||+ filters.tags?.length ||+ filters.folder != null+ )+}+function moveTargetFor(dashboard: DashboardBasicType | undefined): FileSystemEntry | null {if (!dashboard?.file_system_id || !dashboard.file_system_path) {return null@@ -336,15 +347,7 @@ export const dashboardsLogic = kea<dashboardsLogicType>([}),selectors({- isFiltering: [- (s) => [s.filters],- (filters: DashboardsFilters) => {- return Object.keys(filters).some((key) => {- const filterKey = key as keyof DashboardsFilters- return filters[filterKey] !== DEFAULT_FILTERS[filterKey]- })- },- ],+ isFiltering: [(s) => [s.filters], (filters: DashboardsFilters) => hasDashboardFilters(filters)],filteredTags: [(s) => [s.tags, s.tagSearch],(tags: string[], search: string) => {@@ -476,6 +479,10 @@ export const dashboardsLogic = kea<dashboardsLogicType>([const { createdBy, pinned, shared, tags } = values.filtersconst searchParams: Record<string, any> = { ...router.values.searchParams }+ if (searchParams['tab'] === DashboardsTab.Pinned) {+ delete searchParams['tab']+ }+if (createdBy !== DEFAULT_FILTERS.createdBy) {searchParams['created_by'] = createdBy} else {@@ -515,14 +522,15 @@ export const dashboardsLogic = kea<dashboardsLogicType>([})),urlToAction(({ actions, values }) => ({'/dashboard': (_, searchParams) => {- const tab = (searchParams['tab'] as DashboardsTab | undefined) || DashboardsTab.All+ const requestedTab = (searchParams['tab'] as DashboardsTab | undefined) || DashboardsTab.All+ const tab = requestedTab === DashboardsTab.Pinned ? DashboardsTab.All : requestedTabif (values.currentTab !== tab) {actions.setCurrentTab(tab)}- const hasFilterParams = ['created_by', 'pinned', 'shared', 'tags', 'folder', 'search'].some(- (key) => key in searchParams- )+ const hasFilterParams =+ requestedTab === DashboardsTab.Pinned ||+ ['created_by', 'pinned', 'shared', 'tags', 'folder', 'search'].some((key) => key in searchParams)if (tab === DashboardsTab.Yours && values.filters.createdBy !== DEFAULT_FILTERS.createdBy) {actions.setFilters({ createdBy: DEFAULT_FILTERS.createdBy })}@@ -558,7 +566,10 @@ export const dashboardsLogic = kea<dashboardsLogicType>([: []const nextFilters = {createdBy: createdByIds.length > 0 ? createdByIds : DEFAULT_FILTERS.createdBy,- pinned: searchParams['pinned'] === true || searchParams['pinned'] === 'true',+ pinned:+ requestedTab === DashboardsTab.Pinned ||+ searchParams['pinned'] === true ||+ searchParams['pinned'] === 'true',shared: searchParams['shared'] === true || searchParams['shared'] === 'true',tags: Array.isArray(searchParams['tags']) ? searchParams['tags'] : DEFAULT_FILTERS.tags,folder: 'folder' in searchParams ? urlSearchParamToString(searchParams['folder']) : null,diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 8df450062cbe..e07d43a8028d 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -586,6 +586,7 @@ SPECTACULAR_SETTINGS = {"QuarantineModeEnum": "products.engineering_analytics.backend.facade.contracts.QuarantineMode","CITestRunnerEnum": "products.engineering_analytics.backend.facade.contracts.CITestRunner","RestrictionLevelEnum": "products.dashboards.backend.models.dashboard.Dashboard.RestrictionLevel",+ "DashboardSavedViewScopeEnum": "products.dashboards.backend.models.dashboard_saved_view.DashboardSavedView.Scope","OrganizationMembershipLevelEnum": "posthog.models.organization.OrganizationMembership.Level","SetupTaskId": "posthog.models.team.setup_tasks.SetupTaskId","SurveyType": "products.surveys.backend.models.Survey.SurveyType",diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex 58debb86ba69..ab831e86f0f7 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -232,6 +232,7 @@ pre_delete:posthog.storage.team_llm_gateway_policy_signal_handlers._clear_cache_pre_delete:products.alerts.backend.activity_logging.cleanup_alert_hog_functionspre_delete:products.alerts.backend.activity_logging.handle_alert_subscription_deletepre_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_userpre_delete:products.managed_migrations.backend.activity_logging.handle_batch_import_deletepre_delete:products.tasks.backend.models.clear_channel_repositories_on_github_integration_deletepre_delete:products.tasks.backend.team_deletion.cancel_task_workflows_on_team_deletediff --git a/products/dashboards/backend/api/dashboard_saved_view.py b/products/dashboards/backend/api/dashboard_saved_view.pynew file mode 100644index 000000000000..b9bab96c19ed--- /dev/null+++ b/products/dashboards/backend/api/dashboard_saved_view.py@@ -0,0 +1,381 @@+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.feature_flags import dashboard_saved_views_enabled+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)+ if not dashboard_saved_views_enabled(team=team):+ return False+ 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.pynew file mode 100644index 000000000000..d617d1cf15e5--- /dev/null+++ b/products/dashboards/backend/api/test/test_dashboard_saved_views.py@@ -0,0 +1,391 @@+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.saved_views_flag = patch(+ "products.dashboards.backend.api.dashboard_saved_view.dashboard_saved_views_enabled", return_value=True+ )+ self.saved_views_flag.start()+ self.addCleanup(self.saved_views_flag.stop)+ 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++ @patch("products.dashboards.backend.api.dashboard_saved_view.dashboard_saved_views_enabled", return_value=False)+ def test_rejects_requests_when_saved_views_flag_is_disabled(self, _dashboard_saved_views_enabled) -> None:+ response = self.client.get(self.base_url)++ assert response.status_code == status.HTTP_403_FORBIDDEN++ @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/feature_flags.py b/products/dashboards/backend/feature_flags.pyindex ed087aaf87a5..6ba51b198c87 100644--- a/products/dashboards/backend/feature_flags.py+++ b/products/dashboards/backend/feature_flags.py@@ -12,6 +12,7 @@ if TYPE_CHECKING:DASHBOARD_WIDGETS_FLAG = "dashboard-widgets"DASHBOARD_CUSTOMIZATION_FLAG = "dashboard-customization"+DASHBOARD_SAVED_VIEWS_FLAG = "dashboard-saved-views"def widget_flag_enabled(flag: str, *, team: Team, user: User | None = None) -> bool:@@ -41,3 +42,7 @@ def dashboard_widgets_enabled(*, team: Team, user: User | None = None) -> bool:def dashboard_customization_enabled(*, team: Team, user: User | None = None) -> bool:return widget_flag_enabled(DASHBOARD_CUSTOMIZATION_FLAG, team=team, user=user)+++def dashboard_saved_views_enabled(*, team: Team) -> bool:+ return widget_flag_enabled(DASHBOARD_SAVED_VIEWS_FLAG, team=team)diff --git a/products/dashboards/backend/migrations/0016_dashboardsavedview.py b/products/dashboards/backend/migrations/0016_dashboardsavedview.pynew file mode 100644index 000000000000..fa4d32030b4b--- /dev/null+++ b/products/dashboards/backend/migrations/0016_dashboardsavedview.py@@ -0,0 +1,79 @@+import django.db.models.manager+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("dashboards", "0015_dashboard_customization"),+ ("posthog", "1320_remove_oauth_scope_trgm"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="DashboardSavedView",+ fields=[+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("name", models.CharField(max_length=200)),+ ("filters", models.JSONField(default=dict)),+ (+ "scope",+ models.CharField(+ choices=[("private", "Private"), ("team", "Team")],+ db_default="private",+ default="private",+ max_length=20,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "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",+ ),+ ],+ "abstract": False,+ },+ managers=[+ ("all_teams", django.db.models.manager.Manager()),+ ],+ ),+ ]diff --git a/products/dashboards/backend/migrations/max_migration.txt b/products/dashboards/backend/migrations/max_migration.txtindex 57ed3ff27f23..500b16278a7a 100644--- a/products/dashboards/backend/migrations/max_migration.txt+++ b/products/dashboards/backend/migrations/max_migration.txt@@ -1 +1 @@-0015_dashboard_customization+0016_dashboardsavedviewdiff --git a/products/dashboards/backend/models/__init__.py b/products/dashboards/backend/models/__init__.pyindex 20187ed53d46..2204c66cf39c 100644--- a/products/dashboards/backend/models/__init__.py+++ b/products/dashboards/backend/models/__init__.py@@ -1,4 +1,5 @@from .dashboard import Dashboard+from .dashboard_saved_view import DashboardSavedViewfrom .dashboard_templates import DashboardTemplatefrom .dashboard_tile import ButtonTile, DashboardTile, Textfrom .dashboard_widget import DashboardWidget@@ -6,6 +7,7 @@ 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.pynew file mode 100644index 000000000000..9bd77f36c82a--- /dev/null+++ b/products/dashboards/backend/models/dashboard_saved_view.py@@ -0,0 +1,55 @@+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.pyindex 6a95a39e604a..ee51e05f27fe 100644--- a/products/dashboards/backend/routes.py+++ b/products/dashboards/backend/routes.py@@ -2,7 +2,7 @@ from posthog.api import sharingfrom posthog.api.routing import RouterRegistryfrom posthog.settings import EE_AVAILABLE-from products.dashboards.backend.api import dashboard, dashboard_templates+from products.dashboards.backend.api import dashboard, dashboard_saved_view, dashboard_templatesdef register_routes(routers: RouterRegistry) -> None:@@ -16,6 +16,12 @@ 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.tsindex 5ead5de6f459..f56ce2f205ae 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -7,6 +7,105 @@* 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@@ -10202,6 +10301,33 @@ 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.tsindex 228e0445a7ad..7674bca36749 100644--- a/products/dashboards/frontend/generated/api.ts+++ b/products/dashboards/frontend/generated/api.ts@@ -18,6 +18,9 @@ import type {CreateTextTileRequestApi,DashboardApi,DashboardCollaboratorApi,+ DashboardSavedViewApi,+ DashboardSavedViewWriteApi,+ DashboardSavedViewsListParams,DashboardSubscribeNudgeResponseApi,DashboardTemplateApi,DashboardTemplatesListParams,@@ -50,8 +53,10 @@ import type {DeleteTileRequestApi,MoveTileRequestApi,PaginatedDashboardBasicListApi,+ PaginatedDashboardSavedViewListApi,PaginatedDashboardTemplateListApi,PaginatedDataColorThemeListApi,+ PatchedDashboardSavedViewApi,PatchedDashboardTemplateApi,PatchedDataColorThemeApi,PatchedMoveTileRequestApi,@@ -82,6 +87,101 @@ 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.tsindex 2a3bd8c2e7ad..8326fdafb8f4 100644--- a/products/dashboards/frontend/generated/api.zod.ts+++ b/products/dashboards/frontend/generated/api.zod.ts@@ -9,6 +9,146 @@*/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 = 400export const dashboardTemplatesCreateBodyDashboardDescriptionMax = 400diff --git a/products/dashboards/frontend/saved-views/DashboardSavedViews.tsx b/products/dashboards/frontend/saved-views/DashboardSavedViews.tsxnew file mode 100644index 000000000000..29fdbca3a16a--- /dev/null+++ b/products/dashboards/frontend/saved-views/DashboardSavedViews.tsx@@ -0,0 +1,424 @@+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 {+ dashboardSavedViewsEnabled,+ 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 (!dashboardSavedViewsEnabled || 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.tsxnew file mode 100644index 000000000000..af37e1f3387a--- /dev/null+++ b/products/dashboards/frontend/saved-views/ManageDashboardSavedViews.stories.tsx@@ -0,0 +1,134 @@+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.tsxnew file mode 100644index 000000000000..972e69586f53--- /dev/null+++ b/products/dashboards/frontend/saved-views/ManageDashboardSavedViews.tsx@@ -0,0 +1,270 @@+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.tsxnew file mode 100644index 000000000000..b0789eb442be--- /dev/null+++ b/products/dashboards/frontend/saved-views/SavedDashboardViewsPicker.stories.tsx@@ -0,0 +1,168 @@+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.tsxnew file mode 100644index 000000000000..a2eb860cbee3--- /dev/null+++ b/products/dashboards/frontend/saved-views/SavedDashboardViewsPicker.tsx@@ -0,0 +1,261 @@+import { useState } from 'react'++import { IconCheck, IconChevronDown, IconPeople, IconPlus, IconUser } from '@posthog/icons'+import { LemonButton, LemonSkeleton, 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>+ {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.tsnew file mode 100644index 000000000000..bb84d63311eb--- /dev/null+++ b/products/dashboards/frontend/saved-views/dashboardSavedViewsLogic.test.ts@@ -0,0 +1,183 @@+import { expectLogic } from 'kea-test-utils'++import { ApiError } from 'lib/api-error'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+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()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DASHBOARD_SAVED_VIEWS]: true })+ 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('does not load saved views when the feature flag is disabled', async () => {+ featureFlagLogic.actions.setFeatureFlags([], {})+ const logic = dashboardSavedViewsLogic({ teamId: 1 })+ logic.mount()++ await expectLogic(logic).toMatchValues({ dashboardSavedViewsEnabled: false, savedViewsLoading: false })+ expect(dashboardSavedViewsList).not.toHaveBeenCalled()++ logic.unmount()+ })++ it('loads saved views when the feature flag becomes enabled', async () => {+ featureFlagLogic.actions.setFeatureFlags([], {})+ dashboardSavedViewsList.mockImplementation(async () => page([], null))+ const logic = dashboardSavedViewsLogic({ teamId: 1 })+ logic.mount()++ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DASHBOARD_SAVED_VIEWS]: true })++ await expectLogic(logic).toFinishAllListeners().toMatchValues({ dashboardSavedViewsEnabled: true })+ expect(dashboardSavedViewsList).toHaveBeenCalledTimes(2)++ logic.unmount()+ })++ it('keeps pinned dashboards visible when saved views replace the Pinned tab', async () => {+ featureFlagLogic.actions.setFeatureFlags([], {})+ dashboardSavedViewsList.mockImplementation(async () => page([], null))+ const logic = dashboardSavedViewsLogic({ teamId: 1 })+ logic.mount()+ dashboardsLogic.actions.setCurrentTab(DashboardsTab.Pinned)++ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.DASHBOARD_SAVED_VIEWS]: true })++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.currentTab).toBe(DashboardsTab.All)+ expect(logic.values.filters.pinned).toBe(true)++ logic.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({+ dashboardSavedViewsEnabled: true,+ 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.tsnew file mode 100644index 000000000000..8deab7055a19--- /dev/null+++ b/products/dashboards/frontend/saved-views/dashboardSavedViewsLogic.ts@@ -0,0 +1,342 @@+import { deepEqual as isEqual } from 'fast-equals'+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { ApiError } from 'lib/api-error'+import { FEATURE_FLAGS } from 'lib/constants'+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+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+ featureFlags: FeatureFlagsSet // featureFlagLogic+ activeSavedViewId: string | null+ dashboardSavedViewsEnabled: boolean+ loadMoreSavedViewsLoading: boolean+ savedViews: DashboardListSavedView[]+ savedViewsAvailable: boolean+ 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+ setFeatureFlags: (+ flags: string[],+ variants: Record<string, boolean | string>+ ) => {+ flags: string[]+ variants: Record<string, boolean | string>+ } // featureFlagLogic+ 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'+ __keaTypeGenInternalSelectorTypes: {+ dashboardSavedViewsEnabled: (featureFlags: FeatureFlagsSet, savedViewsAvailable: boolean) => boolean+ }+}++export type dashboardSavedViewsLogicType = MakeLogicType<+ dashboardSavedViewsLogicValues,+ dashboardSavedViewsLogicActions,+ DashboardSavedViewsLogicProps,+ dashboardSavedViewsLogicMeta+>++const emptySavedViewCursors: DashboardSavedViewCursors = { private: null, team: null }++function isSavedViewsUnavailableError(error: unknown): boolean {+ return error instanceof ApiError && (error.status === 403 || error.status === 404)+}++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: [featureFlagLogic, ['featureFlags'], dashboardsLogic, ['currentTab', 'filters']],+ actions: [featureFlagLogic, ['setFeatureFlags'], 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+ },+ },+ ],+ savedViewsAvailable: [+ true,+ {+ loadSavedViewsSuccess: () => true,+ loadSavedViewsFailure: (_, { errorObject }) => !isSavedViewsUnavailableError(errorObject),+ },+ ],+ 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: (_, { errorObject }) => !isSavedViewsUnavailableError(errorObject),+ 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),+ },+ ],+ })),+ selectors(({ props }) => ({+ dashboardSavedViewsEnabled: [+ (selectors) => [selectors.featureFlags, selectors.savedViewsAvailable],+ (featureFlags: FeatureFlagsSet, savedViewsAvailable: boolean): boolean =>+ props.teamId != null && !!featureFlags[FEATURE_FLAGS.DASHBOARD_SAVED_VIEWS] && savedViewsAvailable,+ ],+ })),+ 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)+ }+ },+ setFeatureFlags: () => {+ if (values.dashboardSavedViewsEnabled && !values.savedViewsLoading) {+ if (values.currentTab === DashboardsTab.Pinned) {+ actions.setCurrentTab(DashboardsTab.All)+ actions.setFilters({ pinned: true })+ }+ actions.loadSavedViews()+ }+ },+ 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) {+ if (!isSavedViewsUnavailableError(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) {+ if (!isSavedViewsUnavailableError(error)) {+ posthog.captureException(error)+ }+ actions.loadMoreSavedViewsFailure(+ error instanceof Error ? error.message : 'Could not load more saved views',+ error+ )+ }+ },+ })),+ afterMount(({ actions, values }) => {+ if (values.dashboardSavedViewsEnabled) {+ actions.loadSavedViews()+ }+ }),+])diff --git a/products/dashboards/mcp/tools.yaml b/products/dashboards/mcp/tools.yamlindex b5e30ea667cf..2d4fd7192037 100644--- a/products/dashboards/mcp/tools.yaml+++ b/products/dashboards/mcp/tools.yaml@@ -247,6 +247,21 @@ tools:Reorder tiles on a dashboard by providing an array of tile IDs in the desired display order. First, usedashboard-get to see current tile IDs. By default existing tile widths and heights are preserved; see thelayout parameter to force a 2-column or full-width grid instead.+ 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: falsedashboard-templates-copy-between-projects-create:operation: dashboard_templates_copy_between_projects_createenabled: falsediff --git a/pyproject.toml b/pyproject.tomlindex 8aa62bbb61e9..43de9d5c9d22 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -728,6 +728,7 @@ 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.tsindex 5312a7b5358e..4a787e0146c4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -20902,6 +20902,74 @@ 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;@@ -53854,6 +53922,14 @@ export namespace Schemas {results: DashboardBasic[];}+ export interface PaginatedDashboardSavedViewList {+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: DashboardSavedView[];+ }+export interface PaginatedDashboardTemplateList {count: number;/** @nullable */@@ -60679,6 +60755,29 @@ 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;/**@@ -91601,6 +91700,33 @@ 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).