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.

chore(workflows): route the template viewset through the facade (#108488)

Harley Alexanderfeaa7b2b10e7
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index 025372f7f94a..4865ad539b6a 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -5,7 +5,11 @@ from uuid import UUID
from posthog.dataclasses import frozen
-from products.workflows.backend.facade.enums import HogFlowBatchJobState
+from products.workflows.backend.facade.enums import (
+ HogFlowBatchJobState,
+ HogFlowTemplateExitCondition,
+ HogFlowTemplateScope,
+)
if TYPE_CHECKING:
from posthog.models.team.team import Team
@@ -146,6 +150,37 @@ class EmailSendingSuspensionChange:
previously_suspended_at: datetime | None = None
+@frozen
+class WorkflowTemplate:
+ """A workflow template stored in the database, owned by one team.
+
+ ``created_by`` carries the core ``User`` row rather than a projection of it, so the
+ presentation layer keeps serializing it through core's ``UserBasicSerializer``.
+
+ ``edges`` and ``actions`` hold lists, but a row saved without them keeps the model default
+ ``{}``, so both fields can also be a dict.
+ """
+
+ id: UUID
+ team_id: int
+ name: str
+ description: str
+ image_url: str | None
+ tags: list[str]
+ scope: HogFlowTemplateScope
+ created_at: datetime
+ created_by: "User | None"
+ updated_at: datetime
+ trigger: dict[str, Any]
+ trigger_masking: dict[str, Any] | None
+ conversion: dict[str, Any] | None
+ exit_condition: HogFlowTemplateExitCondition
+ edges: list[dict[str, Any]] | dict[str, Any]
+ actions: list[dict[str, Any]] | dict[str, Any]
+ abort_action: str | None
+ variables: list[dict[str, Any]] | None
+
+
# The provider payloads below are TypedDicts, not frozen dataclasses: the email-verify endpoint
# returns them as JSON without a serializer, so the keys are the API response keys.
diff --git a/products/workflows/backend/facade/enums.py b/products/workflows/backend/facade/enums.py
index c5fc46b8398d..667fa859fe39 100644
--- a/products/workflows/backend/facade/enums.py
+++ b/products/workflows/backend/facade/enums.py
@@ -19,6 +19,21 @@ EMAIL_TRACKING_CONSENT_MODE_CHOICES = [
]
+class HogFlowTemplateScope(LabeledStrEnum):
+ """Visibility of the workflow template"""
+
+ ONLY_TEAM = "team", "Only team"
+ ORGANIZATION = "organization", "Organization"
+ GLOBAL = "global", "Global"
+
+
+class HogFlowTemplateExitCondition(LabeledStrEnum):
+ CONVERSION = "exit_on_conversion"
+ TRIGGER_NOT_MATCHED = "exit_on_trigger_not_matched"
+ TRIGGER_NOT_MATCHED_OR_CONVERSION = "exit_on_trigger_not_matched_or_conversion"
+ ONLY_AT_END = "exit_only_at_end"
+
+
class HogFlowBatchJobState(LabeledStrEnum):
WAITING = "waiting"
QUEUED = "queued"
diff --git a/products/workflows/backend/facade/templates.py b/products/workflows/backend/facade/templates.py
new file mode 100644
index 000000000000..a2f90148de37
--- /dev/null
+++ b/products/workflows/backend/facade/templates.py
@@ -0,0 +1,26 @@
+"""Workflow templates: the team and organization templates in the database, and the global
+templates that ship as code."""
+
+from products.workflows.backend.services.hog_flow_templates import (
+ WorkflowTemplateNotFound,
+ create_template,
+ delete_template,
+ function_template_exists,
+ get_global_template,
+ get_template,
+ list_global_templates,
+ list_templates,
+ update_template,
+)
+
+__all__ = [
+ "WorkflowTemplateNotFound",
+ "create_template",
+ "delete_template",
+ "function_template_exists",
+ "get_global_template",
+ "get_template",
+ "list_global_templates",
+ "list_templates",
+ "update_template",
+]
diff --git a/products/workflows/backend/models/hog_flow/hog_flow_template.py b/products/workflows/backend/models/hog_flow/hog_flow_template.py
index 83987df0a6c0..a00e85203d47 100644
--- a/products/workflows/backend/models/hog_flow/hog_flow_template.py
+++ b/products/workflows/backend/models/hog_flow/hog_flow_template.py
@@ -7,6 +7,8 @@ import structlog
from posthog.models.utils import UUIDTModel
+from products.workflows.backend.facade.enums import HogFlowTemplateExitCondition, HogFlowTemplateScope
+
if TYPE_CHECKING:
pass
@@ -24,24 +26,14 @@ class HogFlowTemplate(UUIDTModel):
models.Index(fields=["team"]),
]
- class ExitCondition(models.TextChoices):
- CONVERSION = "exit_on_conversion"
- TRIGGER_NOT_MATCHED = "exit_on_trigger_not_matched"
- TRIGGER_NOT_MATCHED_OR_CONVERSION = "exit_on_trigger_not_matched_or_conversion"
- ONLY_AT_END = "exit_only_at_end"
-
- class Scope(models.TextChoices):
- """Visibility of the workflow template"""
-
- ONLY_TEAM = "team", "Only team"
- ORGANIZATION = "organization", "Organization"
- GLOBAL = "global", "Global"
+ ExitCondition = HogFlowTemplateExitCondition
+ Scope = HogFlowTemplateScope
name = models.CharField(max_length=400)
description = models.TextField(blank=True, default="")
image_url = models.CharField(max_length=8201, null=True, blank=True)
tags = ArrayField(models.CharField(max_length=255), blank=True, default=list)
- scope = models.CharField(max_length=24, choices=Scope)
+ scope = models.CharField(max_length=24, choices=Scope.choices)
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
created_at = models.DateTimeField(auto_now_add=True)
@@ -51,7 +43,9 @@ class HogFlowTemplate(UUIDTModel):
trigger = models.JSONField(default=dict)
trigger_masking = models.JSONField(null=True, blank=True)
conversion = models.JSONField(null=True, blank=True)
- exit_condition = models.CharField(max_length=100, choices=ExitCondition, default=ExitCondition.CONVERSION)
+ exit_condition = models.CharField(
+ max_length=100, choices=ExitCondition.choices, default=ExitCondition.CONVERSION.value
+ )
edges = models.JSONField(default=dict)
actions = models.JSONField(default=dict)
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 757a042dfadd..3d9b344b5317 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -78,12 +78,7 @@ from posthog.api.utils import log_activity_from_viewset
from posthog.auth import InternalAPIAuthentication
from posthog.cdp.filters import DATA_WAREHOUSE_SOURCES, compile_filters_expr
from posthog.cdp.flag_gated_templates import FLAG_GATED_TEMPLATE_IDS, gated_template_enabled
-from posthog.cdp.validation import (
- HogFunctionFiltersSerializer,
- InputsSchemaItemSerializer,
- InputsSerializer,
- generate_template_bytecode,
-)
+from posthog.cdp.validation import HogFunctionFiltersSerializer, InputsSchemaItemSerializer, InputsSerializer
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.dataclasses import frozen
from posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_source, report_user_action
@@ -163,6 +158,11 @@ from products.workflows.backend.presentation.views.hog_flow_batch_job import (
HogFlowBatchJobCancelResponseSerializer,
HogFlowBatchJobSerializer,
)
+from products.workflows.backend.presentation.views.hog_flow_fields import (
+ HOG_FLOW_VARIABLES_MAX_BYTES,
+ HogFlowMaskingSerializer,
+ HogFlowVariableSerializer,
+)
from products.workflows.backend.presentation.views.message_assets import (
MessageAssetContentRequestSerializer,
MessageAssetSerializer,
@@ -2021,59 +2021,6 @@ class HogFlowActionSerializer(serializers.Serializer):
raise serializers.ValidationError({"config": f"delay_until.expression could not be read as SQL: {e}"})
-# Caps both the variable definitions on a workflow and the variable values a single run passes,
-# so the two share one number instead of drifting. The runtime also checks dynamically set
-# variables against this same limit; each cap here front-runs that check with a clearer error.
-HOG_FLOW_VARIABLES_MAX_BYTES = 5120
-
-
-class HogFlowVariableSerializer(serializers.ListSerializer):
- child = serializers.DictField(
- child=serializers.CharField(allow_blank=True),
- help_text="Variable: {key, type: string|number|boolean, default}.",
- )
-
- def validate(self, attrs):
- # Make sure the keys are unique
- keys = [item.get("key") for item in attrs]
- if len(keys) != len(set(keys)):
- raise serializers.ValidationError("Variable keys must be unique")
-
- # Make sure entire variables definition is less than 5KB
- # This is just a check for massive keys / default values, we also have a check for dynamically
- # set variables during execution
- total_size = sum(len(json.dumps(item)) for item in attrs)
- if total_size > HOG_FLOW_VARIABLES_MAX_BYTES:
- raise serializers.ValidationError("Total size of variables definition must be less than 5KB")
-
- return super().validate(attrs)
-
-
-class HogFlowMaskingSerializer(serializers.Serializer):
- ttl = serializers.IntegerField(
- required=False,
- min_value=60,
- max_value=60 * 60 * 24 * 365 * 3,
- allow_null=True,
- help_text="Seconds (60 to ~94M / 3y) to suppress repeat firings of the same hash.",
- )
- threshold = serializers.IntegerField(
- required=False,
- allow_null=True,
- help_text="Fire once per N matches of the same hash within ttl — a sampler: N=3 fires on the 1st, 4th, 7th… match. Omit to fire on the first match, then suppress repeats within ttl.",
- )
- hash = serializers.CharField(
- required=True,
- help_text="HogQL template defining the dedup/grouping key, e.g. '{person.id}' (once per person) within ttl.",
- )
- bytecode = serializers.JSONField(required=False, allow_null=True, help_text="Auto-compiled from hash. Do not set.")
-
- def validate(self, attrs):
- attrs["bytecode"] = generate_template_bytecode(attrs["hash"], input_collector=set())
-
- return super().validate(attrs)
-
-
@extend_schema_field(HogFunctionFiltersSerializer)
class HogFlowConversionEventFiltersField(serializers.JSONField):
# Schema-typed as HogFunctionFilters for codegen, but runtime-lenient: drafts may hold invalid
diff --git a/products/workflows/backend/presentation/views/hog_flow_fields.py b/products/workflows/backend/presentation/views/hog_flow_fields.py
new file mode 100644
index 000000000000..04baf6ce763c
--- /dev/null
+++ b/products/workflows/backend/presentation/views/hog_flow_fields.py
@@ -0,0 +1,57 @@
+import json
+
+from rest_framework import serializers
+
+from posthog.cdp.validation import generate_template_bytecode
+
+# Caps both the variable definitions on a workflow and the variable values a single run passes,
+# so the two share one number instead of drifting. The runtime also checks dynamically set
+# variables against this same limit; each cap here front-runs that check with a clearer error.
+HOG_FLOW_VARIABLES_MAX_BYTES = 5120
+
+
+class HogFlowVariableSerializer(serializers.ListSerializer):
+ child = serializers.DictField(
+ child=serializers.CharField(allow_blank=True),
+ help_text="Variable: {key, type: string|number|boolean, default}.",
+ )
+
+ def validate(self, attrs):
+ # Make sure the keys are unique
+ keys = [item.get("key") for item in attrs]
+ if len(keys) != len(set(keys)):
+ raise serializers.ValidationError("Variable keys must be unique")
+
+ # Make sure entire variables definition is less than 5KB
+ # This is just a check for massive keys / default values, we also have a check for dynamically
+ # set variables during execution
+ total_size = sum(len(json.dumps(item)) for item in attrs)
+ if total_size > HOG_FLOW_VARIABLES_MAX_BYTES:
+ raise serializers.ValidationError("Total size of variables definition must be less than 5KB")
+
+ return super().validate(attrs)
+
+
+class HogFlowMaskingSerializer(serializers.Serializer):
+ ttl = serializers.IntegerField(
+ required=False,
+ min_value=60,
+ max_value=60 * 60 * 24 * 365 * 3,
+ allow_null=True,
+ help_text="Seconds (60 to ~94M / 3y) to suppress repeat firings of the same hash.",
+ )
+ threshold = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text="Fire once per N matches of the same hash within ttl — a sampler: N=3 fires on the 1st, 4th, 7th… match. Omit to fire on the first match, then suppress repeats within ttl.",
+ )
+ hash = serializers.CharField(
+ required=True,
+ help_text="HogQL template defining the dedup/grouping key, e.g. '{person.id}' (once per person) within ttl.",
+ )
+ bytecode = serializers.JSONField(required=False, allow_null=True, help_text="Auto-compiled from hash. Do not set.")
+
+ def validate(self, attrs):
+ attrs["bytecode"] = generate_template_bytecode(attrs["hash"], input_collector=set())
+
+ return super().validate(attrs)
diff --git a/products/workflows/backend/presentation/views/hog_flow_template.py b/products/workflows/backend/presentation/views/hog_flow_template.py
index 9730497f93c5..0fd62e1c44fa 100644
--- a/products/workflows/backend/presentation/views/hog_flow_template.py
+++ b/products/workflows/backend/presentation/views/hog_flow_template.py
@@ -1,10 +1,10 @@
-from typing import Optional, cast
-
-from django.db.models import Q
+from typing import Any, Optional, cast
import structlog
-from drf_spectacular.utils import extend_schema, extend_schema_field
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
from rest_framework import mixins, permissions, serializers, status, viewsets
+from rest_framework.exceptions import NotFound
from rest_framework.permissions import SAFE_METHODS, BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
@@ -17,10 +17,23 @@ from posthog.helpers.impersonation import is_impersonated
from posthog.models import User
from posthog.models.activity_logging.activity_log import Detail, log_activity
-from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
-from products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplate
-from products.workflows.backend.presentation.views.hog_flow import HogFlowMaskingSerializer, HogFlowVariableSerializer
-from products.workflows.backend.templates import get_global_template_by_id, load_global_templates
+from products.workflows.backend.facade.contracts import WorkflowTemplate
+from products.workflows.backend.facade.enums import HogFlowTemplateExitCondition, HogFlowTemplateScope
+from products.workflows.backend.facade.templates import (
+ WorkflowTemplateNotFound,
+ create_template,
+ delete_template,
+ function_template_exists,
+ get_global_template,
+ get_template,
+ list_global_templates,
+ list_templates,
+ update_template,
+)
+from products.workflows.backend.presentation.views.hog_flow_fields import (
+ HogFlowMaskingSerializer,
+ HogFlowVariableSerializer,
+)
logger = structlog.get_logger(__name__)
@@ -36,18 +49,18 @@ class PreventGlobalTemplateDatabaseOperations(BasePermission):
# Block creation of global templates in the database
if request.method == "POST":
scope = request.data.get("scope")
- if scope == HogFlowTemplate.Scope.GLOBAL:
+ if scope == HogFlowTemplateScope.GLOBAL:
return False
return True
- def has_object_permission(self, request: Request, view, obj: HogFlowTemplate) -> bool:
+ def has_object_permission(self, request: Request, view, obj: WorkflowTemplate) -> bool:
if request.method in SAFE_METHODS:
return True
# Block all modifications to global templates (stored in DB or files)
# This includes updating team templates to global scope
- if obj.scope == HogFlowTemplate.Scope.GLOBAL or request.data.get("scope") == HogFlowTemplate.Scope.GLOBAL:
+ if obj.scope == HogFlowTemplateScope.GLOBAL or request.data.get("scope") == HogFlowTemplateScope.GLOBAL:
return False
return True
@@ -97,8 +110,7 @@ class HogFlowTemplateActionSerializer(serializers.Serializer):
# Instead, we just verify the template exists
if "function" in data.get("type", "") or trigger_is_function:
template_id = data.get("config", {}).get("template_id", "")
- template = HogFunctionTemplate.get_template(template_id)
- if not template:
+ if not function_template_exists(template_id):
raise serializers.ValidationError({"template_id": "Template not found"})
conditions = data.get("config", {}).get("conditions", [])
@@ -122,40 +134,50 @@ class HogFlowTemplateActionSerializer(serializers.Serializer):
return data
-class HogFlowTemplateSerializer(serializers.ModelSerializer):
+class HogFlowTemplateSerializer(serializers.Serializer):
"""
Serializer for creating hog flow templates.
Validates and sanitizes the workflow before creating it as a template.
"""
+ id = serializers.UUIDField(read_only=True, help_text="ID of the template.")
+ name = serializers.CharField(max_length=400, help_text="Template name.")
+ description = serializers.CharField(
+ allow_blank=True, required=False, style={"base_template": "textarea.html"}, help_text="Template description."
+ )
+ image_url = serializers.CharField(
+ max_length=8201,
+ allow_blank=True,
+ allow_null=True,
+ required=False,
+ help_text="URL of the image shown on the template card.",
+ )
+ tags = serializers.ListField(
+ child=serializers.CharField(), required=False, default=list, help_text="Tags for filtering templates."
+ )
+ scope = serializers.ChoiceField(
+ choices=HogFlowTemplateScope.choices,
+ help_text="Who can use the template: this project only, or every project in the organization.",
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the template was created.")
created_by = serializers.SerializerMethodField()
- actions = serializers.ListField(child=HogFlowTemplateActionSerializer(), required=True)
+ updated_at = serializers.DateTimeField(read_only=True, help_text="When the template was last updated.")
+ trigger = serializers.JSONField(
+ required=False, help_text="Trigger config. Set from the config of the trigger action on save."
+ )
trigger_masking = HogFlowMaskingSerializer(required=False, allow_null=True)
+ conversion = serializers.JSONField(required=False, allow_null=True, help_text="Conversion goal config.")
+ exit_condition = serializers.ChoiceField(
+ choices=HogFlowTemplateExitCondition.choices,
+ required=False,
+ help_text="When a person exits a workflow created from the template.",
+ )
+ edges = serializers.JSONField(required=False, help_text="Connections between the actions.")
+ actions = serializers.ListField(child=HogFlowTemplateActionSerializer(), required=True)
+ abort_action = serializers.CharField(
+ max_length=400, allow_blank=True, allow_null=True, required=False, help_text="ID of the abort action."
+ )
variables = HogFlowVariableSerializer(required=False)
- tags = serializers.ListField(child=serializers.CharField(), required=False, default=list)
-
- class Meta:
- model = HogFlowTemplate
- fields = [
- "id",
- "name",
- "description",
- "image_url",
- "tags",
- "scope",
- "created_at",
- "created_by",
- "updated_at",
- "trigger",
- "trigger_masking",
- "conversion",
- "exit_condition",
- "edges",
- "actions",
- "abort_action",
- "variables",
- ]
- read_only_fields = ["id", "created_at", "updated_at", "created_by"]
@extend_schema_field({"type": "object", "nullable": True})
def get_created_by(self, obj):
@@ -166,7 +188,7 @@ class HogFlowTemplateSerializer(serializers.ModelSerializer):
return None
def validate(self, data):
- instance = cast(Optional[HogFlowTemplate], self.instance)
+ instance = cast(Optional[WorkflowTemplate], self.instance)
name = data.get("name")
if name is None:
@@ -197,62 +219,51 @@ class HogFlowTemplateSerializer(serializers.ModelSerializer):
return data
- def create(self, validated_data: dict, *args, **kwargs) -> HogFlowTemplate:
- request = self.context["request"]
- team_id = self.context["team_id"]
- # Allow setting created_by via context (e.g. for imports from admin panel)
- if "created_by" in self.context:
- validated_data["created_by"] = self.context["created_by"]
- else:
- validated_data["created_by"] = request.user
- validated_data["team_id"] = team_id
- # Ensure scope is always set (defaults to 'team' if not provided)
- if not validated_data.get("scope"):
- validated_data["scope"] = HogFlowTemplate.Scope.ONLY_TEAM
-
- # Allow preserving ID from context (e.g. for admin panel imports)
- template_id = self.context.get("template_id")
- if template_id:
- validated_data["id"] = template_id
- return super().create(validated_data=validated_data)
+# Without a queryset drf-spectacular cannot read the id type from the model, so the detail routes declare it.
+_TEMPLATE_ID_PARAMETER = OpenApiParameter(
+ "id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="A UUID string identifying this hog flow template."
+)
@extend_schema(extensions={"x-product": "workflows"})
-class HogFlowTemplateViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.ModelViewSet):
+@extend_schema_view(
+ retrieve=extend_schema(parameters=[_TEMPLATE_ID_PARAMETER]),
+ update=extend_schema(parameters=[_TEMPLATE_ID_PARAMETER]),
+ partial_update=extend_schema(parameters=[_TEMPLATE_ID_PARAMETER]),
+ destroy=extend_schema(parameters=[_TEMPLATE_ID_PARAMETER]),
+ logs=extend_schema(parameters=[_TEMPLATE_ID_PARAMETER]),
+)
+class HogFlowTemplateViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.GenericViewSet):
scope_object = "INTERNAL"
- queryset = HogFlowTemplate.objects.all()
serializer_class = HogFlowTemplateSerializer
permission_classes = [PreventGlobalTemplateDatabaseOperations]
log_source = "hog_flow_template"
app_source = "hog_flow_template"
http_method_names = ["get", "post", "put", "patch", "delete", "head", "options"]
- def dangerously_get_queryset(self):
- # NOTE: we use the dangerous version as we want to bypass the team/org scoping and do it here instead depending on the scope
- # Return team-specific templates and org-scoped templates from any team in the same org
- qs = HogFlowTemplate.objects.filter(
- Q(team_id=self.team_id)
- | Q(scope=HogFlowTemplate.Scope.ORGANIZATION, team__organization_id=self.organization.id)
- ).exclude(scope=HogFlowTemplate.Scope.GLOBAL)
-
- if self.action == "list":
- qs = qs.order_by("-updated_at")
-
- return qs
+ def dangerously_get_object(self) -> WorkflowTemplate:
+ # Team and org scoping happens in the facade lookup, as the model has no fail-closed manager.
+ template = get_template(
+ team_id=self.team_id, organization_id=self.organization.id, template_id=str(self.kwargs["pk"])
+ )
+ if template is None:
+ raise NotFound()
+ self.check_object_permissions(self.request, template)
+ return template
- def list(self, request, *args, **kwargs):
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
"""
Override list to include global templates from files alongside team templates from DB.
"""
# Get team templates from database (unpaginated first)
- queryset = self.filter_queryset(self.get_queryset())
- serializer = self.get_serializer(queryset, many=True)
- db_templates = serializer.data
+ db_templates = self.get_serializer(
+ list_templates(team_id=self.team_id, organization_id=self.organization.id), many=True
+ ).data
# Load global templates from files
try:
- file_templates = load_global_templates()
+ file_templates = list_global_templates()
except Exception as e:
logger.warning("Failed to load global templates from files", error=str(e))
file_templates = []
@@ -267,84 +278,108 @@ class HogFlowTemplateViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.Mod
return Response(all_templates)
- def retrieve(self, request, *args, **kwargs):
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
"""
Check file-based global templates first, then DB team templates.
- The queryset excludes all global templates from DB, so this only returns team templates from DB.
+ The DB lookup excludes all global templates, so this only returns team templates from DB.
"""
template_id: str = kwargs["pk"]
# Check if it's a global template from files
- file_template = get_global_template_by_id(template_id)
+ file_template = get_global_template(template_id)
if file_template:
return Response(file_template)
# Not in files, check DB for team templates
- return super().retrieve(request, *args, **kwargs)
+ return Response(self.get_serializer(self.get_object()).data)
- def perform_create(self, serializer):
- serializer.save()
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ template = create_template(
+ team_id=self.team_id, created_by_id=cast(User, request.user).id, fields=serializer.validated_data
+ )
log_activity(
organization_id=self.organization.id,
team_id=self.team_id,
- user=serializer.context["request"].user,
- was_impersonated=is_impersonated(serializer.context["request"]),
- item_id=serializer.instance.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated(request),
+ item_id=template.id,
scope="HogFlowTemplate",
activity="created",
- detail=Detail(name=serializer.instance.name, type="standard"),
+ detail=Detail(name=template.name, type="standard"),
)
try:
# report_user_action injects source and MCP-client properties so template usage is
# attributable per channel (web builder vs MCP vs raw API).
report_user_action(
- serializer.context["request"].user,
+ request.user,
"hog_flow_template_created",
{
- "workflow_template_id": str(serializer.instance.id),
- "workflow_template_name": serializer.instance.name,
- "edges_count": len(serializer.instance.edges or []),
- "actions_count": len(serializer.instance.actions or []),
+ "workflow_template_id": str(template.id),
+ "workflow_template_name": template.name,
+ "edges_count": len(template.edges or []),
+ "actions_count": len(template.actions or []),
"team_id": str(self.team_id),
"organization_id": str(self.organization.id),
- "scope": serializer.instance.scope if serializer.instance else None,
+ "scope": template.scope,
},
team=self.team,
- request=serializer.context["request"],
+ request=request,
)
except Exception as e:
logger.warning("Failed to capture hog_flow_template_created event", error=str(e))
- def perform_update(self, serializer):
- serializer.validated_data["team_id"] = self.team_id
+ return Response(self.get_serializer(template).data, status=status.HTTP_201_CREATED)
+
+ def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ partial = kwargs.pop("partial", False)
+ template = self.get_object()
+ serializer = self.get_serializer(template, data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
log_activity(
organization_id=self.organization.id,
team_id=self.team_id,
- user=serializer.context["request"].user,
- was_impersonated=is_impersonated(self.request),
- item_id=serializer.instance.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated(request),
+ item_id=template.id,
scope="HogFlowTemplate",
activity="updated",
- detail=Detail(name=serializer.instance.name, type="standard"),
+ detail=Detail(name=template.name, type="standard"),
)
- serializer.save()
+ try:
+ updated = update_template(
+ template_id=template.id,
+ team_id=self.team_id,
+ organization_id=self.organization.id,
+ fields=serializer.validated_data,
+ )
+ except WorkflowTemplateNotFound:
+ raise NotFound()
+ return Response(self.get_serializer(updated).data)
+
+ def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ kwargs["partial"] = True
+ return self.update(request, *args, **kwargs)
- def perform_destroy(self, instance: HogFlowTemplate):
+ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ template = self.get_object()
# Authentication is enforced, so user cannot be AnonymousUser
- user = cast(User, self.request.user)
+ user = cast(User, request.user)
log_activity(
organization_id=self.organization.id,
team_id=self.team_id,
user=user,
- was_impersonated=is_impersonated(self.request),
- item_id=instance.id,
+ was_impersonated=is_impersonated(request),
+ item_id=template.id,
scope="HogFlowTemplate",
activity="deleted",
- detail=Detail(name=instance.name, type="standard"),
+ detail=Detail(name=template.name, type="standard"),
)
- super().perform_destroy(instance)
+ delete_template(template_id=template.id, team_id=self.team_id, organization_id=self.organization.id)
+ return Response(status=status.HTTP_204_NO_CONTENT)
class PublicHogFlowTemplateViewSet(
@@ -358,15 +393,13 @@ class PublicHogFlowTemplateViewSet(
permission_classes = [permissions.AllowAny]
serializer_class = HogFlowTemplateSerializer
- # Empty queryset since we load from files
- queryset = HogFlowTemplate.objects.none()
def list(self, request, *args, **kwargs):
"""
Load and return global templates from files.
"""
try:
- templates = load_global_templates()
+ templates = list_global_templates()
# Sort by updated_at descending (most recent first)
templates.sort(key=lambda t: t.get("updated_at", ""), reverse=True)
diff --git a/products/workflows/backend/services/hog_flow_templates.py b/products/workflows/backend/services/hog_flow_templates.py
new file mode 100644
index 000000000000..e8e57698e6b9
--- /dev/null
+++ b/products/workflows/backend/services/hog_flow_templates.py
@@ -0,0 +1,122 @@
+from collections.abc import Mapping
+from typing import Any
+from uuid import UUID
+
+from django.db.models import Q, QuerySet
+
+from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
+from products.workflows.backend.facade.contracts import WorkflowTemplate
+from products.workflows.backend.facade.enums import HogFlowTemplateExitCondition, HogFlowTemplateScope
+from products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplate
+from products.workflows.backend.templates import get_global_template_by_id, load_global_templates
+
+WRITABLE_TEMPLATE_FIELDS = frozenset(
+ {
+ "name",
+ "description",
+ "image_url",
+ "tags",
+ "scope",
+ "trigger",
+ "trigger_masking",
+ "conversion",
+ "exit_condition",
+ "edges",
+ "actions",
+ "abort_action",
+ "variables",
+ }
+)
+
+
+class WorkflowTemplateNotFound(Exception):
+ pass
+
+
+def _to_template(template: HogFlowTemplate) -> WorkflowTemplate:
+ return WorkflowTemplate(
+ id=template.id,
+ team_id=template.team_id,
+ name=template.name,
+ description=template.description,
+ image_url=template.image_url,
+ tags=template.tags,
+ scope=HogFlowTemplateScope(template.scope),
+ created_at=template.created_at,
+ created_by=template.created_by,
+ updated_at=template.updated_at,
+ trigger=template.trigger,
+ trigger_masking=template.trigger_masking,
+ conversion=template.conversion,
+ exit_condition=HogFlowTemplateExitCondition(template.exit_condition),
+ edges=template.edges,
+ actions=template.actions,
+ abort_action=template.abort_action,
+ variables=template.variables,
+ )
+
+
+def _visible_templates(team_id: int, organization_id: UUID) -> QuerySet[HogFlowTemplate]:
+ # A team sees its own templates plus the organization-scoped templates of every team in the
+ # organization. Global templates live in code, so a global row in the table is never served.
+ return (
+ HogFlowTemplate.objects.filter(
+ Q(team_id=team_id) | Q(scope=HogFlowTemplateScope.ORGANIZATION, team__organization_id=organization_id)
+ )
+ .exclude(scope=HogFlowTemplateScope.GLOBAL)
+ .select_related("created_by")
+ )
+
+
+def list_templates(*, team_id: int, organization_id: UUID) -> list[WorkflowTemplate]:
+ return [_to_template(t) for t in _visible_templates(team_id, organization_id).order_by("-updated_at")]
+
+
+def get_template(*, team_id: int, organization_id: UUID, template_id: str) -> WorkflowTemplate | None:
+ try:
+ template_uuid = UUID(template_id)
+ except ValueError:
+ return None
+ template = _visible_templates(team_id, organization_id).filter(id=template_uuid).first()
+ return _to_template(template) if template is not None else None
+
+
+def create_template(*, team_id: int, created_by_id: int, fields: Mapping[str, Any]) -> WorkflowTemplate:
+ values = {key: value for key, value in fields.items() if key in WRITABLE_TEMPLATE_FIELDS}
+ if not values.get("scope"):
+ values["scope"] = HogFlowTemplateScope.ONLY_TEAM
+ template = HogFlowTemplate.objects.create(team_id=team_id, created_by_id=created_by_id, **values)
+ return _to_template(template)
+
+
+def update_template(
+ *, template_id: UUID, team_id: int, organization_id: UUID, fields: Mapping[str, Any]
+) -> WorkflowTemplate:
+ """Apply the changed fields. The editing team becomes the owner, so an organization template
+ edited from another project moves to that project."""
+ template = _visible_templates(team_id, organization_id).filter(id=template_id).first()
+ if template is None:
+ raise WorkflowTemplateNotFound()
+ for key, value in fields.items():
+ if key in WRITABLE_TEMPLATE_FIELDS:
+ setattr(template, key, value)
+ template.team_id = team_id
+ template.save()
+ return _to_template(template)
+
+
+def delete_template(*, template_id: UUID, team_id: int, organization_id: UUID) -> None:
+ _visible_templates(team_id, organization_id).filter(id=template_id).delete()
+
+
+def list_global_templates() -> list[dict[str, Any]]:
+ # A copy, so a caller that sorts the list cannot reorder the shared cache.
+ return list(load_global_templates())
+
+
+def get_global_template(template_id: str) -> dict[str, Any] | None:
+ return get_global_template_by_id(template_id)
+
+
+def function_template_exists(template_id: str) -> bool:
+ return HogFunctionTemplate.get_template(template_id) is not None
diff --git a/products/workflows/backend/tests/api/test_hog_flow_template.py b/products/workflows/backend/tests/api/test_hog_flow_template.py
index 81ffb1cc0667..d483b095a43b 100644
--- a/products/workflows/backend/tests/api/test_hog_flow_template.py
+++ b/products/workflows/backend/tests/api/test_hog_flow_template.py
@@ -400,6 +400,9 @@ class TestHogFlowTemplateAPI(APIBaseTest):
assert response.status_code == 200
assert response.json()["name"] == "Updated Template Name"
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flow_templates/{template_id}/logs")
+ assert response.status_code == 200, response.json()
+
response = self.client.delete(f"/api/projects/{self.team.id}/hog_flow_templates/{template_id}")
assert response.status_code == 204
@@ -467,12 +470,15 @@ class TestHogFlowTemplateAPI(APIBaseTest):
def test_public_list_flow_templates(self):
"""Test that the public endpoint returns global templates from files"""
clear_template_cache()
+ file_order = [template["id"] for template in load_global_templates()]
# Log out to test unauthenticated access
self.client.logout()
response = self.client.get("/api/public_hog_flow_templates/")
assert response.status_code == status.HTTP_200_OK, response.json()
+ # The public list sorts its own copy, so the cached order the authenticated list serves stays put.
+ assert [template["id"] for template in load_global_templates()] == file_order
# Should return file-based templates
results = response.json()["results"]
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index a64b7fcf106d..7141759bedb5 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -142,28 +142,52 @@ export type HogFlowTemplateApiVariablesItem = { [key: string]: string }
* Validates and sanitizes the workflow before creating it as a template.
*/
export interface HogFlowTemplateApi {
+ /** ID of the template. */
readonly id: string
- /** @maxLength 400 */
+ /**
+ * Template name.
+ * @maxLength 400
+ */
name: string
+ /** Template description. */
description?: string
/**
+ * URL of the image shown on the template card.
* @maxLength 8201
* @nullable
*/
image_url?: string | null
+ /** Tags for filtering templates. */
tags?: string[]
+ /** Who can use the template: this project only, or every project in the organization.
+ *
+ * * `team` - Only team
+ * * `organization` - Organization
+ * * `global` - Global */
scope: HogFlowTemplateScopeEnumApi
+ /** When the template was created. */
readonly created_at: string
/** @nullable */
readonly created_by: HogFlowTemplateApiCreatedBy
+ /** When the template was last updated. */
readonly updated_at: string
+ /** Trigger config. Set from the config of the trigger action on save. */
trigger?: unknown
trigger_masking?: HogFlowMaskingApi | null
+ /** Conversion goal config. */
conversion?: unknown
+ /** When a person exits a workflow created from the template.
+ *
+ * * `exit_on_conversion` - Conversion
+ * * `exit_on_trigger_not_matched` - Trigger Not Matched
+ * * `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion
+ * * `exit_only_at_end` - Only At End */
exit_condition?: ExitConditionEnumApi
+ /** Connections between the actions. */
edges?: unknown
actions: HogFlowTemplateActionApi[]
/**
+ * ID of the abort action.
* @maxLength 400
* @nullable
*/
@@ -195,28 +219,52 @@ export type PatchedHogFlowTemplateApiVariablesItem = { [key: string]: string }
* Validates and sanitizes the workflow before creating it as a template.
*/
export interface PatchedHogFlowTemplateApi {
+ /** ID of the template. */
readonly id?: string
- /** @maxLength 400 */
+ /**
+ * Template name.
+ * @maxLength 400
+ */
name?: string
+ /** Template description. */
description?: string
/**
+ * URL of the image shown on the template card.
* @maxLength 8201
* @nullable
*/
image_url?: string | null
+ /** Tags for filtering templates. */
tags?: string[]
+ /** Who can use the template: this project only, or every project in the organization.
+ *
+ * * `team` - Only team
+ * * `organization` - Organization
+ * * `global` - Global */
scope?: HogFlowTemplateScopeEnumApi
+ /** When the template was created. */
readonly created_at?: string
/** @nullable */
readonly created_by?: PatchedHogFlowTemplateApiCreatedBy
+ /** When the template was last updated. */
readonly updated_at?: string
+ /** Trigger config. Set from the config of the trigger action on save. */
trigger?: unknown
trigger_masking?: HogFlowMaskingApi | null
+ /** Conversion goal config. */
conversion?: unknown
+ /** When a person exits a workflow created from the template.
+ *
+ * * `exit_on_conversion` - Conversion
+ * * `exit_on_trigger_not_matched` - Trigger Not Matched
+ * * `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion
+ * * `exit_only_at_end` - Only At End */
exit_condition?: ExitConditionEnumApi
+ /** Connections between the actions. */
edges?: unknown
actions?: HogFlowTemplateActionApi[]
/**
+ * ID of the abort action.
* @maxLength 400
* @nullable
*/
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index c6b15b8d499e..1c205b8f0262 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -154,7 +154,7 @@ export const getHogFlowTemplatesRetrieveUrl = (projectId: string, id: string) =>
/**
* Check file-based global templates first, then DB team templates.
- * The queryset excludes all global templates from DB, so this only returns team templates from DB.
+ * The DB lookup excludes all global templates, so this only returns team templates from DB.
*/
export const hogFlowTemplatesRetrieve = async (
projectId: string,
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 50a49117f244..ee2ef66490d0 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -26,14 +26,24 @@ export const hogFlowTemplatesCreateBodyAbortActionMax = 400
export const HogFlowTemplatesCreateBody = /* @__PURE__ */ zod
.object({
- name: zod.string().max(hogFlowTemplatesCreateBodyNameMax),
- description: zod.string().optional(),
- image_url: zod.string().max(hogFlowTemplatesCreateBodyImageUrlMax).nullish(),
- tags: zod.array(zod.string()).optional(),
+ name: zod.string().max(hogFlowTemplatesCreateBodyNameMax).describe('Template name.'),
+ description: zod.string().optional().describe('Template description.'),
+ image_url: zod
+ .string()
+ .max(hogFlowTemplatesCreateBodyImageUrlMax)
+ .nullish()
+ .describe('URL of the image shown on the template card.'),
+ tags: zod.array(zod.string()).optional().describe('Tags for filtering templates.'),
scope: zod
.enum(['team', 'organization', 'global'])
- .describe('\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global'),
- trigger: zod.unknown().optional(),
+ .describe('\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global')
+ .describe(
+ 'Who can use the template: this project only, or every project in the organization.\n\n\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global'
+ ),
+ trigger: zod
+ .unknown()
+ .optional()
+ .describe('Trigger config. Set from the config of the trigger action on save.'),
trigger_masking: zod
.union([
zod.object({
@@ -59,7 +69,7 @@ export const HogFlowTemplatesCreateBody = /* @__PURE__ */ zod
zod.null(),
])
.optional(),
- conversion: zod.unknown().optional(),
+ conversion: zod.unknown().optional().describe('Conversion goal config.'),
exit_condition: zod
.enum([
'exit_on_conversion',
@@ -67,11 +77,14 @@ export const HogFlowTemplatesCreateBody = /* @__PURE__ */ zod
'exit_on_trigger_not_matched_or_conversion',
'exit_only_at_end',
])
- .optional()
.describe(
'\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End'
+ )
+ .optional()
+ .describe(
+ 'When a person exits a workflow created from the template.\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End'
),
- edges: zod.unknown().optional(),
+ edges: zod.unknown().optional().describe('Connections between the actions.'),
actions: zod.array(
zod
.object({
@@ -125,7 +138,11 @@ export const HogFlowTemplatesCreateBody = /* @__PURE__ */ zod
'Custom action serializer for templates that skips input validation\n(since templates should have default\/empty values).'
)
),
- abort_action: zod.string().max(hogFlowTemplatesCreateBodyAbortActionMax).nullish(),
+ abort_action: zod
+ .string()
+ .max(hogFlowTemplatesCreateBodyAbortActionMax)
+ .nullish()
+ .describe('ID of the abort action.'),
variables: zod
.array(
zod
@@ -155,14 +172,24 @@ export const hogFlowTemplatesUpdateBodyAbortActionMax = 400
export const HogFlowTemplatesUpdateBody = /* @__PURE__ */ zod
.object({
- name: zod.string().max(hogFlowTemplatesUpdateBodyNameMax),
- description: zod.string().optional(),
- image_url: zod.string().max(hogFlowTemplatesUpdateBodyImageUrlMax).nullish(),
- tags: zod.array(zod.string()).optional(),
+ name: zod.string().max(hogFlowTemplatesUpdateBodyNameMax).describe('Template name.'),
+ description: zod.string().optional().describe('Template description.'),
+ image_url: zod
+ .string()
+ .max(hogFlowTemplatesUpdateBodyImageUrlMax)
+ .nullish()
+ .describe('URL of the image shown on the template card.'),
+ tags: zod.array(zod.string()).optional().describe('Tags for filtering templates.'),
scope: zod
.enum(['team', 'organization', 'global'])
- .describe('\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global'),
- trigger: zod.unknown().optional(),
+ .describe('\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global')
+ .describe(
+ 'Who can use the template: this project only, or every project in the organization.\n\n\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global'
+ ),
+ trigger: zod
+ .unknown()
+ .optional()
+ .describe('Trigger config. Set from the config of the trigger action on save.'),
trigger_masking: zod
.union([
zod.object({
@@ -188,7 +215,7 @@ export const HogFlowTemplatesUpdateBody = /* @__PURE__ */ zod
zod.null(),
])
.optional(),
- conversion: zod.unknown().optional(),
+ conversion: zod.unknown().optional().describe('Conversion goal config.'),
exit_condition: zod
.enum([
'exit_on_conversion',
@@ -196,11 +223,14 @@ export const HogFlowTemplatesUpdateBody = /* @__PURE__ */ zod
'exit_on_trigger_not_matched_or_conversion',
'exit_only_at_end',
])
- .optional()
.describe(
'\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End'
+ )
+ .optional()
+ .describe(
+ 'When a person exits a workflow created from the template.\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End'
),
- edges: zod.unknown().optional(),
+ edges: zod.unknown().optional().describe('Connections between the actions.'),
actions: zod.array(
zod
.object({
@@ -254,7 +284,11 @@ export const HogFlowTemplatesUpdateBody = /* @__PURE__ */ zod
'Custom action serializer for templates that skips input validation\n(since templates should have default\/empty values).'
)
),
- abort_action: zod.string().max(hogFlowTemplatesUpdateBodyAbortActionMax).nullish(),
+ abort_action: zod
+ .string()
+ .max(hogFlowTemplatesUpdateBodyAbortActionMax)
+ .nullish()
+ .describe('ID of the abort action.'),
variables: zod
.array(
zod
@@ -284,15 +318,25 @@ export const hogFlowTemplatesPartialUpdateBodyAbortActionMax = 400
export const HogFlowTemplatesPartialUpdateBody = /* @__PURE__ */ zod
.object({
- name: zod.string().max(hogFlowTemplatesPartialUpdateBodyNameMax).optional(),
- description: zod.string().optional(),
- image_url: zod.string().max(hogFlowTemplatesPartialUpdateBodyImageUrlMax).nullish(),
- tags: zod.array(zod.string()).optional(),
+ name: zod.string().max(hogFlowTemplatesPartialUpdateBodyNameMax).optional().describe('Template name.'),
+ description: zod.string().optional().describe('Template description.'),
+ image_url: zod
+ .string()
+ .max(hogFlowTemplatesPartialUpdateBodyImageUrlMax)
+ .nullish()
+ .describe('URL of the image shown on the template card.'),
+ tags: zod.array(zod.string()).optional().describe('Tags for filtering templates.'),
scope: zod
.enum(['team', 'organization', 'global'])
+ .describe('\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global')
.optional()
- .describe('\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global'),
- trigger: zod.unknown().optional(),
+ .describe(
+ 'Who can use the template: this project only, or every project in the organization.\n\n\* `team` - Only team\n\* `organization` - Organization\n\* `global` - Global'
+ ),
+ trigger: zod
+ .unknown()
+ .optional()
+ .describe('Trigger config. Set from the config of the trigger action on save.'),
trigger_masking: zod
.union([
zod.object({
@@ -318,7 +362,7 @@ export const HogFlowTemplatesPartialUpdateBody = /* @__PURE__ */ zod
zod.null(),
])
.optional(),
- conversion: zod.unknown().optional(),
+ conversion: zod.unknown().optional().describe('Conversion goal config.'),
exit_condition: zod
.enum([
'exit_on_conversion',
@@ -326,11 +370,14 @@ export const HogFlowTemplatesPartialUpdateBody = /* @__PURE__ */ zod
'exit_on_trigger_not_matched_or_conversion',
'exit_only_at_end',
])
- .optional()
.describe(
'\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End'
+ )
+ .optional()
+ .describe(
+ 'When a person exits a workflow created from the template.\n\n\* `exit_on_conversion` - Conversion\n\* `exit_on_trigger_not_matched` - Trigger Not Matched\n\* `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion\n\* `exit_only_at_end` - Only At End'
),
- edges: zod.unknown().optional(),
+ edges: zod.unknown().optional().describe('Connections between the actions.'),
actions: zod
.array(
zod
@@ -390,7 +437,11 @@ export const HogFlowTemplatesPartialUpdateBody = /* @__PURE__ */ zod
)
)
.optional(),
- abort_action: zod.string().max(hogFlowTemplatesPartialUpdateBodyAbortActionMax).nullish(),
+ abort_action: zod
+ .string()
+ .max(hogFlowTemplatesPartialUpdateBodyAbortActionMax)
+ .nullish()
+ .describe('ID of the abort action.'),
variables: zod
.array(
zod
diff --git a/pyproject.toml b/pyproject.toml
index 1aa01b3e33ef..5473c551a528 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -761,9 +761,6 @@ ignore_imports = [
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.durations",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.email_sending_tiers",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.rrule_utils",
- "products.workflows.backend.presentation.views.hog_flow_template -> products.cdp.backend.models.hog_function_template",
- "products.workflows.backend.presentation.views.hog_flow_template -> products.workflows.backend.models.hog_flow.hog_flow_template",
- "products.workflows.backend.presentation.views.hog_flow_template -> products.workflows.backend.templates",
# TODO: access-control presentation wave — the consolidated RBAC viewsets carry their ORM
# access with them. Thin them to parse -> facade -> serialize and delete each entry.
"products.access_control.backend.presentation.access_control -> products.access_control.backend.models.access_control",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 04dc6ec4226f..ccea5f50f598 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -52021,28 +52021,52 @@ export namespace Schemas {
* Validates and sanitizes the workflow before creating it as a template.
*/
export interface HogFlowTemplate {
+ /** ID of the template. */
readonly id: string;
- /** @maxLength 400 */
+ /**
+ * Template name.
+ * @maxLength 400
+ */
name: string;
+ /** Template description. */
description?: string;
/**
+ * URL of the image shown on the template card.
* @maxLength 8201
* @nullable
*/
image_url?: string | null;
+ /** Tags for filtering templates. */
tags?: string[];
+ /** Who can use the template: this project only, or every project in the organization.
+ *
+ * * `team` - Only team
+ * * `organization` - Organization
+ * * `global` - Global */
scope: HogFlowTemplateScopeEnum;
+ /** When the template was created. */
readonly created_at: string;
/** @nullable */
readonly created_by: HogFlowTemplateCreatedBy;
+ /** When the template was last updated. */
readonly updated_at: string;
+ /** Trigger config. Set from the config of the trigger action on save. */
trigger?: unknown;
trigger_masking?: HogFlowMasking | null;
+ /** Conversion goal config. */
conversion?: unknown;
+ /** When a person exits a workflow created from the template.
+ *
+ * * `exit_on_conversion` - Conversion
+ * * `exit_on_trigger_not_matched` - Trigger Not Matched
+ * * `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion
+ * * `exit_only_at_end` - Only At End */
exit_condition?: ExitConditionEnum;
+ /** Connections between the actions. */
edges?: unknown;
actions: HogFlowTemplateAction[];
/**
+ * ID of the abort action.
* @maxLength 400
* @nullable
*/
@@ -76554,28 +76578,52 @@ export namespace Schemas {
* Validates and sanitizes the workflow before creating it as a template.
*/
export interface PatchedHogFlowTemplate {
+ /** ID of the template. */
readonly id?: string;
- /** @maxLength 400 */
+ /**
+ * Template name.
+ * @maxLength 400
+ */
name?: string;
+ /** Template description. */
description?: string;
/**
+ * URL of the image shown on the template card.
* @maxLength 8201
* @nullable
*/
image_url?: string | null;
+ /** Tags for filtering templates. */
tags?: string[];
+ /** Who can use the template: this project only, or every project in the organization.
+ *
+ * * `team` - Only team
+ * * `organization` - Organization
+ * * `global` - Global */
scope?: HogFlowTemplateScopeEnum;
+ /** When the template was created. */
readonly created_at?: string;
/** @nullable */
readonly created_by?: PatchedHogFlowTemplateCreatedBy;
+ /** When the template was last updated. */
readonly updated_at?: string;
+ /** Trigger config. Set from the config of the trigger action on save. */
trigger?: unknown;
trigger_masking?: HogFlowMasking | null;
+ /** Conversion goal config. */
conversion?: unknown;
+ /** When a person exits a workflow created from the template.
+ *
+ * * `exit_on_conversion` - Conversion
+ * * `exit_on_trigger_not_matched` - Trigger Not Matched
+ * * `exit_on_trigger_not_matched_or_conversion` - Trigger Not Matched Or Conversion
+ * * `exit_only_at_end` - Only At End */
exit_condition?: ExitConditionEnum;
+ /** Connections between the actions. */
edges?: unknown;
actions?: HogFlowTemplateAction[];
/**
+ * ID of the abort action.
* @maxLength 400
* @nullable
*/