:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cross-project-dashboards): add the org-scoped dashboards backend (#110111)
Yasen5c144833df7e
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 1c9319957663..201b98f8f5fb 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -977,6 +977,8 @@ rules:|BillingAlertEvent|CIMDVerificationToken|ContextLayerConfig+ |CrossProjectDashboard+ |CrossProjectDashboardTile|DesktopBetaTermsAcceptance|IdentityProviderConfig|LegalDocument@@ -1054,6 +1056,8 @@ rules:|BillingAlertEvent|CIMDVerificationToken|ContextLayerConfig+ |CrossProjectDashboard+ |CrossProjectDashboardTile|DesktopBetaTermsAcceptance|IdentityProviderConfig|LegalDocumentdiff --git a/frontend/package.json b/frontend/package.jsonindex 163959da5ef1..ce80f4c3d70e 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -100,6 +100,7 @@"@posthog/products-cdp": "workspace:*","@posthog/products-cohorts": "workspace:*","@posthog/products-conversations": "workspace:*",+ "@posthog/products-cross-project-dashboards": "workspace:*","@posthog/products-customer-analytics": "workspace:*","@posthog/products-dashboards": "workspace:*","@posthog/products-data-catalog": "workspace:*",diff --git a/frontend/src/lib/agentScopes.generated.ts b/frontend/src/lib/agentScopes.generated.tsindex 36042e9dd512..71952e97a1ed 100644--- a/frontend/src/lib/agentScopes.generated.ts+++ b/frontend/src/lib/agentScopes.generated.ts@@ -34,6 +34,7 @@ export const AGENT_USE_CASE_SCOPES = ['comment:read','comment:write','conversation:read',+ 'cross_project_dashboard:read','customer_analytics:read','customer_analytics:write','customer_task:read',diff --git a/frontend/src/lib/oauthScopes.generated.ts b/frontend/src/lib/oauthScopes.generated.tsindex 7a29cbf5383a..c4dd07009231 100644--- a/frontend/src/lib/oauthScopes.generated.ts+++ b/frontend/src/lib/oauthScopes.generated.ts@@ -46,6 +46,8 @@ export const OAUTH_SCOPES_SUPPORTED = ['comment:write','conversation:read','conversation:write',+ 'cross_project_dashboard:read',+ 'cross_project_dashboard:write','customer_analytics:read','customer_analytics:write','customer_task:read',diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 0c61d05be347..40fef20c435c 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -278,6 +278,7 @@ export const API_SCOPES_OMITTED_FROM_MODAL: Partial<Record<APIScopeObject, strin// Remove from posthog/scopes.py once no PAK/OAuth grant references them.batch_import: 'Pending removal: no endpoint enforces it (its viewset is INTERNAL).',mcp_registry: 'Behind a feature flag.',+ cross_project_dashboard: 'Behind a feature flag.',external_data_schema: 'Pending removal: covered by external_data_source; no viewset uses it.',}@@ -406,6 +407,7 @@ export const API_SCOPE_GROUPS: APIScopeGroup[] = ['insight_variable','dashboard','dashboard_template',+ 'cross_project_dashboard','query','notebook','canvas',diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e4d7a064c037..e7f785f8374e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -701,6 +701,9 @@ importers:'@posthog/products-conversations':specifier: workspace:*version: link:../products/conversations+ '@posthog/products-cross-project-dashboards':+ specifier: workspace:*+ version: link:../products/cross_project_dashboards'@posthog/products-customer-analytics':specifier: workspace:*version: link:../products/customer_analytics@@ -2997,6 +3000,40 @@ importers:products/core_events: {}+ products/cross_project_dashboards:+ dependencies:+ '@posthog/icons':+ specifier: 'catalog:'+ '@types/react':+ specifier: 18.3.27+ version: 18.3.27+ clsx:+ specifier: ^2.1.1+ version: 2.1.1+ kea:+ specifier: 'catalog:'+ version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])+ kea-loaders:+ specifier: 'catalog:'+ version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ kea-router:+ specifier: 'catalog:'+ version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ react:+ specifier: 18.3.1+ version: 18.3.1+ react-grid-layout:+ specifier: ^2.2.4+ devDependencies:+ '@testing-library/react':+ specifier: ^14.3.1+ version: 14.3.1(@types/[email protected])([email protected]([email protected]))([email protected])+ kea-test-utils:+ specifier: 'catalog:'+ version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+products/customer_analytics:dependencies:'@dnd-kit/core':diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex f9da30620ff5..edc8d16bf26c 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -40,6 +40,7 @@ ACTIVITY_LOG_WRITE_FAILURES = Counter(ActivityScope = Literal["Cohort",+ "CrossProjectDashboard","FeatureFlag","Person","Group",@@ -624,6 +625,8 @@ activity_visibility_restrictions: list[dict[str, Any]] = [field_exclusions: dict[AuditableScope, list[str]] = {"AccountView": ["version"],+ # Tiles are edited through their own endpoint, so diffing the reverse relation only reads every tile row.+ "CrossProjectDashboard": ["tiles", "organization"],# The reverse relations are listed because the diff reads each one in full; a scanner's# observations run to millions of rows, and its alerts carry their own audit trail."ReplayScanner": [diff --git a/posthog/scopes.py b/posthog/scopes.pyindex b5c4687d14df..90c5bb7ab0b9 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -39,6 +39,7 @@ APIScopeObject = Literal["comment","conversation","context_layer_internal",+ "cross_project_dashboard","customer_analytics","customer_task","customer_journey",diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 918d4fb51d6f..89499091c28b 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -91,6 +91,7 @@ PRODUCTS_APPS = ["products.metrics.backend.apps.MetricsConfig","products.apm.backend.apps.ApmConfig","products.notifications.backend.apps.NotificationsConfig",+ "products.cross_project_dashboards.backend.apps.CrossProjectDashboardsConfig","products.dashboards.backend.apps.DashboardsConfig","products.messaging.backend.apps.MessagingConfig","products.mcp_analytics.backend.apps.McpAnalyticsConfig",diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex e53f6ae770c8..b7cb8207fe34 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -27,6 +27,7 @@ model_activity:products.alerts.backend.activity_logging.handle_threshold_changemodel_activity:products.annotations.backend.activity_logging.handle_annotation_changemodel_activity:products.batch_exports.backend.activity_logging.handle_batch_export_changemodel_activity:products.business_knowledge.backend.signals.handle_knowledge_source_change+model_activity:products.cross_project_dashboards.backend.activity_logging.handle_cross_project_dashboard_changemodel_activity:products.customer_analytics.backend.activity_logging.handle_account_view_changemodel_activity:products.dashboards.backend.activity_logging.handle_dashboard_changemodel_activity:products.dashboards.backend.activity_logging.handle_dashboard_widget_changediff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex a09b655f7f99..1c046eee0450 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -239,6 +239,8 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.tasks.backend.presentation.views.channels_api.ChannelViewSet","products.tasks.backend.presentation.views.channels_api.TaskActivityViewSet","products.tasks.backend.presentation.views.channels_api.TaskMentionViewSet",+ "products.cross_project_dashboards.backend.presentation.views.CrossProjectDashboardTileViewSet",+ "products.cross_project_dashboards.backend.presentation.views.CrossProjectDashboardViewSet","products.tasks.backend.presentation.views.channels_api.TaskThreadMessageViewSet","products.tasks.backend.presentation.views.config_api.TasksTeamConfigViewSet","products.tasks.backend.presentation.views.config_api.TasksUserConfigViewSet",diff --git a/products/access_control/frontend/generated/api.schemas.ts b/products/access_control/frontend/generated/api.schemas.tsindex 2b3060cd67e2..3fe643fb6cf4 100644--- a/products/access_control/frontend/generated/api.schemas.ts+++ b/products/access_control/frontend/generated/api.schemas.ts@@ -62,6 +62,7 @@ export const ResolvedAccessSourceSubjectEnumApi = {* * `cohort` - cohort* * `comment` - comment* * `conversation` - conversation+ * * `cross_project_dashboard` - cross_project_dashboard* * `customer_analytics` - customer_analytics* * `customer_task` - customer_task* * `customer_journey` - customer_journey@@ -181,6 +182,7 @@ export const ScopeObjectEnumApi = {Cohort: 'cohort',Comment: 'comment',Conversation: 'conversation',+ CrossProjectDashboard: 'cross_project_dashboard',CustomerAnalytics: 'customer_analytics',CustomerTask: 'customer_task',CustomerJourney: 'customer_journey',@@ -323,6 +325,7 @@ export interface ProjectAccessSourceApi {* * `cohort` - cohort* * `comment` - comment* * `conversation` - conversation+ * * `cross_project_dashboard` - cross_project_dashboard* * `customer_analytics` - customer_analytics* * `customer_task` - customer_task* * `customer_journey` - customer_journey@@ -485,6 +488,7 @@ export interface AccessControlObjectRuleApi {* * `cohort` - cohort* * `comment` - comment* * `conversation` - conversation+ * * `cross_project_dashboard` - cross_project_dashboard* * `customer_analytics` - customer_analytics* * `customer_task` - customer_task* * `customer_journey` - customer_journey@@ -872,6 +876,7 @@ export interface AccessControlObjectRuleResourceApi {* * `cohort` - cohort* * `comment` - comment* * `conversation` - conversation+ * * `cross_project_dashboard` - cross_project_dashboard* * `customer_analytics` - customer_analytics* * `customer_task` - customer_task* * `customer_journey` - customer_journey@@ -1137,6 +1142,7 @@ export interface ResolvedAccessApi {* * `cohort` - cohort* * `comment` - comment* * `conversation` - conversation+ * * `cross_project_dashboard` - cross_project_dashboard* * `customer_analytics` - customer_analytics* * `customer_task` - customer_task* * `customer_journey` - customer_journeydiff --git a/products/cross_project_dashboards/__init__.py b/products/cross_project_dashboards/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cross_project_dashboards/backend/__init__.py b/products/cross_project_dashboards/backend/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cross_project_dashboards/backend/activity_logging.py b/products/cross_project_dashboards/backend/activity_logging.pynew file mode 100644index 000000000000..c47157fcfd5f--- /dev/null+++ b/products/cross_project_dashboards/backend/activity_logging.py@@ -0,0 +1,48 @@+"""Activity log wiring for cross_project_dashboards.++Rows are written against the organization with no team, which `ActivityLog` allows: its+constraint requires a team id or an organization id, not both.++Lives here rather than in the viewset so the receiver connects in every process, including the+ones that mutate dashboards outside a web request.+"""++from typing import Any, cast++from posthog.models.activity_logging.activity_log import ActivityScope, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver+from posthog.models.user import User++from products.cross_project_dashboards.backend.models import CrossProjectDashboard+++@mutable_receiver(model_activity_signal, sender=CrossProjectDashboard)+def handle_cross_project_dashboard_change(+ sender: Any,+ scope: str,+ before_update: CrossProjectDashboard | None,+ after_update: CrossProjectDashboard | None,+ activity: str,+ user: User | None,+ was_impersonated: bool = False,+ **kwargs: Any,+) -> None:+ instance = after_update or before_update+ if instance is None:+ return+ # Dashboards are soft-deleted, so the flip of `deleted` is the delete or the restore.+ if before_update is not None and after_update is not None and before_update.deleted != after_update.deleted:+ activity = "deleted" if after_update.deleted else "restored"+ log_activity(+ organization_id=instance.organization_id,+ team_id=None,+ user=user,+ was_impersonated=was_impersonated,+ item_id=instance.id,+ scope=scope,+ activity=activity,+ detail=Detail(+ changes=changes_between(cast(ActivityScope, scope), previous=before_update, current=after_update),+ name=instance.name,+ ),+ )diff --git a/products/cross_project_dashboards/backend/apps.py b/products/cross_project_dashboards/backend/apps.pynew file mode 100644index 000000000000..d1fd72ac8d7f--- /dev/null+++ b/products/cross_project_dashboards/backend/apps.py@@ -0,0 +1,14 @@+"""Django app configuration for cross_project_dashboards."""++from django.apps import AppConfig+++class CrossProjectDashboardsConfig(AppConfig):+ name = "products.cross_project_dashboards.backend"+ label = "cross_project_dashboards"++ def ready(self) -> None:+ # Models are not loaded when this module is imported, so the activity receiver cannot+ # be wired at module level. Dashboards are also mutated outside web requests, so this+ # must connect in every process.+ from products.cross_project_dashboards.backend import activity_logging # noqa: F401, PLC0415diff --git a/products/cross_project_dashboards/backend/facade/__init__.py b/products/cross_project_dashboards/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cross_project_dashboards/backend/facade/api.py b/products/cross_project_dashboards/backend/facade/api.pynew file mode 100644index 000000000000..671d243445a4--- /dev/null+++ b/products/cross_project_dashboards/backend/facade/api.py@@ -0,0 +1,82 @@+"""Facade for cross_project_dashboards. The only module other products and the presentation layer import."""++from typing import Any+from uuid import UUID++from posthog.models import User++from ..logic import dashboards+from ..logic.filters import validate_cross_project_filters as _validate_cross_project_filters+from . import contracts+++def validate_cross_project_filters(filters: Any) -> dict[str, Any]:+ """Return the filters normalized, or raise ValidationError for a filter bound to one project."""+ return _validate_cross_project_filters(filters)+++def list_dashboards(*, organization_id: UUID | str, user: User, offset: int, limit: int) -> contracts.DashboardPage:+ """One page of the organization's dashboards. Each counts only the tiles from projects the user can open."""+ return dashboards.list_dashboards(organization_id=organization_id, user=user, offset=offset, limit=limit)+++def get_dashboard(*, organization_id: UUID | str, dashboard_id: UUID, user: User) -> contracts.CrossProjectDashboard:+ """Raises DashboardNotFoundError."""+ return dashboards.get_dashboard(organization_id=organization_id, dashboard_id=dashboard_id, user=user)+++def create_dashboard(+ *, organization_id: UUID | str, user: User, dashboard: contracts.NewDashboard+) -> contracts.CrossProjectDashboard:+ return dashboards.create_dashboard(organization_id=organization_id, user=user, dashboard=dashboard)+++def update_dashboard(+ *, organization_id: UUID | str, dashboard_id: UUID, user: User, changes: contracts.DashboardChanges+) -> contracts.CrossProjectDashboard:+ """Raises DashboardNotFoundError, or DashboardChangeDeniedError when a tile is in a project the user cannot open."""+ return dashboards.update_dashboard(+ organization_id=organization_id, dashboard_id=dashboard_id, user=user, changes=changes+ )+++def delete_dashboard(*, organization_id: UUID | str, dashboard_id: UUID, user: User) -> None:+ """Soft-deletes the dashboard. Raises DashboardNotFoundError or DashboardChangeDeniedError."""+ dashboards.delete_dashboard(organization_id=organization_id, dashboard_id=dashboard_id, user=user)+++def list_tiles(+ *, organization_id: UUID | str, dashboard_id: UUID, user: User, offset: int, limit: int+) -> contracts.TilePage:+ """One page of the dashboard's tiles from projects the user can open. Empty for a deleted dashboard."""+ return dashboards.list_tiles(+ organization_id=organization_id, dashboard_id=dashboard_id, user=user, offset=offset, limit=limit+ )+++def get_tile(+ *, organization_id: UUID | str, dashboard_id: UUID, tile_id: UUID, user: User+) -> contracts.CrossProjectTile:+ """Raises TileNotFoundError."""+ return dashboards.get_tile(organization_id=organization_id, dashboard_id=dashboard_id, tile_id=tile_id, user=user)+++def create_tile(+ *, organization_id: UUID | str, dashboard_id: UUID, user: User, tile: contracts.NewTile+) -> contracts.CrossProjectTile:+ """Raises DashboardNotFoundError, DashboardChangeDeniedError, or ValidationError when the user cannot view the insight."""+ return dashboards.create_tile(organization_id=organization_id, dashboard_id=dashboard_id, user=user, tile=tile)+++def update_tile(+ *, organization_id: UUID | str, dashboard_id: UUID, tile_id: UUID, user: User, changes: contracts.TileChanges+) -> contracts.CrossProjectTile:+ """Raises TileNotFoundError or DashboardChangeDeniedError. A tile's project and insight never change."""+ return dashboards.update_tile(+ organization_id=organization_id, dashboard_id=dashboard_id, tile_id=tile_id, user=user, changes=changes+ )+++def delete_tile(*, organization_id: UUID | str, dashboard_id: UUID, tile_id: UUID, user: User) -> None:+ """Soft-deletes the tile. Raises TileNotFoundError or DashboardChangeDeniedError."""+ dashboards.delete_tile(organization_id=organization_id, dashboard_id=dashboard_id, tile_id=tile_id, user=user)diff --git a/products/cross_project_dashboards/backend/facade/contracts.py b/products/cross_project_dashboards/backend/facade/contracts.pynew file mode 100644index 000000000000..d31c05892fb4--- /dev/null+++ b/products/cross_project_dashboards/backend/facade/contracts.py@@ -0,0 +1,114 @@+"""Contract types for cross_project_dashboards: what the facade returns to the API and MCP tools.++No Django imports.+"""++from datetime import datetime+from typing import Any+from uuid import UUID++from pydantic.dataclasses import dataclass+++class DashboardNotFoundError(Exception):+ """The dashboard does not exist, is deleted, or belongs to another organization."""+++class DashboardChangeDeniedError(Exception):+ """The dashboard holds tiles from a project the user cannot open, so the user cannot change or delete it."""+++class TileNotFoundError(Exception):+ """The tile does not exist, is deleted, or is in a project the reader cannot open."""+++@dataclass(frozen=True)+class DashboardCreator:+ id: int+ first_name: str+ email: str+++@dataclass(frozen=True)+class CrossProjectTile:+ id: UUID+ project_id: int+ insight_id: int+ layouts: dict[str, Any]+ color: str | None+ filters_overrides: dict[str, Any]+++@dataclass(frozen=True)+class CrossProjectDashboard:+ id: UUID+ name: str+ description: str+ filters: dict[str, Any]+ tiles: list[CrossProjectTile]+ created_by: DashboardCreator | None+ created_at: datetime+ updated_at: datetime | None+++@dataclass(frozen=True)+class CrossProjectDashboardSummary:+ """A list row. It counts the tiles instead of carrying them, so a page stays small."""++ id: UUID+ name: str+ description: str+ filters: dict[str, Any]+ tile_count: int+ project_count: int+ created_by: DashboardCreator | None+ created_at: datetime+ updated_at: datetime | None+++@dataclass(frozen=True)+class DashboardPage:+ results: list[CrossProjectDashboardSummary]+ count: int+++@dataclass(frozen=True)+class TilePage:+ results: list[CrossProjectTile]+ count: int+++@dataclass(frozen=True)+class NewDashboard:+ name: str+ description: str+ filters: dict[str, Any]+++@dataclass(frozen=True)+class DashboardChanges:+ """A partial update. Only the fields named in `fields` change."""++ fields: frozenset[str]+ name: str = ""+ description: str = ""+ filters: dict[str, Any] | None = None+++@dataclass(frozen=True)+class NewTile:+ project_id: int+ insight_id: int+ layouts: dict[str, Any]+ color: str | None+ filters_overrides: dict[str, Any]+++@dataclass(frozen=True)+class TileChanges:+ """A partial update. Only the fields named in `fields` change, so a tile's color can be set to null."""++ fields: frozenset[str]+ layouts: dict[str, Any] | None = None+ color: str | None = None+ filters_overrides: dict[str, Any] | None = Nonediff --git a/products/cross_project_dashboards/backend/facade/enums.py b/products/cross_project_dashboards/backend/facade/enums.pynew file mode 100644index 000000000000..34e167626d15--- /dev/null+++ b/products/cross_project_dashboards/backend/facade/enums.py@@ -0,0 +1,9 @@+"""+Exported enums for cross_project_dashboards.++If an enum appears in a contract dataclass field, it belongs here.+Internal-only constants (DB magic values, feature flags) stay in+the implementation (logic/, models.py).++Nothing is exported yet: no other product consumes this one.+"""diff --git a/products/cross_project_dashboards/backend/logic/__init__.py b/products/cross_project_dashboards/backend/logic/__init__.pynew file mode 100644index 000000000000..ad9da222c263--- /dev/null+++ b/products/cross_project_dashboards/backend/logic/__init__.py@@ -0,0 +1,6 @@+"""Business logic for cross_project_dashboards."""++from products.cross_project_dashboards.backend.logic.access import assert_can_reference_insight, visible_project_ids+from products.cross_project_dashboards.backend.logic.filters import validate_cross_project_filters++__all__ = ["assert_can_reference_insight", "validate_cross_project_filters", "visible_project_ids"]diff --git a/products/cross_project_dashboards/backend/logic/access.py b/products/cross_project_dashboards/backend/logic/access.pynew file mode 100644index 000000000000..521d69d19654--- /dev/null+++ b/products/cross_project_dashboards/backend/logic/access.py@@ -0,0 +1,53 @@+"""Access rules for referencing another project's insight from a cross-project dashboard."""++from typing import cast+from uuid import UUID++from rest_framework import serializers++from posthog.models import Organization, Team, User+from posthog.user_permissions import UserPermissions++from products.access_control.backend.facade.user_access_control import UserAccessControl, visible_teams_for_user+from products.product_analytics.backend.facade.api import user_can_view_insight++NOT_AVAILABLE = "That insight is not available to you."+++def visible_project_ids(user: User, organization_id: UUID | str) -> list[int]:+ """Projects in the organization the user may open, by both access-control systems, as the project list applies them."""+ organization = Organization.objects.get(id=organization_id)+ teams = visible_teams_for_user(+ organization,+ UserAccessControl(user=user, organization_id=str(organization_id)),+ UserPermissions(user=user),+ )+ return list(teams.values_list("id", flat=True))+++def assert_can_reference_insight(user: User, organization_id: UUID | str, project_id: int, insight_id: int) -> None:+ """Allow a tile to reference an insight only when the user can already view it.++ This is a usability rule, not the security boundary. Every reader fetches each tile from+ that project's own insight endpoint, which enforces their own access independently.+ """+ # A dashboard references only its own organization's projects. A credential scoped to that+ # organization then cannot use a tile to probe a project in another one.+ team = Team.objects.filter(pk=project_id, organization_id=organization_id).first()+ if team is None:+ raise serializers.ValidationError({"project_id": NOT_AVAILABLE})++ # The project endpoints let an explicit member denial win over an allow for everyone, and+ # the legacy access resolution below does not, so both have to pass.+ if UserPermissions(user=user).team(team).effective_membership_level is None:+ raise serializers.ValidationError({"project_id": NOT_AVAILABLE})++ user_access_control = UserAccessControl(user=cast(User, user), team=team)++ # Resource and object rules fall back to a permissive default, so on their own they grant+ # access in a project the user was explicitly denied. Project access is a separate check.+ if not user_access_control.has_project_access:+ raise serializers.ValidationError({"project_id": NOT_AVAILABLE})++ if not user_can_view_insight(team=team, user=user, insight_id=insight_id):+ raise serializers.ValidationError({"insight_id": NOT_AVAILABLE})diff --git a/products/cross_project_dashboards/backend/logic/dashboards.py b/products/cross_project_dashboards/backend/logic/dashboards.pynew file mode 100644index 000000000000..30fdfacdc11e--- /dev/null+++ b/products/cross_project_dashboards/backend/logic/dashboards.py@@ -0,0 +1,360 @@+"""Reads and writes of cross-project dashboards and their tiles, mapped to contracts."""++from typing import Any+from uuid import UUID++from django.db import IntegrityError, transaction+from django.db.models import Count, Exists, OuterRef, Prefetch, Q, QuerySet++from rest_framework import serializers++from posthog.models import Team, User+from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.models.activity_logging.model_activity import get_was_impersonated++from products.cross_project_dashboards.backend.facade import contracts+from products.cross_project_dashboards.backend.logic.access import assert_can_reference_insight, visible_project_ids+from products.cross_project_dashboards.backend.models import CrossProjectDashboard, CrossProjectDashboardTile++DUPLICATE_TILE = "That insight is already on this dashboard."+# Bounds what one dashboard page can carry, since every page embeds each dashboard's tiles.+MAX_TILES_PER_DASHBOARD = 100+TOO_MANY_TILES = f"A dashboard holds at most {MAX_TILES_PER_DASHBOARD} tiles. Remove one before adding another."+++# Layouts change on every drag, so only these tile fields reach the activity log.+AUDITED_TILE_FIELDS = ("color", "filters_overrides")+++def _tile_reference(tile: CrossProjectDashboardTile) -> dict[str, str]:+ # Any organization member can read the activity log, so the entry names the tile only. The+ # project, the insight and the filter values stay hidden from members denied that project.+ return {"tile_id": str(tile.id)}+++def _log_tile_change(dashboard: CrossProjectDashboard, user: User, change: Change) -> None:+ # Tiles are written through their own endpoint, so the dashboard's model receiver never sees+ # them. Each change is logged on the parent dashboard so it shows in that dashboard's history.+ log_activity(+ organization_id=dashboard.organization_id,+ team_id=None,+ user=user,+ was_impersonated=get_was_impersonated(),+ item_id=dashboard.id,+ scope="CrossProjectDashboard",+ activity="updated",+ detail=Detail(name=dashboard.name, changes=[change]),+ # Written inside the tile's transaction, so a failed audit insert rolls the tile change back.+ strict=True,+ )+++def _to_tile(tile: CrossProjectDashboardTile) -> contracts.CrossProjectTile:+ if not tile.project_exists: # type: ignore[attr-defined]+ # Nobody can open a project that is gone, so nobody may read what was saved for it. That+ # includes the members who were denied the project before it was deleted or moved out of+ # the organization. The tile keeps only what the dashboard needs to place and remove it.+ return contracts.CrossProjectTile(+ id=tile.id,+ project_id=tile.project_id,+ insight_id=tile.insight_id,+ layouts=tile.layouts or {},+ color=None,+ filters_overrides={},+ )+ return contracts.CrossProjectTile(+ id=tile.id,+ project_id=tile.project_id,+ insight_id=tile.insight_id,+ layouts=tile.layouts or {},+ color=tile.color,+ filters_overrides=tile.filters_overrides or {},+ )+++def _creator(dashboard: CrossProjectDashboard) -> contracts.DashboardCreator | None:+ creator = dashboard.created_by+ if creator is None:+ return None+ return contracts.DashboardCreator(id=creator.id, first_name=creator.first_name, email=creator.email)+++def _to_summary(dashboard: CrossProjectDashboard) -> contracts.CrossProjectDashboardSummary:+ return contracts.CrossProjectDashboardSummary(+ id=dashboard.id,+ name=dashboard.name,+ description=dashboard.description,+ filters=dashboard.filters or {},+ tile_count=dashboard.visible_tile_count, # type: ignore[attr-defined]+ project_count=dashboard.visible_project_count, # type: ignore[attr-defined]+ created_by=_creator(dashboard),+ created_at=dashboard.created_at,+ updated_at=dashboard.updated_at,+ )+++def _to_dashboard(dashboard: CrossProjectDashboard) -> contracts.CrossProjectDashboard:+ return contracts.CrossProjectDashboard(+ id=dashboard.id,+ name=dashboard.name,+ description=dashboard.description,+ filters=dashboard.filters or {},+ # Filled by the visible_tiles prefetch, so the reader never sees a tile they cannot open.+ tiles=[_to_tile(tile) for tile in dashboard.visible_tiles], # type: ignore[attr-defined]+ created_by=_creator(dashboard),+ created_at=dashboard.created_at,+ updated_at=dashboard.updated_at,+ )+++def _existing_projects(organization_id: UUID | str) -> QuerySet[Team, dict[str, Any]]:+ return Team.objects.filter(organization_id=organization_id).values("id")+++def _readable_tiles(organization_id: UUID | str, user: User) -> Q:+ """Tiles from projects the user can open, plus tiles whose project no longer exists.++ A deleted project names nothing anyone can open, so every member sees its tile as gone and can+ remove it. Hiding it would leave it on the dashboard for good.+ """+ return Q(project_id__in=visible_project_ids(user, organization_id)) | ~Q(+ project_id__in=_existing_projects(organization_id)+ )+++def _readable_tile_rows(organization_id: UUID | str, user: User) -> QuerySet[CrossProjectDashboardTile]:+ # _to_tile reads project_exists, so every tile it maps must come from this queryset.+ return CrossProjectDashboardTile.objects.filter(_readable_tiles(organization_id, user), deleted=False).annotate(+ project_exists=Exists(_existing_projects(organization_id).filter(id=OuterRef("project_id")))+ )+++def _dashboards(organization_id: UUID | str, user: User) -> QuerySet[CrossProjectDashboard]:+ tiles = _readable_tile_rows(organization_id, user).order_by("created_at", "id")+ return (+ CrossProjectDashboard.objects.filter(organization_id=organization_id, deleted=False)+ .select_related("created_by")+ .prefetch_related(Prefetch("tiles", queryset=tiles, to_attr="visible_tiles"))+ .order_by("-created_at", "-id")+ )+++def _dashboard_row(organization_id: UUID | str, dashboard_id: UUID, user: User) -> CrossProjectDashboard:+ dashboard = _dashboards(organization_id, user).filter(id=dashboard_id).first()+ if dashboard is None:+ raise contracts.DashboardNotFoundError()+ return dashboard+++def _assert_can_change(organization_id: UUID | str, dashboard: CrossProjectDashboard, user: User) -> None:+ # Reads hide the tiles from a project the user is denied, so writes must not let that user+ # rename, re-filter or delete those tiles for the readers who can see them.+ referenced = set(+ CrossProjectDashboardTile.objects.filter(dashboard=dashboard, deleted=False).values_list(+ "project_id", flat=True+ )+ )+ # A tile whose project was deleted protects nothing, so it never blocks a change.+ still_existing = set(+ Team.objects.filter(organization_id=organization_id, id__in=referenced).values_list("id", flat=True)+ )+ if not still_existing <= set(visible_project_ids(user, organization_id)):+ raise contracts.DashboardChangeDeniedError()+++def _lock_for_change(organization_id: UUID | str, dashboard_id: UUID, user: User) -> CrossProjectDashboard:+ """Lock the dashboard row, then check the write rule. Call it inside transaction.atomic().++ The lock keeps a concurrent tile add from changing the set of projects between the check and+ the write.+ """+ dashboard = (+ CrossProjectDashboard.objects.select_for_update()+ .filter(id=dashboard_id, organization_id=organization_id, deleted=False)+ .first()+ )+ if dashboard is None:+ raise contracts.DashboardNotFoundError()+ _assert_can_change(organization_id, dashboard, user)+ return dashboard+++def _tiles(organization_id: UUID | str, dashboard_id: UUID, user: User) -> QuerySet[CrossProjectDashboardTile]:+ # A reader denied a project does not learn which of its insights the dashboard references.+ return (+ _readable_tile_rows(organization_id, user)+ .filter(organization_id=organization_id, dashboard_id=dashboard_id, dashboard__deleted=False)+ .select_related("dashboard")+ .order_by("created_at", "id")+ )+++def _tile_row(organization_id: UUID | str, dashboard_id: UUID, tile_id: UUID, user: User) -> CrossProjectDashboardTile:+ tile = _tiles(organization_id, dashboard_id, user).filter(id=tile_id).first()+ if tile is None:+ raise contracts.TileNotFoundError()+ return tile+++def _lock_tile_for_change(+ organization_id: UUID | str, dashboard_id: UUID, tile_id: UUID, user: User+) -> tuple[CrossProjectDashboardTile, CrossProjectDashboard]:+ """Lock the dashboard, check the write rule, then read the tile again under that lock.++ Reading the tile after the lock means a tile another request removed while this one waited is+ a 404, not a write to a deleted row. Call it inside transaction.atomic().+ """+ _tile_row(organization_id, dashboard_id, tile_id, user)+ try:+ dashboard = _lock_for_change(organization_id, dashboard_id, user)+ except contracts.DashboardNotFoundError as error:+ raise contracts.TileNotFoundError() from error+ tile = _tiles(organization_id, dashboard_id, user).select_for_update(of=("self",)).filter(id=tile_id).first()+ if tile is None:+ raise contracts.TileNotFoundError()+ return tile, dashboard+++def list_dashboards(*, organization_id: UUID | str, user: User, offset: int, limit: int) -> contracts.DashboardPage:+ readable = Q(tiles__project_id__in=visible_project_ids(user, organization_id)) | ~Q(+ tiles__project_id__in=_existing_projects(organization_id)+ )+ visible = Q(tiles__deleted=False) & readable+ dashboards = (+ CrossProjectDashboard.objects.filter(organization_id=organization_id, deleted=False)+ .select_related("created_by")+ .annotate(+ visible_tile_count=Count("tiles", filter=visible),+ visible_project_count=Count("tiles__project_id", filter=visible, distinct=True),+ )+ .order_by("-created_at", "-id")+ )+ page = dashboards[offset : offset + limit]+ return contracts.DashboardPage(results=[_to_summary(dashboard) for dashboard in page], count=dashboards.count())+++def get_dashboard(*, organization_id: UUID | str, dashboard_id: UUID, user: User) -> contracts.CrossProjectDashboard:+ return _to_dashboard(_dashboard_row(organization_id, dashboard_id, user))+++def create_dashboard(+ *, organization_id: UUID | str, user: User, dashboard: contracts.NewDashboard+) -> contracts.CrossProjectDashboard:+ created = CrossProjectDashboard.objects.create(+ organization_id=organization_id,+ created_by=user,+ name=dashboard.name,+ description=dashboard.description,+ filters=dashboard.filters,+ )+ return get_dashboard(organization_id=organization_id, dashboard_id=created.id, user=user)+++def update_dashboard(+ *, organization_id: UUID | str, dashboard_id: UUID, user: User, changes: contracts.DashboardChanges+) -> contracts.CrossProjectDashboard:+ with transaction.atomic():+ dashboard = _lock_for_change(organization_id, dashboard_id, user)+ updated = [name for name in ("name", "description", "filters") if name in changes.fields]+ for name in updated:+ setattr(dashboard, name, getattr(changes, name))+ if updated:+ dashboard.save(update_fields=[*updated, "updated_at"])+ return get_dashboard(organization_id=organization_id, dashboard_id=dashboard_id, user=user)+++def delete_dashboard(*, organization_id: UUID | str, dashboard_id: UUID, user: User) -> None:+ with transaction.atomic():+ dashboard = _lock_for_change(organization_id, dashboard_id, user)+ dashboard.deleted = True+ dashboard.save(update_fields=["deleted"])+++def list_tiles(+ *, organization_id: UUID | str, dashboard_id: UUID, user: User, offset: int, limit: int+) -> contracts.TilePage:+ tiles = _tiles(organization_id, dashboard_id, user)+ page = tiles[offset : offset + limit]+ return contracts.TilePage(results=[_to_tile(tile) for tile in page], count=tiles.count())+++def get_tile(+ *, organization_id: UUID | str, dashboard_id: UUID, tile_id: UUID, user: User+) -> contracts.CrossProjectTile:+ return _to_tile(_tile_row(organization_id, dashboard_id, tile_id, user))+++def create_tile(+ *, organization_id: UUID | str, dashboard_id: UUID, user: User, tile: contracts.NewTile+) -> contracts.CrossProjectTile:+ live = CrossProjectDashboard.objects.filter(id=dashboard_id, organization_id=organization_id, deleted=False)+ if not live.exists():+ raise contracts.DashboardNotFoundError()+ assert_can_reference_insight(user, organization_id, tile.project_id, tile.insight_id)+ # The dashboard row is the lock, so two concurrent creates cannot both pass the tile ceiling.+ with transaction.atomic():+ dashboard = _lock_for_change(organization_id, dashboard_id, user)+ if (+ CrossProjectDashboardTile.objects.filter(dashboard=dashboard, deleted=False).count()+ >= MAX_TILES_PER_DASHBOARD+ ):+ raise serializers.ValidationError({"insight_id": TOO_MANY_TILES})+ try:+ # The savepoint keeps a duplicate from breaking the enclosing transaction.+ with transaction.atomic():+ created = CrossProjectDashboardTile.objects.create(+ dashboard=dashboard,+ organization_id=dashboard.organization_id,+ created_by=user,+ project_id=tile.project_id,+ insight_id=tile.insight_id,+ layouts=tile.layouts,+ color=tile.color,+ filters_overrides=tile.filters_overrides,+ )+ except IntegrityError as error:+ raise serializers.ValidationError({"insight_id": DUPLICATE_TILE}) from error+ _log_tile_change(+ dashboard,+ user,+ Change(type="CrossProjectDashboardTile", action="created", field="tiles", after=_tile_reference(created)),+ )+ return get_tile(organization_id=organization_id, dashboard_id=dashboard_id, tile_id=created.id, user=user)+++def update_tile(+ *, organization_id: UUID | str, dashboard_id: UUID, tile_id: UUID, user: User, changes: contracts.TileChanges+) -> contracts.CrossProjectTile:+ with transaction.atomic():+ tile, dashboard = _lock_tile_for_change(organization_id, dashboard_id, tile_id, user)+ updated = [name for name in ("layouts", "color", "filters_overrides") if name in changes.fields]+ before = {name: getattr(tile, name) for name in AUDITED_TILE_FIELDS}+ for name in updated:+ setattr(tile, name, getattr(changes, name))+ if updated:+ tile.save(update_fields=[*updated, "updated_at"])+ changed = [name for name in AUDITED_TILE_FIELDS if before[name] != getattr(tile, name)]+ if changed:+ _log_tile_change(+ dashboard,+ user,+ Change(+ type="CrossProjectDashboardTile",+ action="changed",+ field="tiles",+ after={**_tile_reference(tile), "changed_fields": changed},+ ),+ )+ return _to_tile(tile)+++def delete_tile(*, organization_id: UUID | str, dashboard_id: UUID, tile_id: UUID, user: User) -> None:+ with transaction.atomic():+ tile, dashboard = _lock_tile_for_change(organization_id, dashboard_id, tile_id, user)+ tile.deleted = True+ tile.save(update_fields=["deleted"])+ _log_tile_change(+ dashboard,+ user,+ Change(type="CrossProjectDashboardTile", action="deleted", field="tiles", before=_tile_reference(tile)),+ )diff --git a/products/cross_project_dashboards/backend/logic/filters.py b/products/cross_project_dashboards/backend/logic/filters.pynew file mode 100644index 000000000000..de63d5b3ad06--- /dev/null+++ b/products/cross_project_dashboards/backend/logic/filters.py@@ -0,0 +1,69 @@+"""Validation for dashboard-level filters on a cross-project dashboard.++A cross-project dashboard applies one filter set to tiles in several projects. Only filters+whose meaning survives that hop are allowed. A filter carrying an identifier means something+different in every project, so it is refused rather than dropped: a dropped filter produces a+plausible wrong number instead of an error.+"""++from typing import Any++from rest_framework import serializers++from posthog.hogql_queries.apply_dashboard_filters import (+ flatten_property_leaves,+ normalize_dashboard_filters_properties,+)++# Filter types that name a property, which resolves the same way in every project. Everything else+# is refused, including a filter with no type, because the schema reads a type-less leaf as a cohort.+NAME_BASED_PROPERTY_TYPES = frozenset({"event", "person", "element", "session", "event_metadata"})++# A breakdown with no type is an event breakdown, so None is allowed here.+NAME_BASED_BREAKDOWN_TYPES = frozenset({None, "event", "person", "session", "event_metadata"})++REFUSAL = (+ "This filter only works inside one project, so a cross-project dashboard cannot apply it. "+ "Use a date range, an interval, or a property filter that refers to a property by name."+)+++def validate_cross_project_filters(filters: Any) -> dict[str, Any]:+ """Return the filters with grouped properties flattened, or raise ValidationError when a filter+ cannot cross a project boundary.++ The insight endpoint flattens AND property groups before it applies them, so a project-bound+ leaf inside a group is refused here the same as a top-level one.+ """+ if filters is None or filters == {}:+ return {}+ if not isinstance(filters, dict):+ raise serializers.ValidationError("Filters must be a dictionary.")++ try:+ normalized = normalize_dashboard_filters_properties(filters)+ leaves = flatten_property_leaves(normalized.get("properties"))+ except ValueError as error:+ raise serializers.ValidationError({"properties": str(error)}) from error++ for property_filter in leaves:+ property_type = property_filter.get("type")+ if property_type not in NAME_BASED_PROPERTY_TYPES:+ raise serializers.ValidationError({"properties": f"{property_type or 'untyped'}: {REFUSAL}"})++ breakdown = normalized.get("breakdown_filter")+ if isinstance(breakdown, dict):+ if breakdown.get("breakdown_type") not in NAME_BASED_BREAKDOWN_TYPES:+ raise serializers.ValidationError({"breakdown_filter": REFUSAL})+ if breakdown.get("breakdown_group_type_index") is not None:+ raise serializers.ValidationError({"breakdown_filter": REFUSAL})+ breakdowns = breakdown.get("breakdowns") or []+ if not isinstance(breakdowns, list):+ raise serializers.ValidationError({"breakdown_filter": "Breakdowns must be a list."})+ for item in breakdowns:+ if isinstance(item, dict) and (+ item.get("type") not in NAME_BASED_BREAKDOWN_TYPES or item.get("group_type_index") is not None+ ):+ raise serializers.ValidationError({"breakdown_filter": REFUSAL})++ return normalizeddiff --git a/products/cross_project_dashboards/backend/migrations/0001_initial.py b/products/cross_project_dashboards/backend/migrations/0001_initial.pynew file mode 100644index 000000000000..5f75c92f0d16--- /dev/null+++ b/products/cross_project_dashboards/backend/migrations/0001_initial.py@@ -0,0 +1,115 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ("posthog", "0001_squash_2026_09_07_initial"),+ ]++ operations = [+ migrations.CreateModel(+ name="CrossProjectDashboard",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True, blank=True)),+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("name", models.CharField(max_length=400)),+ ("description", models.TextField(blank=True, default="")),+ ("deleted", models.BooleanField(default=False)),+ ("filters", models.JSONField(blank=True, default=dict)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "organization",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.organization",+ ),+ ),+ ],+ options={"abstract": False},+ ),+ migrations.CreateModel(+ name="CrossProjectDashboardTile",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True, blank=True)),+ (+ "id",+ models.UUIDField(default=posthog.uuidt.uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("project_id", models.BigIntegerField()),+ ("insight_id", models.BigIntegerField()),+ ("layouts", models.JSONField(blank=True, default=dict)),+ ("color", models.CharField(blank=True, max_length=400, null=True)),+ ("filters_overrides", models.JSONField(blank=True, default=dict)),+ ("deleted", models.BooleanField(default=False)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "dashboard",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="tiles",+ to="cross_project_dashboards.crossprojectdashboard",+ ),+ ),+ (+ "organization",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.organization",+ ),+ ),+ ],+ options={"abstract": False},+ ),+ migrations.AddIndex(+ model_name="crossprojectdashboard",+ index=models.Index(fields=["organization", "deleted"], name="cpd_org_deleted_idx"),+ ),+ migrations.AddIndex(+ model_name="crossprojectdashboardtile",+ index=models.Index(fields=["dashboard", "deleted"], name="cpd_tile_dash_deleted_idx"),+ ),+ migrations.AddConstraint(+ model_name="crossprojectdashboardtile",+ constraint=models.UniqueConstraint(+ condition=models.Q(("deleted", False)),+ fields=("dashboard", "project_id", "insight_id"),+ name="unique_live_tile_per_dashboard_insight",+ ),+ ),+ ]diff --git a/products/cross_project_dashboards/backend/migrations/__init__.py b/products/cross_project_dashboards/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cross_project_dashboards/backend/migrations/max_migration.txt b/products/cross_project_dashboards/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..cbab66dde92a--- /dev/null+++ b/products/cross_project_dashboards/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_initialdiff --git a/products/cross_project_dashboards/backend/models.py b/products/cross_project_dashboards/backend/models.pynew file mode 100644index 000000000000..a8a13b7c8a6a--- /dev/null+++ b/products/cross_project_dashboards/backend/models.py@@ -0,0 +1,82 @@+"""+Django models for cross_project_dashboards.++These models are organization-scoped, not team-scoped, so they do not use+`TeamScopedRootMixin`. A cross-project dashboard spans several projects by design, so scoping+its reads to one team would break it. `check-idor-model-coverage.py` classifies a model with+an `organization` FK and no `team` FK as org_scoped.++Keep models thin — business logic belongs in logic/.+"""++from django.db import models++from posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel, sane_repr+++class CrossProjectDashboard(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):+ """A dashboard the organization owns, holding insights from several projects."""++ # Keys to hot parent tables carry no database constraint, so creating this table takes no lock+ # on them, and no reverse accessor, so this product adds nothing to the parent classes.+ organization = models.ForeignKey(+ "posthog.Organization", on_delete=models.CASCADE, related_name="+", db_constraint=False+ )+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ name = models.CharField(max_length=400)+ description = models.TextField(blank=True, default="")+ deleted = models.BooleanField(default=False)+ filters = models.JSONField(default=dict, blank=True)++ __repr__ = sane_repr("id", "organization_id", "name")++ class Meta:+ indexes = [models.Index(fields=["organization", "deleted"], name="cpd_org_deleted_idx")]++ def __str__(self) -> str:+ return self.name+++class CrossProjectDashboardTile(CreatedMetaFields, UpdatedMetaFields, UUIDModel):+ """One insight from one project, placed on a cross-project dashboard.++ `project_id` and `insight_id` are plain integers, not foreign keys. A foreign key cascades,+ so deleting a project would delete the tile and leave no trace of what was there. Plain+ integers let the tile survive and report that its source is gone.++ The column is `project_id`, never `team_id`. `check-idor-model-coverage.py` treats a non-FK+ `team_id` column as team-scoped, which would require a manager that scopes reads to one team.+ """++ dashboard = models.ForeignKey(CrossProjectDashboard, on_delete=models.CASCADE, related_name="tiles")+ # Denormalized from the dashboard so this table classifies as org-scoped on its own.+ organization = models.ForeignKey(+ "posthog.Organization", on_delete=models.CASCADE, related_name="+", db_constraint=False+ )+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False+ )+ project_id = models.BigIntegerField()+ insight_id = models.BigIntegerField()+ layouts = models.JSONField(default=dict, blank=True)+ color = models.CharField(max_length=400, null=True, blank=True)+ filters_overrides = models.JSONField(default=dict, blank=True)+ deleted = models.BooleanField(default=False)++ __repr__ = sane_repr("id", "dashboard_id", "project_id", "insight_id")++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["dashboard", "project_id", "insight_id"],+ condition=models.Q(deleted=False),+ name="unique_live_tile_per_dashboard_insight",+ )+ ]+ indexes = [models.Index(fields=["dashboard", "deleted"], name="cpd_tile_dash_deleted_idx")]++ def __str__(self) -> str:+ return f"insight {self.insight_id} from project {self.project_id}"diff --git a/products/cross_project_dashboards/backend/presentation/__init__.py b/products/cross_project_dashboards/backend/presentation/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cross_project_dashboards/backend/presentation/serializers.py b/products/cross_project_dashboards/backend/presentation/serializers.pynew file mode 100644index 000000000000..71b63d179ac7--- /dev/null+++ b/products/cross_project_dashboards/backend/presentation/serializers.py@@ -0,0 +1,125 @@+"""DRF serializers for cross_project_dashboards. They convert JSON to and from facade contracts."""++import json+from typing import Any++from rest_framework import serializers++from ..facade.api import validate_cross_project_filters++TILE_FILTERS_HELP = (+ "Filters applied to this tile only, overriding the dashboard's. Supports a date range and an interval. "+ "Filters carrying a project-specific id are rejected."+)+# Every list page carries these blobs, so each one has a size ceiling.+MAX_DASHBOARD_FILTERS_BYTES = 16_384+MAX_TILE_JSON_BYTES = 4_096+++def _within(value: Any, max_bytes: int) -> Any:+ if len(json.dumps(value)) > max_bytes:+ raise serializers.ValidationError(f"Keep this under {max_bytes} bytes.")+ return value+++DASHBOARD_FILTERS_HELP = (+ "Dashboard-level filters applied to every tile. Supports a date range, an interval, and property filters "+ "that refer to a property by name. Filters carrying a project-specific id are rejected."+)+++class CrossProjectDashboardTileSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True, help_text="Id of the tile.")+ project_id = serializers.IntegerField(help_text="Id of the project the tile's insight belongs to.")+ insight_id = serializers.IntegerField(help_text="Id of the insight the tile renders.")+ layouts = serializers.JSONField(default=dict, help_text="Grid position and size of the tile, keyed by layout size.")+ color = serializers.CharField(+ default=None, allow_null=True, allow_blank=True, max_length=400, help_text="Optional color applied to the tile."+ )+ filters_overrides = serializers.JSONField(default=dict, help_text=TILE_FILTERS_HELP)++ def validate_layouts(self, value: Any) -> dict[str, Any]:+ if not isinstance(value, dict):+ raise serializers.ValidationError("Layouts must be an object keyed by layout size.")+ return _within(value, MAX_TILE_JSON_BYTES)++ def validate_filters_overrides(self, value: Any) -> dict[str, Any]:+ return validate_cross_project_filters(_within(value, MAX_TILE_JSON_BYTES))+++class CrossProjectDashboardTileUpdateSerializer(serializers.Serializer):+ """A tile's project and insight never change, so an update carries only its placement and styling."""++ layouts = serializers.JSONField(+ required=False, help_text="Grid position and size of the tile, keyed by layout size."+ )+ color = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ max_length=400,+ help_text="Optional color applied to the tile.",+ )+ filters_overrides = serializers.JSONField(required=False, help_text=TILE_FILTERS_HELP)++ def validate_layouts(self, value: Any) -> dict[str, Any]:+ if not isinstance(value, dict):+ raise serializers.ValidationError("Layouts must be an object keyed by layout size.")+ return _within(value, MAX_TILE_JSON_BYTES)++ def validate_filters_overrides(self, value: Any) -> dict[str, Any]:+ return validate_cross_project_filters(_within(value, MAX_TILE_JSON_BYTES))+++class CrossProjectDashboardCreatorSerializer(serializers.Serializer):+ id = serializers.IntegerField(read_only=True, help_text="Id of the user who created the dashboard.")+ first_name = serializers.CharField(read_only=True, help_text="First name of the user who created the dashboard.")+ email = serializers.EmailField(read_only=True, help_text="Email of the user who created the dashboard.")+++class CrossProjectDashboardListItemSerializer(serializers.Serializer):+ """A dashboard in the list. It counts its tiles instead of carrying them; read one dashboard for its tiles."""++ id = serializers.UUIDField(read_only=True, help_text="Id of the dashboard.")+ name = serializers.CharField(read_only=True, help_text="Name shown in the dashboard list and page header.")+ description = serializers.CharField(read_only=True, help_text="Optional longer description.")+ filters = serializers.JSONField(read_only=True, help_text=DASHBOARD_FILTERS_HELP)+ tile_count = serializers.IntegerField(read_only=True, help_text="Tiles from the projects the reader can open.")+ project_count = serializers.IntegerField(+ read_only=True, help_text="Distinct projects among the tiles the reader can open."+ )+ created_by = CrossProjectDashboardCreatorSerializer(+ read_only=True, allow_null=True, help_text="The user who created the dashboard."+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When the dashboard was created.")+ updated_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="When the dashboard last changed."+ )+++class CrossProjectDashboardSerializer(serializers.Serializer):+ """Carries tile references only.++ The response holds no insight names, queries or results. Each reader fetches each tile from+ that tile's own project endpoint, so their access, quota and cache key stay correct there.+ """++ id = serializers.UUIDField(read_only=True, help_text="Id of the dashboard.")+ name = serializers.CharField(max_length=400, help_text="Name shown in the dashboard list and page header.")+ description = serializers.CharField(+ allow_blank=True, default="", max_length=4000, help_text="Optional longer description."+ )+ filters = serializers.JSONField(default=dict, help_text=DASHBOARD_FILTERS_HELP)+ tiles = CrossProjectDashboardTileSerializer(+ many=True, read_only=True, help_text="Tiles from the projects the reader can open."+ )+ created_by = CrossProjectDashboardCreatorSerializer(+ read_only=True, allow_null=True, help_text="The user who created the dashboard."+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When the dashboard was created.")+ updated_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="When the dashboard last changed."+ )++ def validate_filters(self, value: Any) -> dict[str, Any]:+ return validate_cross_project_filters(_within(value, MAX_DASHBOARD_FILTERS_BYTES))diff --git a/products/cross_project_dashboards/backend/presentation/views.py b/products/cross_project_dashboards/backend/presentation/views.pynew file mode 100644index 000000000000..1da445d523a8--- /dev/null+++ b/products/cross_project_dashboards/backend/presentation/views.py@@ -0,0 +1,264 @@+"""DRF views for cross_project_dashboards. They read the request, call the facade and serialize the result."""++from typing import Any, cast+from uuid import UUID++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, extend_schema+from rest_framework import status, viewsets+from rest_framework.exceptions import NotFound, PermissionDenied+from rest_framework.pagination import LimitOffsetPagination+from rest_framework.permissions import BasePermission+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.models import User+from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids++from ..facade import api, contracts+from .serializers import (+ CrossProjectDashboardListItemSerializer,+ CrossProjectDashboardSerializer,+ CrossProjectDashboardTileSerializer,+ CrossProjectDashboardTileUpdateSerializer,+)++CHANGE_DENIED = "This dashboard has tiles from a project you cannot open, so you cannot change or delete it."+DASHBOARD_ID = OpenApiParameter("id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Id of the dashboard.")+PARENT_DASHBOARD_ID = OpenApiParameter(+ "dashboard_id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Id of the dashboard."+)+TILE_ID = OpenApiParameter("id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Id of the tile.")+++def _uuid(value: str) -> UUID:+ try:+ return UUID(value)+ except ValueError:+ raise NotFound()+++class CrossProjectDashboardPagination(LimitOffsetPagination):+ # The shared paginator has no ceiling, so ?limit= could ask a single request for every row.+ default_limit = 100+ max_limit = 100+++class OrganizationWideCredentialPermission(BasePermission):+ """A dashboard spans the organization, so a credential confined to some projects cannot use it.++ The check reads the credential itself, because a capture token in the query string can give+ an organization route a project and pass the routing mixin's own scope check.+ """++ message = "This credential is limited to specific projects. Cross-project dashboards need organization-wide access."++ def has_permission(self, request: Request, view: Any) -> bool:+ return get_authenticator_scoped_team_ids(getattr(request, "successful_authenticator", None)) is None+++class _FacadePageMixin:+ def _paginated(self, request: Request, page: contracts.DashboardPage | contracts.TilePage, data: Any) -> Response:+ paginator = self.paginator # type: ignore[attr-defined]+ paginator.request = request+ paginator.limit = paginator.get_limit(request)+ paginator.offset = paginator.get_offset(request)+ paginator.count = page.count+ return paginator.get_paginated_response(data)++ def _offset(self, request: Request) -> int:+ return self.paginator.get_offset(request) # type: ignore[attr-defined]++ def _limit(self, request: Request) -> int:+ return self.paginator.get_limit(request) # type: ignore[attr-defined]+++class CrossProjectDashboardViewSet(TeamAndOrgViewSetMixin, _FacadePageMixin, viewsets.GenericViewSet):+ """Dashboards the organization owns, holding insights from one or more projects."""++ # Any organization member may create one, and may edit or delete one whose tiles all come from+ # projects they can open. A dashboard holds only references, and each reader's own project+ # access decides what every tile shows.+ scope_object = "cross_project_dashboard"+ serializer_class = CrossProjectDashboardSerializer+ lookup_field = "id"+ pagination_class = CrossProjectDashboardPagination+ # Server-side rollout boundary: the flag gates the API, not only the UI.+ posthog_feature_flag = "cross-project-dashboards"+ permission_classes = [PostHogFeatureFlagPermission, OrganizationWideCredentialPermission]++ def _user(self) -> User:+ return cast(User, self.request.user)++ def _object_id(self) -> UUID:+ return _uuid(self.kwargs["id"])++ @extend_schema(responses={200: CrossProjectDashboardListItemSerializer(many=True)})+ def list(self, request: Request, **kwargs: Any) -> Response:+ page = api.list_dashboards(+ organization_id=self.organization_id,+ user=self._user(),+ offset=self._offset(request),+ limit=self._limit(request),+ )+ return self._paginated(request, page, CrossProjectDashboardListItemSerializer(page.results, many=True).data)++ @extend_schema(request=CrossProjectDashboardSerializer, responses={201: CrossProjectDashboardSerializer})+ def create(self, request: Request, **kwargs: Any) -> Response:+ serializer = CrossProjectDashboardSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ dashboard = api.create_dashboard(+ organization_id=self.organization_id,+ user=self._user(),+ dashboard=contracts.NewDashboard(**serializer.validated_data),+ )+ return Response(CrossProjectDashboardSerializer(dashboard).data, status=status.HTTP_201_CREATED)++ @extend_schema(parameters=[DASHBOARD_ID], responses={200: CrossProjectDashboardSerializer})+ def retrieve(self, request: Request, **kwargs: Any) -> Response:+ try:+ dashboard = api.get_dashboard(+ organization_id=self.organization_id, dashboard_id=self._object_id(), user=self._user()+ )+ except contracts.DashboardNotFoundError:+ raise NotFound()+ return Response(CrossProjectDashboardSerializer(dashboard).data)++ @extend_schema(+ parameters=[DASHBOARD_ID],+ request=CrossProjectDashboardSerializer(partial=True),+ responses={200: CrossProjectDashboardSerializer},+ )+ def partial_update(self, request: Request, **kwargs: Any) -> Response:+ serializer = CrossProjectDashboardSerializer(data=request.data, partial=True)+ serializer.is_valid(raise_exception=True)+ changes = contracts.DashboardChanges(fields=frozenset(serializer.validated_data), **serializer.validated_data)+ try:+ dashboard = api.update_dashboard(+ organization_id=self.organization_id, dashboard_id=self._object_id(), user=self._user(), changes=changes+ )+ except contracts.DashboardNotFoundError:+ raise NotFound()+ except contracts.DashboardChangeDeniedError:+ raise PermissionDenied(CHANGE_DENIED)+ return Response(CrossProjectDashboardSerializer(dashboard).data)++ @extend_schema(parameters=[DASHBOARD_ID], responses={204: None})+ def destroy(self, request: Request, **kwargs: Any) -> Response:+ try:+ api.delete_dashboard(+ organization_id=self.organization_id, dashboard_id=self._object_id(), user=self._user()+ )+ except contracts.DashboardNotFoundError:+ raise NotFound()+ except contracts.DashboardChangeDeniedError:+ raise PermissionDenied(CHANGE_DENIED)+ return Response(status=status.HTTP_204_NO_CONTENT)+++class CrossProjectDashboardTileViewSet(TeamAndOrgViewSetMixin, _FacadePageMixin, viewsets.GenericViewSet):+ """Tiles on one cross-project dashboard, edited one at a time.++ Writes are per tile rather than a whole-set replace, so two people editing the same+ dashboard cannot overwrite each other's tiles.+ """++ scope_object = "cross_project_dashboard"+ serializer_class = CrossProjectDashboardTileSerializer+ lookup_field = "id"+ pagination_class = CrossProjectDashboardPagination+ posthog_feature_flag = "cross-project-dashboards"+ permission_classes = [PostHogFeatureFlagPermission, OrganizationWideCredentialPermission]++ def _user(self) -> User:+ return cast(User, self.request.user)++ def _object_id(self) -> UUID:+ return _uuid(self.kwargs["id"])++ def _dashboard_id(self) -> UUID:+ return _uuid(self.parents_query_dict["dashboard_id"])++ @extend_schema(parameters=[PARENT_DASHBOARD_ID], responses={200: CrossProjectDashboardTileSerializer(many=True)})+ def list(self, request: Request, **kwargs: Any) -> Response:+ page = api.list_tiles(+ organization_id=self.organization_id,+ dashboard_id=self._dashboard_id(),+ user=self._user(),+ offset=self._offset(request),+ limit=self._limit(request),+ )+ return self._paginated(request, page, CrossProjectDashboardTileSerializer(page.results, many=True).data)++ @extend_schema(+ parameters=[PARENT_DASHBOARD_ID],+ request=CrossProjectDashboardTileSerializer,+ responses={201: CrossProjectDashboardTileSerializer},+ )+ def create(self, request: Request, **kwargs: Any) -> Response:+ serializer = CrossProjectDashboardTileSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ try:+ tile = api.create_tile(+ organization_id=self.organization_id,+ dashboard_id=self._dashboard_id(),+ user=self._user(),+ tile=contracts.NewTile(**serializer.validated_data),+ )+ except contracts.DashboardNotFoundError:+ raise NotFound()+ except contracts.DashboardChangeDeniedError:+ raise PermissionDenied(CHANGE_DENIED)+ return Response(CrossProjectDashboardTileSerializer(tile).data, status=status.HTTP_201_CREATED)++ @extend_schema(parameters=[PARENT_DASHBOARD_ID, TILE_ID], responses={200: CrossProjectDashboardTileSerializer})+ def retrieve(self, request: Request, **kwargs: Any) -> Response:+ try:+ tile = api.get_tile(+ organization_id=self.organization_id,+ dashboard_id=self._dashboard_id(),+ tile_id=self._object_id(),+ user=self._user(),+ )+ except contracts.TileNotFoundError:+ raise NotFound()+ return Response(CrossProjectDashboardTileSerializer(tile).data)++ @extend_schema(+ parameters=[PARENT_DASHBOARD_ID, TILE_ID],+ request=CrossProjectDashboardTileUpdateSerializer(partial=True),+ responses={200: CrossProjectDashboardTileSerializer},+ )+ def partial_update(self, request: Request, **kwargs: Any) -> Response:+ serializer = CrossProjectDashboardTileUpdateSerializer(data=request.data, partial=True)+ serializer.is_valid(raise_exception=True)+ changes = contracts.TileChanges(fields=frozenset(serializer.validated_data), **serializer.validated_data)+ try:+ tile = api.update_tile(+ organization_id=self.organization_id,+ dashboard_id=self._dashboard_id(),+ tile_id=self._object_id(),+ user=self._user(),+ changes=changes,+ )+ except contracts.TileNotFoundError:+ raise NotFound()+ except contracts.DashboardChangeDeniedError:+ raise PermissionDenied(CHANGE_DENIED)+ return Response(CrossProjectDashboardTileSerializer(tile).data)++ @extend_schema(parameters=[PARENT_DASHBOARD_ID, TILE_ID], responses={204: None})+ def destroy(self, request: Request, **kwargs: Any) -> Response:+ try:+ api.delete_tile(+ organization_id=self.organization_id,+ dashboard_id=self._dashboard_id(),+ tile_id=self._object_id(),+ user=self._user(),+ )+ except contracts.TileNotFoundError:+ raise NotFound()+ except contracts.DashboardChangeDeniedError:+ raise PermissionDenied(CHANGE_DENIED)+ return Response(status=status.HTTP_204_NO_CONTENT)diff --git a/products/cross_project_dashboards/backend/routes.py b/products/cross_project_dashboards/backend/routes.pynew file mode 100644index 000000000000..b2a6a934d7bf--- /dev/null+++ b/products/cross_project_dashboards/backend/routes.py@@ -0,0 +1,22 @@+from posthog.api.routing import RouterRegistry++from products.cross_project_dashboards.backend.presentation.views import (+ CrossProjectDashboardTileViewSet,+ CrossProjectDashboardViewSet,+)+++def register_routes(routers: RouterRegistry) -> None:+ dashboards_router = routers.organizations.register(+ r"cross_project_dashboards",+ CrossProjectDashboardViewSet,+ "organization_cross_project_dashboards",+ ["organization_id"],+ )+ # Tiles are edited one at a time so concurrent editors cannot overwrite each other.+ dashboards_router.register(+ r"tiles",+ CrossProjectDashboardTileViewSet,+ "organization_cross_project_dashboard_tiles",+ ["organization_id", "dashboard_id"],+ )diff --git a/products/cross_project_dashboards/backend/tests/__init__.py b/products/cross_project_dashboards/backend/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/cross_project_dashboards/backend/tests/conftest.py b/products/cross_project_dashboards/backend/tests/conftest.pynew file mode 100644index 000000000000..8a7dd5247550--- /dev/null+++ b/products/cross_project_dashboards/backend/tests/conftest.py@@ -0,0 +1,5 @@+"""Test fixtures for cross_project_dashboards.++The scaffold's default conftest forces a team scope around every database test. This product is+organization-scoped, so its models carry no team and need no such scope.+"""diff --git a/products/cross_project_dashboards/backend/tests/test_access.py b/products/cross_project_dashboards/backend/tests/test_access.pynew file mode 100644index 000000000000..ea44600d34c2--- /dev/null+++ b/products/cross_project_dashboards/backend/tests/test_access.py@@ -0,0 +1,75 @@+import pytest+from posthog.test.base import BaseTest++from parameterized import parameterized+from rest_framework.serializers import ValidationError++from posthog.constants import AvailableFeature+from posthog.models import Organization, OrganizationMembership, Team++from products.access_control.backend.facade.api import AccessControl+from products.cross_project_dashboards.backend.logic import assert_can_reference_insight+from products.product_analytics.backend.facade.models import Insight+++class TestAssertCanReferenceInsight(BaseTest):+ def test_allows_an_insight_in_a_reachable_project(self):+ insight = Insight.objects.create(team=self.team, name="Signups")+ assert_can_reference_insight(self.user, self.organization.id, self.team.pk, insight.pk)++ def test_rejects_an_insight_in_another_organization_the_user_belongs_to(self):+ other_organization = Organization.objects.create(name="Other")+ OrganizationMembership.objects.create(organization=other_organization, user=self.user)+ other_team = Team.objects.create(organization=other_organization, name="Other project")+ insight = Insight.objects.create(team=other_team, name="Secret")+ with pytest.raises(ValidationError):+ assert_can_reference_insight(self.user, self.organization.id, other_team.pk, insight.pk)++ def test_rejects_an_insight_that_does_not_exist(self):+ with pytest.raises(ValidationError):+ assert_can_reference_insight(self.user, self.organization.id, self.team.pk, 999999)++ def test_rejects_a_project_that_does_not_exist(self):+ with pytest.raises(ValidationError):+ assert_can_reference_insight(self.user, self.organization.id, 999999, 1)++ def test_rejects_an_insight_from_a_different_project(self):+ other_team = Team.objects.create(organization=self.organization, name="Second project")+ insight = Insight.objects.create(team=other_team, name="Elsewhere")+ with pytest.raises(ValidationError):+ assert_can_reference_insight(self.user, self.organization.id, self.team.pk, insight.pk)++ @parameterized.expand(+ [+ # Resource and object rules fall back to a permissive default, so without the separate+ # has_project_access check this user reaches an insight in a project they were denied.+ ("everyone_denied", True, "none"),+ # Legacy resolution takes the highest matching project rule, so an allow for everyone+ # outranks this member's explicit denial unless membership is checked as well.+ ("member_denied_under_legacy_resolution", False, "member"),+ ]+ )+ def test_honors_a_project_level_deny_in_the_insight_own_project(+ self, _name: str, most_specific_resolution: bool, everyone_level: str+ ):+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.uses_most_specific_access_resolution = most_specific_resolution+ self.organization.save()+ denied_team = Team.objects.create(organization=self.organization, name="Denied project")+ insight = Insight.objects.create(team=denied_team, name="Out of reach")+ AccessControl.objects.create(+ team=denied_team, resource="project", resource_id=str(denied_team.id), access_level=everyone_level+ )+ if everyone_level != "none":+ AccessControl.objects.create(+ team=denied_team,+ resource="project",+ resource_id=str(denied_team.id),+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=self.user),+ access_level="none",+ )++ with pytest.raises(ValidationError):+ assert_can_reference_insight(self.user, self.organization.id, denied_team.pk, insight.pk)diff --git a/products/cross_project_dashboards/backend/tests/test_activity_logging.py b/products/cross_project_dashboards/backend/tests/test_activity_logging.pynew file mode 100644index 000000000000..d374e508c675--- /dev/null+++ b/products/cross_project_dashboards/backend/tests/test_activity_logging.py@@ -0,0 +1,64 @@+from posthog.test.base import BaseTest++from posthog.models.activity_logging.activity_log import ActivityLog++from products.cross_project_dashboards.backend.facade import api, contracts+from products.cross_project_dashboards.backend.models import CrossProjectDashboard+from products.product_analytics.backend.facade.models import Insight+++class TestCrossProjectDashboardActivityLogging(BaseTest):+ def test_creating_a_dashboard_logs_against_the_organization(self):+ CrossProjectDashboard.objects.create(+ organization=self.organization, name="Company overview", created_by=self.user+ )+ log = ActivityLog.objects.filter(scope="CrossProjectDashboard").latest("created_at")+ assert log.organization_id == self.organization.id+ # ActivityLog requires a team id or an organization id, not both. An org dashboard has+ # no team, so the organization carries the row.+ assert log.team_id is None+ assert log.activity == "created"+ assert (log.detail or {})["name"] == "Company overview"++ def test_renaming_a_dashboard_logs_the_change(self):+ dashboard = CrossProjectDashboard.objects.create(+ organization=self.organization, name="Before", created_by=self.user+ )+ dashboard.name = "After"+ dashboard.save()+ log = ActivityLog.objects.filter(scope="CrossProjectDashboard", activity="updated").latest("created_at")+ assert log.organization_id == self.organization.id+ assert log.team_id is None++ def test_soft_deleting_a_dashboard_logs_a_delete(self):+ dashboard = CrossProjectDashboard.objects.create(+ organization=self.organization, name="Overview", created_by=self.user+ )+ api.delete_dashboard(organization_id=self.organization.id, dashboard_id=dashboard.id, user=self.user)++ log = ActivityLog.objects.filter(scope="CrossProjectDashboard", item_id=str(dashboard.id)).latest("created_at")+ assert log.activity == "deleted"++ def test_tile_changes_log_on_the_dashboard_but_layout_moves_do_not(self):+ dashboard = CrossProjectDashboard.objects.create(+ organization=self.organization, name="Overview", created_by=self.user+ )+ insight = Insight.objects.create(team=self.team, name="Signups")+ scope = {"organization_id": self.organization.id, "dashboard_id": dashboard.id, "user": self.user}+ tile = api.create_tile(+ **scope,+ tile=contracts.NewTile(+ project_id=self.team.pk, insight_id=insight.pk, layouts={}, color=None, filters_overrides={}+ ),+ )+ moved = contracts.TileChanges(fields=frozenset({"layouts"}), layouts={"sm": {"x": 6}})+ api.update_tile(**scope, tile_id=tile.id, changes=moved)+ recolored = contracts.TileChanges(fields=frozenset({"color"}), color="red")+ api.update_tile(**scope, tile_id=tile.id, changes=recolored)+ api.delete_tile(**scope, tile_id=tile.id)++ logs = ActivityLog.objects.filter(+ scope="CrossProjectDashboard", item_id=str(dashboard.id), activity="updated"+ ).order_by("created_at")+ assert [(log.detail or {})["changes"][0]["action"] for log in logs] == ["created", "changed", "deleted"]+ assert all("project_id" not in str(log.detail) for log in logs)diff --git a/products/cross_project_dashboards/backend/tests/test_api.py b/products/cross_project_dashboards/backend/tests/test_api.pynew file mode 100644index 000000000000..c09063ba3b84--- /dev/null+++ b/products/cross_project_dashboards/backend/tests/test_api.py@@ -0,0 +1,90 @@+import time_machine+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from rest_framework import status++from posthog.models import Organization+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.cross_project_dashboards.backend.models import CrossProjectDashboard+++@patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)+class TestCrossProjectDashboardAPI(APIBaseTest):+ def _url(self, suffix: str = "") -> str:+ return f"/api/organizations/{self.organization.id}/cross_project_dashboards/{suffix}"++ def _dashboard(self) -> CrossProjectDashboard:+ return CrossProjectDashboard.objects.create(+ organization=self.organization, name="Company overview", created_by=self.user+ )++ def test_creates_a_dashboard(self, _flag):+ response = self.client.post(self._url(), {"name": "Company overview"})+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["name"] == "Company overview"++ def test_rejects_a_project_bound_filter(self, _flag):+ response = self.client.post(+ self._url(),+ {"name": "X", "filters": {"properties": [{"type": "cohort", "key": "id", "value": 42}]}},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "cohort" in str(response.json())++ def test_rejects_filters_over_the_size_ceiling(self, _flag):+ response = self.client.post(self._url(), {"name": "Big", "filters": {"padding": "x" * 20_000}}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ def test_allows_a_date_filter(self, _flag):+ response = self.client.post(+ self._url(), {"name": "X", "filters": {"date_from": "-7d", "interval": "week"}}, format="json"+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()++ def test_does_not_return_another_organizations_dashboard(self, _flag):+ other_organization = Organization.objects.create(name="Other")+ other = CrossProjectDashboard.objects.create(organization=other_organization, name="Theirs")+ response = self.client.get(self._url(f"{other.id}/"))+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_pages_through_dashboards_created_in_the_same_instant(self, _flag):+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False):+ created = {str(self._dashboard().id) for _ in range(3)}++ first = self.client.get(self._url("?limit=2")).json()+ second = self.client.get(self._url("?limit=2&offset=2")).json()++ paged = [dashboard["id"] for dashboard in first["results"] + second["results"]]+ assert first["count"] == 3+ assert sorted(paged) == sorted(created)++ def test_rejects_a_project_scoped_key_even_with_a_capture_token(self, _flag):+ key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Project only",+ user=self.user,+ secure_value=hash_key_value(key),+ scopes=["cross_project_dashboard:read"],+ scoped_teams=[self.team.id],+ )+ self.client.logout()++ response = self.client.get(self._url(f"?token={self.team.api_token}"), HTTP_AUTHORIZATION=f"Bearer {key}")++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()++ def test_delete_is_a_soft_delete(self, _flag):+ dashboard = self._dashboard()+ response = self.client.delete(self._url(f"{dashboard.id}/"))+ assert response.status_code == status.HTTP_204_NO_CONTENT+ dashboard.refresh_from_db()+ assert dashboard.deleted is True++ def test_denies_everything_when_the_flag_is_off(self, flag):+ flag.return_value = False+ response = self.client.get(self._url())+ assert response.status_code == status.HTTP_403_FORBIDDENdiff --git a/products/cross_project_dashboards/backend/tests/test_filters.py b/products/cross_project_dashboards/backend/tests/test_filters.pynew file mode 100644index 000000000000..b5c38df7b197--- /dev/null+++ b/products/cross_project_dashboards/backend/tests/test_filters.py@@ -0,0 +1,90 @@+import pytest++from rest_framework.serializers import ValidationError++from products.cross_project_dashboards.backend.logic import validate_cross_project_filters+++def test_dates_and_interval_are_allowed():+ validate_cross_project_filters({"date_from": "-7d", "date_to": None, "interval": "week"})+++def test_string_keyed_property_filters_are_allowed():+ validate_cross_project_filters(+ {"properties": [{"type": "event", "key": "$browser", "operator": "exact", "value": "Chrome"}]}+ )+++def test_empty_filters_are_allowed():+ validate_cross_project_filters(None)+ validate_cross_project_filters({})+++ "property_filter",+ [+ {"type": "cohort", "key": "id", "value": 42},+ {"type": "group", "key": "name", "group_type_index": 0, "operator": "exact", "value": "a"},+ {"type": "flag", "key": "123", "operator": "flag_evaluates_to", "value": True},+ {"type": "data_warehouse", "key": "col", "operator": "exact", "value": "x"},+ {"type": "error_tracking_issue", "key": "id", "operator": "exact", "value": "x"},+ {"type": "hogql", "key": "1 = 1"},+ # The schema reads a leaf with no type as a cohort filter.+ {"value": 42},+ {"type": "behavioral", "key": "$pageview", "value": "performed_event", "event_type": "events"},+ ],+)+def test_project_bound_property_filters_are_rejected(property_filter):+ with pytest.raises(ValidationError) as err:+ validate_cross_project_filters({"properties": [property_filter]})+ assert property_filter.get("type", "untyped") in str(err.value)+++ "properties",+ [+ {"type": "AND", "values": [{"type": "hogql", "key": "1=1"}]},+ [{"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 42}]}],+ ],+ ids=["group_dict", "nested_group_in_list"],+)+def test_project_bound_filters_inside_property_groups_are_rejected(properties):+ with pytest.raises(ValidationError):+ validate_cross_project_filters({"properties": properties})+++def test_property_group_is_stored_as_the_flat_list_the_tiles_apply():+ leaf = {"type": "event", "key": "$browser", "operator": "exact", "value": "Chrome"}++ normalized = validate_cross_project_filters({"properties": {"type": "AND", "values": [leaf]}})++ assert normalized["properties"] == [leaf]++[email protected]("filters", ["abc", 5, ["date_from"], {"breakdown_filter": {"breakdowns": 5}}])+def test_malformed_filters_are_a_validation_error(filters):+ with pytest.raises(ValidationError):+ validate_cross_project_filters(filters)+++def test_cohort_breakdown_in_the_breakdowns_list_is_rejected():+ with pytest.raises(ValidationError):+ validate_cross_project_filters({"breakdown_filter": {"breakdowns": [{"type": "cohort", "property": 42}]}})+++ "breakdown",+ [{"breakdown_type": "cohort", "breakdown": [42]}, {"breakdown_type": "hogql", "breakdown": "person.foo"}],+)+def test_project_bound_breakdown_types_are_rejected(breakdown):+ with pytest.raises(ValidationError):+ validate_cross_project_filters({"breakdown_filter": breakdown})+++def test_group_breakdown_is_rejected():+ with pytest.raises(ValidationError):+ validate_cross_project_filters({"breakdown_filter": {"breakdown_group_type_index": 0}})+++def test_event_breakdown_is_allowed():+ validate_cross_project_filters({"breakdown_filter": {"breakdown_type": "event", "breakdown": "$browser"}})diff --git a/products/cross_project_dashboards/backend/tests/test_models.py b/products/cross_project_dashboards/backend/tests/test_models.pynew file mode 100644index 000000000000..e135ac2d2d9f--- /dev/null+++ b/products/cross_project_dashboards/backend/tests/test_models.py@@ -0,0 +1,51 @@+from posthog.test.base import BaseTest++from posthog.models import Team++from products.cross_project_dashboards.backend.models import CrossProjectDashboard, CrossProjectDashboardTile+++class TestCrossProjectDashboardModels(BaseTest):+ def _dashboard(self) -> CrossProjectDashboard:+ return CrossProjectDashboard.objects.create(+ organization=self.organization, name="Company overview", created_by=self.user+ )++ def test_tile_references_a_project_and_insight_by_id(self):+ tile = CrossProjectDashboardTile.objects.create(+ dashboard=self._dashboard(),+ organization=self.organization,+ project_id=self.team.pk,+ insight_id=1234,+ )+ assert tile.organization_id == self.organization.id+ assert tile.project_id == self.team.pk+ assert tile.insight_id == 1234++ def test_tile_survives_an_insight_that_does_not_exist(self):+ tile = CrossProjectDashboardTile.objects.create(+ dashboard=self._dashboard(), organization=self.organization, project_id=self.team.pk, insight_id=999999+ )+ assert CrossProjectDashboardTile.objects.filter(pk=tile.pk).exists()++ def test_tile_survives_a_project_that_was_deleted(self):+ # No FK to the project, so deleting one leaves the dashboard loadable and the tile able+ # to report that its source is gone, rather than cascading the tile away with no trace.+ doomed = Team.objects.create(organization=self.organization, name="Doomed project")+ dashboard = self._dashboard()+ tile = CrossProjectDashboardTile.objects.create(+ dashboard=dashboard, organization=self.organization, project_id=doomed.pk, insight_id=42+ )+ doomed_pk = doomed.pk+ doomed.delete()++ tile.refresh_from_db()+ assert tile.project_id == doomed_pk+ assert CrossProjectDashboard.objects.filter(pk=dashboard.pk).exists()++ def test_tile_has_no_team_field(self):+ # A non-FK team_id column makes check-idor-model-coverage.py classify this model as+ # team-scoped, which would demand a manager that scopes reads to a single team.+ field_names = {field.name for field in CrossProjectDashboardTile._meta.get_fields()}+ assert "team" not in field_names+ assert "team_id" not in field_namesdiff --git a/products/cross_project_dashboards/backend/tests/test_tile_api.py b/products/cross_project_dashboards/backend/tests/test_tile_api.pynew file mode 100644index 000000000000..942a8d77aa16--- /dev/null+++ b/products/cross_project_dashboards/backend/tests/test_tile_api.py@@ -0,0 +1,312 @@+import time_machine+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models import Organization, OrganizationMembership, Team++from products.access_control.backend.facade.api import AccessControl, Role, RoleMembership+from products.cross_project_dashboards.backend.models import CrossProjectDashboard, CrossProjectDashboardTile+from products.product_analytics.backend.facade.models import Insight+++@patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)+class TestCrossProjectDashboardTileAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.dashboard = CrossProjectDashboard.objects.create(+ organization=self.organization, name="Company overview", created_by=self.user+ )++ def _url(self, suffix: str = "") -> str:+ return f"/api/organizations/{self.organization.id}/cross_project_dashboards/{self.dashboard.id}/tiles/{suffix}"++ def _insight(self, name: str = "Signups") -> Insight:+ return Insight.objects.create(team=self.team, name=name)++ def test_adds_one_tile(self, _flag):+ insight = self._insight()+ response = self.client.post(self._url(), {"project_id": self.team.pk, "insight_id": insight.pk}, format="json")+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["insight_id"] == insight.pk+ assert self.dashboard.tiles.filter(deleted=False).count() == 1++ def test_rejects_a_project_bound_filter_on_one_tile(self, _flag):+ insight = self._insight()+ response = self.client.post(+ self._url(),+ {+ "project_id": self.team.pk,+ "insight_id": insight.pk,+ "filters_overrides": {"properties": [{"type": "cohort", "key": "id", "value": 7}]},+ },+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ def test_allows_a_date_override_on_one_tile(self, _flag):+ insight = self._insight()+ response = self.client.post(+ self._url(),+ {"project_id": self.team.pk, "insight_id": insight.pk, "filters_overrides": {"date_from": "-7d"}},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["filters_overrides"] == {"date_from": "-7d"}++ def test_adding_a_tile_leaves_existing_tiles_alone(self, _flag):+ first = self._insight("First")+ second = self._insight("Second")+ self.client.post(self._url(), {"project_id": self.team.pk, "insight_id": first.pk}, format="json")++ self.client.post(self._url(), {"project_id": self.team.pk, "insight_id": second.pk}, format="json")++ live = self.dashboard.tiles.filter(deleted=False).values_list("insight_id", flat=True)+ assert sorted(live) == sorted([first.pk, second.pk])++ def test_updates_one_tile_without_touching_others(self, _flag):+ first = self._insight("First")+ second = self._insight("Second")+ created = self.client.post(+ self._url(), {"project_id": self.team.pk, "insight_id": first.pk}, format="json"+ ).json()+ self.client.post(self._url(), {"project_id": self.team.pk, "insight_id": second.pk}, format="json")++ response = self.client.patch(+ self._url(f"{created['id']}/"), {"layouts": {"sm": {"x": 1, "y": 2}}}, format="json"+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["layouts"] == {"sm": {"x": 1, "y": 2}}+ assert self.dashboard.tiles.filter(deleted=False).count() == 2++ def test_a_tile_cannot_be_repointed_at_another_insight(self, _flag):+ first = self._insight("First")+ other = self._insight("Other")+ created = self.client.post(+ self._url(), {"project_id": self.team.pk, "insight_id": first.pk}, format="json"+ ).json()++ self.client.patch(self._url(f"{created['id']}/"), {"insight_id": other.pk}, format="json")++ tile = CrossProjectDashboardTile.objects.get(id=created["id"])+ assert tile.insight_id == first.pk++ def test_deletes_one_tile_and_keeps_the_rest(self, _flag):+ first = self._insight("First")+ second = self._insight("Second")+ created = self.client.post(+ self._url(), {"project_id": self.team.pk, "insight_id": first.pk}, format="json"+ ).json()+ self.client.post(self._url(), {"project_id": self.team.pk, "insight_id": second.pk}, format="json")++ response = self.client.delete(self._url(f"{created['id']}/"))++ assert response.status_code == status.HTTP_204_NO_CONTENT+ live = list(self.dashboard.tiles.filter(deleted=False).values_list("insight_id", flat=True))+ assert live == [second.pk]++ def test_rejects_layouts_that_are_not_an_object(self, _flag):+ insight = self._insight()+ response = self.client.post(+ self._url(), {"project_id": self.team.pk, "insight_id": insight.pk, "layouts": []}, format="json"+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ def test_rejects_a_tile_past_the_per_dashboard_ceiling(self, _flag):+ CrossProjectDashboardTile.objects.bulk_create(+ CrossProjectDashboardTile(+ dashboard=self.dashboard, organization=self.organization, project_id=self.team.pk, insight_id=n+ )+ for n in range(100)+ )+ insight = self._insight()++ response = self.client.post(self._url(), {"project_id": self.team.pk, "insight_id": insight.pk}, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert self.dashboard.tiles.filter(deleted=False).count() == 100++ def test_rejects_an_insight_the_user_cannot_reach(self, _flag):+ response = self.client.post(self._url(), {"project_id": 999999, "insight_id": 1}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_a_deleted_dashboard_tiles_can_no_longer_be_read_or_edited(self, _flag):+ tile = CrossProjectDashboardTile.objects.create(+ dashboard=self.dashboard,+ organization=self.organization,+ project_id=self.team.pk,+ insight_id=self._insight().pk,+ )+ self.dashboard.deleted = True+ self.dashboard.save()++ assert self.client.get(self._url()).json()["results"] == []+ assert self.client.get(self._url(f"{tile.id}/")).status_code == status.HTTP_404_NOT_FOUND+ assert (+ self.client.patch(self._url(f"{tile.id}/"), {"color": "blue"}, format="json").status_code+ == status.HTTP_404_NOT_FOUND+ )++ def test_does_not_expose_another_organizations_tiles(self, _flag):+ other_organization = Organization.objects.create(name="Other")+ other_dashboard = CrossProjectDashboard.objects.create(organization=other_organization, name="Theirs")+ CrossProjectDashboardTile.objects.create(+ dashboard=other_dashboard, organization=other_organization, project_id=self.team.pk, insight_id=1+ )++ response = self.client.get(self._url())++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["results"] == []++ def test_pages_through_tiles_created_in_the_same_instant(self, _flag):+ with time_machine.travel("2026-01-01T00:00:00Z", tick=False):+ created = {+ str(+ CrossProjectDashboardTile.objects.create(+ dashboard=self.dashboard, organization=self.organization, project_id=self.team.pk, insight_id=n+ ).id+ )+ for n in range(3)+ }++ first = self.client.get(self._url("?limit=2")).json()+ second = self.client.get(self._url("?limit=2&offset=2")).json()++ paged = [tile["id"] for tile in first["results"] + second["results"]]+ assert first["count"] == 3+ assert sorted(paged) == sorted(created)++ @parameterized.expand(+ [+ ("everyone_denied", False),+ # Most-specific resolution lets the member's own denial beat the role's grant, while+ # the legacy resolver takes the highest of the two and would show the project.+ ("member_denied_role_allowed", True),+ ]+ )+ def test_a_project_the_reader_is_denied_hides_its_tiles(self, _flag, _name: str, member_denied: bool):+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.uses_most_specific_access_resolution = True+ self.organization.save()+ denied_team = Team.objects.create(organization=self.organization, name="Denied project")+ if member_denied:+ role = Role.objects.create(name="Analysts", organization=self.organization)+ RoleMembership.objects.create(user=self.user, role=role)+ AccessControl.objects.create(+ team=denied_team, resource="project", resource_id=str(denied_team.id), role=role, access_level="admin"+ )+ AccessControl.objects.create(+ team=denied_team,+ resource="project",+ resource_id=str(denied_team.id),+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=self.user),+ access_level="none",+ )+ else:+ AccessControl.objects.create(+ team=denied_team, resource="project", resource_id=str(denied_team.id), access_level="none"+ )+ visible = CrossProjectDashboardTile.objects.create(+ dashboard=self.dashboard, organization=self.organization, project_id=self.team.pk, insight_id=1+ )+ CrossProjectDashboardTile.objects.create(+ dashboard=self.dashboard, organization=self.organization, project_id=denied_team.pk, insight_id=2+ )++ tiles = self.client.get(self._url()).json()["results"]+ dashboard = self.client.get(+ f"/api/organizations/{self.organization.id}/cross_project_dashboards/{self.dashboard.id}/"+ ).json()++ listed = self.client.get(f"/api/organizations/{self.organization.id}/cross_project_dashboards/").json()++ assert [tile["id"] for tile in tiles] == [str(visible.id)]+ assert [tile["id"] for tile in dashboard["tiles"]] == [str(visible.id)]+ assert (listed["results"][0]["tile_count"], listed["results"][0]["project_count"]) == (1, 1)++ @parameterized.expand([("patch",), ("delete",), ("add_tile",), ("patch_tile",), ("delete_tile",)])+ def test_a_member_denied_a_tile_project_cannot_change_the_dashboard(self, _flag, method: str):+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ denied_team = Team.objects.create(organization=self.organization, name="Denied project")+ AccessControl.objects.create(+ team=denied_team, resource="project", resource_id=str(denied_team.id), access_level="none"+ )+ CrossProjectDashboardTile.objects.create(+ dashboard=self.dashboard, organization=self.organization, project_id=denied_team.pk, insight_id=2+ )+ url = f"/api/organizations/{self.organization.id}/cross_project_dashboards/{self.dashboard.id}/"++ visible = CrossProjectDashboardTile.objects.create(+ dashboard=self.dashboard, organization=self.organization, project_id=self.team.pk, insight_id=1+ )++ if method == "add_tile":+ body = {"project_id": self.team.pk, "insight_id": self._insight().pk}+ response = self.client.post(self._url(), body, format="json")+ elif method == "patch_tile":+ response = self.client.patch(self._url(f"{visible.id}/"), {"color": "red"}, format="json")+ elif method == "delete_tile":+ response = self.client.delete(self._url(f"{visible.id}/"))+ else:+ response = getattr(self.client, method)(url, {"name": "Renamed"}, format="json")++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()+ self.dashboard.refresh_from_db()+ assert (self.dashboard.name, self.dashboard.deleted) == ("Company overview", False)+ assert self.dashboard.tiles.filter(deleted=False).count() == 2+ visible.refresh_from_db()+ assert visible.color is None++ @parameterized.expand([("deleted",), ("moved_to_another_organization",)])+ def test_a_tile_whose_project_is_gone_hides_its_settings_and_never_blocks_the_dashboard(self, _flag, how: str):+ if how == "deleted":+ project_id = 987654321+ else:+ project_id = Team.objects.create(organization=Organization.objects.create(name="Other"), name="Moved").pk+ gone = CrossProjectDashboardTile.objects.create(+ dashboard=self.dashboard,+ organization=self.organization,+ project_id=project_id,+ insight_id=1,+ color="red",+ filters_overrides={"properties": [{"type": "person", "key": "email", "value": "[email protected]"}]},+ )+ dashboard_url = f"/api/organizations/{self.organization.id}/cross_project_dashboards/{self.dashboard.id}/"++ listed = self.client.get(self._url()).json()["results"]+ detail = self.client.get(dashboard_url).json()["tiles"]+ renamed = self.client.patch(dashboard_url, {"name": "Renamed"}, format="json")+ removed = self.client.delete(self._url(f"{gone.id}/"))++ assert [(tile["id"], tile["color"], tile["filters_overrides"]) for tile in listed + detail] == [+ (str(gone.id), None, {}),+ (str(gone.id), None, {}),+ ]+ assert renamed.status_code == status.HTTP_200_OK, renamed.json()+ assert removed.status_code == status.HTTP_204_NO_CONTENT++ def test_dashboard_patch_no_longer_writes_tiles(self, _flag):+ insight = self._insight()+ response = self.client.patch(+ f"/api/organizations/{self.organization.id}/cross_project_dashboards/{self.dashboard.id}/",+ {"tiles": [{"project_id": self.team.pk, "insight_id": insight.pk}]},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert self.dashboard.tiles.count() == 0++ def test_denies_everything_when_the_flag_is_off(self, flag):+ flag.return_value = False+ response = self.client.get(self._url())+ assert response.status_code == status.HTTP_403_FORBIDDENdiff --git a/products/cross_project_dashboards/frontend/generated/api.schemas.ts b/products/cross_project_dashboards/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..a865e51d9dc1--- /dev/null+++ b/products/cross_project_dashboards/frontend/generated/api.schemas.ts@@ -0,0 +1,187 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+export interface CrossProjectDashboardCreatorApi {+ /** Id of the user who created the dashboard. */+ readonly id: number+ /** First name of the user who created the dashboard. */+ readonly first_name: string+ /** Email of the user who created the dashboard. */+ readonly email: string+}++/**+ * A dashboard in the list. It counts its tiles instead of carrying them; read one dashboard for its tiles.+ */+export interface CrossProjectDashboardListItemApi {+ /** Id of the dashboard. */+ readonly id: string+ /** Name shown in the dashboard list and page header. */+ readonly name: string+ /** Optional longer description. */+ readonly description: string+ /** Dashboard-level filters applied to every tile. Supports a date range, an interval, and property filters that refer to a property by name. Filters carrying a project-specific id are rejected. */+ readonly filters: unknown+ /** Tiles from the projects the reader can open. */+ readonly tile_count: number+ /** Distinct projects among the tiles the reader can open. */+ readonly project_count: number+ /** The user who created the dashboard. */+ readonly created_by: CrossProjectDashboardCreatorApi | null+ /** When the dashboard was created. */+ readonly created_at: string+ /**+ * When the dashboard last changed.+ * @nullable+ */+ readonly updated_at: string | null+}++export interface PaginatedCrossProjectDashboardListItemListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: CrossProjectDashboardListItemApi[]+}++export interface CrossProjectDashboardTileApi {+ /** Id of the tile. */+ readonly id: string+ /** Id of the project the tile's insight belongs to. */+ project_id: number+ /** Id of the insight the tile renders. */+ insight_id: number+ /** Grid position and size of the tile, keyed by layout size. */+ layouts?: unknown+ /**+ * Optional color applied to the tile.+ * @maxLength 400+ * @nullable+ */+ color?: string | null+ /** Filters applied to this tile only, overriding the dashboard's. Supports a date range and an interval. Filters carrying a project-specific id are rejected. */+ filters_overrides?: unknown+}++/**+ * Carries tile references only.+ *+ * The response holds no insight names, queries or results. Each reader fetches each tile from+ * that tile's own project endpoint, so their access, quota and cache key stay correct there.+ */+export interface CrossProjectDashboardApi {+ /** Id of the dashboard. */+ readonly id: string+ /**+ * Name shown in the dashboard list and page header.+ * @maxLength 400+ */+ name: string+ /**+ * Optional longer description.+ * @maxLength 4000+ */+ description?: string+ /** Dashboard-level filters applied to every tile. Supports a date range, an interval, and property filters that refer to a property by name. Filters carrying a project-specific id are rejected. */+ filters?: unknown+ /** Tiles from the projects the reader can open. */+ readonly tiles: readonly CrossProjectDashboardTileApi[]+ /** The user who created the dashboard. */+ readonly created_by: CrossProjectDashboardCreatorApi | null+ /** When the dashboard was created. */+ readonly created_at: string+ /**+ * When the dashboard last changed.+ * @nullable+ */+ readonly updated_at: string | null+}++export interface PaginatedCrossProjectDashboardTileListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: CrossProjectDashboardTileApi[]+}++/**+ * A tile's project and insight never change, so an update carries only its placement and styling.+ */+export interface PatchedCrossProjectDashboardTileUpdateApi {+ /** Grid position and size of the tile, keyed by layout size. */+ layouts?: unknown+ /**+ * Optional color applied to the tile.+ * @maxLength 400+ * @nullable+ */+ color?: string | null+ /** Filters applied to this tile only, overriding the dashboard's. Supports a date range and an interval. Filters carrying a project-specific id are rejected. */+ filters_overrides?: unknown+}++/**+ * Carries tile references only.+ *+ * The response holds no insight names, queries or results. Each reader fetches each tile from+ * that tile's own project endpoint, so their access, quota and cache key stay correct there.+ */+export interface PatchedCrossProjectDashboardApi {+ /** Id of the dashboard. */+ readonly id?: string+ /**+ * Name shown in the dashboard list and page header.+ * @maxLength 400+ */+ name?: string+ /**+ * Optional longer description.+ * @maxLength 4000+ */+ description?: string+ /** Dashboard-level filters applied to every tile. Supports a date range, an interval, and property filters that refer to a property by name. Filters carrying a project-specific id are rejected. */+ filters?: unknown+ /** Tiles from the projects the reader can open. */+ readonly tiles?: readonly CrossProjectDashboardTileApi[]+ /** The user who created the dashboard. */+ readonly created_by?: CrossProjectDashboardCreatorApi | null+ /** When the dashboard was created. */+ readonly created_at?: string+ /**+ * When the dashboard last changed.+ * @nullable+ */+ readonly updated_at?: string | null+}++export type CrossProjectDashboardsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}++export type CrossProjectDashboardsTilesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}diff --git a/products/cross_project_dashboards/frontend/generated/api.ts b/products/cross_project_dashboards/frontend/generated/api.tsnew file mode 100644index 000000000000..dad14b157b93--- /dev/null+++ b/products/cross_project_dashboards/frontend/generated/api.ts@@ -0,0 +1,294 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type {+ CrossProjectDashboardApi,+ CrossProjectDashboardTileApi,+ CrossProjectDashboardsListParams,+ CrossProjectDashboardsTilesListParams,+ PaginatedCrossProjectDashboardListItemListApi,+ PaginatedCrossProjectDashboardTileListApi,+ PatchedCrossProjectDashboardApi,+ PatchedCrossProjectDashboardTileUpdateApi,+} from './api.schemas'++// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B++type WritableKeys<T> = {+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>+}[keyof T]++type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never++type Writable<T> = Pick<T, WritableKeys<T>>+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]+ ? {+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]+ }+ : DistributeReadOnlyOverUnions<T>++export const getCrossProjectDashboardsListUrl = (organizationId: string, params?: CrossProjectDashboardsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/organizations/${organizationId}/cross_project_dashboards/?${stringifiedParams}`+ : `/api/organizations/${organizationId}/cross_project_dashboards/`+}++/**+ * Dashboards the organization owns, holding insights from one or more projects.+ */+export const crossProjectDashboardsList = async (+ organizationId: string,+ params?: CrossProjectDashboardsListParams,+ options?: RequestInit+): Promise<PaginatedCrossProjectDashboardListItemListApi> => {+ return apiMutator<PaginatedCrossProjectDashboardListItemListApi>(+ getCrossProjectDashboardsListUrl(organizationId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getCrossProjectDashboardsCreateUrl = (organizationId: string) => {+ return `/api/organizations/${organizationId}/cross_project_dashboards/`+}++/**+ * Dashboards the organization owns, holding insights from one or more projects.+ */+export const crossProjectDashboardsCreate = async (+ organizationId: string,+ crossProjectDashboardApi: NonReadonly<CrossProjectDashboardApi>,+ options?: RequestInit+): Promise<CrossProjectDashboardApi> => {+ return apiMutator<CrossProjectDashboardApi>(getCrossProjectDashboardsCreateUrl(organizationId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(crossProjectDashboardApi),+ })+}++export const getCrossProjectDashboardsTilesListUrl = (+ organizationId: string,+ dashboardId: string,+ params?: CrossProjectDashboardsTilesListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/organizations/${organizationId}/cross_project_dashboards/${dashboardId}/tiles/?${stringifiedParams}`+ : `/api/organizations/${organizationId}/cross_project_dashboards/${dashboardId}/tiles/`+}++/**+ * Tiles on one cross-project dashboard, edited one at a time.+ *+ * Writes are per tile rather than a whole-set replace, so two people editing the same+ * dashboard cannot overwrite each other's tiles.+ */+export const crossProjectDashboardsTilesList = async (+ organizationId: string,+ dashboardId: string,+ params?: CrossProjectDashboardsTilesListParams,+ options?: RequestInit+): Promise<PaginatedCrossProjectDashboardTileListApi> => {+ return apiMutator<PaginatedCrossProjectDashboardTileListApi>(+ getCrossProjectDashboardsTilesListUrl(organizationId, dashboardId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getCrossProjectDashboardsTilesCreateUrl = (organizationId: string, dashboardId: string) => {+ return `/api/organizations/${organizationId}/cross_project_dashboards/${dashboardId}/tiles/`+}++/**+ * Tiles on one cross-project dashboard, edited one at a time.+ *+ * Writes are per tile rather than a whole-set replace, so two people editing the same+ * dashboard cannot overwrite each other's tiles.+ */+export const crossProjectDashboardsTilesCreate = async (+ organizationId: string,+ dashboardId: string,+ crossProjectDashboardTileApi: NonReadonly<CrossProjectDashboardTileApi>,+ options?: RequestInit+): Promise<CrossProjectDashboardTileApi> => {+ return apiMutator<CrossProjectDashboardTileApi>(+ getCrossProjectDashboardsTilesCreateUrl(organizationId, dashboardId),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(crossProjectDashboardTileApi),+ }+ )+}++export const getCrossProjectDashboardsTilesRetrieveUrl = (organizationId: string, dashboardId: string, id: string) => {+ return `/api/organizations/${organizationId}/cross_project_dashboards/${dashboardId}/tiles/${id}/`+}++/**+ * Tiles on one cross-project dashboard, edited one at a time.+ *+ * Writes are per tile rather than a whole-set replace, so two people editing the same+ * dashboard cannot overwrite each other's tiles.+ */+export const crossProjectDashboardsTilesRetrieve = async (+ organizationId: string,+ dashboardId: string,+ id: string,+ options?: RequestInit+): Promise<CrossProjectDashboardTileApi> => {+ return apiMutator<CrossProjectDashboardTileApi>(+ getCrossProjectDashboardsTilesRetrieveUrl(organizationId, dashboardId, id),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getCrossProjectDashboardsTilesPartialUpdateUrl = (+ organizationId: string,+ dashboardId: string,+ id: string+) => {+ return `/api/organizations/${organizationId}/cross_project_dashboards/${dashboardId}/tiles/${id}/`+}++/**+ * Tiles on one cross-project dashboard, edited one at a time.+ *+ * Writes are per tile rather than a whole-set replace, so two people editing the same+ * dashboard cannot overwrite each other's tiles.+ */+export const crossProjectDashboardsTilesPartialUpdate = async (+ organizationId: string,+ dashboardId: string,+ id: string,+ patchedCrossProjectDashboardTileUpdateApi?: PatchedCrossProjectDashboardTileUpdateApi,+ options?: RequestInit+): Promise<CrossProjectDashboardTileApi> => {+ return apiMutator<CrossProjectDashboardTileApi>(+ getCrossProjectDashboardsTilesPartialUpdateUrl(organizationId, dashboardId, id),+ {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedCrossProjectDashboardTileUpdateApi),+ }+ )+}++export const getCrossProjectDashboardsTilesDestroyUrl = (organizationId: string, dashboardId: string, id: string) => {+ return `/api/organizations/${organizationId}/cross_project_dashboards/${dashboardId}/tiles/${id}/`+}++/**+ * Tiles on one cross-project dashboard, edited one at a time.+ *+ * Writes are per tile rather than a whole-set replace, so two people editing the same+ * dashboard cannot overwrite each other's tiles.+ */+export const crossProjectDashboardsTilesDestroy = async (+ organizationId: string,+ dashboardId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getCrossProjectDashboardsTilesDestroyUrl(organizationId, dashboardId, id), {+ ...options,+ method: 'DELETE',+ })+}++export const getCrossProjectDashboardsRetrieveUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/cross_project_dashboards/${id}/`+}++/**+ * Dashboards the organization owns, holding insights from one or more projects.+ */+export const crossProjectDashboardsRetrieve = async (+ organizationId: string,+ id: string,+ options?: RequestInit+): Promise<CrossProjectDashboardApi> => {+ return apiMutator<CrossProjectDashboardApi>(getCrossProjectDashboardsRetrieveUrl(organizationId, id), {+ ...options,+ method: 'GET',+ })+}++export const getCrossProjectDashboardsPartialUpdateUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/cross_project_dashboards/${id}/`+}++/**+ * Dashboards the organization owns, holding insights from one or more projects.+ */+export const crossProjectDashboardsPartialUpdate = async (+ organizationId: string,+ id: string,+ patchedCrossProjectDashboardApi?: NonReadonly<PatchedCrossProjectDashboardApi>,+ options?: RequestInit+): Promise<CrossProjectDashboardApi> => {+ return apiMutator<CrossProjectDashboardApi>(getCrossProjectDashboardsPartialUpdateUrl(organizationId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedCrossProjectDashboardApi),+ })+}++export const getCrossProjectDashboardsDestroyUrl = (organizationId: string, id: string) => {+ return `/api/organizations/${organizationId}/cross_project_dashboards/${id}/`+}++/**+ * Dashboards the organization owns, holding insights from one or more projects.+ */+export const crossProjectDashboardsDestroy = async (+ organizationId: string,+ id: string,+ options?: RequestInit+): Promise<void> => {+ return apiMutator<void>(getCrossProjectDashboardsDestroyUrl(organizationId, id), {+ ...options,+ method: 'DELETE',+ })+}diff --git a/products/cross_project_dashboards/frontend/generated/api.zod.ts b/products/cross_project_dashboards/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..8d05d5573041--- /dev/null+++ b/products/cross_project_dashboards/frontend/generated/api.zod.ts@@ -0,0 +1,121 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * Dashboards the organization owns, holding insights from one or more projects.+ */+export const crossProjectDashboardsCreateBodyNameMax = 400++export const crossProjectDashboardsCreateBodyDescriptionDefault = ``+export const crossProjectDashboardsCreateBodyDescriptionMax = 4000++export const CrossProjectDashboardsCreateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(crossProjectDashboardsCreateBodyNameMax)+ .describe('Name shown in the dashboard list and page header.'),+ description: zod+ .string()+ .max(crossProjectDashboardsCreateBodyDescriptionMax)+ .default(crossProjectDashboardsCreateBodyDescriptionDefault)+ .describe('Optional longer description.'),+ filters: zod+ .unknown()+ .optional()+ .describe(+ 'Dashboard-level filters applied to every tile. Supports a date range, an interval, and property filters that refer to a property by name. Filters carrying a project-specific id are rejected.'+ ),+ })+ .describe(+ "Carries tile references only.\n\nThe response holds no insight names, queries or results. Each reader fetches each tile from\nthat tile's own project endpoint, so their access, quota and cache key stay correct there."+ )++/**+ * Tiles on one cross-project dashboard, edited one at a time.+ *+ * Writes are per tile rather than a whole-set replace, so two people editing the same+ * dashboard cannot overwrite each other's tiles.+ */+export const crossProjectDashboardsTilesCreateBodyColorMax = 400++export const CrossProjectDashboardsTilesCreateBody = /* @__PURE__ */ zod.object({+ project_id: zod.number().describe("Id of the project the tile's insight belongs to."),+ insight_id: zod.number().describe('Id of the insight the tile renders.'),+ layouts: zod.unknown().optional().describe('Grid position and size of the tile, keyed by layout size.'),+ color: zod+ .string()+ .max(crossProjectDashboardsTilesCreateBodyColorMax)+ .nullish()+ .describe('Optional color applied to the tile.'),+ filters_overrides: zod+ .unknown()+ .optional()+ .describe(+ "Filters applied to this tile only, overriding the dashboard's. Supports a date range and an interval. Filters carrying a project-specific id are rejected."+ ),+})++/**+ * Tiles on one cross-project dashboard, edited one at a time.+ *+ * Writes are per tile rather than a whole-set replace, so two people editing the same+ * dashboard cannot overwrite each other's tiles.+ */+export const crossProjectDashboardsTilesPartialUpdateBodyColorMax = 400++export const CrossProjectDashboardsTilesPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ layouts: zod.unknown().optional().describe('Grid position and size of the tile, keyed by layout size.'),+ color: zod+ .string()+ .max(crossProjectDashboardsTilesPartialUpdateBodyColorMax)+ .nullish()+ .describe('Optional color applied to the tile.'),+ filters_overrides: zod+ .unknown()+ .optional()+ .describe(+ "Filters applied to this tile only, overriding the dashboard's. Supports a date range and an interval. Filters carrying a project-specific id are rejected."+ ),+ })+ .describe("A tile's project and insight never change, so an update carries only its placement and styling.")++/**+ * Dashboards the organization owns, holding insights from one or more projects.+ */+export const crossProjectDashboardsPartialUpdateBodyNameMax = 400++export const crossProjectDashboardsPartialUpdateBodyDescriptionDefault = ``+export const crossProjectDashboardsPartialUpdateBodyDescriptionMax = 4000++export const CrossProjectDashboardsPartialUpdateBody = /* @__PURE__ */ zod+ .object({+ name: zod+ .string()+ .max(crossProjectDashboardsPartialUpdateBodyNameMax)+ .optional()+ .describe('Name shown in the dashboard list and page header.'),+ description: zod+ .string()+ .max(crossProjectDashboardsPartialUpdateBodyDescriptionMax)+ .default(crossProjectDashboardsPartialUpdateBodyDescriptionDefault)+ .describe('Optional longer description.'),+ filters: zod+ .unknown()+ .optional()+ .describe(+ 'Dashboard-level filters applied to every tile. Supports a date range, an interval, and property filters that refer to a property by name. Filters carrying a project-specific id are rejected.'+ ),+ })+ .describe(+ "Carries tile references only.\n\nThe response holds no insight names, queries or results. Each reader fetches each tile from\nthat tile's own project endpoint, so their access, quota and cache key stay correct there."+ )diff --git a/products/cross_project_dashboards/manifest.tsx b/products/cross_project_dashboards/manifest.tsxnew file mode 100644index 000000000000..4a6f7cdda9d1--- /dev/null+++ b/products/cross_project_dashboards/manifest.tsx@@ -0,0 +1,23 @@+/**+ * Product manifest for cross_project_dashboards.+ *+ * Defines scenes, routes, URLs, and navigation for this product.+ */+import { ProductManifest } from '../../frontend/src/types'++export const manifest: ProductManifest = {+ name: 'CrossProjectDashboards',+ scenes: {+ // Define scenes here+ },+ routes: {+ // Define routes here+ },+ redirects: {},+ urls: {+ // Define URL helpers here+ },+ fileSystemTypes: {},+ treeItemsNew: [],+ treeItemsProducts: [],+}diff --git a/products/cross_project_dashboards/mcp/tools.yaml b/products/cross_project_dashboards/mcp/tools.yamlnew file mode 100644index 000000000000..c29d99be284e--- /dev/null+++ b/products/cross_project_dashboards/mcp/tools.yaml@@ -0,0 +1,79 @@+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.+# The tool list and operation IDs are kept in sync automatically:+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all+#+# To enable a tool, set enabled: true and add required scopes + annotations.+# All other fields (title, description, enrich_url, etc.) are yours to configure.+category: Cross-project dashboards+feature: cross_project_dashboards+url_prefix: /+ui_apps: {}+tools:+ cross-project-dashboard-tiles-list:+ operation: cross_project_dashboards_tiles_list+ enabled: true+ scopes:+ - cross_project_dashboard:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List the tiles on a cross-project dashboard+ description: >+ The tiles on one dashboard. Each tile carries the project id and insight id it references, its grid position+ and any filters that apply to it alone.+ feature_flag: cross-project-dashboards+ feature_flag_behavior: enable+ cross-project-dashboards-create:+ operation: cross_project_dashboards_create+ enabled: false+ cross-project-dashboards-destroy:+ operation: cross_project_dashboards_destroy+ enabled: false+ cross-project-dashboards-get:+ operation: cross_project_dashboards_retrieve+ enabled: true+ scopes:+ - cross_project_dashboard:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get one cross-project dashboard+ description: >+ One dashboard with its tiles. Each tile names the project and the insight it points at, never the insight's+ name, query or numbers. To read a tile's numbers, switch to that project and query the insight there.+ feature_flag: cross-project-dashboards+ feature_flag_behavior: enable+ cross-project-dashboards-list:+ operation: cross_project_dashboards_list+ enabled: true+ scopes:+ - cross_project_dashboard:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List cross-project dashboards+ description: >+ Dashboards the organization owns, each holding insights from one or more projects. Each dashboard comes with+ its filters and counts of the tiles and projects the reader can open. Get one dashboard to read its tiles.+ feature_flag: cross-project-dashboards+ feature_flag_behavior: enable+ cross-project-dashboards-partial-update:+ operation: cross_project_dashboards_partial_update+ enabled: false+ cross-project-dashboards-tiles-create:+ operation: cross_project_dashboards_tiles_create+ enabled: false+ cross-project-dashboards-tiles-destroy:+ operation: cross_project_dashboards_tiles_destroy+ enabled: false+ cross-project-dashboards-tiles-partial-update:+ operation: cross_project_dashboards_tiles_partial_update+ enabled: false+ cross-project-dashboards-tiles-retrieve:+ operation: cross_project_dashboards_tiles_retrieve+ enabled: falsediff --git a/products/cross_project_dashboards/package.json b/products/cross_project_dashboards/package.jsonnew file mode 100644index 000000000000..cbb2b41d994b--- /dev/null+++ b/products/cross_project_dashboards/package.json@@ -0,0 +1,23 @@+{+ "name": "@posthog/products-cross-project-dashboards",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",+ "backend:contract-check": "echo 'Contract files unchanged'"+ },+ "dependencies": {+ "clsx": "^2.1.1",+ "kea": "catalog:",+ "kea-loaders": "catalog:",+ "kea-router": "catalog:"+ },+ "devDependencies": {+ "@testing-library/react": "^14.3.1",+ "kea-test-utils": "catalog:"+ },+ "peerDependencies": {+ "@posthog/icons": "catalog:",+ "@types/react": "*",+ "react": "*",+ "react-grid-layout": "^2.2.4"+ }+}diff --git a/products/cross_project_dashboards/product.yaml b/products/cross_project_dashboards/product.yamlnew file mode 100644index 000000000000..f40eb6d7d1be--- /dev/null+++ b/products/cross_project_dashboards/product.yaml@@ -0,0 +1,3 @@+name: Cross-project dashboards+owners:+ - team-platform-featuresdiff --git a/products/cross_project_dashboards/tsconfig.json b/products/cross_project_dashboards/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/cross_project_dashboards/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/products/cross_project_dashboards/turbo.json b/products/cross_project_dashboards/turbo.jsonnew file mode 100644index 000000000000..2f891fa60904--- /dev/null+++ b/products/cross_project_dashboards/turbo.json@@ -0,0 +1,16 @@+{+ "extends": ["//"],+ "tasks": {+ "backend:contract-check": {+ "inputs": [+ "backend/facade/**",+ "backend/presentation/**",+ "backend/routes.py",+ "backend/models.py",+ "backend/migrations/**"+ ],+ "outputs": [],+ "cache": true+ }+ }+}diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 66a235b14779..883085e2b4d4 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1359,6 +1359,7 @@ export type ActivityLogListParams = {* Filter by a single activity scope, e.g. "FeatureFlag", "Insight", "Dashboard", "Experiment".** * `Cohort` - Cohort+ * * `CrossProjectDashboard` - CrossProjectDashboard* * `FeatureFlag` - FeatureFlag* * `Person` - Person* * `Group` - Group@@ -1462,6 +1463,7 @@ export type ActivityLogListScope = (typeof ActivityLogListScope)[keyof typeof Acexport const ActivityLogListScope = {Cohort: 'Cohort',+ CrossProjectDashboard: 'CrossProjectDashboard',FeatureFlag: 'FeatureFlag',Person: 'Person',Group: 'Group',@@ -1552,6 +1554,7 @@ export const ActivityLogListScope = {/*** * `Cohort` - Cohort+ * * `CrossProjectDashboard` - CrossProjectDashboard* * `FeatureFlag` - FeatureFlag* * `Person` - Person* * `Group` - Group@@ -1643,6 +1646,7 @@ export type ActivityLogListScopesItem = (typeof ActivityLogListScopesItem)[keyofexport const ActivityLogListScopesItem = {Cohort: 'Cohort',+ CrossProjectDashboard: 'CrossProjectDashboard',FeatureFlag: 'FeatureFlag',Person: 'Person',Group: 'Group',diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.pyindex ff5f98515f1b..77a957ef38f3 100644--- a/products/product_analytics/backend/facade/api.py+++ b/products/product_analytics/backend/facade/api.py@@ -184,6 +184,15 @@ def saved_insight_for_update(*, team: Team, user: User, short_id: str) -> SavedI)+def user_can_view_insight(*, team: Team, user: User, insight_id: int) -> bool:+ """Whether the user may view the insight, which can live in any environment of the team's project."""+ insight = Insight.objects.filter(pk=insight_id, team__project_id=team.project_id, deleted=False).first()+ if insight is None:+ return False+ access_control = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))+ return access_control.check_access_level_for_object(insight, "viewer")++def save_saved_insight_query(*, team: Team, user: User, insight_id: int, expected_query: dict[str, Any], query: dict[str, Any]) -> str | None:diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 7f713ab525fb..05c1d9f120cd 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3000,6 +3000,54 @@"readOnlyHint": false}},+ "cross-project-dashboard-tiles-list": {+ "description": "The tiles on one dashboard. Each tile carries the project id and insight id it references, its grid position and any filters that apply to it alone.",+ "category": "Cross-project dashboards",+ "feature": "cross_project_dashboards",+ "summary": "List the tiles on a cross-project dashboard",+ "title": "List the tiles on a cross-project dashboard",+ "required_scopes": ["cross_project_dashboard:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "cross-project-dashboards",+ "feature_flag_behavior": "enable"+ },+ "cross-project-dashboards-get": {+ "description": "One dashboard with its tiles. Each tile names the project and the insight it points at, never the insight's name, query or numbers. To read a tile's numbers, switch to that project and query the insight there.",+ "category": "Cross-project dashboards",+ "feature": "cross_project_dashboards",+ "summary": "Get one cross-project dashboard",+ "title": "Get one cross-project dashboard",+ "required_scopes": ["cross_project_dashboard:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "cross-project-dashboards",+ "feature_flag_behavior": "enable"+ },+ "cross-project-dashboards-list": {+ "description": "Dashboards the organization owns, each holding insights from one or more projects. Each dashboard comes with its filters and counts of the tiles and projects the reader can open. Get one dashboard to read its tiles.",+ "category": "Cross-project dashboards",+ "feature": "cross_project_dashboards",+ "summary": "List cross-project dashboards",+ "title": "List cross-project dashboards",+ "required_scopes": ["cross_project_dashboard:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "cross-project-dashboards",+ "feature_flag_behavior": "enable"+ },"custom-property-definitions-create": {"description": "Create a Customer Analytics custom property definition — the shape of a custom attribute. Provide `name` (required, unique within the team), optional `description`, `display_type` (required; one of text, number, currency, percent, date, datetime, boolean), and optional `is_big_number` to abbreviate large numeric values (e.g. 10,000 → 10K; only valid for numeric display types). `target_type` picks what the property attaches to: `account` (default; value set manually or from a materialized view), `person`, or `group` (person/group properties are populated from a warehouse table or a materialized view via a custom property source and become usable like any other person/group property in feature flags, cohorts, and insights). For `group` targets, also pass `group_type_index` (0-4) selecting the group type. Person and group targets require the `warehouse-person-properties` feature; creating a `group` target additionally requires the `group:write` scope. Definitions are team-scoped; for account targets, set the value a specific account holds via the account custom property value tools.","category": "Customer analytics",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex fa7657a3505a..1e476132b307 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3015,6 +3015,54 @@"readOnlyHint": false}},+ "cross-project-dashboard-tiles-list": {+ "description": "The tiles on one dashboard. Each tile carries the project id and insight id it references, its grid position and any filters that apply to it alone.",+ "category": "Cross-project dashboards",+ "feature": "cross_project_dashboards",+ "summary": "List the tiles on a cross-project dashboard",+ "title": "List the tiles on a cross-project dashboard",+ "required_scopes": ["cross_project_dashboard:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "cross-project-dashboards",+ "feature_flag_behavior": "enable"+ },+ "cross-project-dashboards-get": {+ "description": "One dashboard with its tiles. Each tile names the project and the insight it points at, never the insight's name, query or numbers. To read a tile's numbers, switch to that project and query the insight there.",+ "category": "Cross-project dashboards",+ "feature": "cross_project_dashboards",+ "summary": "Get one cross-project dashboard",+ "title": "Get one cross-project dashboard",+ "required_scopes": ["cross_project_dashboard:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "cross-project-dashboards",+ "feature_flag_behavior": "enable"+ },+ "cross-project-dashboards-list": {+ "description": "Dashboards the organization owns, each holding insights from one or more projects. Each dashboard comes with its filters and counts of the tiles and projects the reader can open. Get one dashboard to read its tiles.",+ "category": "Cross-project dashboards",+ "feature": "cross_project_dashboards",+ "summary": "List cross-project dashboards",+ "title": "List cross-project dashboards",+ "required_scopes": ["cross_project_dashboard:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "cross-project-dashboards",+ "feature_flag_behavior": "enable"+ },"custom-property-definitions-create": {"description": "Create a Customer Analytics custom property definition — the shape of a custom attribute. Provide `name` (required, unique within the team), optional `description`, `display_type` (required; one of text, number, currency, percent, date, datetime, boolean), and optional `is_big_number` to abbreviate large numeric values (e.g. 10,000 → 10K; only valid for numeric display types). `target_type` picks what the property attaches to: `account` (default; value set manually or from a materialized view), `person`, or `group` (person/group properties are populated from a warehouse table or a materialized view via a custom property source and become usable like any other person/group property in feature flags, cohorts, and insights). For `group` targets, also pass `group_type_index` (0-4) selecting the group type. Person and group targets require the `warehouse-person-properties` feature; creating a `group` target additionally requires the `group:write` scope. Definitions are team-scoped; for account targets, set the value a specific account holds via the account custom property value tools.","category": "Customer analytics",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5acbfa0d93df..863dc1ba7562 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -306,6 +306,7 @@ export namespace Schemas {* * `cohort` - cohort* * `comment` - comment* * `conversation` - conversation+ * * `cross_project_dashboard` - cross_project_dashboard* * `customer_analytics` - customer_analytics* * `customer_task` - customer_task* * `customer_journey` - customer_journey@@ -426,6 +427,7 @@ export namespace Schemas {Cohort: 'cohort',Comment: 'comment',Conversation: 'conversation',+ CrossProjectDashboard: 'cross_project_dashboard',CustomerAnalytics: 'customer_analytics',CustomerTask: 'customer_task',CustomerJourney: 'customer_journey',@@ -546,6 +548,7 @@ export namespace Schemas {* * `cohort` - cohort* * `comment` - comment* * `conversation` - conversation+ * * `cross_project_dashboard` - cross_project_dashboard* * `customer_analytics` - customer_analytics* * `customer_task` - customer_task* * `customer_journey` - customer_journey@@ -770,6 +773,7 @@ export namespace Schemas {* * `cohort` - cohort* * `comment` - comment* * `conversation` - conversation+ * * `cross_project_dashboard` - cross_project_dashboard* * `customer_analytics` - customer_analytics* * `customer_task` - customer_task* * `customer_journey` - customer_journey@@ -1176,6 +1180,7 @@ export namespace Schemas {* * `cohort` - cohort* * `comment` - comment* * `conversation` - conversation+ * * `cross_project_dashboard` - cross_project_dashboard* * `customer_analytics` - customer_analytics* * `customer_task` - customer_task* * `customer_journey` - customer_journey@@ -25612,6 +25617,95 @@ export namespace Schemas {api_version?: string | null;}+ export interface CrossProjectDashboardTile {+ /** Id of the tile. */+ readonly id: string;+ /** Id of the project the tile's insight belongs to. */+ project_id: number;+ /** Id of the insight the tile renders. */+ insight_id: number;+ /** Grid position and size of the tile, keyed by layout size. */+ layouts?: unknown;+ /**+ * Optional color applied to the tile.+ * @maxLength 400+ * @nullable+ */+ color?: string | null;+ /** Filters applied to this tile only, overriding the dashboard's. Supports a date range and an interval. Filters carrying a project-specific id are rejected. */+ filters_overrides?: unknown;+ }++ export interface CrossProjectDashboardCreator {+ /** Id of the user who created the dashboard. */+ readonly id: number;+ /** First name of the user who created the dashboard. */+ readonly first_name: string;+ /** Email of the user who created the dashboard. */+ readonly email: string;+ }++ /**+ * Carries tile references only.+ *+ * The response holds no insight names, queries or results. Each reader fetches each tile from+ * that tile's own project endpoint, so their access, quota and cache key stay correct there.+ */+ export interface CrossProjectDashboard {+ /** Id of the dashboard. */+ readonly id: string;+ /**+ * Name shown in the dashboard list and page header.+ * @maxLength 400+ */+ name: string;+ /**+ * Optional longer description.+ * @maxLength 4000+ */+ description?: string;+ /** Dashboard-level filters applied to every tile. Supports a date range, an interval, and property filters that refer to a property by name. Filters carrying a project-specific id are rejected. */+ filters?: unknown;+ /** Tiles from the projects the reader can open. */+ readonly tiles: readonly CrossProjectDashboardTile[];+ /** The user who created the dashboard. */+ readonly created_by: CrossProjectDashboardCreator | null;+ /** When the dashboard was created. */+ readonly created_at: string;+ /**+ * When the dashboard last changed.+ * @nullable+ */+ readonly updated_at: string | null;+ }++ /**+ * A dashboard in the list. It counts its tiles instead of carrying them; read one dashboard for its tiles.+ */+ export interface CrossProjectDashboardListItem {+ /** Id of the dashboard. */+ readonly id: string;+ /** Name shown in the dashboard list and page header. */+ readonly name: string;+ /** Optional longer description. */+ readonly description: string;+ /** Dashboard-level filters applied to every tile. Supports a date range, an interval, and property filters that refer to a property by name. Filters carrying a project-specific id are rejected. */+ readonly filters: unknown;+ /** Tiles from the projects the reader can open. */+ readonly tile_count: number;+ /** Distinct projects among the tiles the reader can open. */+ readonly project_count: number;+ /** The user who created the dashboard. */+ readonly created_by: CrossProjectDashboardCreator | null;+ /** When the dashboard was created. */+ readonly created_at: string;+ /**+ * When the dashboard last changed.+ * @nullable+ */+ readonly updated_at: string | null;+ }+export interface CurrentBranchHealth {/** Detected default branch ('master' or 'main') from runs in the same 24-hour window. */default_branch: string;@@ -63168,6 +63262,7 @@ export namespace Schemas {* * `cohort` - cohort* * `comment` - comment* * `conversation` - conversation+ * * `cross_project_dashboard` - cross_project_dashboard* * `customer_analytics` - customer_analytics* * `customer_task` - customer_task* * `customer_journey` - customer_journey@@ -66949,6 +67044,24 @@ export namespace Schemas {results: CoreEvent[];}+ export interface PaginatedCrossProjectDashboardListItemList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: CrossProjectDashboardListItem[];+ }++ export interface PaginatedCrossProjectDashboardTileList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: CrossProjectDashboardTile[];+ }+export interface PaginatedCustomPropertyDefinitionList {count: number;/** @nullable */@@ -74945,6 +75058,56 @@ export namespace Schemas {readonly updated_at?: string;}+ /**+ * Carries tile references only.+ *+ * The response holds no insight names, queries or results. Each reader fetches each tile from+ * that tile's own project endpoint, so their access, quota and cache key stay correct there.+ */+ export interface PatchedCrossProjectDashboard {+ /** Id of the dashboard. */+ readonly id?: string;+ /**+ * Name shown in the dashboard list and page header.+ * @maxLength 400+ */+ name?: string;+ /**+ * Optional longer description.+ * @maxLength 4000+ */+ description?: string;+ /** Dashboard-level filters applied to every tile. Supports a date range, an interval, and property filters that refer to a property by name. Filters carrying a project-specific id are rejected. */+ filters?: unknown;+ /** Tiles from the projects the reader can open. */+ readonly tiles?: readonly CrossProjectDashboardTile[];+ /** The user who created the dashboard. */+ readonly created_by?: CrossProjectDashboardCreator | null;+ /** When the dashboard was created. */+ readonly created_at?: string;+ /**+ * When the dashboard last changed.+ * @nullable+ */+ readonly updated_at?: string | null;+ }++ /**+ * A tile's project and insight never change, so an update carries only its placement and styling.+ */+ export interface PatchedCrossProjectDashboardTileUpdate {+ /** Grid position and size of the tile, keyed by layout size. */+ layouts?: unknown;+ /**+ * Optional color applied to the tile.+ * @maxLength 400+ * @nullable+ */+ color?: string | null;+ /** Filters applied to this tile only, overriding the dashboard's. Supports a date range and an interval. Filters carrying a project-specific id are rejected. */+ filters_overrides?: unknown;+ }+/*** A team-scoped definition of a custom account property — the attribute side of the model.*@@ -111919,6 +112082,28 @@ export namespace Schemas {offset?: number;};+ export type CrossProjectDashboardsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };++ export type CrossProjectDashboardsTilesListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type DomainsListParams = {/*** Number of results to return per page.@@ -112607,6 +112792,7 @@ export namespace Schemas {* Filter by a single activity scope, e.g. "FeatureFlag", "Insight", "Dashboard", "Experiment".** * `Cohort` - Cohort+ * * `CrossProjectDashboard` - CrossProjectDashboard* * `FeatureFlag` - FeatureFlag* * `Person` - Person* * `Group` - Group@@ -112711,6 +112897,7 @@ export namespace Schemas {export const ActivityLogListScope = {Cohort: 'Cohort',+ CrossProjectDashboard: 'CrossProjectDashboard',FeatureFlag: 'FeatureFlag',Person: 'Person',Group: 'Group',@@ -112801,6 +112988,7 @@ export namespace Schemas {/*** * `Cohort` - Cohort+ * * `CrossProjectDashboard` - CrossProjectDashboard* * `FeatureFlag` - FeatureFlag* * `Person` - Person* * `Group` - Group@@ -112893,6 +113081,7 @@ export namespace Schemas {export const ActivityLogListScopesItem = {Cohort: 'Cohort',+ CrossProjectDashboard: 'CrossProjectDashboard',FeatureFlag: 'FeatureFlag',Person: 'Person',Group: 'Group',diff --git a/services/mcp/src/generated/cross_project_dashboards/api.ts b/services/mcp/src/generated/cross_project_dashboards/api.tsnew file mode 100644index 000000000000..50002d1ebc25--- /dev/null+++ b/services/mcp/src/generated/cross_project_dashboards/api.ts@@ -0,0 +1,57 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * MCP service uses these Zod schemas for generated tool handlers.+ * To regenerate: hogli build:openapi+ *+ * PostHog API - MCP 3 enabled ops+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++/**+ * Dashboards the organization owns, holding insights from one or more projects.+ */+export const CrossProjectDashboardsListParams = () => zod.object({+ organization_id: zod+ .string()+ .describe(+ "ID of the organization you're trying to access. To find the ID of the organization, make a call to \/api\/organizations\/."+ ),+})++export const CrossProjectDashboardsListQueryParams = () => zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++/**+ * Tiles on one cross-project dashboard, edited one at a time.+ *+ * Writes are per tile rather than a whole-set replace, so two people editing the same+ * dashboard cannot overwrite each other's tiles.+ */+export const CrossProjectDashboardsTilesListParams = () => zod.object({+ dashboard_id: zod.string().describe('Id of the dashboard.'),+ organization_id: zod+ .string()+ .describe(+ "ID of the organization you're trying to access. To find the ID of the organization, make a call to \/api\/organizations\/."+ ),+})++export const CrossProjectDashboardsTilesListQueryParams = () => zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++/**+ * Dashboards the organization owns, holding insights from one or more projects.+ */+export const CrossProjectDashboardsRetrieveParams = () => zod.object({+ id: zod.string().describe('Id of the dashboard.'),+ organization_id: zod+ .string()+ .describe(+ "ID of the organization you're trying to access. To find the ID of the organization, make a call to \/api\/organizations\/."+ ),+})diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex 7a29cbf5383a..c4dd07009231 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -46,6 +46,8 @@ export const OAUTH_SCOPES_SUPPORTED = ['comment:write','conversation:read','conversation:write',+ 'cross_project_dashboard:read',+ 'cross_project_dashboard:write','customer_analytics:read','customer_analytics:write','customer_task:read',diff --git a/services/mcp/src/tools/generated/cross_project_dashboards.ts b/services/mcp/src/tools/generated/cross_project_dashboards.tsnew file mode 100644index 000000000000..9b09fd803f68--- /dev/null+++ b/services/mcp/src/tools/generated/cross_project_dashboards.ts@@ -0,0 +1,87 @@+// AUTO-GENERATED from products/cross_project_dashboards/mcp/tools.yaml + OpenAPI — do not edit+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import * as orvalSchemas from '@/generated/cross_project_dashboards/api'+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'++const CrossProjectDashboardTilesListSchema = () => {+ const CrossProjectDashboardsTilesListParams = orvalSchemas.CrossProjectDashboardsTilesListParams()+ const CrossProjectDashboardsTilesListQueryParams = orvalSchemas.CrossProjectDashboardsTilesListQueryParams()+ return CrossProjectDashboardsTilesListParams.omit({ organization_id: true }).extend(+ CrossProjectDashboardsTilesListQueryParams.shape+ )+}++const crossProjectDashboardTilesList = (): ToolBase<+ ReturnType<typeof CrossProjectDashboardTilesListSchema>,+ WithPostHogUrl<Schemas.PaginatedCrossProjectDashboardTileList>+> => ({+ name: 'cross-project-dashboard-tiles-list',+ schema: CrossProjectDashboardTilesListSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof CrossProjectDashboardTilesListSchema>>) => {+ const orgId = await context.stateManager.getOrgID()+ const result = await context.api.request<Schemas.PaginatedCrossProjectDashboardTileList>({+ method: 'GET',+ path: `/api/organizations/${encodeURIComponent(String(orgId))}/cross_project_dashboards/${encodeURIComponent(String(params.dashboard_id))}/tiles/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ return await withPostHogUrl(context, result, '/')+ },+})++const CrossProjectDashboardsGetSchema = () => {+ const CrossProjectDashboardsRetrieveParams = orvalSchemas.CrossProjectDashboardsRetrieveParams()+ return CrossProjectDashboardsRetrieveParams.omit({ organization_id: true })+}++const crossProjectDashboardsGet = (): ToolBase<+ ReturnType<typeof CrossProjectDashboardsGetSchema>,+ Schemas.CrossProjectDashboard+> => ({+ name: 'cross-project-dashboards-get',+ schema: CrossProjectDashboardsGetSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof CrossProjectDashboardsGetSchema>>) => {+ const orgId = await context.stateManager.getOrgID()+ const result = await context.api.request<Schemas.CrossProjectDashboard>({+ method: 'GET',+ path: `/api/organizations/${encodeURIComponent(String(orgId))}/cross_project_dashboards/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const CrossProjectDashboardsListSchema = () => {+ const CrossProjectDashboardsListQueryParams = orvalSchemas.CrossProjectDashboardsListQueryParams()+ return CrossProjectDashboardsListQueryParams+}++const crossProjectDashboardsList = (): ToolBase<+ ReturnType<typeof CrossProjectDashboardsListSchema>,+ WithPostHogUrl<Schemas.PaginatedCrossProjectDashboardListItemList>+> => ({+ name: 'cross-project-dashboards-list',+ schema: CrossProjectDashboardsListSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof CrossProjectDashboardsListSchema>>) => {+ const orgId = await context.stateManager.getOrgID()+ const result = await context.api.request<Schemas.PaginatedCrossProjectDashboardListItemList>({+ method: 'GET',+ path: `/api/organizations/${encodeURIComponent(String(orgId))}/cross_project_dashboards/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ return await withPostHogUrl(context, result, '/')+ },+})++export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'cross-project-dashboard-tiles-list': crossProjectDashboardTilesList,+ 'cross-project-dashboards-get': crossProjectDashboardsGet,+ 'cross-project-dashboards-list': crossProjectDashboardsList,+}diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.tsindex c60149579581..2783c4c0be02 100644--- a/services/mcp/src/tools/generated/index.ts+++ b/services/mcp/src/tools/generated/index.ts@@ -18,6 +18,7 @@ import { GENERATED_TOOLS as cohorts } from './cohorts'import { GENERATED_TOOLS as context_layer } from './context_layer'import { GENERATED_TOOLS as conversations } from './conversations'import { GENERATED_TOOLS as core } from './core'+import { GENERATED_TOOLS as cross_project_dashboards } from './cross_project_dashboards'import { GENERATED_TOOLS as customer_analytics } from './customer_analytics'import { GENERATED_TOOLS as dashboards } from './dashboards'import { GENERATED_TOOLS as data_catalog } from './data_catalog'@@ -86,6 +87,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =...context_layer,...conversations,...core,+ ...cross_project_dashboards,...customer_analytics,...dashboards,...data_catalog,diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 0656cd2fb058..95608861275a 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1051,6 +1051,7 @@ describe('Tool Filtering - Feature Flags', () => {'self-optimising-workflows','business-knowledge-github-repos','signals-report-checks-replace',+ 'cross-project-dashboards',]expect(allFlags).toEqual(expect.arrayContaining(branchFlags))// The flags branches add are asserted on the line above and held out of the list anddiff --git a/tach.toml b/tach.tomlindex b12d5417120f..f377f22287b4 100644--- a/tach.toml+++ b/tach.toml@@ -1641,3 +1641,17 @@ expose = [from = ["products.webmcp",]++[[modules]]+path = "products.cross_project_dashboards"+depends_on = ["posthog", "products.access_control", "products.product_analytics"]+layer = "modules"++[[interfaces]]+expose = [+ "backend\\.facade.*",+ "backend\\.presentation\\.views.*",+]+from = [+ "products.cross_project_dashboards",+]