Skip to content

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

feat(dashboards): turn view dashboard templates into manage templates (#113703)

Thomas Obermüller4219fc364b8f
diff --git a/frontend/bin/build-app-url-manifest.mjs b/frontend/bin/build-app-url-manifest.mjs
index 55f4f8612df9..081714dd188c 100644
--- a/frontend/bin/build-app-url-manifest.mjs
+++ b/frontend/bin/build-app-url-manifest.mjs
@@ -57,10 +57,12 @@ const isProjectScoped = (template) =>
// `urls` helpers that build prefixes/origins rather than linkable destinations.
const EXCLUDED_HELPERS = new Set(['absolute', 'default', 'project', 'currentProject', 'newTab'])
-// Builders whose required arguments all live in the query string, which the probe drops. Most
-// base-only entries are still fine (`/surveys` without its `tab` is a real page), but these resolve
-// to a scene that renders its missing-parameter error, so an entry would be a confident dead link.
-const EXCLUDED_BUILDERS = new Set(['tracingOperation'])
+// Builders whose destination lives in the query string, which the probe drops. Most base-only
+// entries are still fine (`/surveys` without its `tab` is a real page), but these resolve to a page
+// that does not show what the builder names, so an entry would be a confident wrong link:
+// `tracingOperation` renders its missing-parameter error, and `dashboardTemplates` opens the
+// dashboard list without its templates modal.
+const EXCLUDED_BUILDERS = new Set(['tracingOperation', 'dashboardTemplates'])
// Flag-gated surfaces for PostHog staff only: a link an agent hands a customer would land on a scene that refuses them.
const INTERNAL_BUILDERS = new Set(['decisionPlayground', 'library', 'todayReport'])
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 476f423ee4b1..c00e51bc30d6 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6746,10 +6746,18 @@ snapshots:
hash: v1.k794b7964.afaa4c654f2d95f18590c9126b7b17aac88a822dc7bab5094d76d0661cca1eb9.jqTV_gwOgEJZ4kHk1nStIOW2uJSHE_tpv4oYTSCtLeA
products-dashboards-templates-dashboard-template-item--all-versions--light:
hash: v1.k794b7964.58a4bbcdd839c5e177c8bccbf79bcdb62f614dba597d5034337683b0a84fd2aa.SYAyuyJdGZe1cb2h88RaMalIuEFo2g1dkuJNADOrbbA
+ products-dashboards-templates-dashboard-templates-table--customer--dark:
+ hash: v1.k794b7964.ec756adbdedeaef8aad8a5548ddb534136265d286264f1d0c7b1ade5c8a2575b.dYUlmxU-aksrtKjE9e8RRiqI9gheOWZhWmcX5HKbUOs
+ products-dashboards-templates-dashboard-templates-table--customer--light:
+ hash: v1.k794b7964.759287925c125ea55c2fc75fd57be12bacc1a36e32876957066ed4514b1d0e93.uInp_-_5jqS5NsA54x7-N0r9xVrbqrZh7f3wHpiCO6w
+ products-dashboards-templates-dashboard-templates-table--customer-with-no-templates--dark:
+ hash: v1.k794b7964.c2a77b438816ff3502bd1760e702290b1d27af3666ad3a6fcbdbf02822993c7f.bXyjwFcTD5N6oL37D9RjPYhGm925oWyw-EUTn-PdlhE
+ products-dashboards-templates-dashboard-templates-table--customer-with-no-templates--light:
+ hash: v1.k794b7964.78213b7d708fafb29b386f7146fa537b00f66f3cb0efb78ce89a5405f7d9de59.3fGGK5ZnuIGzDWyf2aPMoCfzvxw3SwV1lNZhYloaOb4
products-dashboards-templates-dashboard-templates-table--default--dark:
- hash: v1.k794b7964.c3299d127a3141feb0668e1d37332e0ece55e90dbee0c7e1db562c23855db31b.dxn6lN-QvqzT6rjjGe6iMouM36QAUVeAc0sC-dFdNxk
+ hash: v1.k794b7964.0fdd80c846ff58c60fb39f781571a19f4fd28082dc3bb64310d288a32841e74f.0hEZP1rr80U3xaOxDxZETVrQ2WwqSQO-GCdIUkryPv8
products-dashboards-templates-dashboard-templates-table--default--light:
- hash: v1.k794b7964.7b7b2b8d679f0d373f4433b79e4f9858359471b7ad3ff3b69942a3906321534f.PsGKdz-A5Qe5DV67w49rfJqSyjeNhMt7g-xc9BszWvQ
+ hash: v1.k794b7964.1fb821a9ed0da632cf256e3bd3e819705a09de5b83ff2311cc6e2149b836179c.BEfVLd8JtTYg2ysTnNGhJcxmAasbZ4tXa4haDIscRRo
products-dashboards-templates-dashboardtemplatemodal--create--dark:
hash: v1.k794b7964.9a606fa34acff2efb269d60b9bbe3106c3e2031c5fcd2ac871f13c7f3e131a16.ryQ-EeL6jW95KP9CnQqQV-nRlMq1x6uZ_b2obz3v70w
products-dashboards-templates-dashboardtemplatemodal--create--light:
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index c69dccc823d5..01e58567bec3 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1388,6 +1388,7 @@ export const productUrls = {
warehouseProperties: (tab?: WarehousePropertiesSceneTab): string =>
`/data-management/warehouse-properties${tab ? `/${tab}` : ''}`,
dashboards: (): string => '/dashboard',
+ dashboardTemplates: (): string => combineUrl('/dashboard', { templates: '1' }).url,
dashboard: (id: string | number, highlightInsightId?: string): string =>
combineUrl(`/dashboard/${id}`, highlightInsightId ? { highlightInsightId } : {}).url,
dashboardTile: (id: string | number, tileId: string | number): string => `${urls.dashboard(id)}/tiles/${tileId}`,
diff --git a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
index c4e971a1b3bf..f6860836b4df 100644
--- a/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/Dashboards.tsx
@@ -33,6 +33,7 @@ import { NewCrossProjectDashboardButton } from 'products/cross_project_dashboard
import { dashboardsEmptyState } from 'products/dashboards/frontend/emptyState/dashboardsEmptyState'
import { DashboardsTableContainer } from './DashboardsTable'
+import { NewDashboardMenu } from './NewDashboardMenu'
export const scene: SceneExport = {
component: Dashboards,
@@ -66,7 +67,7 @@ export function Dashboards(): JSX.Element {
<DuplicateDashboardModal />
<DeleteDashboardModal />
<LemonModal
- title="Dashboard templates"
+ title="Manage templates"
isOpen={templatesModalOpen}
onClose={() =>
router.actions.push(urls.dashboards(), {
@@ -111,11 +112,12 @@ export function Dashboards(): JSX.Element {
type="primary"
sideAction={{
icon: <IconChevronDown />,
- tooltip: 'View dashboard templates',
- 'aria-label': 'View dashboard templates',
- 'data-attr': 'view-dashboard-templates',
- onClick: () =>
- router.actions.push(urls.dashboards(), { ...searchParams, templates: '1' }),
+ 'aria-label': 'More dashboard options',
+ 'data-attr': 'new-dashboard-dropdown',
+ dropdown: {
+ placement: 'bottom-end',
+ overlay: <NewDashboardMenu />,
+ },
}}
>
New dashboard
diff --git a/frontend/src/scenes/dashboard/dashboards/NewDashboardMenu.tsx b/frontend/src/scenes/dashboard/dashboards/NewDashboardMenu.tsx
new file mode 100644
index 000000000000..10164a79ffc4
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboards/NewDashboardMenu.tsx
@@ -0,0 +1,42 @@
+import { useActions, useValues } from 'kea'
+import { combineUrl, router } from 'kea-router'
+
+import { IconPencil, IconPlusSmall } from '@posthog/icons'
+import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
+
+import { newDashboardLogic } from 'scenes/dashboard/newDashboardLogic'
+import { urls } from 'scenes/urls'
+
+export function NewDashboardMenu(): JSX.Element {
+ const { showNewDashboardModal } = useActions(newDashboardLogic)
+ const { searchParams } = useValues(router)
+
+ return (
+ <>
+ <LemonButton
+ icon={<IconPlusSmall />}
+ onClick={showNewDashboardModal}
+ data-attr="new-dashboard-menu-item"
+ fullWidth
+ >
+ <div className="flex flex-col text-sm py-1">
+ <strong>New dashboard</strong>
+ <span className="text-xs font-sans font-normal">Start blank or from a template</span>
+ </div>
+ </LemonButton>
+ <LemonDivider className="my-1" />
+ <LemonButton
+ icon={<IconPencil />}
+ to={combineUrl(urls.dashboardTemplates(), searchParams).url}
+ // Pinned analytics value: insights built on clicks that open the templates list match on it.
+ data-attr="view-dashboard-templates"
+ fullWidth
+ >
+ <div className="flex flex-col text-sm py-1">
+ <strong>Manage templates</strong>
+ <span className="text-xs font-sans font-normal">Edit, share or delete your templates</span>
+ </div>
+ </LemonButton>
+ </>
+ )
+}
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateCopyScene.tsx b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateCopyScene.tsx
index 132107fbc01f..08ea1016ce0b 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateCopyScene.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateCopyScene.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
+import { router } from 'kea-router'
import { LemonBanner, LemonButton, LemonSelect, LemonSkeleton, Link } from '@posthog/lemon-ui'
@@ -53,7 +53,7 @@ export function DashboardTemplateCopyScene(props: DashboardTemplateCopyLogicProp
? `Copy "${sourceTemplate.template_name}" to another project`
: 'Copy template to another project'
- const templatesListUrl = combineUrl(urls.dashboards(), { templates: '1' }).url
+ const templatesListUrl = urls.dashboardTemplates()
const loadFailed = sourceTemplateLoadFailed
const hasDestinationProjects = teamOptions.length > 0
const showNoDestinationsEmptyState = !sourceTemplateLoading && !loadFailed && !hasDestinationProjects
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesEmptyState.tsx b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesEmptyState.tsx
new file mode 100644
index 000000000000..14365501bff9
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesEmptyState.tsx
@@ -0,0 +1,65 @@
+import { router } from 'kea-router'
+
+import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'
+import { urls } from 'scenes/urls'
+
+export interface DashboardTemplatesEmptyStateProps {
+ isStaff: boolean
+ searchText: string | null
+ hasActiveFilters: boolean
+ loadFailed: boolean
+ onClearFilters: () => void
+ onRetry: () => void
+}
+
+/** Drops `templates` so the manage modal closes, and `templateFilter` so its search does not filter the gallery. */
+function openNewDashboardGallery(): void {
+ const { templates: _templates, templateFilter: _templateFilter, ...searchParams } = router.values.searchParams
+ router.actions.push(urls.dashboards(), searchParams, { newDashboard: 'modal' })
+}
+
+export function DashboardTemplatesEmptyState({
+ isStaff,
+ searchText,
+ hasActiveFilters,
+ loadFailed,
+ onClearFilters,
+ onRetry,
+}: DashboardTemplatesEmptyStateProps): JSX.Element {
+ if (loadFailed) {
+ return (
+ <EmptyMessage
+ title="Couldn't load templates"
+ description="The request failed. Try again, and contact support if it keeps happening."
+ buttonText="Try again"
+ buttonOnClick={onRetry}
+ buttonDataAttr="dashboard-templates-empty-retry"
+ />
+ )
+ }
+ if (!hasActiveFilters) {
+ return (
+ <EmptyMessage
+ title="No templates yet"
+ description='Open a dashboard and choose "Save as dashboard template" to add one here.'
+ buttonText="Browse PostHog templates"
+ buttonOnClick={openNewDashboardGallery}
+ buttonDataAttr="dashboard-templates-empty-browse-official"
+ />
+ )
+ }
+ return (
+ <EmptyMessage
+ title={searchText ? `No templates match "${searchText}"` : 'No templates match this filter'}
+ description={
+ // A customer's search can't match PostHog's templates here, so point them to where those live.
+ searchText && !isStaff
+ ? "PostHog's templates are under New dashboard."
+ : 'Clear the filters to see every template.'
+ }
+ buttonText="Clear filters"
+ buttonOnClick={onClearFilters}
+ buttonDataAttr="dashboard-templates-empty-clear-filters"
+ />
+ )
+}
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.test.tsx b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.test.tsx
index 6a73dd82907f..4c80888f75af 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.test.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.test.tsx
@@ -3,7 +3,6 @@ import '@testing-library/jest-dom'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { useActions, useValues } from 'kea'
-import { userHasAccess } from 'lib/utils/accessControlUtils'
import { getAppContext } from 'lib/utils/getAppContext'
import { userLogic } from 'scenes/userLogic'
@@ -17,21 +16,24 @@ jest.mock('kea', () => ({
useActions: jest.fn(),
}))
-// Render every column's cell for each row so the row-action menu (last column) is exercised.
+// Render every column's cell for each row so the row-action menu (last column) is exercised, and the empty state
+// when there are no rows.
jest.mock('lib/lemon-ui/LemonTable', () => ({
- LemonTable: ({ dataSource, columns }: any) => (
+ LemonTable: ({ dataSource, columns, emptyState }: any) => (
<div data-attr="mock-lemon-table">
- {dataSource.map((row: any, rowIndex: number) => (
- <div key={rowIndex}>
- {columns.map((col: any, colIndex: number) => (
- <div key={colIndex}>
- {col.render
- ? col.render(col.dataIndex ? row[col.dataIndex] : undefined, row, rowIndex)
- : null}
- </div>
- ))}
- </div>
- ))}
+ {dataSource.length === 0
+ ? emptyState
+ : dataSource.map((row: any, rowIndex: number) => (
+ <div key={rowIndex}>
+ {columns.map((col: any, colIndex: number) => (
+ <div key={colIndex}>
+ {col.render
+ ? col.render(col.dataIndex ? row[col.dataIndex] : undefined, row, rowIndex)
+ : null}
+ </div>
+ ))}
+ </div>
+ ))}
</div>
),
}))
@@ -42,7 +44,8 @@ jest.mock('lib/lemon-ui/LemonButton/More', () => ({
}))
// The table calls `dashboardTemplatesLogic({...})` at module load; return a stable sentinel so that import works.
-// `useValues` keys only on `userLogic` below — every other logic falls through to the table-values branch.
+// `useValues` keys only on `userLogic` below; every other logic falls through to the table values.
+// Which templates a viewer can manage is decided by the logic's selectors and tested in dashboardTemplatesLogic.test.ts.
jest.mock('scenes/dashboard/dashboards/templates/dashboardTemplatesLogic', () => ({
dashboardTemplatesLogic: jest.fn(() => ({ __mock: 'templatesTableLogic' })),
}))
@@ -51,16 +54,16 @@ jest.mock('lib/utils/getAppContext', () => ({
getAppContext: jest.fn(() => ({})),
}))
-jest.mock('lib/utils/accessControlUtils', () => ({
- userHasAccess: jest.fn(() => true),
-}))
-
const mockedUseValues = useValues as jest.Mock
const mockedUseActions = useActions as jest.Mock
const CURRENT_TEAM_ID = 1
+const OTHER_TEAM = { id: 2, name: 'Marketing site' }
-function makeTemplate(scope: DashboardTemplateScope): DashboardTemplateType {
+function makeTemplate(
+ scope: DashboardTemplateScope,
+ overrides: Partial<DashboardTemplateType> = {}
+): DashboardTemplateType {
// Only id/template_name/tiles are required on DashboardTemplateType; the rest are optional, so no cast is needed.
return {
id: 'template-123',
@@ -72,21 +75,34 @@ function makeTemplate(scope: DashboardTemplateScope): DashboardTemplateType {
team_id: CURRENT_TEAM_ID,
created_at: '2024-01-01T00:00:00Z',
created_by: null,
+ ...overrides,
}
}
function mountTable({
isStaff,
- scope,
+ templates,
+ searchText = null,
+ loadFailed = false,
+ canManage = true,
+ canEditTemplates = true,
+ managedInAnotherProject = false,
}: {
isStaff: boolean
- scope: DashboardTemplateScope
+ templates: DashboardTemplateType[]
+ searchText?: string | null
+ loadFailed?: boolean
+ canManage?: boolean
+ canEditTemplates?: boolean
+ managedInAnotherProject?: boolean
}): Record<string, jest.Mock> {
- // One shared action bag for all three useActions() callers; the component reads disjoint keys from each.
+ // One shared action bag for every useActions() caller; the component reads disjoint keys from each.
const actions: Record<string, jest.Mock> = {
setTemplateFilter: jest.fn(),
setTemplateNameOrdering: jest.fn(),
setTemplatesTabVisibility: jest.fn(),
+ clearFilters: jest.fn(),
+ getAllTemplates: jest.fn(),
deleteDashboardTemplate: jest.fn(),
updateDashboardTemplate: jest.fn(),
toggleTemplateOrganizationScope: jest.fn(),
@@ -94,14 +110,28 @@ function mountTable({
}
mockedUseValues.mockImplementation((logic: unknown) => {
if (logic === userLogic) {
- return { user: { is_staff: isStaff, team: { id: CURRENT_TEAM_ID } } }
+ return {
+ user: {
+ is_staff: isStaff,
+ team: { id: CURRENT_TEAM_ID },
+ organization: { teams: [{ id: CURRENT_TEAM_ID, name: 'Default project' }, OTHER_TEAM] },
+ },
+ }
}
return {
- allTemplates: [makeTemplate(scope)],
+ allTemplates: templates,
allTemplatesLoading: false,
- templateFilter: '',
+ allTemplatesLoadFailed: loadFailed,
+ templateFilter: searchText ?? '',
+ searchText,
+ hasActiveFilters: searchText !== null,
templateNameOrdering: '',
templatesTabVisibility: 'all',
+ isStaffViewer: isStaff,
+ currentTeamId: CURRENT_TEAM_ID,
+ canEditTemplates,
+ canManageTemplate: () => canManage,
+ isManagedInAnotherProject: () => managedInAnotherProject,
}
})
mockedUseActions.mockReturnValue(actions)
@@ -109,45 +139,43 @@ function mountTable({
return actions
}
+const VIEWERS = [
+ { label: 'staff', isStaff: true },
+ { label: 'customer editor', isStaff: false },
+]
+
describe('DashboardTemplatesTable', () => {
afterEach(() => {
cleanup()
jest.clearAllMocks()
;(getAppContext as jest.Mock).mockReturnValue({})
- ;(userHasAccess as jest.Mock).mockReturnValue(true)
})
// The organization-scope toggle originally shipped in the customer menu only, so staff couldn't share a
// template org-wide. It must be present in both the staff and the customer row menus.
- it.each([
- { label: 'staff', isStaff: true },
- { label: 'customer editor', isStaff: false },
- ])('offers "Make visible to whole organization" on a team template for $label', ({ isStaff }) => {
- mountTable({ isStaff, scope: 'team' })
+ it.each(VIEWERS)('offers "Make visible to whole organization" on a team template for $label', ({ isStaff }) => {
+ mountTable({ isStaff, templates: [makeTemplate('team')] })
expect(screen.getByText('Make visible to whole organization')).toBeInTheDocument()
})
- it.each([
- { label: 'staff', isStaff: true },
- { label: 'customer editor', isStaff: false },
- ])('offers the demote action on an organization template for $label', ({ isStaff }) => {
- mountTable({ isStaff, scope: 'organization' })
+ it.each(VIEWERS)('offers the demote action on an organization template for $label', ({ isStaff }) => {
+ mountTable({ isStaff, templates: [makeTemplate('organization')] })
- expect(screen.getByText('Make visible to this team only')).toBeInTheDocument()
+ expect(screen.getByText('Make visible to this project only')).toBeInTheDocument()
})
// Global templates are not org-shareable, so the staff guard `scope === 'team' || scope === 'organization'`
- // must keep the org toggle out. The global toggle ("...this team only") still renders, proving the menu mounted.
+ // must keep the org toggle out. The global toggle ("...this project only") still renders, proving the menu mounted.
it('hides the organization toggle on a global template for staff', () => {
- mountTable({ isStaff: true, scope: 'global' })
+ mountTable({ isStaff: true, templates: [makeTemplate('global')] })
- expect(screen.getByText('Make visible to this team only')).toBeInTheDocument()
+ expect(screen.getByText('Make visible to this project only')).toBeInTheDocument()
expect(screen.queryByText('Make visible to whole organization')).not.toBeInTheDocument()
})
it('dispatches toggleTemplateOrganizationScope with the record when the toggle is clicked', () => {
- const actions = mountTable({ isStaff: true, scope: 'team' })
+ const actions = mountTable({ isStaff: true, templates: [makeTemplate('team')] })
fireEvent.click(screen.getByText('Make visible to whole organization'))
@@ -156,4 +184,102 @@ describe('DashboardTemplatesTable', () => {
expect.objectContaining({ id: 'template-123', scope: 'team' })
)
})
+
+ it.each(VIEWERS)('opens the edit modal when $label clicks a template name', ({ isStaff }) => {
+ const template = makeTemplate('team')
+ const actions = mountTable({ isStaff, templates: [template] })
+
+ fireEvent.click(screen.getByText('My template'))
+
+ expect(actions.openEdit).toHaveBeenCalledWith(template)
+ })
+
+ it.each([
+ {
+ label: 'an organization template managed in another project',
+ template: makeTemplate('organization', { team_id: OTHER_TEAM.id }),
+ managedInAnotherProject: true,
+ canEditTemplates: true,
+ lockLabel: 'Managed in Marketing site',
+ },
+ {
+ label: 'a viewer without editor access',
+ template: makeTemplate('team'),
+ managedInAnotherProject: false,
+ canEditTemplates: false,
+ lockLabel: 'You need editor access to dashboards to manage templates',
+ },
+ ])(
+ 'shows a read-only row with a lock that explains why for $label',
+ ({ template, managedInAnotherProject, canEditTemplates, lockLabel }) => {
+ mountTable({
+ isStaff: false,
+ templates: [template],
+ canManage: false,
+ canEditTemplates,
+ managedInAnotherProject,
+ })
+
+ expect(screen.getByLabelText(lockLabel)).toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-template-name-edit"]')).not.toBeInTheDocument()
+ expect(screen.queryByText('Edit')).not.toBeInTheDocument()
+ }
+ )
+
+ it.each([
+ { label: 'staff', isStaff: true, showsOfficial: true },
+ { label: 'customers', isStaff: false, showsOfficial: false },
+ ])('$label sees official templates mentioned and filterable: $showsOfficial', ({ isStaff, showsOfficial }) => {
+ mountTable({ isStaff, templates: [makeTemplate('team')] })
+ const expectedCount = showsOfficial ? 1 : 0
+
+ expect(screen.queryAllByText(/PostHog's official templates/)).toHaveLength(expectedCount)
+ expect(document.querySelectorAll('[data-attr="dashboard-templates-filter-official"]')).toHaveLength(
+ expectedCount
+ )
+ })
+
+ describe('empty states', () => {
+ it('explains how to add a template when there are none', () => {
+ mountTable({ isStaff: false, templates: [] })
+
+ expect(screen.getByText('No templates yet')).toBeInTheDocument()
+ expect(screen.getByText('Browse PostHog templates')).toBeInTheDocument()
+ })
+
+ it.each([
+ {
+ label: 'a search matches nothing',
+ searchText: 'churn',
+ loadFailed: false,
+ title: 'No templates match "churn"',
+ button: 'Clear filters',
+ action: 'clearFilters',
+ },
+ {
+ label: 'the templates failed to load',
+ searchText: null,
+ loadFailed: true,
+ title: "Couldn't load templates",
+ button: 'Try again',
+ action: 'getAllTemplates',
+ },
+ {
+ label: 'a reload failed after rows loaded',
+ templates: [makeTemplate('team')],
+ searchText: 'churn',
+ loadFailed: true,
+ title: "Couldn't load templates",
+ button: 'Try again',
+ action: 'getAllTemplates',
+ },
+ ])('offers a next step when $label', ({ templates = [], searchText, loadFailed, title, button, action }) => {
+ const actions = mountTable({ isStaff: false, templates, searchText, loadFailed })
+
+ expect(screen.getByText(title)).toBeInTheDocument()
+ fireEvent.click(screen.getByText(button))
+
+ expect(actions[action]).toHaveBeenCalledTimes(1)
+ })
+ })
})
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.tsx b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.tsx
index 99e0db3e00c3..4482c8ed9d33 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.tsx
@@ -2,8 +2,8 @@ import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { useMemo } from 'react'
-import { IconBuilding, IconChevronDown, IconGlobe, IconPeople, IconThumbsUpFilled } from '@posthog/icons'
-import { LemonButton, LemonDialog, LemonDivider, LemonInput, LemonMenu, LemonTag } from '@posthog/lemon-ui'
+import { IconBuilding, IconChevronDown, IconGlobe, IconLock, IconPeople, IconThumbsUpFilled } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonDivider, LemonInput, LemonMenu, LemonTag, Link } from '@posthog/lemon-ui'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { More } from 'lib/lemon-ui/LemonButton/More'
@@ -12,7 +12,6 @@ import type { Sorting } from 'lib/lemon-ui/LemonTable'
import { atColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { userHasAccess } from 'lib/utils/accessControlUtils'
import { getAppContext } from 'lib/utils/getAppContext'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { dashboardTemplatesLogic } from 'scenes/dashboard/dashboards/templates/dashboardTemplatesLogic'
@@ -20,9 +19,10 @@ import { dashboardTemplateEditorLogic } from 'scenes/dashboard/dashboardTemplate
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
-import { AccessControlLevel, AccessControlResourceType, DashboardTemplateType } from '~/types'
+import { DashboardTemplateType } from '~/types'
import { dashboardTemplateModalLogic } from './dashboardTemplateModalLogic'
+import { DashboardTemplatesEmptyState } from './DashboardTemplatesEmptyState'
const templatesTableLogic = dashboardTemplatesLogic({ scope: 'default', templatesTabList: true })
@@ -66,9 +66,23 @@ function countTemplateInsightTiles(tiles: DashboardTemplateType['tiles'] | undef
}
export const DashboardTemplatesTable = (): JSX.Element | null => {
- const { allTemplates, allTemplatesLoading, templateFilter, templateNameOrdering, templatesTabVisibility } =
- useValues(templatesTableLogic)
- const { setTemplateFilter, setTemplateNameOrdering, setTemplatesTabVisibility } = useActions(templatesTableLogic)
+ const {
+ allTemplates,
+ allTemplatesLoading,
+ allTemplatesLoadFailed,
+ templateFilter,
+ templateNameOrdering,
+ templatesTabVisibility,
+ isStaffViewer,
+ searchText,
+ hasActiveFilters,
+ canEditTemplates,
+ canManageTemplate,
+ isManagedInAnotherProject,
+ currentTeamId,
+ } = useValues(templatesTableLogic)
+ const { setTemplateFilter, setTemplateNameOrdering, setTemplatesTabVisibility, clearFilters, getAllTemplates } =
+ useActions(templatesTableLogic)
const tableSorting: Sorting | null = useMemo(() => {
if (!templateNameOrdering) {
@@ -94,22 +108,10 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
const { openEdit: openDashboardTemplateModalEdit } = useActions(dashboardTemplateModalLogic)
const { user } = useValues(userLogic)
- /** Django `is_staff` (not org role). Prefer loaded API user; until then use SSR/bootstrap context so row actions are not blank. */
- const isDjangoStaffForTemplateUi =
- user != null ? Boolean(user.is_staff) : Boolean(getAppContext()?.current_user?.is_staff)
- /** Team-scoped template row actions for non–Django-staff. `dashboard_template` inherits `dashboard` in RBAC (#54694). */
- const canCustomerManageTeamTemplates =
- !isDjangoStaffForTemplateUi && userHasAccess(AccessControlResourceType.Dashboard, AccessControlLevel.Editor)
-
- const currentTeamId = user?.team?.id ?? getAppContext()?.current_team?.id ?? null
const organizationTeams = user?.organization?.teams ?? getAppContext()?.current_user?.organization?.teams ?? []
- const eligibleDestinationTeamsCount = useMemo(() => {
- if (currentTeamId == null) {
- return 0
- }
- return organizationTeams.filter((t) => t.id !== currentTeamId).length
- }, [organizationTeams, currentTeamId])
+ const eligibleDestinationTeamsCount =
+ currentTeamId == null ? 0 : organizationTeams.filter((t) => t.id !== currentTeamId).length
const copyTemplateToProjectMenuSection = (
templateId: string | undefined,
@@ -171,13 +173,17 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
fullWidth
data-attr="dashboard-template-toggle-organization-visibility"
>
- {record.scope === 'organization' ? 'Make visible to this team only' : 'Make visible to whole organization'}
+ {record.scope === 'organization'
+ ? 'Make visible to this project only'
+ : 'Make visible to whole organization'}
</LemonButton>
)
const columns: LemonTableColumns<DashboardTemplateType> = [
{
key: 'featured',
+ // Only staff see official templates here, and only official templates can be featured.
+ isHidden: !isStaffViewer,
width: '2rem',
align: 'center',
className: 'align-middle',
@@ -194,19 +200,29 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
{
title: 'Name',
dataIndex: 'template_name',
- className: 'min-w-[220px]',
+ className: 'min-w-40',
sorter: true,
- render: (_, { template_name }) => {
- return <>{template_name}</>
+ render: (_, record) => {
+ if (!canManageTemplate(record)) {
+ return <span className="font-semibold">{record.template_name}</span>
+ }
+ return (
+ <Link
+ subtle
+ className="font-semibold"
+ onClick={() => openDashboardTemplateModalEdit(record)}
+ data-attr="dashboard-template-name-edit"
+ >
+ {record.template_name}
+ </Link>
+ )
},
},
{
title: 'Description',
dataIndex: 'dashboard_description',
- className: 'min-w-[400px] align-top',
- render: (_, { dashboard_description }) => (
- <div className="max-w-3xl break-words">{dashboard_description}</div>
- ),
+ className: 'min-w-60',
+ render: (_, { dashboard_description }) => <div className="break-words">{dashboard_description}</div>,
},
{
title: 'Tags',
@@ -250,7 +266,7 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
title: 'Type',
dataIndex: 'team_id',
render: (_, { scope }) =>
- scope === 'global' ? 'Official' : scope === 'organization' ? 'Organization' : 'Team',
+ scope === 'global' ? 'Official' : scope === 'organization' ? 'Organization' : 'Project',
},
{
title: 'Created by',
@@ -268,7 +284,7 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
}
const { created_by } = record
return (
- <div className="flex flex-row flex-nowrap items-center">
+ <div className="flex max-w-40 flex-row flex-nowrap items-center [&_.profile-name]:truncate [&_.profile-package]:max-w-full">
{created_by ? (
<ProfilePicture user={created_by} size="md" showName />
) : (
@@ -290,23 +306,40 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
const { id, scope } = record
const builtInOfficial = isBuiltInOfficialTemplate(record)
- if (isDjangoStaffForTemplateUi) {
+ if (!canManageTemplate(record)) {
+ const lockReason = isManagedInAnotherProject(record)
+ ? `Managed in ${organizationTeams.find((t) => t.id === record.team_id)?.name ?? 'another project'}`
+ : !canEditTemplates
+ ? 'You need editor access to dashboards to manage templates'
+ : null
+ if (!lockReason) {
+ return null
+ }
+ return (
+ <Tooltip title={lockReason}>
+ <span
+ className="flex size-7 items-center justify-center text-secondary"
+ role="img"
+ aria-label={lockReason}
+ >
+ <IconLock className="size-4" />
+ </span>
+ </Tooltip>
+ )
+ }
+
+ const editButton = (
+ <LemonButton onClick={() => openDashboardTemplateModalEdit(record)} fullWidth>
+ Edit
+ </LemonButton>
+ )
+
+ if (isStaffViewer) {
return (
<More
overlay={
<>
- <LemonButton
- onClick={() => {
- if (id === undefined) {
- console.error('Dashboard template id not defined')
- return
- }
- openDashboardTemplateModalEdit(record)
- }}
- fullWidth
- >
- Edit
- </LemonButton>
+ {editButton}
<LemonButton
onClick={() => {
if (id === undefined) {
@@ -322,7 +355,7 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
}}
fullWidth
>
- Make visible to {scope === 'global' ? 'this team only' : 'everyone'}
+ Make visible to {scope === 'global' ? 'this project only' : 'everyone'}
</LemonButton>
{scope === 'team' || scope === 'organization'
@@ -345,11 +378,11 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
scope === 'global'
? builtInOfficial
? 'Built-in official templates cannot be deleted'
- : 'Cannot delete a global template until it is team-only'
+ : 'Make this template visible to this project only before deleting it'
: undefined
}
>
- Delete dashboard
+ Delete template
</LemonButton>
</>
}
@@ -357,64 +390,41 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
)
}
- // Org-scoped templates are readable org-wide but only their owning project may edit/delete/demote
- // them (see CustomerDashboardTemplateWritePermission). Team templates listed here are always owned.
- const ownedByCurrentTeam =
- scope === 'team' || (record.team_id != null && record.team_id === currentTeamId)
-
- if (
- canCustomerManageTeamTemplates &&
- (scope === 'team' || scope === 'organization') &&
- ownedByCurrentTeam
- ) {
- return (
- <More
- overlay={
- <>
- <LemonButton
- onClick={() => {
- if (id === undefined) {
- console.error('Dashboard template id not defined')
- return
- }
- openDashboardTemplateModalEdit(record)
- }}
- fullWidth
- >
- Edit
- </LemonButton>
- {organizationVisibilityToggleButton(record)}
- {scope === 'team'
- ? copyTemplateToProjectMenuSection(
- id,
- 'dashboard-template-copy-to-project-customer'
- )
- : null}
- <LemonDivider />
- <LemonButton
- onClick={() => confirmDeleteTemplate(record)}
- fullWidth
- status="danger"
- >
- Delete
- </LemonButton>
- </>
- }
- />
- )
- }
-
- return null
+ return (
+ <More
+ overlay={
+ <>
+ {editButton}
+ {organizationVisibilityToggleButton(record)}
+ {scope === 'team'
+ ? copyTemplateToProjectMenuSection(
+ id,
+ 'dashboard-template-copy-to-project-customer'
+ )
+ : null}
+ <LemonDivider />
+ <LemonButton onClick={() => confirmDeleteTemplate(record)} fullWidth status="danger">
+ Delete template
+ </LemonButton>
+ </>
+ }
+ />
+ )
},
},
]
return (
<>
+ <p className="mt-0 mb-4 text-secondary">
+ {isStaffViewer
+ ? "Templates saved for this project and shared across your organization, plus PostHog's official templates."
+ : 'Templates saved for this project and shared across your organization.'}
+ </p>
<div className="flex justify-between gap-2 flex-wrap mb-4">
<LemonInput
type="search"
- placeholder="Search dashboard templates (min. 3 characters)"
+ placeholder="Search templates"
onChange={setTemplateFilter}
value={templateFilter}
data-attr="dashboard-templates-search"
@@ -422,18 +432,22 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
<div className="flex items-center gap-2 flex-wrap">
<span>Filter to:</span>
<div className="flex items-center gap-2">
- <LemonButton
- active={templatesTabVisibility === 'official'}
- type="secondary"
- size="small"
- icon={<IconGlobe />}
- onClick={() =>
- setTemplatesTabVisibility(templatesTabVisibility === 'official' ? 'all' : 'official')
- }
- data-attr="dashboard-templates-filter-official"
- >
- Official
- </LemonButton>
+ {isStaffViewer ? (
+ <LemonButton
+ active={templatesTabVisibility === 'official'}
+ type="secondary"
+ size="small"
+ icon={<IconGlobe />}
+ onClick={() =>
+ setTemplatesTabVisibility(
+ templatesTabVisibility === 'official' ? 'all' : 'official'
+ )
+ }
+ data-attr="dashboard-templates-filter-official"
+ >
+ Official
+ </LemonButton>
+ ) : null}
<LemonButton
active={templatesTabVisibility === 'project'}
type="secondary"
@@ -442,9 +456,10 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
onClick={() =>
setTemplatesTabVisibility(templatesTabVisibility === 'project' ? 'all' : 'project')
}
+ // Pinned analytics value: it keeps the old "team" name because insights match on it.
data-attr="dashboard-templates-filter-team"
>
- Team
+ Project
</LemonButton>
<LemonButton
active={templatesTabVisibility === 'organization'}
@@ -467,7 +482,9 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
id="dashboard-templates"
data-attr="dashboards-template-table"
pagination={{ pageSize: 25 }}
- dataSource={Object.values(allTemplates)}
+ // A failed request keeps the rows of the previous load, which do not match the current filter.
+ // Hide them so that the empty state shows the load error and its retry button.
+ dataSource={allTemplatesLoadFailed ? [] : Object.values(allTemplates)}
columns={columns}
loading={allTemplatesLoading}
sorting={tableSorting}
@@ -484,7 +501,16 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
}
}}
useURLForSorting={false}
- emptyState={<>There are no dashboard templates.</>}
+ emptyState={
+ <DashboardTemplatesEmptyState
+ isStaff={isStaffViewer}
+ searchText={searchText}
+ hasActiveFilters={hasActiveFilters}
+ loadFailed={allTemplatesLoadFailed}
+ onClearFilters={clearFilters}
+ onRetry={() => getAllTemplates()}
+ />
+ }
nouns={['template', 'templates']}
/>
</>
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCopyLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCopyLogic.test.ts
index 82a4754d0131..0419516cc7a2 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCopyLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCopyLogic.test.ts
@@ -144,7 +144,7 @@ describe('dashboardTemplateCopyLogic', () => {
expect(api.dashboardTemplates.copyBetweenProjects).toHaveBeenCalledWith(2, 'src-1')
expect(getAllTemplates).toHaveBeenCalled()
expect(lemonToast.success).toHaveBeenCalled()
- expect(router.actions.push).toHaveBeenCalledWith(urls.dashboards(), { templates: '1' })
+ expect(router.actions.push).toHaveBeenCalledWith(urls.dashboardTemplates())
})
it('submitCopy shows an error toast when the API fails', async () => {
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCopyLogic.ts b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCopyLogic.ts
index d318d0f03a74..0f3b1f827223 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCopyLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateCopyLogic.ts
@@ -190,7 +190,7 @@ export const dashboardTemplateCopyLogic = kea<dashboardTemplateCopyLogicType>([
: {}
)
dashboardTemplatesLogic.findMounted({ scope: 'default', templatesTabList: true })?.actions.getAllTemplates()
- router.actions.push(urls.dashboards(), { templates: '1' })
+ router.actions.push(urls.dashboardTemplates())
},
})),
afterMount(({ actions, props, values }) => {
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateModalLogic.ts b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateModalLogic.ts
index a052616a00cd..65b2e2a5e07d 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateModalLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateModalLogic.ts
@@ -1,9 +1,11 @@
import { MakeLogicType, actions, kea, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { urls } from 'scenes/urls'
import { DashboardTemplateEditorType, DashboardTemplateType } from '~/types'
@@ -156,7 +158,13 @@ export const dashboardTemplateModalLogic = kea<dashboardTemplateModalLogicType>(
tags,
}
await api.dashboardTemplates.create(data)
- lemonToast.success('Project template saved')
+ lemonToast.success('Project template saved', {
+ button: {
+ label: 'Manage templates',
+ dataAttr: 'dashboard-template-saved-manage-templates',
+ action: () => router.actions.push(urls.dashboardTemplates()),
+ },
+ })
} else {
const id = values.editingTemplate?.id
if (id === undefined) {
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.test.ts
index d64371ec6bdd..b35123cdc941 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.test.ts
@@ -1,14 +1,25 @@
+import { MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'
+
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+import { userLogic } from 'scenes/userLogic'
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import type { DashboardTemplateListParams, DashboardTemplateType } from '~/types'
import { dashboardTemplatesLogic } from './dashboardTemplatesLogic'
+jest.mock('lib/utils/accessControlUtils', () => ({
+ ...jest.requireActual('lib/utils/accessControlUtils'),
+ userHasAccess: jest.fn(() => true),
+}))
+
describe('dashboardTemplatesLogic', () => {
let logic: ReturnType<typeof dashboardTemplatesLogic.build> | undefined
@@ -16,6 +27,9 @@ describe('dashboardTemplatesLogic', () => {
initKeaTests()
featureFlagLogic.mount()
jest.spyOn(api.dashboardTemplates, 'list').mockResolvedValue({ results: [] })
+ // `restoreAllMocks` does not reset a `jest.mock` factory's `jest.fn`, so a return value set in one test would
+ // leak into the next.
+ jest.mocked(userHasAccess).mockReturnValue(true)
logic = undefined
})
@@ -23,6 +37,7 @@ describe('dashboardTemplatesLogic', () => {
logic?.unmount()
logic = undefined
jest.restoreAllMocks()
+ resumeKeaLoadersErrors()
})
it.each([
@@ -106,6 +121,169 @@ describe('dashboardTemplatesLogic', () => {
}
)
+ it.each([
+ { filter: 'ch', expected: null },
+ { filter: 'churn', expected: 'churn' },
+ ])('searches for "$filter" only from three characters (search text: $expected)', async ({ filter, expected }) => {
+ const mounted = dashboardTemplatesLogic({ scope: 'default', templatesTabList: true })
+ logic = mounted
+ mounted.mount()
+
+ await expectLogic(mounted, () => mounted.actions.setTemplateFilter(filter)).toMatchValues({
+ searchText: expected,
+ })
+ })
+
+ // The default test user is staff, so the cases above cover the staff list, official templates included.
+ it("lists only this project's and the organization's templates for customers, without official ones", async () => {
+ userLogic.mount()
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_staff: false })
+ const teamTemplate = {
+ id: 'team-b',
+ template_name: 'B team',
+ tiles: [],
+ scope: 'team',
+ } as DashboardTemplateType
+ const organizationTemplate = {
+ id: 'org-a',
+ template_name: 'A organization',
+ tiles: [],
+ scope: 'organization',
+ } as DashboardTemplateType
+ const requestedScopes: (string | null)[] = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/dashboard_templates/': ({ request }) => {
+ const scope = new URL(request.url).searchParams.get('scope')
+ requestedScopes.push(scope)
+ const results =
+ scope === 'team' ? [teamTemplate] : scope === 'organization' ? [organizationTemplate] : []
+ return [200, { results }]
+ },
+ },
+ })
+ const mounted = dashboardTemplatesLogic({ scope: 'default', templatesTabList: true })
+ logic = mounted
+ mounted.mount()
+
+ await expectLogic(mounted, () => mounted.actions.getAllTemplates())
+ .toFinishAllListeners()
+ .toMatchValues({ allTemplates: [organizationTemplate, teamTemplate] })
+
+ expect(new Set(requestedScopes)).toEqual(new Set(['team', 'organization']))
+ })
+
+ it.each([
+ {
+ label: 'staff on an official template',
+ isStaff: true,
+ canEditDashboards: true,
+ template: { scope: 'global', team_id: null },
+ canManage: true,
+ managedInAnotherProject: false,
+ canEditTemplates: true,
+ },
+ {
+ label: 'an editor on a team template',
+ isStaff: false,
+ canEditDashboards: true,
+ template: { scope: 'team', team_id: MOCK_TEAM_ID },
+ canManage: true,
+ managedInAnotherProject: false,
+ canEditTemplates: true,
+ },
+ {
+ label: "an editor on this project's organization template",
+ isStaff: false,
+ canEditDashboards: true,
+ template: { scope: 'organization', team_id: MOCK_TEAM_ID },
+ canManage: true,
+ managedInAnotherProject: false,
+ canEditTemplates: true,
+ },
+ {
+ label: "an editor on another project's organization template",
+ isStaff: false,
+ canEditDashboards: true,
+ template: { scope: 'organization', team_id: MOCK_TEAM_ID + 1 },
+ canManage: false,
+ managedInAnotherProject: true,
+ canEditTemplates: true,
+ },
+ {
+ label: 'an editor on an organization template with no owning project',
+ isStaff: false,
+ canEditDashboards: true,
+ template: { scope: 'organization', team_id: null },
+ canManage: false,
+ managedInAnotherProject: true,
+ canEditTemplates: true,
+ },
+ {
+ label: 'a viewer without editor access on a team template',
+ isStaff: false,
+ canEditDashboards: false,
+ template: { scope: 'team', team_id: MOCK_TEAM_ID },
+ canManage: false,
+ managedInAnotherProject: false,
+ canEditTemplates: false,
+ },
+ ])(
+ '$label: can manage $canManage, managed in another project $managedInAnotherProject, can edit templates $canEditTemplates',
+ ({ isStaff, canEditDashboards, template, canManage, managedInAnotherProject, canEditTemplates }) => {
+ jest.mocked(userHasAccess).mockReturnValue(canEditDashboards)
+ userLogic.mount()
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, is_staff: isStaff })
+ const mounted = dashboardTemplatesLogic({ scope: 'default', templatesTabList: true })
+ logic = mounted
+ mounted.mount()
+ const record = {
+ id: 'template-1',
+ template_name: 'Weekly KPIs',
+ tiles: [],
+ ...template,
+ } as DashboardTemplateType
+
+ expect(mounted.values.canManageTemplate(record)).toBe(canManage)
+ expect(mounted.values.isManagedInAnotherProject(record)).toBe(managedInAnotherProject)
+ expect(mounted.values.canEditTemplates).toBe(canEditTemplates)
+ }
+ )
+
+ it('flags a failed load until a reload succeeds, so an error does not read as an empty list', async () => {
+ silenceKeaLoadersErrors()
+ const listMock = (api.dashboardTemplates.list as jest.Mock).mockRejectedValueOnce(new Error('Network error'))
+ const mounted = dashboardTemplatesLogic({ scope: 'default', templatesTabList: true })
+ logic = mounted
+ mounted.mount()
+
+ await expectLogic(mounted, () => mounted.actions.getAllTemplates())
+ .toDispatchActions(['getAllTemplatesFailure'])
+ .toMatchValues({ allTemplatesLoadFailed: true })
+
+ listMock.mockResolvedValueOnce({ results: [] })
+ await expectLogic(mounted, () => mounted.actions.getAllTemplates())
+ .toDispatchActions(['getAllTemplatesSuccess'])
+ .toMatchValues({ allTemplatesLoadFailed: false })
+ })
+
+ it('clears the search and the visibility filter, removes the search from the URL, and reloads', async () => {
+ router.actions.push('/dashboard', { templates: '1', templateFilter: 'churn' })
+ const listMock = api.dashboardTemplates.list as jest.Mock
+ const mounted = dashboardTemplatesLogic({ scope: 'default', templatesTabList: true })
+ logic = mounted
+ mounted.mount()
+ mounted.actions.setTemplatesTabVisibility('project')
+ await expectLogic(mounted).toFinishAllListeners().toMatchValues({ hasActiveFilters: true })
+
+ await expectLogic(mounted, () => mounted.actions.clearFilters())
+ .toFinishAllListeners()
+ .toMatchValues({ templateFilter: '', templatesTabVisibility: 'all', hasActiveFilters: false })
+
+ expect(router.values.searchParams).not.toHaveProperty('templateFilter')
+ expect(listMock).toHaveBeenLastCalledWith(expect.objectContaining({ scope: undefined, search: undefined }))
+ })
+
it('clears the template search when the dashboard list URL no longer includes a search (stale query no longer hides templates)', async () => {
router.actions.push('/dashboard', { templateFilter: 'needle' })
const mounted = dashboardTemplatesLogic({ scope: 'default' })
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.tsx b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.tsx
index 62b97e6820b1..d76c28601989 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.tsx
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { lazyLoaders } from 'kea-loaders'
import { router } from 'kea-router'
import { actionToUrl } from 'kea-router'
@@ -7,14 +7,23 @@ import { urlToAction } from 'kea-router'
import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+import { getAppContext } from 'lib/utils/getAppContext'
+import { teamLogic } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
import {
+ AccessControlLevel,
+ AccessControlResourceType,
DashboardTemplateListParams,
DashboardTemplateScope,
DashboardTemplateType,
TemplateAvailabilityContext,
+ UserType,
} from '~/types'
+import { dashboardTemplatesList } from 'products/dashboards/frontend/generated/api'
+
import type { FeatureFlagsSet } from '../../../../lib/logic/featureFlagLogic'
export interface DashboardTemplateProps {
@@ -38,8 +47,8 @@ export type DashboardTemplatesTabVisibility = 'all' | 'official' | 'project' | '
export type DashboardTemplateTableOrdering = '' | 'template_name' | '-template_name' | 'created_at' | '-created_at'
/**
- * Mixed template lists (project + official): project-scoped rows first, then global/official.
- * Respects active table ordering when set; otherwise featured first, then A–Z by name (matches API defaults within each bucket).
+ * Official templates go last. Inside each group, the table ordering applies, or featured first and then A–Z by name,
+ * which matches the API default. The API cannot do this for the mixed unscoped list or the merged customer list.
*/
function sortTemplatesTeamScopeBeforeOfficial(
templates: DashboardTemplateType[],
@@ -87,9 +96,19 @@ function listQueryFeaturedKeySegment(p: DashboardTemplatesLogicProps): 'featured
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardTemplatesLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentProjectId: number | string // teamLogic
+ currentTeamId: number | null // teamLogic
+ user: UserType | null // userLogic
allTemplates: DashboardTemplateType[]
+ allTemplatesLoadFailed: boolean
allTemplatesLoaded: boolean
allTemplatesLoading: boolean
+ canEditTemplates: boolean
+ canManageTemplate: (template: DashboardTemplateType) => boolean
+ hasActiveFilters: boolean
+ isManagedInAnotherProject: (template: DashboardTemplateType) => boolean
+ isStaffViewer: boolean
+ searchText: string | null
templateFilter: string
templateNameOrdering: DashboardTemplateTableOrdering
templatesTabVisibility: DashboardTemplatesTabVisibility
@@ -97,6 +116,9 @@ export interface dashboardTemplatesLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardTemplatesLogicActions {
+ clearFilters: () => {
+ value: true
+ }
getAllTemplates: () => any
getAllTemplatesFailure: (
error: string,
@@ -129,6 +151,21 @@ export interface dashboardTemplatesLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardTemplatesLogicMeta {
key: string
+ __keaTypeGenInternalSelectorTypes: {
+ isStaffViewer: (user: UserType | null) => boolean
+ searchText: (templateFilter: string) => string | null
+ hasActiveFilters: (
+ searchText: string | null,
+ templatesTabVisibility: DashboardTemplatesTabVisibility
+ ) => boolean
+ isManagedInAnotherProject: (currentTeamId: number | null) => (template: DashboardTemplateType) => boolean
+ canEditTemplates: (isStaffViewer: boolean) => boolean
+ canManageTemplate: (
+ isStaffViewer: boolean,
+ canEditTemplates: boolean,
+ isManagedInAnotherProject: (template: DashboardTemplateType) => boolean
+ ) => (template: DashboardTemplateType) => boolean
+ }
}
export type dashboardTemplatesLogicType = MakeLogicType<
@@ -146,13 +183,21 @@ export const dashboardTemplatesLogic = kea<dashboardTemplatesLogicType>([
`${p.scope ?? 'default'}-${listQueryFeaturedKeySegment(p)}${p.templatesTabList ? '-templatesTab' : ''}`
),
connect(() => ({
- values: [featureFlagLogic, ['featureFlags']],
+ values: [
+ featureFlagLogic,
+ ['featureFlags'],
+ teamLogic,
+ ['currentTeamId', 'currentProjectId'],
+ userLogic,
+ ['user'],
+ ],
})),
actions({
setTemplates: (allTemplates: DashboardTemplateType[]) => ({ allTemplates }),
setTemplateFilter: (search: string) => ({ search }),
setTemplateNameOrdering: (ordering: DashboardTemplateTableOrdering) => ({ ordering }),
setTemplatesTabVisibility: (visibility: DashboardTemplatesTabVisibility) => ({ visibility }),
+ clearFilters: true,
}),
reducers({
templateFilter: [
@@ -161,6 +206,7 @@ export const dashboardTemplatesLogic = kea<dashboardTemplatesLogicType>([
setTemplateFilter: (_, { search }) => {
return search
},
+ clearFilters: () => '',
},
],
templateNameOrdering: [
@@ -176,13 +222,68 @@ export const dashboardTemplatesLogic = kea<dashboardTemplatesLogicType>([
getAllTemplatesSuccess: () => true,
},
],
+ // A failed request keeps the loader's last value, so a failed first load would look like an empty list.
+ allTemplatesLoadFailed: [
+ false,
+ {
+ getAllTemplates: () => false,
+ getAllTemplatesSuccess: () => false,
+ getAllTemplatesFailure: () => true,
+ },
+ ],
templatesTabVisibility: [
'all' as DashboardTemplatesTabVisibility,
{
setTemplatesTabVisibility: (_, { visibility }) => visibility,
+ clearFilters: () => 'all',
},
],
}),
+ selectors({
+ /** Django `is_staff`, not the organization role. Until the user loads, read the bootstrap context so row actions are not blank. */
+ isStaffViewer: [
+ (s) => [s.user],
+ (user: UserType | null): boolean =>
+ user != null ? Boolean(user.is_staff) : Boolean(getAppContext()?.current_user?.is_staff),
+ ],
+ searchText: [
+ (s) => [s.templateFilter],
+ (templateFilter: string): string | null => (templateFilter.length >= 3 ? templateFilter : null),
+ ],
+ hasActiveFilters: [
+ (s) => [s.searchText, s.templatesTabVisibility],
+ (searchText: string | null, templatesTabVisibility: DashboardTemplatesTabVisibility): boolean =>
+ searchText !== null || templatesTabVisibility !== 'all',
+ ],
+ // Org-scoped templates are readable org-wide but only their owning project may edit/delete/demote
+ // them (see CustomerDashboardTemplateWritePermission). Team templates listed here are always owned.
+ isManagedInAnotherProject: [
+ (s) => [s.currentTeamId],
+ (currentTeamId: number | null): ((template: DashboardTemplateType) => boolean) =>
+ (template) =>
+ template.scope === 'organization' && template.team_id !== currentTeamId,
+ ],
+ canEditTemplates: [
+ (s) => [s.isStaffViewer],
+ (isStaffViewer: boolean): boolean =>
+ // `dashboard_template` inherits `dashboard` in RBAC (#54694). The access level comes from the bootstrap
+ // context, which changes only on a page load.
+ isStaffViewer || userHasAccess(AccessControlResourceType.Dashboard, AccessControlLevel.Editor),
+ ],
+ canManageTemplate: [
+ (s) => [s.isStaffViewer, s.canEditTemplates, s.isManagedInAnotherProject],
+ (
+ isStaffViewer: boolean,
+ canEditTemplates: boolean,
+ isManagedInAnotherProject: (template: DashboardTemplateType) => boolean
+ ): ((template: DashboardTemplateType) => boolean) =>
+ (template) =>
+ isStaffViewer ||
+ (canEditTemplates &&
+ (template.scope === 'team' || template.scope === 'organization') &&
+ !isManagedInAnotherProject(template)),
+ ],
+ }),
lazyLoaders(({ props, values }) => ({
allTemplates: [
[] as DashboardTemplateType[],
@@ -192,7 +293,8 @@ export const dashboardTemplatesLogic = kea<dashboardTemplatesLogicType>([
const featuredOnly = logicProps.listQuery?.is_featured === true
// Curated featured list (empty dashboards) must ignore `templateFilter` synced from the URL via
// `urlToAction` when the templates modal or another surface leaves `?templateFilter=` on /dashboard.
- const useSearch = !featuredOnly && values.templateFilter.length > 2
+ const search = featuredOnly ? null : values.searchText
+ const useSearch = search !== null
let listScope: DashboardTemplateScope | undefined
if (logicProps.scope !== 'default' && logicProps.scope !== undefined) {
@@ -213,11 +315,28 @@ export const dashboardTemplatesLogic = kea<dashboardTemplatesLogicType>([
const params: DashboardTemplateListParams = {
scope: listScope,
- search: useSearch ? values.templateFilter : undefined,
+ search: search ?? undefined,
// Search results are relevance-ranked; omit ordering (see API `dangerously_get_queryset`).
ordering: useSearch ? undefined : values.templateNameOrdering || undefined,
...logicProps.listQuery,
}
+ // Customers can't manage PostHog's templates, so their "all" list is this project's plus the
+ // organization's. The API has no scope for that pair, so request both and merge. Staff keep the
+ // unscoped list.
+ if (logicProps.templatesTabList && listScope === undefined && !values.isStaffViewer) {
+ const projectId = String(values.currentProjectId)
+ const [teamPage, organizationPage] = await Promise.all([
+ dashboardTemplatesList(projectId, { ...params, scope: 'team' }),
+ dashboardTemplatesList(projectId, { ...params, scope: 'organization' }),
+ ])
+ // A search ranks each page on the server, but the rank is not returned, so team matches come first.
+ // The generated type leaves `tiles` untyped, so cast to the shape the rest of the list uses.
+ const results = [...teamPage.results, ...organizationPage.results] as DashboardTemplateType[]
+ return useSearch
+ ? results
+ : sortTemplatesTeamScopeBeforeOfficial(results, values.templateNameOrdering)
+ }
+
const page = await api.dashboardTemplates.list(params)
if (!useSearch && listScope === undefined) {
return sortTemplatesTeamScopeBeforeOfficial(page.results, values.templateNameOrdering)
@@ -238,6 +357,9 @@ export const dashboardTemplatesLogic = kea<dashboardTemplatesLogicType>([
setTemplatesTabVisibility: () => {
actions.getAllTemplates()
},
+ clearFilters: () => {
+ actions.getAllTemplates()
+ },
})),
urlToAction(({ actions, values }) => ({
'/dashboard': (_, searchParams) => {
@@ -252,14 +374,23 @@ export const dashboardTemplatesLogic = kea<dashboardTemplatesLogicType>([
}
},
})),
- actionToUrl(({ values }) => ({
- setTemplateFilter: () => {
+ actionToUrl(({ values }) => {
+ const templateFilterToUrl = (): [
+ string,
+ Record<string, unknown>,
+ Record<string, unknown>,
+ { replace: boolean },
+ ] => {
const searchParams = { ...router.values.searchParams }
searchParams.templateFilter = values.templateFilter
if (!values.templateFilter) {
delete searchParams.templateFilter
}
return ['/dashboard', searchParams, router.values.hashParams, { replace: true }]
- },
- })),
+ }
+ return {
+ setTemplateFilter: templateFilterToUrl,
+ clearFilters: templateFilterToUrl,
+ }
+ }),
])
diff --git a/products/dashboards/frontend/components/DashboardTemplates/DashboardTemplatesTable.stories.tsx b/products/dashboards/frontend/components/DashboardTemplates/DashboardTemplatesTable.stories.tsx
index 0dce65434104..3914c33d6d14 100644
--- a/products/dashboards/frontend/components/DashboardTemplates/DashboardTemplatesTable.stories.tsx
+++ b/products/dashboards/frontend/components/DashboardTemplates/DashboardTemplatesTable.stories.tsx
@@ -21,6 +21,7 @@ import { userLogic } from 'scenes/userLogic'
import { mswDecorator } from '~/mocks/browser'
import { toPaginatedResponse } from '~/mocks/handlers'
+import type { MockSignature } from '~/mocks/utils'
import {
InsightColor,
type DashboardTemplateType,
@@ -173,12 +174,6 @@ const sampleTemplates: DashboardTemplateType[] = [
),
]
-const tableListMocks = {
- get: {
- '/api/projects/:team_id/dashboard_templates/': toPaginatedResponse(sampleTemplates),
- },
-}
-
/** Second project in the org so `eligibleDestinationTeamsCount` is non-zero and Copy appears in the row menu. */
const storySecondTeam: TeamType = {
...MOCK_DEFAULT_TEAM,
@@ -188,6 +183,43 @@ const storySecondTeam: TeamType = {
project_id: 1002,
}
+const organizationTemplates: DashboardTemplateType[] = [
+ {
+ id: 'tpl-org-own',
+ template_name: 'Release health',
+ dashboard_description: 'Organization template saved from this project.',
+ scope: 'organization',
+ team_id: MOCK_TEAM_ID,
+ created_by: MOCK_DEFAULT_BASIC_USER,
+ tags: ['releases'],
+ dashboard_filters: {},
+ variables: [],
+ tiles: [insightTile],
+ },
+ {
+ id: 'tpl-org-other-project',
+ template_name: 'Marketing funnel',
+ dashboard_description: 'Organization template shared from another project.',
+ scope: 'organization',
+ team_id: storySecondTeam.id,
+ created_by: MOCK_DEFAULT_BASIC_USER,
+ tags: [],
+ dashboard_filters: {},
+ variables: [],
+ tiles: [insightTile, insightTile],
+ },
+]
+
+const allStoryTemplates = [...sampleTemplates, ...organizationTemplates]
+
+/** Honors `?scope=` like the API, so the customer list (team + organization requests) leaves official templates out. */
+function templatesListMock(templates: DashboardTemplateType[]): MockSignature {
+ return ({ request }) => {
+ const scope = new URL(request.url).searchParams.get('scope')
+ return [200, toPaginatedResponse(scope ? templates.filter((t) => t.scope === scope) : templates)]
+ }
+}
+
const storySecondProject: ProjectType = {
id: storySecondTeam.id,
name: storySecondTeam.name,
@@ -243,15 +275,17 @@ function storyUserForViewerMode(viewerMode: ViewerMode): UserType {
}
/** MSW follows `viewerMode` (Controls → Viewer mode). Always mock `@me` so `userLogic` loadUser does not overwrite the story org with a single-team user (staff mode previously had no handler). */
-const withViewerModeMsw: Decorator = (Story, context) => {
- const viewerMode = ((context.args as { viewerMode?: ViewerMode }).viewerMode ?? 'staff') as ViewerMode
- const mocks = {
- get: {
- ...tableListMocks.get,
- '/api/users/@me/': (): [number, UserType] => [200, storyUserForViewerMode(viewerMode)],
- },
+function withViewerModeMsw(templates: DashboardTemplateType[], defaultViewerMode: ViewerMode): Decorator {
+ return (Story, context) => {
+ const viewerMode = ((context.args as { viewerMode?: ViewerMode }).viewerMode ?? defaultViewerMode) as ViewerMode
+ const mocks = {
+ get: {
+ '/api/projects/:team_id/dashboard_templates/': templatesListMock(templates),
+ '/api/users/@me/': (): [number, UserType] => [200, storyUserForViewerMode(viewerMode)],
+ },
+ }
+ return mswDecorator(mocks)(Story, context)
}
- return mswDecorator(mocks)(Story, context)
}
function DashboardTemplatesTableStory({
@@ -290,9 +324,20 @@ export const Default: Story = {
name: 'Viewer mode',
},
},
- decorators: [withViewerModeMsw],
+ decorators: [withViewerModeMsw(allStoryTemplates, 'staff')],
render: (_, { args }) => {
const viewerMode = ((args as { viewerMode?: ViewerMode }).viewerMode ?? 'staff') as ViewerMode
return <DashboardTemplatesTableStory perspective={viewerMode === 'nonStaff' ? 'nonstaff' : 'staff'} />
},
}
+
+/** Customers manage their own templates here, so official ones are left out and other projects' are read-only. */
+export const Customer: Story = {
+ decorators: [withViewerModeMsw(allStoryTemplates, 'nonStaff')],
+ render: () => <DashboardTemplatesTableStory perspective="nonstaff" />,
+}
+
+export const CustomerWithNoTemplates: Story = {
+ decorators: [withViewerModeMsw([], 'nonStaff')],
+ render: () => <DashboardTemplatesTableStory perspective="nonstaff" />,
+}
diff --git a/products/dashboards/manifest.tsx b/products/dashboards/manifest.tsx
index 96e125007df8..bc720d4c2a50 100644
--- a/products/dashboards/manifest.tsx
+++ b/products/dashboards/manifest.tsx
@@ -10,6 +10,7 @@ export const manifest: ProductManifest = {
name: 'Dashboards',
urls: {
dashboards: (): string => '/dashboard',
+ dashboardTemplates: (): string => combineUrl('/dashboard', { templates: '1' }).url,
dashboard: (id: string | number, highlightInsightId?: string): string =>
combineUrl(`/dashboard/${id}`, highlightInsightId ? { highlightInsightId } : {}).url,
dashboardTile: (id: string | number, tileId: string | number): string =>