Skip to content

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

feat(workflows): offer to create a batch email workflow as a broadcast (#119390)

Meikel Ratz04d555042c70
diff --git a/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsx b/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsx
index 44075d7eced7..93926c04b317 100644
--- a/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsx
+++ b/frontend/src/lib/lemon-ui/LemonDialog/LemonDialog.tsx
@@ -286,12 +286,29 @@ export const LemonDialog = LemonDialogComponent as typeof LemonDialogComponent &
LemonDialog.open = (props: LemonDialogProps) => {
const { root, onDestroy } = createAndInsertRoot()
- root.render(<LemonDialog {...props} onAfterClose={onDestroy} />)
+ root.render(
+ <LemonDialog
+ {...props}
+ onAfterClose={() => {
+ props.onAfterClose?.()
+ onDestroy()
+ }}
+ />
+ )
}
LemonDialog.openForm = (props: LemonFormDialogProps) => {
const { root, onDestroy } = createAndInsertRoot()
// Each dialog gets a unique key so nested dialogs don't share the same
// lemonDialogLogic instance and corrupt each other's form state.
- root.render(<LemonFormDialog {...props} dialogKey={uuid()} onAfterClose={onDestroy} />)
+ root.render(
+ <LemonFormDialog
+ {...props}
+ dialogKey={uuid()}
+ onAfterClose={() => {
+ props.onAfterClose?.()
+ onDestroy()
+ }}
+ />
+ )
}
diff --git a/products/workflows/backend/facade/broadcast_conversion.py b/products/workflows/backend/facade/broadcast_conversion.py
new file mode 100644
index 000000000000..3b9ae989647a
--- /dev/null
+++ b/products/workflows/backend/facade/broadcast_conversion.py
@@ -0,0 +1,13 @@
+"""Moving workflows that only send one email to a batch audience over to the broadcasts product."""
+
+from products.workflows.backend.services.broadcast_conversion import (
+ BROADCAST_CONVERSION_CANDIDATE_LIMIT,
+ convert_workflow_to_broadcast,
+ list_broadcast_conversion_candidates,
+)
+
+__all__ = [
+ "BROADCAST_CONVERSION_CANDIDATE_LIMIT",
+ "convert_workflow_to_broadcast",
+ "list_broadcast_conversion_candidates",
+]
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 46258ed647b6..17a0ac30df64 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -159,6 +159,11 @@ from products.workflows.backend.facade.blast_radius import (
is_account_audience,
parse_account_audience_filters,
)
+from products.workflows.backend.facade.broadcast_conversion import (
+ BROADCAST_CONVERSION_CANDIDATE_LIMIT,
+ convert_workflow_to_broadcast,
+ list_broadcast_conversion_candidates,
+)
from products.workflows.backend.facade.content import DRAFT_CONTENT_FIELDS, deep_merge, snapshot_content
from products.workflows.backend.facade.contracts import (
EmailDesignRenderFailed,
@@ -2722,6 +2727,34 @@ class WorkflowEmailPauseStatusSerializer(serializers.Serializer):
)
+class BroadcastConversionCandidateSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="Workflow id.")
+ name = serializers.CharField(read_only=True, allow_blank=True, help_text="Workflow name. Empty when unnamed.")
+ status = serializers.ChoiceField(choices=HogFlowState.choices, read_only=True, help_text="Workflow status.")
+
+
+class BroadcastConversionCandidatesSerializer(serializers.Serializer):
+ """Workflows that only send one email to a batch audience and can move to broadcasts."""
+
+ has_more = serializers.BooleanField(
+ read_only=True, help_text="True when more workflows can move than `results` lists."
+ )
+ results = BroadcastConversionCandidateSerializer(
+ many=True,
+ read_only=True,
+ help_text=f"The most recently updated candidates, at most {BROADCAST_CONVERSION_CANDIDATE_LIMIT}.",
+ )
+
+
+class HogFlowConvertedToBroadcastSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="Id of the workflow that is now a broadcast.")
+ origin_product = serializers.ChoiceField(
+ choices=HogFlowOriginProduct.choices,
+ read_only=True,
+ help_text="The product that now owns the workflow. Always `broadcasts`.",
+ )
+
+
class HogFlowLastRunSerializer(serializers.Serializer):
task_id = serializers.UUIDField(read_only=True, help_text="The task this run belongs to.")
status = serializers.CharField(
@@ -4490,6 +4523,7 @@ class HogFlowViewSet(
"metrics_global",
"team_reputation",
"email_sending_suspension",
+ "broadcast_conversion_candidates",
"user_blast_radius",
"assets",
"asset_content",
@@ -4518,6 +4552,7 @@ class HogFlowViewSet(
"discard_draft",
"restore_revision",
"resume_email_sending",
+ "convert_to_broadcast",
"approve_proposal",
"reject_proposal",
]
@@ -6554,6 +6589,61 @@ class HogFlowViewSet(
).data
)
+ @extend_schema(
+ operation_id="hog_flows_broadcast_conversion_candidates_retrieve",
+ responses={200: BroadcastConversionCandidatesSerializer},
+ )
+ @action(
+ detail=False,
+ methods=["GET"],
+ pagination_class=None,
+ filter_backends=[],
+ url_path="broadcast_conversion_candidates",
+ )
+ def broadcast_conversion_candidates(self, request: Request, **kwargs) -> Response:
+ """
+ List the workflows that could become broadcasts: one email to a batch audience, with nothing the
+ broadcast editor would drop. Only workflows the caller may edit are listed.
+ """
+ # One past the cap tells whether more exist without loading them all.
+ candidates = list_broadcast_conversion_candidates(
+ team_id=self.team_id,
+ user_access_control=None if is_service_auth(request) else self.user_access_control,
+ limit=BROADCAST_CONVERSION_CANDIDATE_LIMIT + 1,
+ )
+ return Response(
+ BroadcastConversionCandidatesSerializer(
+ {
+ "has_more": len(candidates) > BROADCAST_CONVERSION_CANDIDATE_LIMIT,
+ "results": candidates[:BROADCAST_CONVERSION_CANDIDATE_LIMIT],
+ }
+ ).data
+ )
+
+ @extend_schema(
+ operation_id="hog_flows_convert_to_broadcast",
+ request=None,
+ responses={200: HogFlowConvertedToBroadcastSerializer},
+ )
+ @action(detail=True, methods=["POST"], pagination_class=None, filter_backends=[], url_path="convert_to_broadcast")
+ def convert_to_broadcast(self, request: Request, **kwargs) -> Response:
+ """
+ Move a workflow to broadcasts. It keeps its id, runs and metrics, leaves the workflows list and opens
+ in the broadcast editor. This cannot be undone.
+ """
+ hog_flow = self._workflow_ref()
+ if not convert_workflow_to_broadcast(
+ team_id=hog_flow.team_id, hog_flow_id=hog_flow.id, actor=self._activity_actor()
+ ):
+ raise exceptions.ValidationError(
+ {"detail": "Only a workflow that sends one email to a batch audience can become a broadcast."}
+ )
+ return Response(
+ HogFlowConvertedToBroadcastSerializer(
+ {"id": hog_flow.id, "origin_product": HogFlowOriginProduct.BROADCASTS}
+ ).data
+ )
+
@extend_schema(methods=["GET"], responses=HogFlowBatchJobSerializer(many=True))
@extend_schema(methods=["POST"], request=HogFlowBatchJobSerializer, responses=HogFlowBatchJobSerializer)
# GET returns a bare list (no pagination) and ignores the viewset's HogFlow filterset; disable both so the
diff --git a/products/workflows/backend/services/broadcast_conversion.py b/products/workflows/backend/services/broadcast_conversion.py
new file mode 100644
index 000000000000..63d72ca384eb
--- /dev/null
+++ b/products/workflows/backend/services/broadcast_conversion.py
@@ -0,0 +1,156 @@
+"""Moving a workflow that only sends one email to a batch audience over to the broadcasts product."""
+
+from typing import Final, Optional, cast
+from uuid import UUID
+
+from django.db import models, transaction
+from django.utils import timezone
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.workflows.backend.facade.contracts import WorkflowActor, WorkflowSummary
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.services.hog_flow_activity import log_workflow_activity
+from products.workflows.backend.services.hog_flow_reads import BROADCAST_TRIGGER_TYPE, annotate_broadcast_shape
+from products.workflows.backend.services.hog_flow_writes import field_values
+
+BROADCAST_CONVERSION_CANDIDATE_LIMIT: Final = 100
+
+
+def is_convertible_to_broadcast(flow: HogFlow) -> bool:
+ """Whether the broadcast editor can own this workflow without losing anything it holds.
+
+ Mirrors canEditInWizard in the frontend: one trigger, one email and one exit, joined trigger to email
+ to exit, for a person audience. The editor always saves `exit_only_at_end` and edits the live graph,
+ so another exit condition or a staged draft would be dropped on its next save."""
+ if flow.origin_product is not None or flow.status == HogFlow.State.ARCHIVED:
+ return False
+ if flow.exit_condition != HogFlow.ExitCondition.ONLY_AT_END or flow.draft is not None:
+ return False
+ actions = [action for action in flow.actions or [] if isinstance(action, dict)]
+ steps = {
+ step_type: [action for action in actions if action.get("type") == step_type]
+ for step_type in ("trigger", "function_email", "exit")
+ }
+ if len(actions) != 3 or any(len(found) != 1 for found in steps.values()):
+ return False
+ trigger, email, exit_step = steps["trigger"][0], steps["function_email"][0], steps["exit"][0]
+ config = trigger.get("config") or {}
+ if config.get("type") != BROADCAST_TRIGGER_TYPE or (config.get("filters") or {}).get("audience_type") == "accounts":
+ return False
+ return _joins_in_order(flow, trigger.get("id"), email.get("id"), exit_step.get("id"))
+
+
+def _joins_in_order(flow: HogFlow, trigger_id: object, email_id: object, exit_id: object) -> bool:
+ """Whether the only edges run trigger to email and email to exit."""
+ paths = {(edge.get("from"), edge.get("to")) for edge in flow.edges or [] if isinstance(edge, dict)}
+ return paths == {(trigger_id, email_id), (email_id, exit_id)}
+
+
+def _json_path(path: str) -> models.Func:
+ return models.Func(models.Value(path), template="%(expressions)s::jsonpath", output_field=models.TextField())
+
+
+def _step_count(step_type: str) -> models.Func:
+ steps = models.Func(
+ models.F("actions"),
+ _json_path(f'$[*] ? (@.type == "{step_type}")'),
+ function="jsonb_path_query_array",
+ output_field=models.JSONField(),
+ )
+ return models.Func(steps, function="jsonb_array_length", output_field=models.IntegerField())
+
+
+def _step_id(step_type: str) -> models.Func:
+ return models.Func(
+ models.F("actions"),
+ _json_path(f'$[*] ? (@.type == "{step_type}").id'),
+ function="jsonb_path_query_first",
+ output_field=models.JSONField(),
+ )
+
+
+def list_broadcast_conversion_candidates(
+ *, team_id: int, user_access_control: Optional[UserAccessControl], limit: int
+) -> list[WorkflowSummary]:
+ """Up to `limit` of the team's workflows that could become broadcasts and that the caller may edit,
+ newest first. The shape checks run in Postgres, so only small columns load and never every row."""
+ queryset = (
+ annotate_broadcast_shape(
+ HogFlow.objects.filter(
+ team_id=team_id,
+ origin_product__isnull=True,
+ exit_condition=HogFlow.ExitCondition.ONLY_AT_END,
+ draft__isnull=True,
+ ).exclude(status=HogFlow.State.ARCHIVED)
+ )
+ .annotate(
+ _step_count=models.Func(
+ models.F("actions"), function="jsonb_array_length", output_field=models.IntegerField()
+ ),
+ _trigger_count=_step_count("trigger"),
+ _exit_count=_step_count("exit"),
+ _trigger_id=_step_id("trigger"),
+ _email_id=_step_id("function_email"),
+ _exit_id=_step_id("exit"),
+ _account_audience=models.Func(
+ models.F("actions"),
+ _json_path('$[*] ? (@.type == "trigger" && @.config.filters.audience_type == "accounts")'),
+ function="jsonb_path_exists",
+ output_field=models.BooleanField(),
+ ),
+ )
+ .filter(
+ _has_batch_trigger=True,
+ _email_step_count=1,
+ _has_other_step=False,
+ _step_count=3,
+ _trigger_count=1,
+ _exit_count=1,
+ _account_audience=False,
+ )
+ .only("id", "team_id", "name", "status", "edges", "created_by")
+ .order_by("-updated_at", "id")
+ )
+ found: list[HogFlow] = []
+ offset = 0
+ while len(found) < limit:
+ page = list(queryset[offset : offset + limit])
+ if not page:
+ break
+ offset += len(page)
+ page = [flow for flow in page if _joins_in_order(flow, flow._trigger_id, flow._email_id, flow._exit_id)]
+ if user_access_control is not None:
+ # Converting needs editor access, so a workflow the caller can only view is not offered.
+ user_access_control.preload_object_access_controls(cast("list[models.Model]", page))
+ page = [
+ flow
+ for flow in page
+ if user_access_control.check_access_level_for_object(flow, required_level="editor")
+ ]
+ found.extend(page)
+ return [WorkflowSummary(id=str(flow.id), name=flow.name or "", status=flow.status) for flow in found[:limit]]
+
+
+def convert_workflow_to_broadcast(*, team_id: int, hog_flow_id: UUID, actor: WorkflowActor) -> bool:
+ """Hand the workflow to the broadcasts product and log it. Returns False when it cannot become one."""
+ with transaction.atomic():
+ flow = HogFlow.objects.select_for_update().filter(team_id=team_id, pk=hog_flow_id).first()
+ if flow is None or not is_convertible_to_broadcast(flow):
+ return False
+ before = field_values(flow)
+ flow.origin_product = HogFlow.OriginProduct.BROADCASTS
+ flow.updated_at = timezone.now()
+ # A queryset update skips the worker reload that save() sends, since the owner does not change how
+ # the workflow runs.
+ HogFlow.objects.filter(team_id=team_id, pk=hog_flow_id).update(
+ origin_product=flow.origin_product, updated_at=flow.updated_at
+ )
+ log_workflow_activity(
+ actor=actor,
+ workflow_id=hog_flow_id,
+ name=flow.name,
+ activity="converted_to_broadcast",
+ previous=before,
+ current=field_values(flow),
+ )
+ return True
diff --git a/products/workflows/backend/tests/api/test_broadcast_conversion.py b/products/workflows/backend/tests/api/test_broadcast_conversion.py
new file mode 100644
index 000000000000..54498d98385f
--- /dev/null
+++ b/products/workflows/backend/tests/api/test_broadcast_conversion.py
@@ -0,0 +1,107 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.activity_logging.activity_log import ActivityLog
+
+from products.workflows.backend.models import HogFlow
+
+TRIGGER = {"id": "trigger_node", "name": "Audience", "type": "trigger", "config": {"type": "batch", "filters": {}}}
+EMAIL = {"id": "email_node", "name": "Email", "type": "function_email", "config": {"inputs": {}}}
+EXIT = {"id": "exit_node", "name": "Exit", "type": "exit", "config": {}}
+DELAY = {"id": "delay_node", "name": "Delay", "type": "delay", "config": {"delay_duration": "1h"}}
+EDGES = [
+ {"from": "trigger_node", "to": "email_node", "type": "continue"},
+ {"from": "email_node", "to": "exit_node", "type": "continue"},
+]
+
+
+class TestBroadcastConversionAPI(APIBaseTest):
+ def _flow(self, **overrides: Any) -> HogFlow:
+ fields: dict[str, Any] = {
+ "team": self.team,
+ "name": "Monthly update",
+ "status": "draft",
+ "exit_condition": "exit_only_at_end",
+ "trigger": TRIGGER["config"],
+ "actions": [TRIGGER, EMAIL, EXIT],
+ "edges": EDGES,
+ **overrides,
+ }
+ return HogFlow.objects.create(**fields)
+
+ def _candidate_ids(self) -> list[str]:
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/broadcast_conversion_candidates/")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ return [row["id"] for row in response.json()["results"]]
+
+ def _convert(self, flow: HogFlow) -> Any:
+ return self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow.id}/convert_to_broadcast/")
+
+ @parameterized.expand(
+ [
+ ("draft", {}, True),
+ ("active", {"status": "active"}, True),
+ ("archived", {"status": "archived"}, False),
+ ("already a broadcast", {"origin_product": "broadcasts"}, False),
+ ("exit on conversion", {"exit_condition": "exit_on_conversion"}, False),
+ ("staged draft", {"draft": {"actions": [TRIGGER, EMAIL, EXIT]}}, False),
+ (
+ "event trigger",
+ {"actions": [{**TRIGGER, "config": {"type": "event", "filters": {}}}, EMAIL, EXIT]},
+ False,
+ ),
+ (
+ "account audience",
+ {
+ "actions": [
+ {**TRIGGER, "config": {"type": "batch", "filters": {"audience_type": "accounts"}}},
+ EMAIL,
+ EXIT,
+ ]
+ },
+ False,
+ ),
+ ("extra step", {"actions": [TRIGGER, EMAIL, DELAY, EXIT]}, False),
+ ("edge that skips the email", {"edges": [*EDGES, {"from": "trigger_node", "to": "exit_node"}]}, False),
+ ]
+ )
+ def test_only_workflows_the_broadcast_editor_can_own_are_offered_and_converted(
+ self, _name: str, overrides: dict[str, Any], convertible: bool
+ ) -> None:
+ flow = self._flow(**overrides)
+
+ assert (str(flow.id) in self._candidate_ids()) is convertible
+
+ response = self._convert(flow)
+ flow.refresh_from_db()
+ if convertible:
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {"id": str(flow.id), "origin_product": "broadcasts"}
+ assert flow.origin_product == "broadcasts"
+ assert ActivityLog.objects.filter(
+ team_id=self.team.id, item_id=str(flow.id), activity="converted_to_broadcast"
+ ).exists()
+ assert str(flow.id) not in self._candidate_ids()
+ else:
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert flow.origin_product == overrides.get("origin_product")
+
+ def test_candidates_stop_at_the_cap_and_say_more_exist(self) -> None:
+ newest = self._flow(name="Newest")
+ self._flow(name="Broken", edges=[{"from": "trigger_node", "to": "exit_node"}])
+ self._flow(name="Oldest")
+ HogFlow.objects.filter(pk=newest.pk).update(updated_at="2030-01-01T00:00:00Z")
+
+ with patch("products.workflows.backend.presentation.views.hog_flow.BROADCAST_CONVERSION_CANDIDATE_LIMIT", 1):
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/broadcast_conversion_candidates/")
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {
+ "has_more": True,
+ "results": [{"id": str(newest.id), "name": "Newest", "status": "draft"}],
+ }
diff --git a/products/workflows/frontend/Broadcasts/broadcastLifecycle.test.ts b/products/workflows/frontend/Broadcasts/broadcastLifecycle.test.ts
index dc5a3ac9f38a..6a7e56723967 100644
--- a/products/workflows/frontend/Broadcasts/broadcastLifecycle.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastLifecycle.test.ts
@@ -1,14 +1,58 @@
-import { archiveDisabledReason } from './broadcastLifecycle'
-
-describe('archiveDisabledReason', () => {
- it.each([
- { runs: 'runs not loaded yet', statuses: null, blocked: true },
- { runs: 'no runs', statuses: [], blocked: false },
- { runs: 'a finished and a failed run', statuses: ['completed', 'failed'], blocked: false },
- { runs: 'rows whose runs have not loaded', statuses: [undefined], blocked: false },
- { runs: 'a queued run', statuses: ['queued'], blocked: true },
- { runs: 'an older run still sending', statuses: ['completed', 'active'], blocked: true },
- ])('with $runs blocks archiving: $blocked', ({ statuses, blocked }) => {
- expect(!!archiveDisabledReason(statuses)).toBe(blocked)
+import '@testing-library/jest-dom'
+
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+
+import { archiveDisabledReason, confirmCreateAsBroadcast } from './broadcastLifecycle'
+
+const TITLE = 'Track this send as a broadcast?'
+
+describe('broadcastLifecycle', () => {
+ describe('archiveDisabledReason', () => {
+ it.each([
+ { runs: 'runs not loaded yet', statuses: null, blocked: true },
+ { runs: 'no runs', statuses: [], blocked: false },
+ { runs: 'a finished and a failed run', statuses: ['completed', 'failed'], blocked: false },
+ { runs: 'rows whose runs have not loaded', statuses: [undefined], blocked: false },
+ { runs: 'a queued run', statuses: ['queued'], blocked: true },
+ { runs: 'an older run still sending', statuses: ['completed', 'active'], blocked: true },
+ ])('with $runs blocks archiving: $blocked', ({ statuses, blocked }) => {
+ expect(!!archiveDisabledReason(statuses)).toBe(blocked)
+ })
+ })
+
+ describe('confirmCreateAsBroadcast', () => {
+ const escape = (): boolean =>
+ fireEvent.keyDown(screen.getByText(TITLE).closest('.ReactModal__Content')!, { key: 'Escape', keyCode: 27 })
+
+ const others = [
+ { id: 'wf-a', name: 'September newsletter', status: 'draft' as const },
+ { id: 'wf-b', name: '', status: 'active' as const },
+ ]
+
+ it.each([
+ { offered: [], button: 'Create broadcast', choice: 'broadcast' },
+ { offered: [], button: 'Keep as workflow', choice: 'workflow' },
+ { offered: [], button: null, choice: null },
+ { offered: others, button: 'Create and move 2 more', choice: 'broadcast_and_move' },
+ { offered: others, button: 'Create broadcast', choice: 'broadcast' },
+ { offered: others, button: 'Keep as workflow', choice: 'workflow' },
+ ])('with $offered.length other workflows, $button resolves to $choice', async ({ offered, button, choice }) => {
+ const result = confirmCreateAsBroadcast(offered)
+ await screen.findByText(TITLE)
+ for (const name of offered.length
+ ? ['Also move these 2 workflows to broadcasts?', 'September newsletter', 'Untitled workflow']
+ : []) {
+ expect(screen.getByText(name)).toBeInTheDocument()
+ }
+
+ if (button) {
+ fireEvent.click(screen.getByText(button))
+ } else {
+ escape()
+ }
+
+ await expect(result).resolves.toBe(choice)
+ await waitFor(() => expect(screen.queryByText(TITLE)).not.toBeInTheDocument())
+ })
})
})
diff --git a/products/workflows/frontend/Broadcasts/broadcastLifecycle.ts b/products/workflows/frontend/Broadcasts/broadcastLifecycle.tsx
similarity index 54%
rename from products/workflows/frontend/Broadcasts/broadcastLifecycle.ts
rename to products/workflows/frontend/Broadcasts/broadcastLifecycle.tsx
index 4abc11a649de..1f665a5783d0 100644
--- a/products/workflows/frontend/Broadcasts/broadcastLifecycle.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastLifecycle.tsx
@@ -1,14 +1,18 @@
import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { pluralize } from 'lib/utils/strings'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
import {
hogFlowsBatchJobsList,
+ hogFlowsBroadcastConversionCandidatesRetrieve,
+ hogFlowsConvertToBroadcast,
hogFlowsDestroy,
hogFlowsPartialUpdate,
} from 'products/workflows/frontend/generated/api'
+import type { BroadcastConversionCandidateApi } from 'products/workflows/frontend/generated/api.schemas'
export interface ManagedBroadcast {
id: string
@@ -133,3 +137,91 @@ export function confirmOpenInWorkflowEditor(onConfirm: () => void): void {
secondaryButton: { children: 'Cancel' },
})
}
+
+export type CreateAsBroadcastChoice = 'broadcast' | 'broadcast_and_move' | 'workflow'
+
+/**
+ * Resolves to null when the user closes the dialog without a choice. `others` are the existing
+ * workflows that could move to broadcasts too; the dialog names them and offers to move them.
+ */
+export function confirmCreateAsBroadcast(
+ others: readonly BroadcastConversionCandidateApi[] = []
+): Promise<CreateAsBroadcastChoice | null> {
+ const overview =
+ 'Broadcasts come with an overview built for sends to an audience. Watch deliveries, opens, clicks and conversions come in, and compare them across sends.'
+ const keepAsWorkflow = {
+ children: 'Keep as workflow',
+ 'data-attr': 'workflow-create-as-broadcast-decline',
+ }
+ const hasOthers = others.length > 0
+ return new Promise((resolve) => {
+ LemonDialog.open({
+ // Three buttons do not fit on one row at the default width.
+ width: hasOthers ? 600 : 500,
+ title: 'Track this send as a broadcast?',
+ description: hasOthers ? (
+ <>
+ <p className="mb-2">{overview}</p>
+ <p className="mb-1">
+ Also move {others.length === 1 ? 'this workflow' : `these ${others.length} workflows`} to
+ broadcasts?
+ </p>
+ <ul className="list-disc pl-5 mb-0 max-h-40 overflow-y-auto">
+ {others.map((other) => (
+ <li key={other.id}>{other.name || 'Untitled workflow'}</li>
+ ))}
+ </ul>
+ </>
+ ) : (
+ overview
+ ),
+ primaryButton: hasOthers
+ ? {
+ children: `Create and move ${others.length} more`,
+ type: 'primary',
+ 'data-attr': 'workflow-create-as-broadcast-and-move',
+ onClick: () => resolve('broadcast_and_move'),
+ }
+ : {
+ children: 'Create broadcast',
+ type: 'primary',
+ 'data-attr': 'workflow-create-as-broadcast-confirm',
+ onClick: () => resolve('broadcast'),
+ },
+ secondaryButton: hasOthers
+ ? {
+ children: 'Create broadcast',
+ 'data-attr': 'workflow-create-as-broadcast-confirm',
+ onClick: () => resolve('broadcast'),
+ }
+ : { ...keepAsWorkflow, onClick: () => resolve('workflow') },
+ tertiaryButton: hasOthers ? { ...keepAsWorkflow, onClick: () => resolve('workflow') } : undefined,
+ // A button click resolves first, so this only takes effect when the dialog is dismissed.
+ onAfterClose: () => resolve(null),
+ })
+ })
+}
+
+/** The existing workflows that could move to broadcasts. Empty when the list cannot load. */
+export async function loadBroadcastConversionCandidates(
+ projectId: string
+): Promise<readonly BroadcastConversionCandidateApi[]> {
+ try {
+ return (await hogFlowsBroadcastConversionCandidatesRetrieve(projectId)).results
+ } catch {
+ // The offer to move other workflows is optional, so a failed lookup must not block the save.
+ return []
+ }
+}
+
+/** Moves each workflow to broadcasts and returns how many moved. */
+export async function moveWorkflowsToBroadcasts(projectId: string, workflowIds: string[]): Promise<number> {
+ const results = await Promise.allSettled(workflowIds.map((id) => hogFlowsConvertToBroadcast(projectId, id)))
+ return results.filter((result) => result.status === 'fulfilled').length
+}
+
+export function movedToBroadcastsMessage(requested: number, moved: number): string {
+ return moved === requested
+ ? `Broadcast saved. ${pluralize(moved, 'other workflow')} moved to broadcasts.`
+ : `Broadcast saved. ${requested - moved} of ${requested} other workflows did not move. They stay in the Workflows list.`
+}
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index 2d5702f06705..278a59140364 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -2353,9 +2353,10 @@ export function buildBroadcastPayload(values: {
broadcast?: HogFlowApi | null
}): Record<string, any> {
const existing = values.broadcast
- if (existing && existing.origin_product !== 'broadcasts') {
- // A workflow shaped like a broadcast keeps its own steps: its ids, names and any setting the
- // wizard does not manage survive, and origin_product stays as it was created.
+ if (existing) {
+ // A saved broadcast keeps its own steps: its ids, names and any setting the wizard does not manage
+ // survive, such as step conditions or a test-account exclusion on a workflow moved to broadcasts.
+ // origin_product and the exit condition stay as they were.
return {
name: values.name,
conversion: values.goalEnabled ? values.conversion : null,
diff --git a/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts b/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts
index f5c438fd5475..933af92a2721 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWorkflowEdits.test.ts
@@ -83,10 +83,18 @@ describe('broadcast edits to broadcast-shaped workflows', () => {
expect(canMoveToDraft(broadcast, jobs)).toBe(expected)
})
- it('saves the audience and email into the existing steps without replacing them', () => {
+ it.each([
+ ['a workflow shaped like a broadcast', null],
+ ['a workflow moved to broadcasts', 'broadcasts'],
+ ])('saves the audience and email of %s into the existing steps without replacing them', (_, originProduct) => {
+ const condition = { properties: [{ key: 'email', operator: 'is_set', type: 'person' }] }
const existing = {
- origin_product: null,
- actions: [trigger({ properties: [], cohort_hint: 'kept' }), email(), exit],
+ origin_product: originProduct,
+ actions: [
+ trigger({ properties: [], cohort_hint: 'kept', filter_test_accounts: true }),
+ { ...email(), filters: condition },
+ exit,
+ ],
edges,
} as unknown as HogFlowApi
@@ -110,7 +118,9 @@ describe('broadcast edits to broadcast-shaped workflows', () => {
expect(payload.actions[0].config.filters).toEqual({
properties: [{ key: 'plan', value: 'pro', operator: 'exact', type: 'person' }],
cohort_hint: 'kept',
+ filter_test_accounts: true,
})
+ expect(payload.actions[1].filters).toEqual(condition)
expect(payload.actions[1].on_error).toBe('continue')
expect(payload.actions[1].config.inputs.extra).toEqual({ value: 1 })
expect(payload.actions[1].config.inputs.email.value.subject).toBe('New subject')
diff --git a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
index 8f9e57c31f23..3b9e29caff59 100644
--- a/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastsLogic.ts
@@ -64,10 +64,10 @@ export interface BroadcastsFilters {
const DEFAULT_FILTERS: BroadcastsFilters = { search: '', status: 'all', createdBy: null, page: 1 }
+type FlowStep = { id?: string; type?: string; config?: Record<string, any> }
+
/** Mirrors the list API's broadcast_eligible filter: a batch trigger, one email step, nothing else. */
-export function isBroadcastShaped(
- actions: { type?: string; config?: { type?: string } }[] | null | undefined
-): boolean {
+export function isBroadcastShaped(actions: FlowStep[] | null | undefined): boolean {
const steps = actions ?? []
return (
steps.some((step) => step.type === 'trigger' && step.config?.type === 'batch') &&
@@ -76,7 +76,6 @@ export function isBroadcastShaped(
)
}
-type FlowStep = { id?: string; type?: string; config?: Record<string, any> }
type FlowEdge = { from?: string; to?: string }
/**
diff --git a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx
index 0f04e0e70c16..2d5dafa8b602 100644
--- a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx
+++ b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx
@@ -346,6 +346,22 @@ export function workflowActivityDescriber(logItem: ActivityLogItem, asNotificati
}
}
+ if (logItem.activity == 'converted_to_broadcast') {
+ return {
+ summary: activityLogSummary(
+ logItem,
+ 'Moved to broadcasts',
+ nameOrLinkToWorkflow(logItem.item_id, logItem.detail.name)
+ ),
+ description: (
+ <>
+ <ActivityLogUserName logItem={logItem} /> moved the {objectNoun} to broadcasts:{' '}
+ {nameOrLinkToWorkflow(logItem?.item_id, logItem?.detail.name)}
+ </>
+ ),
+ }
+ }
+
if (logItem.activity == 'updated' || logItem.activity == 'published') {
return describeWorkflowUpdate(logItem)
}
diff --git a/products/workflows/frontend/Workflows/workflowLogic.broadcastSuggestion.test.ts b/products/workflows/frontend/Workflows/workflowLogic.broadcastSuggestion.test.ts
new file mode 100644
index 000000000000..e47d37f1005c
--- /dev/null
+++ b/products/workflows/frontend/Workflows/workflowLogic.broadcastSuggestion.test.ts
@@ -0,0 +1,176 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { confirmCreateAsBroadcast } from '../Broadcasts/broadcastLifecycle'
+import { HogFlow } from './hogflows/types'
+import { workflowLogic } from './workflowLogic'
+
+jest.mock('../Broadcasts/broadcastLifecycle', () => ({
+ ...jest.requireActual('../Broadcasts/broadcastLifecycle'),
+ confirmCreateAsBroadcast: jest.fn(),
+}))
+
+const CREATED_ID = 'created-flow'
+
+const step = (id: string, type: string, config: Record<string, any>): HogFlow['actions'][number] =>
+ ({ id, type, name: id, description: '', created_at: 0, updated_at: 0, config }) as HogFlow['actions'][number]
+
+const trigger = (type: string): HogFlow['actions'][number] => step('trigger_node', 'trigger', { type, filters: {} })
+const email = step('email_node', 'function_email', { template_id: 'template-email', inputs: {} })
+const exit = step('exit_node', 'exit', { reason: 'Default exit' })
+const emailEdges: HogFlow['edges'] = [
+ { from: 'trigger_node', to: 'email_node', type: 'continue' },
+ { from: 'email_node', to: 'exit_node', type: 'continue' },
+]
+
+describe('workflowLogic broadcast suggestion on create', () => {
+ let logic: ReturnType<typeof workflowLogic.build>
+ let createdBodies: Record<string, any>[]
+ let convertedIds: string[]
+ let submittingDuringMove: boolean[]
+ let otherIds: string[]
+
+ beforeEach(() => {
+ createdBodies = []
+ convertedIds = []
+ submittingDuringMove = []
+ otherIds = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/hog_function_templates/': { results: [], count: 0 },
+ '/api/projects/:team_id/hog_flows/broadcast_conversion_candidates/': () => [
+ 200,
+ {
+ has_more: false,
+ results: otherIds.map((id) => ({ id, name: id, status: 'draft' })),
+ },
+ ],
+ '/api/environments/:team_id/hog_flows/:id/schedules': { results: [] },
+ },
+ post: {
+ '/api/projects/:team_id/hog_flows/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ createdBodies.push(body)
+ return [201, { ...body, id: CREATED_ID, updated_at: '2026-05-01T00:00:00.000Z' }]
+ },
+ '/api/projects/:team_id/hog_flows/:id/convert_to_broadcast/': ({ params }) => {
+ convertedIds.push(params.id as string)
+ submittingDuringMove.push(logic.values.isWorkflowSubmitting)
+ return [200, { id: params.id, origin_product: 'broadcasts' }]
+ },
+ },
+ })
+ initKeaTests()
+ logic = workflowLogic({ id: 'new' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.mocked(confirmCreateAsBroadcast).mockReset()
+ })
+
+ it.each([
+ {
+ name: 'a batch email accepted as a broadcast',
+ actions: [trigger('batch'), email, exit],
+ exitCondition: 'exit_only_at_end' as const,
+ choice: 'broadcast' as const,
+ asked: true,
+ others: ['wf-a'],
+ moved: [],
+ originProduct: 'broadcasts',
+ path: `/broadcasts/${CREATED_ID}`,
+ },
+ {
+ name: 'a batch email accepted as a broadcast with the others moved',
+ actions: [trigger('batch'), email, exit],
+ exitCondition: 'exit_only_at_end' as const,
+ choice: 'broadcast_and_move' as const,
+ asked: true,
+ others: ['wf-a', 'wf-b'],
+ moved: ['wf-a', 'wf-b'],
+ originProduct: 'broadcasts',
+ path: `/broadcasts/${CREATED_ID}`,
+ },
+ {
+ name: 'a batch email kept as a workflow',
+ actions: [trigger('batch'), email, exit],
+ exitCondition: 'exit_only_at_end' as const,
+ choice: 'workflow' as const,
+ asked: true,
+ others: ['wf-a'],
+ moved: [],
+ originProduct: undefined,
+ path: `/workflows/${CREATED_ID}/workflow`,
+ },
+ {
+ name: 'an event-triggered email',
+ actions: [trigger('event'), email, exit],
+ exitCondition: 'exit_only_at_end' as const,
+ choice: 'broadcast' as const,
+ asked: false,
+ others: [],
+ moved: [],
+ originProduct: undefined,
+ path: `/workflows/${CREATED_ID}/workflow`,
+ },
+ {
+ name: 'a batch email that exits on conversion',
+ actions: [trigger('batch'), email, exit],
+ exitCondition: 'exit_on_conversion' as const,
+ choice: 'broadcast' as const,
+ asked: false,
+ others: [],
+ moved: [],
+ originProduct: undefined,
+ path: `/workflows/${CREATED_ID}/workflow`,
+ },
+ ])(
+ 'creates $name with the right owner and opens it',
+ async ({ actions, exitCondition, choice, asked, others, moved, originProduct, path }) => {
+ otherIds = others
+ jest.mocked(confirmCreateAsBroadcast).mockResolvedValue(choice)
+ logic.actions.setWorkflowValues({
+ name: 'Monthly update',
+ actions,
+ edges: emailEdges,
+ exit_condition: exitCondition,
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitWorkflow()
+ })
+ .toDispatchActions(['saveWorkflowSuccess'])
+ .toFinishAllListeners()
+
+ expect(
+ jest.mocked(confirmCreateAsBroadcast).mock.calls.map(([offered]) => offered?.map((o) => o.id))
+ ).toEqual(asked ? [others] : [])
+ expect(convertedIds.sort()).toEqual(moved)
+ // Save stays disabled while the other workflows move, so a second click cannot create a duplicate.
+ expect(submittingDuringMove).toEqual(moved.map(() => true))
+ expect(createdBodies).toHaveLength(1)
+ expect(createdBodies[0].origin_product).toBe(originProduct)
+ expect(router.values.location.pathname).toMatch(new RegExp(`${path}$`))
+ }
+ )
+
+ it('creates nothing when the user closes the dialog', async () => {
+ jest.mocked(confirmCreateAsBroadcast).mockResolvedValue(null)
+ logic.actions.setWorkflowValues({
+ name: 'Monthly update',
+ actions: [trigger('batch'), email, exit],
+ edges: emailEdges,
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.submitWorkflow()
+ }).toDispatchActions(['submitWorkflowSuccess'])
+
+ expect(createdBodies).toHaveLength(0)
+ })
+})
diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.ts
index 5dcd68874080..3b1a4f2818f2 100644
--- a/products/workflows/frontend/Workflows/workflowLogic.ts
+++ b/products/workflows/frontend/Workflows/workflowLogic.ts
@@ -7,7 +7,7 @@ import posthog from 'posthog-js'
import { LemonDialog } from '@posthog/lemon-ui'
-import api, { ApiError } from 'lib/api'
+import api, { ApiConfig, ApiError } from 'lib/api'
import { CyclotronJobInputsValidation } from 'lib/components/CyclotronJob/CyclotronJobInputsValidation'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
@@ -29,10 +29,17 @@ import { userLogic } from 'scenes/userLogic'
import { AccessControlLevel, HogFunctionTemplateType, IntegrationType } from '~/types'
import { resourceEditedLogic } from 'products/notifications/frontend/resourceEditedLogic'
-import { hogFlowsResumeEmailSending } from 'products/workflows/frontend/generated/api'
+import { hogFlowsCreate, hogFlowsResumeEmailSending } from 'products/workflows/frontend/generated/api'
import type { EmailDraftRequestApi } from 'products/workflows/frontend/generated/api.schemas'
import type { ResourceEditedEvent, UserBasicType, UserType } from '../../../../frontend/src/types'
+import {
+ confirmCreateAsBroadcast,
+ loadBroadcastConversionCandidates,
+ moveWorkflowsToBroadcasts,
+ movedToBroadcastsMessage,
+} from '../Broadcasts/broadcastLifecycle'
+import { canEditInWizard, isBroadcastShaped } from '../Broadcasts/broadcastsLogic'
import { loadEntrySource, saveEntrySource } from '../Broadcasts/broadcastUsage'
import { resolveDefaultEmailSender } from '../Channels/defaultEmailSender'
import {
@@ -238,6 +245,10 @@ function pickWorkflowEdits(workflow: HogFlow): Partial<HogFlow> {
interface SaveContext {
initiatedByAutoSave: boolean
pendingSchedule: { rrule: string; starts_at: string; timezone?: string } | null | false
+ // Existing workflows to move to broadcasts once this save creates a broadcast.
+ moveToBroadcastIds: string[]
+ // How many of them moved. The save sets it before it finishes.
+ movedToBroadcasts?: number
}
function omitWorkflowContent(workflow: HogFlow): Partial<HogFlow> {
@@ -3343,7 +3354,13 @@ export const workflowLogic = kea<workflowLogicType>([
// The pending schedule rides along because an earlier save's reset clears it,
// which would drop a schedule change the user asked a manual save to persist.
const saveContexts = (cache.saveContexts ??= []) as SaveContext[]
- saveContexts.push({ initiatedByAutoSave, pendingSchedule: values.pendingSchedule })
+ const saveContext: SaveContext = {
+ initiatedByAutoSave,
+ pendingSchedule: values.pendingSchedule,
+ moveToBroadcastIds: (cache.nextSaveMovesWorkflowIds ?? []) as string[],
+ }
+ saveContexts.push(saveContext)
+ cache.nextSaveMovesWorkflowIds = []
// Whether this save means to change the lifecycle. Only the enable and disable
// control does, and it says so when it dispatches. Comparing the payload's
// status against the stored one cannot tell the difference: that control does
@@ -3351,12 +3368,20 @@ export const workflowLogic = kea<workflowLogicType>([
// carries the old value and reads as a transition back to it.
const isStatusSave = cache.nextSaveChangesStatus === true
cache.nextSaveChangesStatus = false
+ const createsBroadcast = cache.nextSaveCreatesBroadcast === true
+ cache.nextSaveCreatesBroadcast = false
const runSave = async (): Promise<HogFlow> => {
updates = sanitizeWorkflow(updates, values.hogFunctionTemplatesById)
if (!props.id || props.id === 'new') {
- const result = await api.hogFlows.createHogFlow(updates)
+ // The editor's HogFlow schema and the generated HogFlowApi describe the same payload.
+ // The selected environment, as the legacy client used, not its parent project.
+ const teamId = String(ApiConfig.getCurrentTeamId())
+ const result = (await hogFlowsCreate(teamId, {
+ ...updates,
+ ...(createsBroadcast ? { origin_product: 'broadcasts' } : {}),
+ } as unknown as Parameters<typeof hogFlowsCreate>[1])) as unknown as HogFlow
if (props.templateId) {
posthog.capture('hog_flow_created_from_template', {
@@ -3367,11 +3392,32 @@ export const workflowLogic = kea<workflowLogicType>([
if (props.entrySource) {
saveEntrySource(result.id, props.entrySource)
}
- // pinned: analytics event name
- posthog.capture('workflow draft created', {
- workflow_id: result.id,
- entry_source: props.entrySource ?? null,
- })
+ if (createsBroadcast) {
+ // pinned: analytics event name
+ posthog.capture('broadcast draft created', {
+ broadcast_id: result.id,
+ entry_source: props.entrySource ?? null,
+ created_from: 'workflow_editor',
+ })
+ // Moved inside the save so the form stays submitting, and Save stays
+ // disabled, until the moves finish and the editor leaves the new page.
+ if (saveContext.moveToBroadcastIds.length > 0) {
+ saveContext.movedToBroadcasts = await moveWorkflowsToBroadcasts(
+ teamId,
+ saveContext.moveToBroadcastIds
+ )
+ posthog.capture('workflows moved to broadcasts', {
+ requested: saveContext.moveToBroadcastIds.length,
+ moved: saveContext.movedToBroadcasts,
+ })
+ }
+ } else {
+ // pinned: analytics event name
+ posthog.capture('workflow draft created', {
+ workflow_id: result.id,
+ entry_source: props.entrySource ?? null,
+ })
+ }
return result
}
@@ -3501,7 +3547,7 @@ export const workflowLogic = kea<workflowLogicType>([
},
],
})),
- forms(({ actions, values, cache }) => ({
+ forms(({ actions, values, cache, props }) => ({
workflow: {
defaults: NEW_WORKFLOW,
errors: ({ name, actions, status }) => {
@@ -3516,12 +3562,36 @@ export const workflowLogic = kea<workflowLogicType>([
return errors
},
- submit: async (values) => {
- if (!values) {
+ submit: async (workflow) => {
+ if (!workflow) {
return
}
- actions.saveWorkflow(values)
+ // A new workflow that only sends one email to a batch is a broadcast. Offer to create it
+ // as one, so it opens in the broadcast editor and lists under broadcasts.
+ if (
+ (!props.id || props.id === 'new') &&
+ !props.editTemplateId &&
+ // The broadcast editor always saves this exit condition, so any other one would be lost.
+ workflow.exit_condition === 'exit_only_at_end' &&
+ isBroadcastShaped(workflow.actions) &&
+ canEditInWizard(workflow.actions, workflow.edges)
+ ) {
+ const others = await loadBroadcastConversionCandidates(String(ApiConfig.getCurrentTeamId()))
+ const choice = await confirmCreateAsBroadcast(others)
+ posthog.capture('workflow broadcast suggestion answered', {
+ choice: choice ?? 'dismissed',
+ other_workflows: others.length,
+ })
+ if (!choice) {
+ return
+ }
+ cache.nextSaveCreatesBroadcast = choice !== 'workflow'
+ cache.nextSaveMovesWorkflowIds =
+ choice === 'broadcast_and_move' ? others.map((other) => other.id) : []
+ }
+
+ actions.saveWorkflow(workflow)
// Hold the form in its submitting state until the save lands, so the save button
// keeps a loading state and cannot fire a second save. The loader created the queue
// while it handled the action above.
@@ -4390,6 +4460,19 @@ export const workflowLogic = kea<workflowLogicType>([
action: () => actions.publishDraft(),
},
})
+ } else if (originalWorkflow.origin_product === 'broadcasts') {
+ const moveIds = saveContext?.moveToBroadcastIds ?? []
+ if (moveIds.length > 0) {
+ const moved = saveContext?.movedToBroadcasts ?? 0
+ const message = movedToBroadcastsMessage(moveIds.length, moved)
+ if (moved === moveIds.length) {
+ lemonToast.success(message)
+ } else {
+ lemonToast.warning(message)
+ }
+ } else {
+ lemonToast.success('Broadcast saved')
+ }
} else {
lemonToast.success('Workflow saved')
}
@@ -4400,10 +4483,12 @@ export const workflowLogic = kea<workflowLogicType>([
if (props.id === 'new' && originalWorkflow.id) {
router.actions.replace(
- urls.workflow(
- originalWorkflow.id,
- workflowSceneLogic.findMounted()?.values.currentTab || 'workflow'
- )
+ originalWorkflow.origin_product === 'broadcasts'
+ ? urls.broadcast(originalWorkflow.id)
+ : urls.workflow(
+ originalWorkflow.id,
+ workflowSceneLogic.findMounted()?.values.currentTab || 'workflow'
+ )
)
}
}
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index e804a74fd590..85dd9246e1cd 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -1107,6 +1107,17 @@ export interface HogFlowBatchJobCancelResponseApi {
done: boolean
}
+export interface HogFlowConvertedToBroadcastApi {
+ /** Id of the workflow that is now a broadcast. */
+ readonly id: string
+ /** The product that now owns the workflow. Always `broadcasts`.
+ *
+ * * `loops` - Loops
+ * * `broadcasts` - Broadcasts
+ * * `transactional_emails` - Transactional emails */
+ readonly origin_product: HogFlowOriginProductEnumApi
+}
+
/**
* * `update_action` - update_action
* * `add_action` - add_action
@@ -1798,6 +1809,29 @@ export interface PatchedHogFlowScheduleApi {
readonly updated_at?: string
}
+export interface BroadcastConversionCandidateApi {
+ /** Workflow id. */
+ readonly id: string
+ /** Workflow name. Empty when unnamed. */
+ readonly name: string
+ /** Workflow status.
+ *
+ * * `draft` - Draft
+ * * `active` - Active
+ * * `archived` - Archived */
+ readonly status: HogFlowStateEnumApi
+}
+
+/**
+ * Workflows that only send one email to a batch audience and can move to broadcasts.
+ */
+export interface BroadcastConversionCandidatesApi {
+ /** True when more workflows can move than `results` lists. */
+ readonly has_more: boolean
+ /** The most recently updated candidates, at most 100. */
+ readonly results: readonly BroadcastConversionCandidateApi[]
+}
+
/**
* Cheap suspension-only read for the persistent scene-wide banner — no reputation computation.
*/
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 2dd52c088eab..310ea8aec0ed 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -13,6 +13,7 @@ import type {
AppMetricsTotalsResponseApi,
BlastRadiusApi,
BlastRadiusRequestApi,
+ BroadcastConversionCandidatesApi,
DataSuggestionBuildRequestApi,
DataSuggestionBuildResponseApi,
DataSuggestionGenerateRequestApi,
@@ -23,6 +24,7 @@ import type {
HogFlowApi,
HogFlowBatchJobApi,
HogFlowBatchJobCancelResponseApi,
+ HogFlowConvertedToBroadcastApi,
HogFlowInFlightApi,
HogFlowInvocationApi,
HogFlowOptimizationApi,
@@ -500,6 +502,25 @@ export const hogFlowsBatchJobsCancelCreate = async (
)
}
+export const getHogFlowsConvertToBroadcastUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/convert_to_broadcast/`
+}
+
+/**
+ * Move a workflow to broadcasts. It keeps its id, runs and metrics, leaves the workflows list and opens
+ * in the broadcast editor. This cannot be undone.
+ */
+export const hogFlowsConvertToBroadcast = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<HogFlowConvertedToBroadcastApi> => {
+ return apiMutator<HogFlowConvertedToBroadcastApi>(getHogFlowsConvertToBroadcastUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getHogFlowsDiscardDraftCreateUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/hog_flows/${id}/discard_draft/`
}
@@ -1224,6 +1245,27 @@ export const hogFlowsSchedulesDestroy = async (
})
}
+export const getHogFlowsBroadcastConversionCandidatesRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/hog_flows/broadcast_conversion_candidates/`
+}
+
+/**
+ * List the workflows that could become broadcasts: one email to a batch audience, with nothing the
+ * broadcast editor would drop. Only workflows the caller may edit are listed.
+ */
+export const hogFlowsBroadcastConversionCandidatesRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<BroadcastConversionCandidatesApi> => {
+ return apiMutator<BroadcastConversionCandidatesApi>(
+ getHogFlowsBroadcastConversionCandidatesRetrieveUrl(projectId),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getHogFlowsBulkDeleteCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/hog_flows/bulk_delete/`
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2b8c3c536b41..f6256c738d27 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19084,6 +19084,43 @@ export namespace Schemas {
confidence: number;
}
+ /**
+ * * `draft` - Draft
+ * * `active` - Active
+ * * `archived` - Archived
+ */
+ export type HogFlowStateEnum = typeof HogFlowStateEnum[keyof typeof HogFlowStateEnum];
+
+
+ export const HogFlowStateEnum = {
+ Draft: 'draft',
+ Active: 'active',
+ Archived: 'archived',
+ } as const;
+
+ export interface BroadcastConversionCandidate {
+ /** Workflow id. */
+ readonly id: string;
+ /** Workflow name. Empty when unnamed. */
+ readonly name: string;
+ /** Workflow status.
+ *
+ * * `draft` - Draft
+ * * `active` - Active
+ * * `archived` - Archived */
+ readonly status: HogFlowStateEnum;
+ }
+
+ /**
+ * Workflows that only send one email to a batch audience and can move to broadcasts.
+ */
+ export interface BroadcastConversionCandidates {
+ /** True when more workflows can move than `results` lists. */
+ readonly has_more: boolean;
+ /** The most recently updated candidates, at most 100. */
+ readonly results: readonly BroadcastConversionCandidate[];
+ }
+
/**
* * `breaking_master` - Breaking Master
* * `blocking_merge_queue` - Blocking Merge Queue
@@ -55639,20 +55676,6 @@ export namespace Schemas {
*/
export type HogFlowActionRedirects = {[key: string]: string} | null;
- /**
- * * `draft` - Draft
- * * `active` - Active
- * * `archived` - Archived
- */
- export type HogFlowStateEnum = typeof HogFlowStateEnum[keyof typeof HogFlowStateEnum];
-
-
- export const HogFlowStateEnum = {
- Draft: 'draft',
- Active: 'active',
- Archived: 'archived',
- } as const;
-
/**
* * `loops` - Loops
* * `broadcasts` - Broadcasts
@@ -56119,6 +56142,17 @@ export namespace Schemas {
done: boolean;
}
+ export interface HogFlowConvertedToBroadcast {
+ /** Id of the workflow that is now a broadcast. */
+ readonly id: string;
+ /** The product that now owns the workflow. Always `broadcasts`.
+ *
+ * * `loops` - Loops
+ * * `broadcasts` - Broadcasts
+ * * `transactional_emails` - Transactional emails */
+ readonly origin_product: HogFlowOriginProductEnum;
+ }
+
/**
* * `update_action` - update_action
* * `add_action` - add_action