Skip to content

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

feat(dashboards): add organization scope to dashboard templates (#64271)

Christophe Eynius Tranbergb28fa89ffde5
diff --git a/frontend/src/scenes/dashboard/dashboardTemplateEditorLogic.ts b/frontend/src/scenes/dashboard/dashboardTemplateEditorLogic.ts
index b282ff5b50be..177d3a779989 100644
--- a/frontend/src/scenes/dashboard/dashboardTemplateEditorLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboardTemplateEditorLogic.ts
@@ -2,12 +2,12 @@ import { actions, afterMount, connect, kea, listeners, path, reducers } from 'ke
import { loaders } from 'kea-loaders'
import { createElement, Fragment } from 'react'
-import { lemonToast } from '@posthog/lemon-ui'
+import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { DashboardTemplateEditorType, DashboardTemplateType, MonacoMarker } from '~/types'
+import { DashboardTemplateEditorType, DashboardTemplateType, MonacoMarker, NonPortableReferences } from '~/types'
import { dashboardTemplatesLogic } from './dashboards/templates/dashboardTemplatesLogic'
import type { dashboardTemplateEditorLogicType } from './dashboardTemplateEditorLogicType'
@@ -32,6 +32,26 @@ function refreshDashboardTemplateListsAfterMutation(): void {
?.actions.getAllTemplates()
}
+/** Human-readable phrases for the project-specific references that may not resolve when sharing a template org-wide. */
+function describeNonPortableReferences(refs: NonPortableReferences | null | undefined): string[] {
+ const warnings: string[] = []
+ if (!refs) {
+ return warnings
+ }
+ if (refs.actions > 0) {
+ warnings.push(`${refs.actions} action${refs.actions === 1 ? '' : 's'}`)
+ }
+ if (refs.cohorts > 0) {
+ warnings.push(`${refs.cohorts} cohort${refs.cohorts === 1 ? '' : 's'}`)
+ }
+ if (refs.warehouse_tables.length > 0) {
+ warnings.push(
+ `${refs.warehouse_tables.length === 1 ? 'data warehouse table' : 'data warehouse tables'} ${refs.warehouse_tables.join(', ')}`
+ )
+ }
+ return warnings
+}
+
function parseDashboardTemplateEditorPayload(raw: string | undefined): DashboardTemplateEditorType | undefined {
const trimmed = raw?.trim()
if (!trimmed) {
@@ -63,6 +83,9 @@ export const dashboardTemplateEditorLogic = kea<dashboardTemplateEditorLogicType
openDashboardTemplateEditor: true,
closeDashboardTemplateEditor: true,
updateValidationErrors: (markers: MonacoMarker[] | undefined) => ({ markers }),
+ /** Promote a team template to organization-wide, or demote it back. Confirms before either to avoid
+ * accidental changes, and warns on promote when the template embeds project-specific references. */
+ toggleTemplateOrganizationScope: (template: DashboardTemplateType) => ({ template }),
}),
reducers({
editorValue: [
@@ -281,6 +304,53 @@ export const dashboardTemplateEditorLogic = kea<dashboardTemplateEditorLogicType
actions.setEditorValue(JSON.stringify(dashboardTemplate, null, 4))
}
},
+ toggleTemplateOrganizationScope: async ({ template }) => {
+ const { id, scope } = template
+ if (id === undefined) {
+ console.error('Dashboard template id not defined')
+ return
+ }
+ if (scope === 'organization') {
+ LemonDialog.open({
+ title: 'Make this template visible to this project only?',
+ description:
+ 'It will no longer be shared with the other projects in your organization. They will lose access to it.',
+ primaryButton: {
+ children: 'Make project-only',
+ onClick: () =>
+ actions.updateDashboardTemplate({ id, dashboardTemplateUpdates: { scope: 'team' } }),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ return
+ }
+ // `non_portable_references` is only computed on single-template retrieve, so fetch before warning.
+ let refs: NonPortableReferences | null | undefined = template.non_portable_references
+ if (!refs) {
+ try {
+ refs = (await api.dashboardTemplates.get(id)).non_portable_references
+ } catch {
+ refs = undefined
+ }
+ }
+ const warnings = describeNonPortableReferences(refs)
+ if (warnings.length === 0) {
+ actions.updateDashboardTemplate({ id, dashboardTemplateUpdates: { scope: 'organization' } })
+ return
+ }
+ LemonDialog.open({
+ title: 'Share this template with your whole organization?',
+ description: `This template references items specific to this project (${warnings.join(
+ ', '
+ )}). Insights using them may show errors in other projects — events and properties work everywhere.`,
+ primaryButton: {
+ children: 'Share with organization',
+ onClick: () =>
+ actions.updateDashboardTemplate({ id, dashboardTemplateUpdates: { scope: 'organization' } }),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ },
})),
afterMount(({ actions }) => {
actions.getTemplateSchema()
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateChooser.tsx b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateChooser.tsx
index 00c43b8893c9..dea81b0226ca 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateChooser.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateChooser.tsx
@@ -64,8 +64,10 @@ export function DashboardTemplateChooser(props: DashboardTemplateProps): JSX.Ele
{teamTemplates.length > 0 ? (
<section>
<div className="mb-3">
- <h3 className="text-base font-semibold m-0">Team templates</h3>
- <p className="text-secondary text-sm m-0 mt-1">Templates saved for this project.</p>
+ <h3 className="text-base font-semibold m-0">Your templates</h3>
+ <p className="text-secondary text-sm m-0 mt-1">
+ Templates saved for this project and shared across your organization.
+ </p>
</div>
<div className={teamTemplateGridClass}>
{teamTemplates.map((template, index) => (
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateItem.tsx b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateItem.tsx
index 65d030b83062..5d4835a55504 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateItem.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplateItem.tsx
@@ -4,6 +4,7 @@ import { useId } from 'react'
import { IconBuilding, IconHeartFilled } from '@posthog/icons'
import { FallbackCoverImage } from 'lib/components/FallbackCoverImage/FallbackCoverImage'
+import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { DashboardTemplateType } from '~/types'
@@ -26,7 +27,7 @@ const featuredImageColumnClass =
export type TemplateItemSize = 'default' | 'large'
export interface DashboardTemplateItemProps {
- template: Pick<DashboardTemplateType, 'template_name' | 'dashboard_description' | 'image_url' | 'tags'>
+ template: Pick<DashboardTemplateType, 'template_name' | 'dashboard_description' | 'image_url' | 'tags' | 'scope'>
onClick: () => void
index: number
'data-attr': string
@@ -46,6 +47,20 @@ function TemplateItemBuildingGlyph({ size }: { size: 'sm' | 'lg' }): JSX.Element
)
}
+/** Tag distinguishing org-shared templates from this project's own; team templates are the implicit default and unbadged. */
+function OrganizationScopeBadge({ scope }: { scope?: DashboardTemplateType['scope'] }): JSX.Element | null {
+ if (scope !== 'organization') {
+ return null
+ }
+ return (
+ <Tooltip title="Shared with everyone in your organization">
+ <LemonTag type="muted" size="small" className="shrink-0">
+ Organization
+ </LemonTag>
+ </Tooltip>
+ )
+}
+
function TemplateItemTitleDescription({
titleId,
template,
@@ -54,16 +69,19 @@ function TemplateItemTitleDescription({
descriptionClassName,
}: {
titleId: string
- template: Pick<DashboardTemplateType, 'template_name' | 'dashboard_description'>
+ template: Pick<DashboardTemplateType, 'template_name' | 'dashboard_description' | 'scope'>
wrapClassName: string
titleClassName: string
descriptionClassName: string
}): JSX.Element {
return (
<div className={wrapClassName}>
- <h5 id={titleId} className={titleClassName}>
- {template?.template_name}
- </h5>
+ <div className="flex items-center gap-2 min-w-0">
+ <h5 id={titleId} className={titleClassName}>
+ {template?.template_name}
+ </h5>
+ <OrganizationScopeBadge scope={template?.scope} />
+ </div>
<p className={descriptionClassName}>{template?.dashboard_description ?? ' '}</p>
</div>
)
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.tsx b/frontend/src/scenes/dashboard/dashboards/templates/DashboardTemplatesTable.tsx
index 0d3cc208a096..79f4d787b7d7 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, IconThumbsUpFilled } from '@posthog/icons'
-import { LemonButton, LemonDivider, LemonInput, LemonMenu, LemonTag } from '@posthog/lemon-ui'
+import { IconBuilding, IconChevronDown, IconGlobe, IconPeople, IconThumbsUpFilled } from '@posthog/icons'
+import { LemonButton, LemonDialog, LemonDivider, LemonInput, LemonMenu, LemonTag } from '@posthog/lemon-ui'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { More } from 'lib/lemon-ui/LemonButton/More'
@@ -89,7 +89,8 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
return null
}, [templateNameOrdering])
- const { deleteDashboardTemplate, updateDashboardTemplate } = useActions(dashboardTemplateEditorLogic)
+ const { deleteDashboardTemplate, updateDashboardTemplate, toggleTemplateOrganizationScope } =
+ useActions(dashboardTemplateEditorLogic)
const { openEdit: openDashboardTemplateModalEdit } = useActions(dashboardTemplateModalLogic)
const { user } = useValues(userLogic)
@@ -137,6 +138,30 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
)
}
+ /** Org-wide templates affect every project, so confirm before deleting; project templates delete straight away. */
+ const confirmDeleteTemplate = (record: DashboardTemplateType): void => {
+ const { id } = record
+ if (id === undefined) {
+ console.error('Dashboard template id not defined')
+ return
+ }
+ if (record.scope === 'organization') {
+ LemonDialog.open({
+ title: 'Delete this organization-wide template?',
+ description:
+ 'This template is shared with every project in your organization. Deleting it removes it for all of them.',
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deleteDashboardTemplate({ id, templateName: record.template_name }),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ return
+ }
+ deleteDashboardTemplate({ id, templateName: record.template_name })
+ }
+
const columns: LemonTableColumns<DashboardTemplateType> = [
{
key: 'featured',
@@ -210,7 +235,8 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
{
title: 'Type',
dataIndex: 'team_id',
- render: (_, { scope }) => (scope === 'global' ? 'Official' : 'Team'),
+ render: (_, { scope }) =>
+ scope === 'global' ? 'Official' : scope === 'organization' ? 'Organization' : 'Team',
},
{
title: 'Created by',
@@ -294,16 +320,7 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
<LemonDivider />
<LemonButton
- onClick={() => {
- if (id === undefined) {
- console.error('Dashboard template id not defined')
- return
- }
- deleteDashboardTemplate({
- id,
- templateName: record.template_name,
- })
- }}
+ onClick={() => confirmDeleteTemplate(record)}
fullWidth
status="danger"
disabledReason={
@@ -322,7 +339,16 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
)
}
- if (canCustomerManageTeamTemplates && scope === 'team') {
+ // 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={
@@ -339,22 +365,24 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
>
Edit
</LemonButton>
- {copyTemplateToProjectMenuSection(
- id,
- 'dashboard-template-copy-to-project-customer'
- )}
+ <LemonButton
+ onClick={() => toggleTemplateOrganizationScope(record)}
+ fullWidth
+ data-attr="dashboard-template-toggle-organization-visibility"
+ >
+ {scope === 'organization'
+ ? 'Make visible to this team only'
+ : 'Make visible to whole organization'}
+ </LemonButton>
+ {scope === 'team'
+ ? copyTemplateToProjectMenuSection(
+ id,
+ 'dashboard-template-copy-to-project-customer'
+ )
+ : null}
<LemonDivider />
<LemonButton
- onClick={() => {
- if (id === undefined) {
- console.error('Dashboard template id not defined')
- return
- }
- deleteDashboardTemplate({
- id,
- templateName: record.template_name,
- })
- }}
+ onClick={() => confirmDeleteTemplate(record)}
fullWidth
status="danger"
>
@@ -408,6 +436,20 @@ export const DashboardTemplatesTable = (): JSX.Element | null => {
>
Team
</LemonButton>
+ <LemonButton
+ active={templatesTabVisibility === 'organization'}
+ type="secondary"
+ size="small"
+ icon={<IconPeople />}
+ onClick={() =>
+ setTemplatesTabVisibility(
+ templatesTabVisibility === 'organization' ? 'all' : 'organization'
+ )
+ }
+ data-attr="dashboard-templates-filter-organization"
+ >
+ Organization
+ </LemonButton>
</div>
</div>
</div>
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateChooserLogic.ts b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateChooserLogic.ts
index 579a9a3f1ab0..37ff28644a4a 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateChooserLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplateChooserLogic.ts
@@ -18,8 +18,10 @@ function availabilityContextsKey(contexts: DashboardTemplateProps['availabilityC
return [...contexts].sort().join(',')
}
-function isTeamTemplate(template: DashboardTemplateType): boolean {
- return template.scope === 'team'
+// Customer-authored templates (team- or organization-scoped) as opposed to PostHog's official/global ones.
+// Both share the chooser's "Team templates" bucket; org-scoped cards are tagged "Organization" in the UI.
+function isCustomerTemplate(template: DashboardTemplateType): boolean {
+ return template.scope === 'team' || template.scope === 'organization'
}
function filterTemplatesByAvailability(
@@ -92,20 +94,20 @@ export const dashboardTemplateChooserLogic = kea<dashboardTemplateChooserLogicTy
teamTemplates: [
(s) => [s.allTemplates, (_, props) => props.availabilityContexts],
(raw: DashboardTemplateType[], availabilityContexts: DashboardTemplateProps['availabilityContexts']) =>
- filterTemplatesByAvailability(raw, availabilityContexts).filter(isTeamTemplate),
+ filterTemplatesByAvailability(raw, availabilityContexts).filter(isCustomerTemplate),
],
featuredTemplates: [
(s) => [s.allTemplates, (_, props) => props.availabilityContexts],
(raw: DashboardTemplateType[], availabilityContexts: DashboardTemplateProps['availabilityContexts']) =>
filterTemplatesByAvailability(raw, availabilityContexts)
- .filter((t) => !isTeamTemplate(t))
+ .filter((t) => !isCustomerTemplate(t))
.filter((t) => t.is_featured === true),
],
nonFeaturedOfficial: [
(s) => [s.allTemplates, (_, props) => props.availabilityContexts],
(raw: DashboardTemplateType[], availabilityContexts: DashboardTemplateProps['availabilityContexts']) =>
filterTemplatesByAvailability(raw, availabilityContexts)
- .filter((t) => !isTeamTemplate(t))
+ .filter((t) => !isCustomerTemplate(t))
.filter((t) => t.is_featured !== true),
],
hasActiveFilter: [(s) => [s.templateFilter], (filterText: string) => filterText.trim().length > 0],
@@ -121,7 +123,7 @@ export const dashboardTemplateChooserLogic = kea<dashboardTemplateChooserLogicTy
(s) => [s.allTemplates, (_, props) => props.availabilityContexts],
(raw: DashboardTemplateType[], availabilityContexts: DashboardTemplateProps['availabilityContexts']) => {
const official = filterTemplatesByAvailability(raw, availabilityContexts).filter(
- (t) => !isTeamTemplate(t)
+ (t) => !isCustomerTemplate(t)
)
const nonFeatured = official.filter((t) => t.is_featured !== true)
const featured = official.filter((t) => t.is_featured === true)
@@ -139,7 +141,7 @@ export const dashboardTemplateChooserLogic = kea<dashboardTemplateChooserLogicTy
return true
}
const official = filterTemplatesByAvailability(raw, availabilityContexts).filter(
- (t) => !isTeamTemplate(t)
+ (t) => !isCustomerTemplate(t)
)
const nonFeatured = official.filter((t) => t.is_featured !== true)
const featured = official.filter((t) => t.is_featured === true)
diff --git a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.test.ts
index 79d909d3ddcb..d64371ec6bdd 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.test.ts
@@ -83,6 +83,29 @@ describe('dashboardTemplatesLogic', () => {
expect(listMock.mock.calls.some(([params]: [DashboardTemplateListParams]) => expectedParams(params))).toBe(true)
})
+ it.each([
+ { visibility: 'official' as const, expectedScope: 'global' },
+ { visibility: 'project' as const, expectedScope: 'team' },
+ { visibility: 'organization' as const, expectedScope: 'organization' },
+ { visibility: 'all' as const, expectedScope: undefined },
+ ])(
+ 'templates tab visibility "$visibility" maps to list scope "$expectedScope"',
+ async ({ visibility, expectedScope }) => {
+ const listMock = api.dashboardTemplates.list as jest.Mock
+ const mounted = dashboardTemplatesLogic({ scope: 'default', templatesTabList: true })
+ logic = mounted
+ mounted.mount()
+
+ await expectLogic(mounted, () =>
+ mounted.actions.setTemplatesTabVisibility(visibility)
+ ).toFinishAllListeners()
+
+ expect(
+ listMock.mock.calls.some(([params]: [DashboardTemplateListParams]) => params.scope === expectedScope)
+ ).toBe(true)
+ }
+ )
+
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 0e851f8fdc69..246c0a87949e 100644
--- a/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/templates/dashboardTemplatesLogic.tsx
@@ -32,7 +32,7 @@ export type DashboardTemplatesLogicProps = DashboardTemplateProps & {
templatesTabList?: boolean
}
-export type DashboardTemplatesTabVisibility = 'all' | 'official' | 'project'
+export type DashboardTemplatesTabVisibility = 'all' | 'official' | 'project' | 'organization'
/** List sort for the templates table (passed through to API when not searching). */
export type DashboardTemplateTableOrdering = '' | 'template_name' | '-template_name' | 'created_at' | '-created_at'
@@ -148,6 +148,8 @@ export const dashboardTemplatesLogic = kea<dashboardTemplatesLogicType>([
listScope = 'global'
} else if (values.templatesTabVisibility === 'project') {
listScope = 'team'
+ } else if (values.templatesTabVisibility === 'organization') {
+ listScope = 'organization'
} else {
listScope = undefined
}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 157b98ae6d39..064917815c10 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2558,7 +2558,7 @@ export interface DashboardTemplateListParams {
is_featured?: boolean
}
-export type DashboardTemplateScope = 'team' | 'global' | 'feature_flag'
+export type DashboardTemplateScope = 'team' | 'global' | 'feature_flag' | 'organization'
export interface DashboardType<T = InsightModel> extends DashboardBasicType {
tiles: DashboardTile<T>[]
@@ -2623,6 +2623,13 @@ export type DashboardTemplateStoredTile =
| DashboardTemplateStoredButtonTile
| DashboardTemplateStoredWidgetTile
+/** Project-specific references embedded in a template's tiles that may not resolve in another project. */
+export interface NonPortableReferences {
+ actions: number
+ cohorts: number
+ warehouse_tables: string[]
+}
+
export interface DashboardTemplateType {
id: string
team_id?: number
@@ -2641,6 +2648,8 @@ export interface DashboardTemplateType {
is_featured?: boolean
/** Soft delete; API allows PATCH for staff undo (restore). */
deleted?: boolean
+ /** Read-only. Project-specific references in tiles (actions, cohorts, warehouse tables) that may not resolve in another project. */
+ non_portable_references?: NonPortableReferences
}
export interface MonacoMarker {
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 9926b922b9d0..f230cea5ed94 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -1557,7 +1557,9 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
[
("same_team_only_team", "self", "team", status.HTTP_201_CREATED),
("global", "none", "global", status.HTTP_201_CREATED),
+ ("same_org_organization", "sibling", "organization", status.HTTP_201_CREATED),
("other_team_only_team", "other", "team", status.HTTP_400_BAD_REQUEST),
+ ("other_org_organization", "other", "organization", status.HTTP_400_BAD_REQUEST),
]
)
def test_use_template_respects_team_scoping(self, _name: str, owner: str, scope: str, expected_status: int) -> None:
@@ -1565,6 +1567,8 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
if owner == "self":
template_team: Team | None = self.team
+ elif owner == "sibling":
+ template_team = Team.objects.create(organization=self.organization, name="sibling team")
elif owner == "other":
other_org = Organization.objects.create(name="other org")
template_team = Team.objects.create(organization=other_org, name="other team")
diff --git a/posthog/helpers/dashboard_templates.py b/posthog/helpers/dashboard_templates.py
index 5d2a6dd13265..396dfbc33b18 100644
--- a/posthog/helpers/dashboard_templates.py
+++ b/posthog/helpers/dashboard_templates.py
@@ -683,7 +683,9 @@ def create_dashboard_from_template(
return DASHBOARD_TEMPLATES[template_key](dashboard)
template = DashboardTemplate.objects.filter(
- Q(team_id=dashboard.team_id) | Q(scope=DashboardTemplate.Scope.GLOBAL),
+ Q(team_id=dashboard.team_id)
+ | Q(scope=DashboardTemplate.Scope.GLOBAL)
+ | Q(scope=DashboardTemplate.Scope.ORGANIZATION, team__organization_id=dashboard.team.organization_id),
template_name=template_key,
).first()
if not template:
diff --git a/products/dashboards/backend/api/dashboard_templates.py b/products/dashboards/backend/api/dashboard_templates.py
index 68683ea82ab2..6768ea941c49 100644
--- a/products/dashboards/backend/api/dashboard_templates.py
+++ b/products/dashboards/backend/api/dashboard_templates.py
@@ -13,7 +13,7 @@ from django.views.decorators.cache import cache_page
import structlog
from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view
+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
from rest_framework import request, response, serializers, status, viewsets
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.permissions import SAFE_METHODS, BasePermission
@@ -24,7 +24,9 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
from posthog.event_usage import report_user_action
+from posthog.exceptions_capture import capture_exception
from posthog.helpers.full_text_search import build_rank
+from posthog.models.resource_transfer.visitors.insight import InsightVisitor
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.rbac.user_access_control import UserAccessControl
@@ -38,8 +40,15 @@ logger = structlog.get_logger(__name__)
# arbitary limit, just to prevent abuse
MAX_DASHBOARD_TEMPLATES_PER_ORGANIZATION = 100
-_NON_STAFF_ALLOWED_PATCH_KEYS = frozenset({"template_name", "dashboard_description", "tags", "deleted"})
+_NON_STAFF_ALLOWED_PATCH_KEYS = frozenset({"template_name", "dashboard_description", "tags", "deleted", "scope"})
_NON_STAFF_FORBIDDEN_CREATE_FIELDS = frozenset({"availability_contexts", "image_url", "github_url"})
+_NON_STAFF_ALLOWED_SCOPES = frozenset({DashboardTemplate.Scope.ONLY_TEAM, DashboardTemplate.Scope.ORGANIZATION})
+
+
+def _non_staff_allowed_scopes_display() -> str:
+ """Human-readable list of scopes non-staff editors may set, derived from `_NON_STAFF_ALLOWED_SCOPES`."""
+ return " or ".join(sorted(str(scope.value) for scope in _NON_STAFF_ALLOWED_SCOPES))
+
# load dashboard_template_schema.json
dashboard_template_schema = json.loads((Path(__file__).parent / "dashboard_template_schema.json").read_text())
@@ -73,10 +82,56 @@ def _dashboard_template_list_order_by(ordering: str | None) -> list[Any]:
return ["-is_featured", Lower("template_name")]
+def _collect_warehouse_table_names(node: Any) -> set[str]:
+ """Recursively collect `DataWarehouseNode.table_name` values from a query JSON tree."""
+ names: set[str] = set()
+ if isinstance(node, dict):
+ if node.get("kind") == "DataWarehouseNode":
+ table_name = node.get("table_name")
+ if isinstance(table_name, str) and table_name:
+ names.add(table_name)
+ for value in node.values():
+ names |= _collect_warehouse_table_names(value)
+ elif isinstance(node, list):
+ for item in node:
+ names |= _collect_warehouse_table_names(item)
+ return names
+
+
+def detect_non_portable_references(tiles: list[Any]) -> dict[str, Any]:
+ """Project-scoped references in template tiles that may not resolve when used in another project.
+
+ Events and properties are portable (matched by name), so they are not reported.
+ """
+ action_ids: set[int] = set()
+ cohort_ids: set[int] = set()
+ warehouse_tables: set[str] = set()
+ for tile in tiles:
+ if not isinstance(tile, dict):
+ continue
+ query = tile.get("query")
+ if not isinstance(query, dict):
+ continue
+ try:
+ action_ids |= InsightVisitor._extract_action_ids(None, query)
+ cohort_ids |= InsightVisitor._extract_cohort_ids(None, query)
+ except (ValueError, TypeError) as exc:
+ # Detection is best-effort; a malformed tile must never break serialization.
+ logger.warning("dashboard_template_non_portable_reference_detection_failed", exc_info=exc)
+ capture_exception(exc)
+ warehouse_tables |= _collect_warehouse_table_names(query)
+ return {
+ "actions": len(action_ids),
+ "cohorts": len(cohort_ids),
+ "warehouse_tables": sorted(warehouse_tables),
+ }
+
+
class CustomerDashboardTemplateWritePermission(BasePermission):
"""
Staff: any unsafe method (delegates object rules to has_object_permission).
- Non-staff: team-scoped templates only (see has_object_permission); global / feature-flag rows forbidden.
+ Non-staff: only templates owned by the requesting project (team- or org-scoped); global / feature-flag rows
+ forbidden. Org-scoped templates stay readable org-wide but writeable only from their owning project.
Project RBAC is enforced separately by AccessControlPermission (editor on `dashboard_template`).
"""
@@ -100,11 +155,35 @@ class CustomerDashboardTemplateWritePermission(BasePermission):
return False
if obj.scope == DashboardTemplate.Scope.ONLY_TEAM and obj.team_id is not None and obj.team_id != view_team_id:
return False
+ # Org-scoped templates are readable org-wide, but rename/delete/demote is restricted to the owning
+ # project's editors. Every org row keeps its creating team_id, so ownership is always derivable.
+ if obj.scope == DashboardTemplate.Scope.ORGANIZATION and obj.team_id != view_team_id:
+ return False
return True
+class NonPortableReferencesSerializer(serializers.Serializer):
+ actions = serializers.IntegerField(
+ help_text="Count of distinct action references in the template's tiles that are specific to the source project."
+ )
+ cohorts = serializers.IntegerField(
+ help_text="Count of distinct cohort references in the template's tiles that are specific to the source project."
+ )
+ warehouse_tables = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Names of data warehouse tables referenced by the template's tiles that are specific to the source project.",
+ )
+
+
class DashboardTemplateSerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
+ non_portable_references = serializers.SerializerMethodField(
+ help_text=(
+ "Read-only. Project-specific references (actions, cohorts, data warehouse tables) embedded in this "
+ "template's tiles that may not resolve when it is used in another project. Events and properties are "
+ "matched by name and are portable, so they are not reported here."
+ ),
+ )
class Meta:
model = DashboardTemplate
@@ -124,6 +203,7 @@ class DashboardTemplateSerializer(serializers.ModelSerializer):
"scope",
"availability_contexts",
"is_featured",
+ "non_portable_references",
]
def _handle_integrity_error(self, exc: IntegrityError) -> NoReturn:
@@ -140,6 +220,15 @@ class DashboardTemplateSerializer(serializers.ModelSerializer):
user = getattr(request, "user", None) if request else None
return bool(user and user.is_authenticated and user.is_staff)
+ @extend_schema_field(NonPortableReferencesSerializer)
+ def get_non_portable_references(self, obj: DashboardTemplate) -> dict[str, Any] | None:
+ # O(tiles) per row, so only compute when a single template is fetched (retrieve). List responses — the
+ # dashboard chooser and the management table — return null and fetch references on demand when promoting.
+ view = self.context.get("view")
+ if view is None or getattr(view, "action", None) != "retrieve":
+ return None
+ return detect_non_portable_references(obj.tiles or [])
+
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
request = self.context.get("request")
user = getattr(request, "user", None) if request else None
@@ -160,24 +249,71 @@ class DashboardTemplateSerializer(serializers.ModelSerializer):
if forbidden_patch:
raise ValidationError(
{
- k: ["Only name, description, tags, and delete can be changed for project templates."]
+ k: ["Only name, description, tags, scope, and delete can be changed for project templates."]
for k in sorted(forbidden_patch)
}
)
- if self.instance is None and not is_staff:
- requested_scope = attrs.get("scope") or initial.get("scope")
- if requested_scope not in (None, "", DashboardTemplate.Scope.ONLY_TEAM, "team"):
- raise ValidationError(
- {"scope": ["Project templates must use team scope."]},
- )
- is_featured_val = initial.get("is_featured", attrs.get("is_featured"))
- if is_featured_val:
- raise ValidationError({"is_featured": ["Only staff can mark templates as featured."]})
- attrs["scope"] = DashboardTemplate.Scope.ONLY_TEAM
- attrs["is_featured"] = False
+ if not is_staff:
+ if self.instance is None:
+ # Create: default to team scope; allow team or organization, reject global / feature-flag.
+ requested_scope = attrs.get("scope") or initial.get("scope") or DashboardTemplate.Scope.ONLY_TEAM
+ if requested_scope not in _NON_STAFF_ALLOWED_SCOPES:
+ raise ValidationError(
+ {"scope": [f"Project templates can only use {_non_staff_allowed_scopes_display()} scope."]},
+ )
+ is_featured_val = initial.get("is_featured", attrs.get("is_featured"))
+ if is_featured_val:
+ raise ValidationError({"is_featured": ["Only staff can mark templates as featured."]})
+ attrs["scope"] = requested_scope
+ attrs["is_featured"] = False
+ elif "scope" in initial:
+ # Update: only a team <-> organization transition is allowed for non-staff.
+ requested_scope = attrs.get("scope") or initial.get("scope")
+ if (
+ self.instance.scope not in _NON_STAFF_ALLOWED_SCOPES
+ or requested_scope not in _NON_STAFF_ALLOWED_SCOPES
+ ):
+ raise ValidationError(
+ {"scope": ["You can only switch a template between team and organization visibility."]},
+ )
+ attrs["scope"] = requested_scope
+
+ self._validate_unique_organization_template_name(attrs)
return attrs
+ def _validate_unique_organization_template_name(self, attrs: dict[str, Any]) -> None:
+ """Organization-scoped templates must have a unique name within their organization."""
+ effective_scope = attrs.get("scope") or (self.instance.scope if self.instance is not None else None)
+ if effective_scope != DashboardTemplate.Scope.ORGANIZATION:
+ return
+ template_name = attrs.get("template_name")
+ if template_name is None and self.instance is not None:
+ template_name = self.instance.template_name
+ if not template_name:
+ return
+ if self.instance is not None and self.instance.team_id is not None:
+ team_id = self.instance.team_id
+ else:
+ team_id = self.context.get("team_id")
+ if team_id is None:
+ return
+ org_id = Team.objects.filter(pk=team_id).values_list("organization_id", flat=True).first()
+ if org_id is None:
+ return
+ clashing = DashboardTemplate.objects.filter(
+ scope=DashboardTemplate.Scope.ORGANIZATION,
+ team__organization_id=org_id,
+ template_name=template_name,
+ )
+ if self.instance is not None:
+ clashing = clashing.exclude(pk=self.instance.pk)
+ if clashing.exists():
+ raise ValidationError(
+ {"template_name": ["An organization template with this name already exists in this organization."]},
+ code="unique_org_template_name",
+ )
+
def create(self, validated_data: dict, *args, **kwargs) -> DashboardTemplate:
if not validated_data["tiles"]:
raise ValidationError(detail="You need to provide tiles for the template.")
@@ -217,7 +353,7 @@ class DashboardTemplateSerializer(serializers.ModelSerializer):
validated_data["team_id"] = context_team_id
if not self._request_user_is_staff():
- validated_data.pop("scope", None)
+ # `scope` is intentionally allowed through (validated as a team <-> organization transition above).
validated_data.pop("team_id", None)
validated_data.pop("tiles", None)
validated_data.pop("variables", None)
@@ -308,10 +444,11 @@ def _assert_user_can_read_source_for_copy(*, user: User, source_team: Team) -> N
location=OpenApiParameter.QUERY,
description=(
"Optional. `global`: official templates only. `team`: this project's saved templates only "
- "(`scope=team` rows for the current project). `feature_flag`: feature-flag dashboard templates only. "
- "Omit for both official and this project's templates (default dashboard template picker behavior)."
+ "(`scope=team` rows for the current project). `organization`: templates shared across all projects "
+ "in this organization. `feature_flag`: feature-flag dashboard templates only. "
+ "Omit for official, organization, and this project's templates (default dashboard template picker behavior)."
),
- enum=["global", "team", "feature_flag"],
+ enum=["global", "team", "organization", "feature_flag"],
),
],
),
@@ -344,6 +481,26 @@ class DashboardTemplateViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, views
organization=self.organization,
)
+ def perform_update(self, serializer):
+ scope_before = serializer.instance.scope
+ instance = serializer.save()
+ user = self.request.user if self.request.user.is_authenticated else None
+ if instance.scope != scope_before and isinstance(user, User):
+ report_user_action(
+ user,
+ "dashboard template scope changed",
+ properties={
+ "template_id": str(instance.id),
+ "from_scope": scope_before or "",
+ "to_scope": instance.scope or "",
+ "team_id": instance.team_id,
+ "organization_id": self.organization_id,
+ "is_staff": bool(user.is_staff),
+ },
+ team=self.team,
+ organization=self.organization,
+ )
+
@method_decorator(cache_page(60 * 2)) # cache for 2 minutes
@action(methods=["GET"], detail=False)
def json_schema(self, request: request.Request, **kwargs) -> response.Response:
@@ -453,6 +610,10 @@ class DashboardTemplateViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, views
search = filters.pop("search", None)
ordering = self.request.GET.get("ordering")
+ # Organization-scoped templates are visible to every team in the same organization. The org arm must
+ # always be AND-ed with `team__organization_id` so it never leaks templates from other organizations.
+ org_id = self.organization_id
+
# if scope is feature flag, then only return feature flag templates
# they're implicitly global, so they are not associated with any teams
if scope == DashboardTemplate.Scope.FEATURE_FLAG:
@@ -461,9 +622,15 @@ class DashboardTemplateViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, views
query_condition = Q(scope=DashboardTemplate.Scope.GLOBAL)
elif scope == DashboardTemplate.Scope.ONLY_TEAM:
query_condition = Q(team_id=self.team_id) & Q(scope=DashboardTemplate.Scope.ONLY_TEAM)
- # otherwise we are in the new dashboard context so show global templates and ones from this team
+ elif scope == DashboardTemplate.Scope.ORGANIZATION:
+ query_condition = Q(scope=DashboardTemplate.Scope.ORGANIZATION) & Q(team__organization_id=org_id)
+ # otherwise we are in the new dashboard context so show global, organization, and this team's templates
else:
- query_condition = Q(team_id=self.team_id) | Q(scope=DashboardTemplate.Scope.GLOBAL)
+ query_condition = (
+ Q(team_id=self.team_id)
+ | Q(scope=DashboardTemplate.Scope.GLOBAL)
+ | (Q(scope=DashboardTemplate.Scope.ORGANIZATION) & Q(team__organization_id=org_id))
+ )
# Include soft-deleted rows for retrieve/update so PATCH `{deleted: false}` (undo) can resolve the object.
# The default manager excludes `deleted=True`, which made undo 404 after soft delete.
@@ -488,7 +655,10 @@ class DashboardTemplateViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, views
else:
qs = qs.order_by(*_dashboard_template_list_order_by(ordering))
- if self.action == "list":
+ # Soft-deleted rows stay resolvable only for unsafe methods, so PATCH `{deleted: false}` (undo) by the
+ # owning project still works. Safe reads (list + retrieve) exclude them, so a sibling project that
+ # captured the UUID can't GET an organization template after its owning project deleted it.
+ if self.request.method in SAFE_METHODS:
qs = qs.exclude(deleted=True)
return qs
diff --git a/products/dashboards/backend/api/test/test_dashboard_templates.py b/products/dashboards/backend/api/test/test_dashboard_templates.py
index 5f109a986e7d..666711d6826a 100644
--- a/products/dashboards/backend/api/test/test_dashboard_templates.py
+++ b/products/dashboards/backend/api/test/test_dashboard_templates.py
@@ -402,7 +402,8 @@ class TestDashboardTemplates(APIBaseTest):
assert update_response.status_code == status.HTTP_400_BAD_REQUEST, update_response
def test_non_staff_cannot_edit_dashboard_template(self) -> None:
- default_template = DashboardTemplate.objects.all()[0]
+ default_template = DashboardTemplate.objects.filter(scope=DashboardTemplate.Scope.GLOBAL).first()
+ assert default_template is not None
assert default_template.scope == "global"
update_response = self.client.patch(
@@ -942,6 +943,147 @@ class TestDashboardTemplates(APIBaseTest):
assert another_attempted_escape_response.status_code == status.HTTP_200_OK
assert id not in [r["id"] for r in another_attempted_escape_response.json()["results"]]
+ def test_organization_scoped_template_visible_to_sibling_team_in_same_org(self) -> None:
+ sibling_team = Team.objects.create(organization=self.organization, name="Sibling team org scope")
+ org_template = DashboardTemplate.objects.create(
+ team_id=self.team.pk,
+ scope=DashboardTemplate.Scope.ORGANIZATION,
+ template_name="Shared org template",
+ dashboard_description="",
+ dashboard_filters={},
+ tiles=variable_template["tiles"],
+ variables=[],
+ tags=[],
+ )
+
+ list_response = self.client.get(f"/api/projects/{sibling_team.pk}/dashboard_templates/")
+ assert list_response.status_code == status.HTTP_200_OK, list_response
+ assert str(org_template.id) in [r["id"] for r in list_response.json()["results"]]
+
+ retrieve_response = self.client.get(f"/api/projects/{sibling_team.pk}/dashboard_templates/{org_template.id}")
+ assert retrieve_response.status_code == status.HTTP_200_OK, retrieve_response
+ assert retrieve_response.json()["scope"] == "organization"
+
+ def test_organization_scoped_template_not_visible_to_other_org(self) -> None:
+ org_template = DashboardTemplate.objects.create(
+ team_id=self.team.pk,
+ scope=DashboardTemplate.Scope.ORGANIZATION,
+ template_name="Org A only template",
+ dashboard_description="",
+ dashboard_filters={},
+ tiles=variable_template["tiles"],
+ variables=[],
+ tags=[],
+ )
+ other_org = Organization.objects.create(name="Other org for org-scope idor")
+ other_team = Team.objects.create(organization=other_org, name="Other org team")
+ other_user = User.objects.create_and_join(
+ organization=other_org, first_name="Other", email="[email protected]", password="wat"
+ )
+ self.client.force_login(other_user)
+
+ list_response = self.client.get(f"/api/projects/{other_team.pk}/dashboard_templates/")
+ assert list_response.status_code == status.HTTP_200_OK, list_response
+ assert str(org_template.id) not in [r["id"] for r in list_response.json()["results"]]
+
+ retrieve_response = self.client.get(f"/api/projects/{other_team.pk}/dashboard_templates/{org_template.id}")
+ assert retrieve_response.status_code == status.HTTP_404_NOT_FOUND, retrieve_response
+
+ def test_scope_organization_filter_returns_only_caller_org(self) -> None:
+ DashboardTemplate.objects.all().delete()
+ org_template_id = self.create_template(
+ {"scope": DashboardTemplate.Scope.ORGANIZATION, "template_name": "org scoped via filter"}
+ )
+ team_template_id = self.create_template(
+ {"scope": DashboardTemplate.Scope.ONLY_TEAM, "template_name": "team scoped via filter"}
+ )
+ other_org = Organization.objects.create(name="Other org scope filter")
+ other_team = Team.objects.create(organization=other_org, name="Other team scope filter")
+ DashboardTemplate.objects.create(
+ team_id=other_team.pk,
+ scope=DashboardTemplate.Scope.ORGANIZATION,
+ template_name="other org org-scoped",
+ dashboard_description="",
+ dashboard_filters={},
+ tiles=variable_template["tiles"],
+ variables=[],
+ tags=[],
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.pk}/dashboard_templates/?scope=organization")
+ assert response.status_code == status.HTTP_200_OK
+ rows = [(r["id"], r["scope"]) for r in response.json()["results"]]
+ assert rows == [(org_template_id, "organization")]
+ assert team_template_id not in [r_id for r_id, _ in rows]
+
+ def test_non_portable_references_detected(self) -> None:
+ tiles_with_refs = [
+ {
+ "name": "Action and cohort series",
+ "type": "INSIGHT",
+ "query": {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "ActionsNode", "id": 12345}],
+ "properties": [{"type": "cohort", "value": 999}],
+ },
+ },
+ "layouts": {},
+ },
+ {
+ "name": "Warehouse series",
+ "type": "INSIGHT",
+ "query": {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "DataWarehouseNode", "table_name": "stripe_invoices"}],
+ },
+ },
+ "layouts": {},
+ },
+ ]
+ create = self.client.post(
+ f"/api/projects/{self.team.pk}/dashboard_templates",
+ {**variable_template, "template_name": "Refs template", "tiles": tiles_with_refs},
+ )
+ assert create.status_code == status.HTTP_201_CREATED, create
+
+ retrieve = self.client.get(f"/api/projects/{self.team.pk}/dashboard_templates/{create.json()['id']}")
+ assert retrieve.status_code == status.HTTP_200_OK
+ assert retrieve.json()["non_portable_references"] == {
+ "actions": 1,
+ "cohorts": 1,
+ "warehouse_tables": ["stripe_invoices"],
+ }
+
+ def test_non_portable_references_empty_for_event_only_template(self) -> None:
+ create = self.client.post(
+ f"/api/projects/{self.team.pk}/dashboard_templates",
+ {**variable_template, "template_name": "Portable template"},
+ )
+ assert create.status_code == status.HTTP_201_CREATED, create
+
+ retrieve = self.client.get(f"/api/projects/{self.team.pk}/dashboard_templates/{create.json()['id']}")
+ assert retrieve.status_code == status.HTTP_200_OK
+ assert retrieve.json()["non_portable_references"] == {"actions": 0, "cohorts": 0, "warehouse_tables": []}
+
+ def test_non_portable_references_null_in_list_response(self) -> None:
+ create = self.client.post(
+ f"/api/projects/{self.team.pk}/dashboard_templates",
+ {**variable_template, "template_name": "Listed template"},
+ )
+ assert create.status_code == status.HTTP_201_CREATED, create
+ # Not computed on the create (non-retrieve) response, nor in list responses — only on single retrieve.
+ assert create.json()["non_portable_references"] is None
+
+ list_response = self.client.get(f"/api/projects/{self.team.pk}/dashboard_templates?scope=team")
+ assert list_response.status_code == status.HTTP_200_OK
+ listed = [t for t in list_response.json()["results"] if t["id"] == create.json()["id"]]
+ assert len(listed) == 1
+ assert listed[0]["non_portable_references"] is None
+
class TestCustomerDashboardTemplateAuthoring(APIBaseTest):
"""Customer authoring: editor on `dashboard_template` (RBAC), team-scoped templates only for non-staff."""
@@ -1093,6 +1235,155 @@ class TestCustomerDashboardTemplateAuthoring(APIBaseTest):
)
mock_report.assert_not_called()
+ def test_non_staff_editor_can_create_organization_scoped_template(self) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/dashboard_templates",
+ {**variable_template, "template_name": "Org scoped by editor", "scope": "organization"},
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response
+ assert response.json()["scope"] == "organization"
+ assert response.json()["team_id"] == self.team.pk
+
+ def test_non_staff_editor_can_promote_and_demote_between_team_and_organization(self) -> None:
+ create = self.client.post(
+ f"/api/projects/{self.team.pk}/dashboard_templates",
+ {**variable_template, "template_name": "Promote demote me"},
+ )
+ assert create.status_code == status.HTTP_201_CREATED, create
+ assert create.json()["scope"] == "team"
+ tid = create.json()["id"]
+
+ promote = self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboard_templates/{tid}",
+ {"scope": "organization"},
+ )
+ assert promote.status_code == status.HTTP_200_OK, promote
+ assert promote.json()["scope"] == "organization"
+
+ demote = self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboard_templates/{tid}",
+ {"scope": "team"},
+ )
+ assert demote.status_code == status.HTTP_200_OK, demote
+ assert demote.json()["scope"] == "team"
+
+ def test_non_staff_cannot_modify_org_template_owned_by_sibling_team(self) -> None:
+ sibling_team = Team.objects.create(organization=self.organization, name="Sibling owns org template")
+ org_template = DashboardTemplate.objects.create(
+ team_id=sibling_team.pk,
+ scope=DashboardTemplate.Scope.ORGANIZATION,
+ template_name="Sibling-owned org template",
+ dashboard_description="",
+ dashboard_filters={},
+ tiles=variable_template["tiles"],
+ variables=[],
+ tags=[],
+ )
+
+ # Readable org-wide from the current project...
+ retrieve = self.client.get(f"/api/projects/{self.team.pk}/dashboard_templates/{org_template.id}")
+ assert retrieve.status_code == status.HTTP_200_OK, retrieve
+
+ # ...but rename / demote / delete are rejected because this project does not own it.
+ rename = self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboard_templates/{org_template.id}",
+ {"template_name": "Hijacked"},
+ )
+ assert rename.status_code == status.HTTP_403_FORBIDDEN, rename
+
+ demote = self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboard_templates/{org_template.id}",
+ {"scope": "team"},
+ )
+ assert demote.status_code == status.HTTP_403_FORBIDDEN, demote
+
+ delete = self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboard_templates/{org_template.id}",
+ {"deleted": True},
+ )
+ assert delete.status_code == status.HTTP_403_FORBIDDEN, delete
+
+ def test_sibling_team_cannot_retrieve_soft_deleted_org_template(self) -> None:
+ owning_team = Team.objects.create(organization=self.organization, name="Owns deleted org template")
+ org_template = DashboardTemplate.objects.create(
+ team_id=owning_team.pk,
+ scope=DashboardTemplate.Scope.ORGANIZATION,
+ template_name="Soon to be deleted org template",
+ dashboard_description="",
+ dashboard_filters={},
+ tiles=variable_template["tiles"],
+ variables=[],
+ tags=[],
+ deleted=True,
+ )
+
+ # A sibling project that captured the UUID must not be able to read it once it's soft-deleted.
+ retrieve = self.client.get(f"/api/projects/{self.team.pk}/dashboard_templates/{org_template.id}")
+ assert retrieve.status_code == status.HTTP_404_NOT_FOUND, retrieve
+
+ @patch("products.dashboards.backend.api.dashboard_templates.report_user_action")
+ def test_scope_change_emits_analytics(self, mock_report) -> None:
+ create = self.client.post(
+ f"/api/projects/{self.team.pk}/dashboard_templates",
+ {**variable_template, "template_name": "Scope change analytics"},
+ )
+ tid = create.json()["id"]
+ mock_report.reset_mock()
+
+ promote = self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboard_templates/{tid}",
+ {"scope": "organization"},
+ )
+ assert promote.status_code == status.HTTP_200_OK, promote
+ mock_report.assert_called_once()
+ call_kwargs = mock_report.call_args.kwargs
+ assert mock_report.call_args.args[1] == "dashboard template scope changed"
+ assert call_kwargs["properties"]["from_scope"] == "team"
+ assert call_kwargs["properties"]["to_scope"] == "organization"
+
+ # A no-op update (no scope change) must not emit the event.
+ mock_report.reset_mock()
+ rename = self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboard_templates/{tid}",
+ {"template_name": "Scope change analytics renamed"},
+ )
+ assert rename.status_code == status.HTTP_200_OK, rename
+ mock_report.assert_not_called()
+
+ @parameterized.expand([("global",), ("feature_flag",)])
+ def test_non_staff_cannot_promote_to_restricted_scope(self, bad_scope: str) -> None:
+ create = self.client.post(
+ f"/api/projects/{self.team.pk}/dashboard_templates",
+ {**variable_template, "template_name": f"No promote to {bad_scope}"},
+ )
+ tid = create.json()["id"]
+ resp = self.client.patch(
+ f"/api/projects/{self.team.pk}/dashboard_templates/{tid}",
+ {"scope": bad_scope},
+ )
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST, resp
+ assert resp.json().get("attr") == "scope"
+
+ def test_organization_template_name_unique_within_organization(self) -> None:
+ sibling_team = Team.objects.create(organization=self.organization, name="Sibling for uniqueness")
+ DashboardTemplate.objects.create(
+ team_id=sibling_team.pk,
+ scope=DashboardTemplate.Scope.ORGANIZATION,
+ template_name="Duplicated org name",
+ dashboard_description="",
+ dashboard_filters={},
+ tiles=variable_template["tiles"],
+ variables=[],
+ tags=[],
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.pk}/dashboard_templates",
+ {**variable_template, "template_name": "Duplicated org name", "scope": "organization"},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response
+ assert response.json().get("attr") == "template_name"
+
class TestDashboardTemplateCopyBetweenProjects(APIBaseTest):
"""POST .../dashboard_templates/copy_between_projects/ — same-org, team source only."""
diff --git a/products/dashboards/backend/migrations/0012_alter_dashboardtemplate_scope.py b/products/dashboards/backend/migrations/0012_alter_dashboardtemplate_scope.py
new file mode 100644
index 000000000000..c67bfb4eb6c8
--- /dev/null
+++ b/products/dashboards/backend/migrations/0012_alter_dashboardtemplate_scope.py
@@ -0,0 +1,27 @@
+# Generated by Django 5.2.14 on 2026-06-17 09:06
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("dashboards", "0011_dashboardtile_widget_id_idx"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="dashboardtemplate",
+ name="scope",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("team", "Only team"),
+ ("organization", "Organization"),
+ ("global", "Global"),
+ ("feature_flag", "Feature Flag"),
+ ],
+ max_length=24,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/dashboards/backend/migrations/max_migration.txt b/products/dashboards/backend/migrations/max_migration.txt
index bb4a14248aa7..4f4c0cdd9857 100644
--- a/products/dashboards/backend/migrations/max_migration.txt
+++ b/products/dashboards/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_dashboardtile_widget_id_idx
+0012_alter_dashboardtemplate_scope
diff --git a/products/dashboards/backend/models/dashboard_templates.py b/products/dashboards/backend/models/dashboard_templates.py
index 22bf9c62bb3c..4e9a32cf7e77 100644
--- a/products/dashboards/backend/models/dashboard_templates.py
+++ b/products/dashboards/backend/models/dashboard_templates.py
@@ -18,6 +18,7 @@ class DashboardTemplate(UUIDTModel, RootTeamMixin):
"""Visibility of the dashboard template"""
ONLY_TEAM = "team", "Only team"
+ ORGANIZATION = "organization", "Organization"
GLOBAL = "global", "Global"
FEATURE_FLAG = "feature_flag", "Feature Flag"
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 661a6e34ff3a..dca2d6e94203 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -64,6 +64,7 @@ export interface UserBasicApi {
/**
* * `team` - Only team
+ * * `organization` - Organization
* * `global` - Global
* * `feature_flag` - Feature Flag
*/
@@ -72,10 +73,20 @@ export type DashboardTemplateScopeEnumApi =
export const DashboardTemplateScopeEnumApi = {
Team: 'team',
+ Organization: 'organization',
Global: 'global',
FeatureFlag: 'feature_flag',
} as const
+export interface NonPortableReferencesApi {
+ /** Count of distinct action references in the template's tiles that are specific to the source project. */
+ actions: number
+ /** Count of distinct cohort references in the template's tiles that are specific to the source project. */
+ cohorts: number
+ /** Names of data warehouse tables referenced by the template's tiles that are specific to the source project. */
+ warehouse_tables: string[]
+}
+
export interface DashboardTemplateApi {
readonly id: string
/**
@@ -116,6 +127,8 @@ export interface DashboardTemplateApi {
availability_contexts?: string[] | null
/** Manually curated; used to highlight templates in the UI. */
is_featured?: boolean
+ /** Read-only. Project-specific references (actions, cohorts, data warehouse tables) embedded in this template's tiles that may not resolve when it is used in another project. Events and properties are matched by name and are portable, so they are not reported here. */
+ readonly non_portable_references: NonPortableReferencesApi
}
export interface PaginatedDashboardTemplateListApi {
@@ -167,6 +180,8 @@ export interface PatchedDashboardTemplateApi {
availability_contexts?: string[] | null
/** Manually curated; used to highlight templates in the UI. */
is_featured?: boolean
+ /** Read-only. Project-specific references (actions, cohorts, data warehouse tables) embedded in this template's tiles that may not resolve when it is used in another project. Events and properties are matched by name and are portable, so they are not reported here. */
+ readonly non_portable_references?: NonPortableReferencesApi
}
export interface CopyDashboardTemplateApi {
@@ -8418,7 +8433,7 @@ export type DashboardTemplatesListParams = {
*/
ordering?: string
/**
- * Optional. `global`: official templates only. `team`: this project's saved templates only (`scope=team` rows for the current project). `feature_flag`: feature-flag dashboard templates only. Omit for both official and this project's templates (default dashboard template picker behavior).
+ * Optional. `global`: official templates only. `team`: this project's saved templates only (`scope=team` rows for the current project). `organization`: templates shared across all projects in this organization. `feature_flag`: feature-flag dashboard templates only. Omit for official, organization, and this project's templates (default dashboard template picker behavior).
*/
scope?: DashboardTemplatesListScope
}
@@ -8428,6 +8443,7 @@ export type DashboardTemplatesListScope = (typeof DashboardTemplatesListScope)[k
export const DashboardTemplatesListScope = {
FeatureFlag: 'feature_flag',
Global: 'global',
+ Organization: 'organization',
Team: 'team',
} as const
diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.ts
index 5f98d8293204..4063fc104308 100644
--- a/products/dashboards/frontend/generated/api.zod.ts
+++ b/products/dashboards/frontend/generated/api.zod.ts
@@ -31,8 +31,10 @@ export const DashboardTemplatesCreateBody = /* @__PURE__ */ zod.object({
scope: zod
.union([
zod
- .enum(['team', 'global', 'feature_flag'])
- .describe('\* `team` - Only team\n\* `global` - Global\n\* `feature_flag` - Feature Flag'),
+ .enum(['team', 'organization', 'global', 'feature_flag'])
+ .describe(
+ '\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global\n\* `feature_flag` - Feature Flag'
+ ),
zod.enum(['']),
zod.null(),
])
@@ -65,8 +67,10 @@ export const DashboardTemplatesUpdateBody = /* @__PURE__ */ zod.object({
scope: zod
.union([
zod
- .enum(['team', 'global', 'feature_flag'])
- .describe('\* `team` - Only team\n\* `global` - Global\n\* `feature_flag` - Feature Flag'),
+ .enum(['team', 'organization', 'global', 'feature_flag'])
+ .describe(
+ '\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global\n\* `feature_flag` - Feature Flag'
+ ),
zod.enum(['']),
zod.null(),
])
@@ -99,8 +103,10 @@ export const DashboardTemplatesPartialUpdateBody = /* @__PURE__ */ zod.object({
scope: zod
.union([
zod
- .enum(['team', 'global', 'feature_flag'])
- .describe('\* `team` - Only team\n\* `global` - Global\n\* `feature_flag` - Feature Flag'),
+ .enum(['team', 'organization', 'global', 'feature_flag'])
+ .describe(
+ '\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global\n\* `feature_flag` - Feature Flag'
+ ),
zod.enum(['']),
zod.null(),
])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 21618ed4f25d..a282109d3220 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14159,6 +14159,7 @@ export namespace Schemas {
/**
* * `team` - Only team
+ * * `organization` - Organization
* * `global` - Global
* * `feature_flag` - Feature Flag
*/
@@ -14167,10 +14168,20 @@ export namespace Schemas {
export const DashboardTemplateScopeEnum = {
Team: 'team',
+ Organization: 'organization',
Global: 'global',
FeatureFlag: 'feature_flag',
} as const;
+ export interface NonPortableReferences {
+ /** Count of distinct action references in the template's tiles that are specific to the source project. */
+ actions: number;
+ /** Count of distinct cohort references in the template's tiles that are specific to the source project. */
+ cohorts: number;
+ /** Names of data warehouse tables referenced by the template's tiles that are specific to the source project. */
+ warehouse_tables: string[];
+ }
+
export interface DashboardTemplate {
readonly id: string;
/**
@@ -14211,6 +14222,8 @@ export namespace Schemas {
availability_contexts?: string[] | null;
/** Manually curated; used to highlight templates in the UI. */
is_featured?: boolean;
+ /** Read-only. Project-specific references (actions, cohorts, data warehouse tables) embedded in this template's tiles that may not resolve when it is used in another project. Events and properties are matched by name and are portable, so they are not reported here. */
+ readonly non_portable_references: NonPortableReferences;
}
/**
@@ -34270,6 +34283,8 @@ export namespace Schemas {
availability_contexts?: string[] | null;
/** Manually curated; used to highlight templates in the UI. */
is_featured?: boolean;
+ /** Read-only. Project-specific references (actions, cohorts, data warehouse tables) embedded in this template's tiles that may not resolve when it is used in another project. Events and properties are matched by name and are portable, so they are not reported here. */
+ readonly non_portable_references?: NonPortableReferences;
}
export interface PatchedDataColorTheme {
@@ -56359,7 +56374,7 @@ export namespace Schemas {
*/
ordering?: string;
/**
- * Optional. `global`: official templates only. `team`: this project's saved templates only (`scope=team` rows for the current project). `feature_flag`: feature-flag dashboard templates only. Omit for both official and this project's templates (default dashboard template picker behavior).
+ * Optional. `global`: official templates only. `team`: this project's saved templates only (`scope=team` rows for the current project). `organization`: templates shared across all projects in this organization. `feature_flag`: feature-flag dashboard templates only. Omit for official, organization, and this project's templates (default dashboard template picker behavior).
*/
scope?: DashboardTemplatesListScope;
};
@@ -56370,6 +56385,7 @@ export namespace Schemas {
export const DashboardTemplatesListScope = {
FeatureFlag: 'feature_flag',
Global: 'global',
+ Organization: 'organization',
Team: 'team',
} as const;