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.

6.8 KB
Raw Blame
from dataclasses import asdict
from typing import TYPE_CHECKING, Union

from django.db import models
from django.db.models import QuerySet
from django.db.models.signals import post_delete, post_save
from django.dispatch.dispatcher import receiver
from django.utils import timezone

from posthog.hogql.errors import BaseHogQLError

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.signals import mutable_receiver
from posthog.models.tagged_items_relation import Taggable
from posthog.models.utils import RootTeamMixin
from posthog.plugins.plugin_server_api import drop_action_on_workers, reload_action_on_workers

from products.actions.backend.facade.contracts import ActionSaved, ActionStep
from products.actions.backend.logic import saved_handlers

if TYPE_CHECKING:
    from posthog.models.team import Team


class Action(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.Model):
    name = models.CharField(max_length=400, null=True, blank=True)
    description = models.TextField(blank=True, default="")
    team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
    project = models.ForeignKey("posthog.Project", on_delete=models.CASCADE, null=True, blank=True, related_name="+")
    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)
    events = models.ManyToManyField("posthog.Event", blank=True, related_name="+")  # type: models.ManyToManyField
    post_to_slack = models.BooleanField(default=False)
    slack_message_format = models.CharField(default="", max_length=1200, blank=True)
    updated_at = models.DateTimeField(auto_now=True)
    bytecode = models.JSONField(null=True, blank=True)
    bytecode_error = models.TextField(blank=True, null=True)
    steps_json = models.JSONField(null=True, blank=True)
    pinned_at = models.DateTimeField(blank=True, null=True, default=None)
    summary = models.TextField(blank=True, null=True, help_text="A summary of the action, generated by AI")
    last_summarized_at = models.DateTimeField(
        blank=True, null=True, help_text="The last time the action was summarized by AI"
    )
    embedding_last_synced_at = models.DateTimeField(
        blank=True, null=True, help_text="The last time the action was synced to the vector database"
    )
    embedding_version = models.PositiveSmallIntegerField(
        blank=True, null=True, help_text="The version of the embedding model used to embed the action"
    )

    # DEPRECATED: these were used before ClickHouse was our database
    is_calculating = models.BooleanField(default=False)
    last_calculated_at = models.DateTimeField(default=timezone.now, blank=True)

    class Meta:
        indexes = [models.Index(fields=["team_id", "-updated_at"])]
        db_table = "posthog_action"

    def __str__(self) -> str:
        return self.name or ""

    def save(self, *args, **kwargs) -> None:
        self.refresh_bytecode()
        super().save(*args, **kwargs)

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

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

    def get_analytics_metadata(self) -> dict:
        return {
            "post_to_slack": self.post_to_slack,
            "name_length": len(self.name or ""),
            "custom_slack_message_format": self.slack_message_format != "",
            "event_count_precalc": self.events.count(),  # `precalc` because events are computed async
            "step_count": len(self.steps),
            "match_text_count": sum(1 if step.text else 0 for step in self.steps),
            "match_href_count": sum(1 if step.href else 0 for step in self.steps),
            "match_selector_count": sum(1 if step.selector else 0 for step in self.steps),
            "match_url_count": sum(1 if step.url else 0 for step in self.steps),
            "has_properties": any(step.properties for step in self.steps),
            "deleted": self.deleted,
            "pinned": bool(self.pinned_at),
            "pinned_at": self.pinned_at,
        }

    @property
    def steps(self) -> list[ActionStep]:
        return [ActionStep(**step) for step in self.steps_json or []]

    @steps.setter
    def steps(self, value: list[dict]) -> None:
        # TRICKY: This is a little tricky as DRF will deserialize this here as a dict but typing wise we would expect an ActionStep
        self.steps_json = [asdict(ActionStep(**step)) for step in value]

    def get_step_events(self) -> list[Union[str, None]]:
        return [action_step.event for action_step in self.steps]

    def refresh_bytecode(self) -> None:
        from posthog.hogql.compiler.bytecode import create_bytecode
        from posthog.hogql.property import steps_to_expr

        try:
            new_bytecode = create_bytecode(steps_to_expr(self.steps, self.team)).bytecode
            if new_bytecode != self.bytecode or self.bytecode_error is not None:
                self.bytecode = new_bytecode
                self.bytecode_error = None
        except BaseHogQLError as e:
            # There are several known cases when bytecode generation can fail. Instead of spamming
            # with errors, ignore those cases for now.
            if self.bytecode is not None or self.bytecode_error != str(e):
                self.bytecode = None
                self.bytecode_error = str(e)


@receiver(post_save, sender=Action)
def action_saved(sender: type, instance: Action, created: bool, **kwargs: object) -> None:
    reload_action_on_workers(team_id=instance.team_id, action_id=instance.id)
    saved_handlers.dispatch(ActionSaved(action_id=instance.id, team_id=instance.team_id, created=created))


@mutable_receiver(post_delete, sender=Action)
def action_deleted(sender: type, instance: Action, **kwargs: object) -> None:
    drop_action_on_workers(team_id=instance.team_id, action_id=instance.id)