Skip to content

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

7.6 KB
Raw Blame
from typing import TYPE_CHECKING, Any

from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models import Q, QuerySet

from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.file_system.constants import DEFAULT_SURFACE
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
from posthog.models.file_system.file_system_representation import FileSystemRepresentation
from posthog.models.tagged_items_relation import Taggable
from posthog.models.utils import RootTeamManager, RootTeamMixin, sane_repr
from posthog.utils import absolute_uri

if TYPE_CHECKING:
    from posthog.models.team import Team


DASHBOARD_GRID_SPACING_GAPS = {
    "tight": 8,
    "condensed": 12,
    "standard": 16,
    "relaxed": 32,
    "wide": 48,
}


class LayoutCompaction(models.TextChoices):
    VERTICAL = "vertical", "vertical"
    HORIZONTAL = "horizontal", "horizontal"
    STABLE = "stable", "stable"


DASHBOARD_GRID_COMPACTION_MODES = tuple(LayoutCompaction.values)


class TileGroupDisplay(models.TextChoices):
    SECTIONS = "sections", "sections"
    TABS = "tabs", "tabs"


DASHBOARD_TILE_GROUP_DISPLAY_MODES = tuple(TileGroupDisplay.values)


class DashboardTileGroupColor(models.TextChoices):
    BLUE = "blue", "Blue"
    PURPLE = "purple", "Purple"
    GREEN = "green", "Green"
    YELLOW = "yellow", "Yellow"
    ORANGE = "orange", "Orange"
    RED = "red", "Red"


class DashboardManager(RootTeamManager):
    def get_queryset(self):
        return super().get_queryset().exclude(deleted=True)


class Dashboard(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Model):
    class CreationMode(models.TextChoices):
        DEFAULT = "default", "Default"
        TEMPLATE = (
            "template",
            "Template",
        )  # dashboard was created from a predefined template
        DUPLICATE = (
            "duplicate",
            "Duplicate",
        )  # dashboard was duplicated from another dashboard
        UNLISTED = (
            "unlisted",
            "Unlisted (product-embedded)",
        )  # Product dashboards (e.g. AI observability) - hidden from general lists, accessed via tag queries

    name = models.CharField(max_length=400, null=True, blank=True)
    description = models.TextField(blank=True)
    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
    pinned = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True, blank=True)
    created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    deleted = models.BooleanField(default=False)
    last_accessed_at = models.DateTimeField(blank=True, null=True)
    last_refresh = models.DateTimeField(blank=True, null=True)
    filters = models.JSONField(default=dict)
    variables = models.JSONField(default=dict, null=True, blank=True)
    breakdown_colors = models.JSONField(default=list, null=True, blank=True)
    data_color_theme = models.ForeignKey(
        "posthog.DataColorTheme", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
    )
    creation_mode = models.CharField(max_length=16, default="default", choices=CreationMode)
    insights = models.ManyToManyField(
        "product_analytics.Insight", related_name="dashboards", through="DashboardTile", blank=True
    )  # type: models.ManyToManyField
    quick_filter_ids = models.JSONField(default=list, blank=True, null=True)
    customization = models.JSONField(default=dict, db_default={}, blank=True)

    # Deprecated in favour of app-wide tagging model. See EnterpriseTaggedItem
    deprecated_tags: ArrayField = ArrayField(models.CharField(max_length=32), null=True, blank=True, default=list)
    deprecated_tags_v2: ArrayField = ArrayField(
        models.CharField(max_length=32),
        null=True,
        blank=True,
        default=None,
        db_column="tags",
    )

    # DEPRECATED: using the new "sharing" relation instead
    share_token = models.CharField(max_length=400, null=True, blank=True)
    # DEPRECATED: using the new "is_sharing_enabled" relation instead
    is_shared = models.BooleanField(default=False)

    objects = DashboardManager()  # type: ignore
    objects_including_soft_deleted: models.Manager["Dashboard"] = RootTeamManager()

    __repr__ = sane_repr("team_id", "id", "name")

    class Meta:
        indexes = [
            models.Index(
                name="idx_dashboard_deleted_team_id",
                fields=["-pinned", "name", "deleted", "team_id"],
                condition=models.Q(deleted=False),
            ),
        ]
        db_table = "posthog_dashboard"

    def __str__(self):
        return self.name or str(self.id)

    def delete(self, *args, **kwargs):
        from posthog.models.group_type_mapping import clear_dashboard_from_group_type_mapping

        clear_dashboard_from_group_type_mapping(
            team_id=self.team_id, dashboard_id=self.id, project_id=self.team.project_id
        )
        return super().delete(*args, **kwargs)

    @classmethod
    def get_file_system_unfiled(cls, team: "Team", surface: str = DEFAULT_SURFACE) -> QuerySet["Dashboard"]:
        base_qs = cls.objects.filter(team=team, deleted=False).exclude(creation_mode="template")
        return cls._filter_unfiled_queryset(base_qs, team, type="dashboard", ref_field="id", surface=surface)

    def get_file_system_representation(self) -> FileSystemRepresentation:
        should_delete = self.deleted or (self.creation_mode == "template")
        return FileSystemRepresentation(
            base_folder=self._get_assigned_folder("Unfiled/Dashboards"),
            type="dashboard",  # sync with APIScopeObject in scopes.py
            ref=str(self.id),
            name=self.name or "Untitled",
            href=f"/dashboard/{self.id}",
            meta={
                "created_at": str(self.created_at),
                "created_by": self.created_by_id,
            },
            should_delete=should_delete,
        )

    @property
    def is_sharing_enabled(self):
        # uses .all and not .first so that prefetching in serializers can be used
        sharing_configurations = self.sharingconfiguration_set.all()
        return sharing_configurations[0].enabled if sharing_configurations and sharing_configurations[0] else False

    @property
    def url(self):
        return absolute_uri(f"/dashboard/{self.id}")

    def get_analytics_metadata(self) -> dict[str, Any]:
        """
        Returns serialized information about the object for analytics reporting.
        """
        return {
            "dashboard_id": self.pk,
            "pinned": self.pinned,
            "item_count": self.tiles.exclude(insight=None).count(),
            "is_shared": self.is_sharing_enabled,
            "created_at": self.created_at,
            "has_description": self.description != "",
            "tags_count": self.tagged_items.count(),
            "creation_mode": self.creation_mode,
            "group_display": self.group_display,
            "group_count": self.tile_group_count,
        }

    @property
    def group_display(self) -> str:
        group_display = self.customization.get("group_display") if isinstance(self.customization, dict) else None
        return group_display if group_display in DASHBOARD_TILE_GROUP_DISPLAY_MODES else TileGroupDisplay.SECTIONS

    @property
    def tile_group_keys(self) -> set[str]:
        visible_tiles = self.tiles.filter(Q(insight__deleted=False) | Q(insight__isnull=True))
        return {group_key for group_key in visible_tiles.values_list("group_key", flat=True) if group_key}

    @property
    def tile_group_count(self) -> int:
        return len(self.tile_group_keys)