:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(workflows): load the send calendar from one slim endpoint (#119293)
Meikel Ratz68a1c1baa8d1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 58dbfeb0980e..8b85297a6bc2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8235,25 +8235,25 @@ snapshots:products-workflows-reputation--shared-sending-domain--light:hash: v1.k794b7964.d2f19057ecd63916468e49499852f4b90854405ad3d4f8bbb04e766a6180a0bf.SIZeFe7wNudMSeL2euN2W8tSq5ATz9vp6KGnFbgeUmwproducts-workflows-send-calendar--busy-week--dark:- hash: v1.k794b7964.39afa422487dc061f94a4ec6398437e7eec01d3d2af64abc161bc52f9190ea54.-lZbR8UwepYyXHdTtBKYA6fO_oE3GnJxWofpm3LfjsY+ hash: v1.k794b7964.1edf0999ab5e390b86d0a8d48ab5821c5cb291b35eba58eb4000587652ba79af.4plcEAYl06VvPXCtAKWYvMcbQLWV-U1_khdj3SHu5Hoproducts-workflows-send-calendar--busy-week--light:- hash: v1.k794b7964.de536a827450a4177db2b69dab61584db5f9d76a88f7f13e0de28fb09a03c490.Mc2K6bqJx4Fww7yaS7gS5BpFaJ5YktzZdL-EUXUBUCw+ hash: v1.k794b7964.41b0edfff41f5bd11d916fa6f081fecbbd9ce443c467922b6bcb023a2ffeac90.nl-bjqzGcWaq49TId69VJnA4iaiXAFAfgc74hO4izsYproducts-workflows-send-calendar--month-view--dark:hash: v1.k794b7964.cecd17eafa4403fc327696ca01e18d89e9ab20055147174bc1cf4d3b9e01e542.OziIUxzKe2NSoO_dsw75-h9W1G2-JXARS9Y-vWCnCL4products-workflows-send-calendar--month-view--light:hash: v1.k794b7964.ec1c298f638778f07b234cc8ccbab29e07518762aa2df6964df155164a03fb2d.EF5lJojKTeDEG9EulMEK3sHHvxvxfkv_kj-D7uZV4Qoproducts-workflows-send-calendar--narrow-width--dark:- hash: v1.k794b7964.69ec31afe8d91cde95130a01137235085229d7eefb3982e46efae482e2ca5541.m6sFedELuEDLHQdH3I9Vii81Jns-2-PhbyCFi1S_7oQ+ hash: v1.k794b7964.b0839130eba311e8dfb27419f30ad80fc1afad86edb413ce969ece95bcdbf5fc.9fl8uTCF8-AW7cBO4skS416WS_ACqu4vyuI6vOmPqGAproducts-workflows-send-calendar--narrow-width--light:- hash: v1.k794b7964.f81d64ad25f9dd5c324de05f3486e4670e231384b6ef9f1218b71264a56f6fc9.qiSArgztEf8Bgy-CigvE-2Wrn8D6AyZ7QMDNh5of-j8+ hash: v1.k794b7964.2e0efe725b20aab2db789b0bfef533a1b2e27aa33ae51944e9a49f79678ad99d.u4syELhPlHpgVZVFBrFukIkE-tk-sd7m-4zFrT_1ePMproducts-workflows-send-calendar--nothing-scheduled--dark:- hash: v1.k794b7964.e49af2419c9e74175a1cabbfe01f44acf29c8fea8bff95eb425e00b7163413fe.Ah8ueSoHSilObSRoM-KsXH_RKl5xqKpapInbI6zD3OI+ hash: v1.k794b7964.0df0c80ba3b1e4f56a9ca297d55adb4b6cd5c58aa7968e638c55b01e25eda308.jBDSsX-jXLcOHSDudHiI18nzeBKTH_XUJ4UxHnmx7qwproducts-workflows-send-calendar--nothing-scheduled--light:- hash: v1.k794b7964.7b96f8bc40e1099363decb68e74dc99f0c94770e357faf6ecf2002f1b6ca748f.MbSByJrs9lR7-T6XxqCAhD1MyjpuO74VJ5jYW8j7C-4+ hash: v1.k794b7964.f962c9fb4ae9bd548a4f110e3230649791194c60409c13575dbdd33d9f11324f.dalGC0qyruSRv__DR2AYm8X1wGM_YCGpMPpYxmkhBhQproducts-workflows-send-calendar--send-details--dark:- hash: v1.k794b7964.5ec26f2be0e3ccc0c66d4c76a053b2297f161987d8b07789d3812e276310f4bb.gUaDqSUhaUWckeDBW5u172smdN7GTZipTrfrolPQhnw+ hash: v1.k794b7964.4e302efcdf3bbe84471a1db8de00985e0137bdf4e412e1a9bd11767b902bab45.9SLKWqpXIRSSN_LgMQrrlfxdesKpYm6vdX2DpwP2nmQproducts-workflows-send-calendar--send-details--light:- hash: v1.k794b7964.4baf13346e5c827c9c8eeeafa125b5ee89b026a1e664dcbdc1892b67f8582b6a.dOFZmzdzpwwtnnC3MHbRTRI55VeKeBvxvYo0Istk6YM+ hash: v1.k794b7964.a4ebf0a739215b12953d9c17ec9b0cfa7f09251da07043ebc9117a8ac61cbeb4.SWCmephcDTdKIK5x2P0Li8lIQ1p8rYU4kqdEiQI0T_kproducts-workflows-steps-customer-task-reference-input--account--dark:hash: v1.k794b7964.884dda5b1415d9a041c053804964a19d7a9adb2b28edc1797a9cbed8f5dc6782.YXjfbjz9Kxh9TbLWc8Dai7nySVQz9UByZVxWqopauE8products-workflows-steps-customer-task-reference-input--account--light:diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 518bb7554d92..c078fae66c57 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -117,6 +117,38 @@ class WorkflowSchedule:updated_at: datetime+@frozen+class SendCalendarBatchJob:+ """One batch run, with only the fields the send calendar shows."""++ id: UUID+ status: HogFlowBatchJobState+ created_at: datetime+++@frozen+class SendCalendarFlow:+ """An active, scheduled email workflow, with only the fields a send calendar card shows.++ The email fields come from the first email step. ``audience_properties`` and ``audience_type``+ come from a batch trigger's filters, and ``email_to`` only from a schedule trigger, which has no+ audience. ``batch_jobs`` holds only the runs inside the requested range.+ """++ id: UUID+ name: str | None+ origin_product: str | None+ created_by: "User | None"+ user_access_level: str | None+ trigger_type: str+ audience_properties: list[dict[str, Any]]+ audience_type: str | None+ email_to: str | None+ message_category_id: str | None+ schedules: tuple[WorkflowSchedule, ...]+ batch_jobs: tuple[SendCalendarBatchJob, ...]++class WorkflowScheduleNotFound(Exception):passdiff --git a/products/workflows/backend/facade/send_calendar.py b/products/workflows/backend/facade/send_calendar.pynew file mode 100644index 000000000000..b4d04356b591--- /dev/null+++ b/products/workflows/backend/facade/send_calendar.py@@ -0,0 +1,8 @@+"""The send calendar: a team's scheduled marketing email workflows, with only what a calendar card shows."""++from products.workflows.backend.services.send_calendar import SEND_CALENDAR_MAX_RANGE_DAYS, list_send_calendar_flows++__all__ = [+ "SEND_CALENDAR_MAX_RANGE_DAYS",+ "list_send_calendar_flows",+]diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 633521e82c6e..46258ed647b6 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -51,6 +51,7 @@ from posthog.api.app_metrics2 import ()from posthog.api.documentation import _FallbackSerializerfrom posthog.api.log_entries import LogEntryMixin+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.auth import InternalAPIAuthentication@@ -254,6 +255,7 @@ from products.workflows.backend.facade.secrets import (secret_keys_for_action,strip_content_secrets,)+from products.workflows.backend.facade.send_calendar import SEND_CALENDAR_MAX_RANGE_DAYS, list_send_calendar_flowsfrom products.workflows.backend.facade.suggestions_scout import (PROPOSAL_WRITE_SCOPE,suggestions_scout_refusal,@@ -2231,6 +2233,73 @@ class HogFlowScheduleSerializer(serializers.Serializer):return data+class SendCalendarQuerySerializer(serializers.Serializer):+ start = serializers.DateTimeField(help_text="Start of the shown range, inclusive, as an ISO 8601 datetime.")+ end = serializers.DateTimeField(+ help_text=(+ f"End of the shown range, exclusive, as an ISO 8601 datetime. At most {SEND_CALENDAR_MAX_RANGE_DAYS} "+ "days after start."+ )+ )++ def validate(self, data: dict) -> dict:+ if data["end"] <= data["start"]:+ raise serializers.ValidationError({"end": "End must be after start."})+ if data["end"] - data["start"] > timedelta(days=SEND_CALENDAR_MAX_RANGE_DAYS):+ raise serializers.ValidationError(+ {"end": f"The range can be at most {SEND_CALENDAR_MAX_RANGE_DAYS} days long."}+ )+ return data+++class SendCalendarBatchJobSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True, help_text="ID of the batch run.")+ status = serializers.ChoiceField(+ choices=HogFlowBatchJobState.choices, read_only=True, help_text="Status of the batch run."+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When the batch run started.")+++class SendCalendarFlowSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True, help_text="ID of the workflow.")+ name = serializers.CharField(read_only=True, allow_null=True, help_text="Name of the workflow.")+ origin_product = serializers.ChoiceField(+ choices=HogFlowOriginProduct.choices,+ read_only=True,+ allow_null=True,+ help_text="The product surface that owns the workflow, such as broadcasts. Null for a plain workflow.",+ )+ created_by = UserBasicSerializer(read_only=True, allow_null=True, help_text="User who created the workflow.")+ user_access_level = serializers.CharField(+ read_only=True, allow_null=True, help_text="The reader's access level on the workflow."+ )+ trigger_type = serializers.CharField(read_only=True, help_text="The trigger type: batch or schedule.")+ audience_properties = serializers.ListField(+ child=serializers.DictField(),+ read_only=True,+ help_text="The property filters of a batch trigger's audience. Empty for a schedule trigger.",+ )+ audience_type = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="persons or accounts for a batch trigger's audience. Null when the trigger does not set it.",+ )+ email_to = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="The 'To' address of the first email step. A schedule trigger has no audience, so it sends here.",+ )+ message_category_id = serializers.CharField(+ read_only=True, allow_null=True, help_text="ID of the message category of the first email step."+ )+ schedules = HogFlowScheduleSerializer(+ many=True, read_only=True, help_text="The schedules that still have sends to come."+ )+ batch_jobs = SendCalendarBatchJobSerializer(+ many=True, read_only=True, help_text="The batch runs that started inside the requested range."+ )++class HogFlowRunRequestSerializer(serializers.Serializer):variables = serializers.DictField(child=serializers.JSONField(allow_null=True, help_text="Override value for one workflow variable."),@@ -4429,6 +4498,7 @@ class HogFlowViewSet("proposal_detail","proposal_outcome","in_flight",+ "send_calendar",]scope_object_write_actions = ["create",@@ -4709,6 +4779,27 @@ class HogFlowViewSet(paginator.count = page.countreturn paginator.get_paginated_response(self.get_serializer(page.results, many=True).data)+ @validated_request(+ query_serializer=SendCalendarQuerySerializer,+ responses={200: OpenApiResponse(response=SendCalendarFlowSerializer(many=True))},+ summary="List the scheduled sends for the send calendar",+ description=(+ "Active batch and schedule workflows with an email step that is not transactional, and that have "+ "a schedule with sends to come or a batch run inside the range. Each carries only the fields a "+ "calendar card shows. Read a single workflow for its full configuration."+ ),+ )+ @action(detail=False, methods=["GET"], url_path="send_calendar", pagination_class=None, filter_backends=[])+ def send_calendar(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:+ flows = list_send_calendar_flows(+ team_id=self.team_id,+ start=request.validated_query_data["start"],+ end=request.validated_query_data["end"],+ # Service credentials are synthetic users that UserAccessControl cannot evaluate.+ user_access_control=None if is_service_auth(request) else self.user_access_control,+ )+ return Response(SendCalendarFlowSerializer(flows, many=True).data)+def safely_get_object(self, queryset):# TODO(team-workflows): Somehow implement version lookupsreturn super().safely_get_object(queryset)diff --git a/products/workflows/backend/services/hog_flow_schedules.py b/products/workflows/backend/services/hog_flow_schedules.pyindex 20e3a05e9701..17d038bb2387 100644--- a/products/workflows/backend/services/hog_flow_schedules.py+++ b/products/workflows/backend/services/hog_flow_schedules.py@@ -1,4 +1,4 @@-from collections.abc import Mapping+from collections.abc import Collection, Mappingfrom datetime import datetimefrom typing import Anyfrom uuid import UUID@@ -57,6 +57,16 @@ def list_schedules_oldest_first(*, team_id: int, hog_flow_id: UUID) -> list[Workreturn [_to_schedule(s) for s in schedules]+def list_open_schedules(*, team_id: int, hog_flow_ids: Collection[UUID]) -> list[WorkflowSchedule]:+ """The schedules of several workflows that still have sends to come, oldest first."""+ schedules = (+ HogFlowSchedule.objects.filter(team_id=team_id, hog_flow_id__in=hog_flow_ids)+ .exclude(status=HogFlowScheduleStatus.COMPLETED)+ .order_by("created_at", "id")+ )+ return [_to_schedule(s) for s in schedules]++def get_schedule(*, team_id: int, hog_flow_id: UUID, schedule_id: str) -> WorkflowSchedule:return _to_schedule(_get_schedule_row(team_id, hog_flow_id, schedule_id))diff --git a/products/workflows/backend/services/send_calendar.py b/products/workflows/backend/services/send_calendar.pynew file mode 100644index 000000000000..7ae8ccbf6794--- /dev/null+++ b/products/workflows/backend/services/send_calendar.py@@ -0,0 +1,138 @@+"""The send calendar's read: a team's active, scheduled email workflows that are not transactional, with+only the fields a calendar card shows and the runs inside the shown range."""++from collections import defaultdict+from collections.abc import Mapping+from datetime import datetime+from typing import TYPE_CHECKING, Final, cast+from uuid import UUID++from django.db import models+from django.db.models import F, Q, Value+from django.db.models.functions import Coalesce++from products.workflows.backend.facade.contracts import SendCalendarBatchJob, SendCalendarFlow, WorkflowSchedule+from products.workflows.backend.facade.enums import HogFlowBatchJobState, HogFlowScheduleStatus+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob+from products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedule+from products.workflows.backend.services.hog_flow_schedules import list_open_schedules++if TYPE_CHECKING:+ from products.access_control.backend.facade.user_access_control import UserAccessControl++# A project with more workflows on the calendar shows the most recently updated ones.+SEND_CALENDAR_FLOW_LIMIT: Final = 500+# A month grid shows at most six weeks. The cap bounds how many runs one request reads.+SEND_CALENDAR_MAX_RANGE_DAYS: Final = 92++TRANSACTIONAL_CATEGORY_TYPE: Final = "transactional"+++def _json_text(source: str, *path: str) -> models.Func:+ return models.Func(+ F(source), *(Value(key) for key in path), function="jsonb_extract_path_text", output_field=models.TextField()+ )+++def list_send_calendar_flows(+ *,+ team_id: int,+ start: datetime,+ end: datetime,+ user_access_control: "UserAccessControl | None",+) -> list[SendCalendarFlow]:+ """The workflows with an open schedule or a run in [start, end) that the reader may see. Pass None for+ `user_access_control` to skip the access filter, as a service credential does."""+ open_schedules = HogFlowSchedule.objects.filter(team_id=team_id).exclude(status=HogFlowScheduleStatus.COMPLETED)+ runs_in_range = HogFlowBatchJob.objects.filter(team_id=team_id, created_at__gte=start, created_at__lt=end)+ queryset = (+ HogFlow.objects.filter(+ team_id=team_id, status=HogFlow.State.ACTIVE, trigger__type__in=list(SCHEDULED_TRIGGER_TYPES)+ )+ .exclude(origin_product=HogFlow.OriginProduct.TRANSACTIONAL_EMAILS)+ .filter(Q(id__in=open_schedules.values("hog_flow_id")) | Q(id__in=runs_in_range.values("hog_flow_id")))+ # The card reads a few keys of the first email step and the trigger. Postgres extracts them, so the+ # full step configuration, which holds the email body, never leaves the database.+ .alias(+ _email_step=models.Func(+ F("actions"),+ models.Func(+ Value('$[*] ? (@.type == "function_email")'),+ template="%(expressions)s::jsonpath",+ output_field=models.TextField(),+ ),+ function="jsonb_path_query_first",+ output_field=models.JSONField(),+ )+ )+ .filter(_email_step__isnull=False)+ .annotate(+ _category_type=Coalesce(+ _json_text("_email_step", "config", "message_category_type"),+ Value(""),+ output_field=models.TextField(),+ ),+ _category_id=_json_text("_email_step", "config", "message_category_id"),+ _email_to=_json_text("_email_step", "config", "inputs", "email", "value", "to", "email"),+ _trigger_type=_json_text("trigger", "type"),+ _audience_type=_json_text("trigger", "filters", "audience_type"),+ _audience_properties=models.Func(+ F("trigger"),+ Value("filters"),+ Value("properties"),+ function="jsonb_extract_path",+ output_field=models.JSONField(),+ ),+ )+ .exclude(_category_type=TRANSACTIONAL_CATEGORY_TYPE)+ .select_related("created_by")+ .only("id", "team_id", "name", "origin_product", "created_by")+ .order_by("-updated_at", "-id")+ )+ if user_access_control is not None:+ queryset = user_access_control.filter_queryset_by_access_level(queryset)+ flows = list(queryset[:SEND_CALENDAR_FLOW_LIMIT])+ if not flows:+ return []+ if user_access_control is not None:+ user_access_control.preload_object_access_controls(cast("list[models.Model]", flows))++ flow_ids = [flow.id for flow in flows]+ schedules_by_flow: defaultdict[UUID, list[WorkflowSchedule]] = defaultdict(list)+ for schedule in list_open_schedules(team_id=team_id, hog_flow_ids=flow_ids):+ schedules_by_flow[schedule.hog_flow_id].append(schedule)+ runs_by_flow: defaultdict[UUID, list[SendCalendarBatchJob]] = defaultdict(list)+ for run in (+ runs_in_range.filter(hog_flow_id__in=flow_ids)+ .only("id", "hog_flow_id", "status", "created_at")+ .order_by("created_at", "id")+ ):+ runs_by_flow[run.hog_flow_id].append(+ SendCalendarBatchJob(id=run.id, status=HogFlowBatchJobState(run.status), created_at=run.created_at)+ )++ return [_to_send_calendar_flow(flow, user_access_control, schedules_by_flow, runs_by_flow) for flow in flows]+++def _to_send_calendar_flow(+ flow: HogFlow,+ user_access_control: "UserAccessControl | None",+ schedules_by_flow: Mapping[UUID, list[WorkflowSchedule]],+ runs_by_flow: Mapping[UUID, list[SendCalendarBatchJob]],+) -> SendCalendarFlow:+ audience_properties = getattr(flow, "_audience_properties", None)+ return SendCalendarFlow(+ id=flow.id,+ name=flow.name,+ origin_product=flow.origin_product,+ created_by=flow.created_by,+ user_access_level=user_access_control.get_user_access_level(flow) if user_access_control is not None else None,+ trigger_type=getattr(flow, "_trigger_type", None) or "",+ audience_properties=audience_properties if isinstance(audience_properties, list) else [],+ audience_type=getattr(flow, "_audience_type", None),+ email_to=getattr(flow, "_email_to", None) or None,+ message_category_id=getattr(flow, "_category_id", None) or None,+ schedules=tuple(schedules_by_flow.get(flow.id, [])),+ batch_jobs=tuple(runs_by_flow.get(flow.id, [])),+ )diff --git a/products/workflows/backend/test/test_hog_flow_schedule.py b/products/workflows/backend/test/test_hog_flow_schedule.pyindex 8ea26a2b3ecc..c607f7e8016f 100644--- a/products/workflows/backend/test/test_hog_flow_schedule.py+++ b/products/workflows/backend/test/test_hog_flow_schedule.py@@ -24,10 +24,8 @@ from products.workflows.backend.presentation.views.hog_flow import ()from products.workflows.backend.utils.rrule_utils import compute_next_occurrences-BATCH_TRIGGER = {- "type": "batch",- "filters": {"properties": [{"key": "$browser", "type": "person", "value": ["Chrome"], "operator": "exact"}]},-}+BATCH_AUDIENCE = [{"key": "$browser", "type": "person", "value": ["Chrome"], "operator": "exact"}]+BATCH_TRIGGER = {"type": "batch", "filters": {"properties": BATCH_AUDIENCE}}SCHEDULE_DATA = {"rrule": "FREQ=WEEKLY;INTERVAL=1;BYDAY=MO",@@ -837,3 +835,114 @@ class TestHogFlowRun(APIBaseTest):assert retried.status_code == status.HTTP_200_OKassert mock_invocation.call_count == 2+++def _email_step(category_type=None, to=None):+ config = {+ "template_id": "template-email",+ "inputs": {"email": {"value": {"to": {"email": to}, "html": "<p>Hi</p>"}}},+ }+ if category_type:+ config.update(message_category_id="category-1", message_category_type=category_type)+ return {"id": "email", "name": "email", "type": "function_email", "config": config}+++class TestSendCalendarAPI(APIBaseTest):+ RANGE_START = datetime(2030, 3, 1, tzinfo=UTC)+ RANGE_END = datetime(2030, 4, 12, tzinfo=UTC)++ def _flow(self, name, *, trigger=BATCH_TRIGGER, email=None, flow_status="active", origin_product=None):+ hog_flow = HogFlow.objects.create(+ team=self.team,+ name=name,+ status=flow_status,+ origin_product=origin_product,+ trigger=trigger,+ actions=[email] if email else [],+ )+ HogFlowSchedule.objects.create(+ team=self.team,+ hog_flow=hog_flow,+ rrule="FREQ=WEEKLY;BYDAY=MO",+ starts_at=self.RANGE_START,+ timezone="UTC",+ status="active",+ )+ return hog_flow++ def _run(self, hog_flow, created_at):+ # bulk_create skips the signal that dispatches the run to the plugin server.+ [job] = HogFlowBatchJob.objects.bulk_create(+ [HogFlowBatchJob(team=self.team, hog_flow=hog_flow, status="completed")]+ )+ HogFlowBatchJob.objects.filter(id=job.id).update(created_at=created_at)+ return str(job.id)++ def _get(self, start=None, end=None):+ return self.client.get(+ f"/api/projects/{self.team.id}/hog_flows/send_calendar/",+ {"start": (start or self.RANGE_START).isoformat(), "end": (end or self.RANGE_END).isoformat()},+ )++ @parameterized.expand(+ [+ ("marketing_broadcast", {"email": _email_step("marketing"), "origin_product": "broadcasts"}, True),+ ("uncategorized_email", {"email": _email_step()}, True),+ ("schedule_trigger", {"trigger": {"type": "schedule"}, "email": _email_step()}, True),+ ("transactional_category", {"email": _email_step("transactional")}, False),+ (+ "transactional_email_product",+ {"trigger": {"type": "batch"}, "email": _email_step(), "origin_product": "transactional_emails"},+ False,+ ),+ ("no_email_step", {}, False),+ ("draft", {"email": _email_step(), "flow_status": "draft"}, False),+ ("event_trigger", {"trigger": {"type": "event"}, "email": _email_step()}, False),+ ]+ )+ def test_lists_only_active_scheduled_email_flows_that_are_not_transactional(self, _name, flow_kwargs, listed):+ hog_flow = self._flow("Flow", **flow_kwargs)++ response = self._get()++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert [row["id"] for row in response.json()] == ([str(hog_flow.id)] if listed else [])++ def test_returns_card_fields_and_only_the_runs_inside_the_range(self):+ hog_flow = self._flow("October update", email=_email_step("marketing", to="[email protected]"))+ HogFlowSchedule.objects.create(+ team=self.team,+ hog_flow=hog_flow,+ rrule="FREQ=DAILY;COUNT=1",+ starts_at=self.RANGE_START,+ timezone="UTC",+ status="completed",+ )+ self._run(hog_flow, self.RANGE_START - timedelta(seconds=1))+ inside = self._run(hog_flow, self.RANGE_START)++ [row] = self._get().json()++ assert row["name"] == "October update"+ assert row["trigger_type"] == "batch"+ assert row["audience_properties"] == BATCH_AUDIENCE+ assert row["message_category_id"] == "category-1"+ assert row["user_access_level"] == "editor"+ assert "actions" not in row+ assert [schedule["status"] for schedule in row["schedules"]] == ["active"]+ assert [job["id"] for job in row["batch_jobs"]] == [inside]++ def test_a_flow_with_only_a_past_run_inside_the_range_is_listed(self):+ hog_flow = self._flow("Sent broadcast", email=_email_step("marketing"))+ HogFlowSchedule.objects.filter(hog_flow=hog_flow).update(status="completed")+ self._run(hog_flow, self.RANGE_START + timedelta(days=2))++ assert [row["id"] for row in self._get().json()] == [str(hog_flow.id)]+ assert self._get(end=self.RANGE_START + timedelta(days=1)).json() == []++ @parameterized.expand([("end_before_start", -1), ("range_too_long", 93)])+ def test_rejects_an_unusable_range(self, _name, days):+ response = self._get(end=self.RANGE_START + timedelta(days=days))++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "end"diff --git a/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsx b/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsxindex 02531fc20f7a..4ca56ace78d6 100644--- a/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsx+++ b/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsx@@ -9,16 +9,16 @@ import { toPaginatedResponse } from '~/mocks/handlers'import type { MessageCategoryApi } from 'products/messaging/frontend/generated/api.schemas'import type {- HogFlowBatchJobApi,- HogFlowMinimalApi,HogFlowScheduleApi,+ SendCalendarBatchJobApi,+ SendCalendarFlowApi,UserBasicApi,} from 'products/workflows/frontend/generated/api.schemas'import { SendCalendar } from './SendCalendar'import { sendCalendarLogic } from './sendCalendarLogic'import { SendCalendarSendDetails } from './SendCalendarSendDetails'-import { CalendarSend, describeRepeat, sendAudience, sendCategory } from './sendCalendarUtils'+import { CalendarSend, describeRepeat, sendAudience } from './sendCalendarUtils'const meta: Meta<typeof SendCalendar> = {title: 'Products/Workflows/Send calendar',@@ -44,19 +44,18 @@ const SAM = person(2, 'Sam')const flowId = (n: number): string => `0199e0aa-0000-7000-8000-0000000000${String(n).padStart(2, '0')}`-const category = (n: number, name: string, category_type: 'marketing' | 'transactional'): MessageCategoryApi =>+const category = (n: number, name: string): MessageCategoryApi =>({id: `0199e0aa-0000-7000-8000-0000000003${String(n).padStart(2, '0')}`,key: name.toLowerCase().replace(/\W+/g, '-'),name,- category_type,+ category_type: 'marketing',}) as MessageCategoryApi-const PRODUCT_UPDATES = category(1, 'Product updates', 'marketing')-const NEWSLETTER = category(2, 'Newsletter', 'marketing')-const ACCOUNT_NOTICES = category(3, 'Account notices', 'transactional')-const EVENT_REMINDERS = category(4, 'Event reminders', 'transactional')-const CATEGORIES = [PRODUCT_UPDATES, NEWSLETTER, ACCOUNT_NOTICES, EVENT_REMINDERS]+const PRODUCT_UPDATES = category(1, 'Product updates')+const NEWSLETTER = category(2, 'Newsletter')+const EVENT_REMINDERS = category(4, 'Event reminders')+const CATEGORIES = [PRODUCT_UPDATES, NEWSLETTER, EVENT_REMINDERS]const cohort = (id: number, name: string, count: number, is_static = false): Record<string, unknown> => ({id,@@ -97,28 +96,21 @@ const flow = (trigger: 'batch' | 'schedule',created_by: UserBasicApi,{ audience = [], to = '{{ person.properties.email }}', category }: FlowRecipients = {}-): HogFlowMinimalApi =>+): SendCalendarFlowApi =>({id: flowId(n),name,- description: '',- status: 'active',origin_product,created_by,- trigger: trigger === 'batch' ? { type: 'batch', filters: { properties: audience } } : { type: 'schedule' },- actions: [- { id: 'trigger', type: 'trigger' },- {- id: 'email',- type: 'function_email',- config: {- message_category_id: category?.id,- message_category_type: category?.category_type,- inputs: { email: { value: { to: { email: to } } } },- },- },- ],- }) as unknown as HogFlowMinimalApi+ user_access_level: 'editor',+ trigger_type: trigger,+ audience_properties: trigger === 'batch' ? audience : [],+ audience_type: null,+ email_to: trigger === 'schedule' ? to : null,+ message_category_id: category?.id ?? null,+ schedules: SCHEDULES[flowId(n)] ?? [],+ batch_jobs: BATCH_JOBS[flowId(n)] ?? [],+ }) as SendCalendarFlowApiconst schedule = (n: number,@@ -136,32 +128,11 @@ const schedule = (updated_at: starts_at,})-const job = (id: string, status: HogFlowBatchJobApi['status'], created_at: string): HogFlowBatchJobApi =>- ({ id, status, created_at }) as HogFlowBatchJobApi--const FLOWS: HogFlowMinimalApi[] = [- flow(1, 'October product update', 'broadcasts', 'batch', PRIYA, {- audience: [inCohort(21), personProperty('email', 'is_set', 'is_set')],- category: PRODUCT_UPDATES,- }),- flow(2, 'Weekly digest', null, 'batch', SAM, { audience: [inCohort(22)], category: NEWSLETTER }),- flow(3, 'Webinar reminder', 'broadcasts', 'batch', PRIYA, { audience: [inCohort(23)], category: EVENT_REMINDERS }),- flow(4, 'Product tips: dashboards', null, 'batch', SAM, {- audience: [inCohort(21), personProperty('plan', 'exact', ['free'])],- category: PRODUCT_UPDATES,- }),- flow(5, 'Partner newsletter', 'broadcasts', 'batch', PRIYA, { audience: [inCohort(24)], category: NEWSLETTER }),- flow(6, 'Customer survey', 'broadcasts', 'batch', PRIYA),- flow(7, 'Win-back: 30 days inactive', null, 'batch', SAM, {- audience: [personProperty('days_since_last_seen', 'gt', 30)],- category: PRODUCT_UPDATES,- }),- flow(8, 'Trial ending reminder', null, 'batch', SAM, { audience: [inCohort(21)], category: ACCOUNT_NOTICES }),- flow(9, 'Monthly account summary', null, 'schedule', SAM, {- to: '[email protected]',- category: ACCOUNT_NOTICES,- }),-]+const job = (id: string, status: SendCalendarBatchJobApi['status'], created_at: string): SendCalendarBatchJobApi => ({+ id,+ status,+ created_at,+})const SCHEDULES: Record<string, HogFlowScheduleApi[]> = {[flowId(1)]: [schedule(1, 'FREQ=DAILY;COUNT=1', '2026-10-20T11:00:00Z')],@@ -174,7 +145,7 @@ const SCHEDULES: Record<string, HogFlowScheduleApi[]> = {[flowId(9)]: [schedule(9, 'FREQ=MONTHLY;BYMONTHDAY=25', '2026-09-25T08:00:00Z')],}-const BATCH_JOBS: Record<string, HogFlowBatchJobApi[]> = {+const BATCH_JOBS: Record<string, SendCalendarBatchJobApi[]> = {[flowId(2)]: [job('digest-oct-13', 'completed', '2026-10-13T09:00:04Z'),job('digest-oct-6', 'completed', '2026-10-06T09:00:03Z'),@@ -185,23 +156,38 @@ const BATCH_JOBS: Record<string, HogFlowBatchJobApi[]> = {[flowId(7)]: [job('win-back-oct-8', 'failed', '2026-10-08T10:00:06Z')],}-function useCalendarMocks(flows: HogFlowMinimalApi[]): void {+const FLOWS: SendCalendarFlowApi[] = [+ flow(1, 'October product update', 'broadcasts', 'batch', PRIYA, {+ audience: [inCohort(21), personProperty('email', 'is_set', 'is_set')],+ category: PRODUCT_UPDATES,+ }),+ flow(2, 'Weekly digest', null, 'batch', SAM, { audience: [inCohort(22)], category: NEWSLETTER }),+ flow(3, 'Webinar reminder', 'broadcasts', 'batch', PRIYA, { audience: [inCohort(23)], category: EVENT_REMINDERS }),+ flow(4, 'Product tips: dashboards', null, 'batch', SAM, {+ audience: [inCohort(21), personProperty('plan', 'exact', ['free'])],+ category: PRODUCT_UPDATES,+ }),+ flow(5, 'Partner newsletter', 'broadcasts', 'batch', PRIYA, { audience: [inCohort(24)], category: NEWSLETTER }),+ flow(6, 'Customer survey', 'broadcasts', 'batch', PRIYA),+ flow(7, 'Win-back: 30 days inactive', null, 'batch', SAM, {+ audience: [personProperty('days_since_last_seen', 'gt', 30)],+ category: PRODUCT_UPDATES,+ }),+ flow(8, 'Trial ending reminder', null, 'batch', SAM, { audience: [inCohort(21)], category: PRODUCT_UPDATES }),+ flow(9, 'Monthly metrics report', null, 'schedule', SAM, { to: '[email protected]' }),+]++function useCalendarMocks(flows: SendCalendarFlowApi[]): void {useStorybookMocks({get: {- '/api/projects/:team_id/hog_flows/': (info) => {- const trigger = new URL(info.request.url).searchParams.get('trigger') ?? '{}'- const type = (JSON.parse(trigger) as { type?: string }).type- const results = flows.filter((item) => (item.trigger as { type: string }).type === type)- return [200, { count: results.length, next: null, previous: null, results }]+ // The server returns only the runs inside the requested range.+ '/api/projects/:team_id/hog_flows/send_calendar/': (info) => {+ const params = new URL(info.request.url).searchParams+ const [start, end] = [dayjs(params.get('start')), dayjs(params.get('end'))]+ const inRange = (run: SendCalendarBatchJobApi): boolean =>+ !dayjs(run.created_at).isBefore(start) && dayjs(run.created_at).isBefore(end)+ return [200, flows.map((item) => ({ ...item, batch_jobs: item.batch_jobs.filter(inRange) }))]},- '/api/projects/:team_id/hog_flows/:id/schedules/': (info) => [- 200,- SCHEDULES[info.params.id as string] ?? [],- ],- '/api/projects/:team_id/hog_flows/:id/batch_jobs/': (info) => [- 200,- BATCH_JOBS[info.params.id as string] ?? [],- ],'/api/projects/:team_id/cohorts/': toPaginatedResponse(COHORTS),'/api/projects/:team_id/cohorts/:id/': (info) => {const match = COHORTS.find((item) => String(item.id) === info.params.id)@@ -266,7 +252,7 @@ NothingScheduled.parameters = {testOptions: { waitForLoadersToDisappear: true, waitForSelector: '[data-attr=send-calendar]' },}-const detailsSend = (item: HogFlowMinimalApi): CalendarSend => {+const detailsSend = (item: SendCalendarFlowApi): CalendarSend => {const itemSchedule = SCHEDULES[item.id][0]return {key: `details-${item.id}`,@@ -281,7 +267,7 @@ const detailsSend = (item: HogFlowMinimalApi): CalendarSend => {schedule: itemSchedule,userAccessLevel: item.user_access_level ?? null,audience: sendAudience(item),- category: sendCategory(item),+ categoryId: item.message_category_id,}}diff --git a/products/workflows/frontend/SendCalendar/SendCalendar.tsx b/products/workflows/frontend/SendCalendar/SendCalendar.tsxindex bccbe801ccfb..b379002934b0 100644--- a/products/workflows/frontend/SendCalendar/SendCalendar.tsx+++ b/products/workflows/frontend/SendCalendar/SendCalendar.tsx@@ -61,6 +61,7 @@ export function SendCalendar(): JSX.Element {data-attr="send-calendar-next"/><h3 className="mb-0 ml-1 text-base font-semibold">{periodLabel}</h3>+ {scheduledFlowsLoading && scheduledFlows ? <Spinner className="ml-1" /> : null}</div><div className="flex items-center gap-2"><LemonSegmentedButton<CalendarView>@@ -88,7 +89,8 @@ export function SendCalendar(): JSX.Element {</div></div><div className="text-xs text-secondary">- Times use the project time zone ({timezone}). Drafts and event-triggered workflows do not show.{' '}+ Times use the project time zone ({timezone}). Drafts, transactional emails, and event-triggered+ workflows do not show.{' '}<span className="hidden @min-[40rem]:inline">Drag a scheduled send to another day to move it.</span></div><SendCalendarLegend />@@ -102,7 +104,8 @@ export function SendCalendar(): JSX.Element {</div>) : !scheduledFlows?.length ? (<div className="rounded border bg-surface-primary p-8 text-center text-secondary">- Nothing is scheduled yet. Active broadcasts, and scheduled workflows with an email step, show here.+ Nothing is scheduled in this period. Active broadcasts, and scheduled workflows with an email step,+ show here.</div>) : (<DndContextdiff --git a/products/workflows/frontend/SendCalendar/SendCalendarSendDetails.tsx b/products/workflows/frontend/SendCalendar/SendCalendarSendDetails.tsxindex e5c1e293f041..e5e2729d978e 100644--- a/products/workflows/frontend/SendCalendar/SendCalendarSendDetails.tsx+++ b/products/workflows/frontend/SendCalendar/SendCalendarSendDetails.tsx@@ -7,7 +7,7 @@ import { urls } from 'scenes/urls'import { SendCalendarAudience } from './SendCalendarAudience'import { sendCalendarLogic } from './sendCalendarLogic'-import { CalendarSend, CalendarSendState, SendCategory, moveBlockedReason } from './sendCalendarUtils'+import { CalendarSend, CalendarSendState, moveBlockedReason } from './sendCalendarUtils'const STATE_TAGS: Record<CalendarSendState, { label: string; type: LemonTagType }> = {planned: { label: 'Scheduled', type: 'warning' },@@ -17,17 +17,11 @@ const STATE_TAGS: Record<CalendarSendState, { label: string; type: LemonTagTypefailed: { label: 'Failed', type: 'danger' },}-const CATEGORY_TYPES: Record<NonNullable<SendCategory['type']>, { label: string; type: LemonTagType }> = {- marketing: { label: 'Marketing', type: 'highlight' },- transactional: { label: 'Transactional', type: 'default' },-}-export function SendCalendarSendDetails({ send }: { send: CalendarSend }): JSX.Element {const { messageCategoryNames, timezone } = useValues(sendCalendarLogic)const isBroadcast = send.kind === 'broadcast'const moveReason = send.state === 'planned' ? moveBlockedReason(send) : null- const categoryType = send.category.type ? CATEGORY_TYPES[send.category.type] : null- const categoryName = send.category.id ? messageCategoryNames[send.category.id] : null+ const categoryName = send.categoryId ? messageCategoryNames[send.categoryId] : nullreturn (<div className="flex w-96 max-w-[calc(100vw-2rem)] flex-col gap-3 p-3" data-attr="send-calendar-send-details">@@ -55,15 +49,8 @@ export function SendCalendarSendDetails({ send }: { send: CalendarSend }): JSX.E</dd><dt className="text-secondary">Category</dt><dd className="m-0 min-w-0">- {categoryType || categoryName ? (- <div className="flex min-w-0 items-center gap-1">- {categoryType ? (- <LemonTag size="small" type={categoryType.type}>- {categoryType.label}- </LemonTag>- ) : null}- {categoryName ? <span className="truncate">{categoryName}</span> : null}- </div>+ {categoryName ? (+ <div className="truncate">{categoryName}</div>) : (<span className="text-secondary">No category</span>)}@@ -81,11 +68,6 @@ export function SendCalendarSendDetails({ send }: { send: CalendarSend }): JSX.E</>) : null}</dl>- {send.category.type === 'transactional' && !send.audience.address ? (- <div className="text-xs text-warning">- Transactional emails go to everyone in the audience, including people who unsubscribed.- </div>- ) : null}{send.state === 'paused' ? (<div className="text-xs text-secondary">This schedule paused because its recipients changed. Open it to schedule it again.diff --git a/products/workflows/frontend/SendCalendar/sendCalendarLogic.test.ts b/products/workflows/frontend/SendCalendar/sendCalendarLogic.test.tsindex c4cca993dd8e..e47e72431ab3 100644--- a/products/workflows/frontend/SendCalendar/sendCalendarLogic.test.ts+++ b/products/workflows/frontend/SendCalendar/sendCalendarLogic.test.ts@@ -7,19 +7,17 @@ import { dayjs } from 'lib/dayjs'import { initKeaTests } from '~/test/init'import {- hogFlowsBatchJobsList,- hogFlowsList,hogFlowsSchedulesList,hogFlowsSchedulesPartialUpdate,+ hogFlowsSendCalendarRetrieve,} from 'products/workflows/frontend/generated/api'-import type { HogFlowMinimalApi, HogFlowScheduleApi } from 'products/workflows/frontend/generated/api.schemas'+import type { HogFlowScheduleApi, SendCalendarFlowApi } from 'products/workflows/frontend/generated/api.schemas'import { sendCalendarLogic } from './sendCalendarLogic'jest.mock('products/workflows/frontend/generated/api', () => ({- hogFlowsList: jest.fn(),+ hogFlowsSendCalendarRetrieve: jest.fn(),hogFlowsSchedulesList: jest.fn(),- hogFlowsBatchJobsList: jest.fn(),hogFlowsSchedulesPartialUpdate: jest.fn(),}))jest.mock('@posthog/lemon-ui', () => ({@@ -45,12 +43,13 @@ const SCHEDULE: HogFlowScheduleApi = {const FLOW = {id: 'flow-1',name: 'October product update',- status: 'active',origin_product: 'broadcasts',- trigger: { type: 'batch' },- actions: [{ type: 'function_email' }],+ trigger_type: 'batch',+ audience_properties: [],user_access_level: 'editor',-} as unknown as HogFlowMinimalApi+ schedules: [SCHEDULE],+ batch_jobs: [],+} as unknown as SendCalendarFlowApidescribe('sendCalendarLogic', () => {let logic: ReturnType<typeof sendCalendarLogic.build>@@ -67,19 +66,13 @@ describe('sendCalendarLogic', () => {beforeEach(async () => {jest.clearAllMocks()initKeaTests()- jest.mocked(hogFlowsList).mockImplementation(async (_projectId, params) => ({- count: 1,- next: null,- previous: null,- results: params?.trigger?.includes('batch') ? [FLOW] : [],- }))+ jest.mocked(hogFlowsSendCalendarRetrieve).mockResolvedValue([FLOW])jest.mocked(hogFlowsSchedulesList).mockResolvedValue([SCHEDULE])- jest.mocked(hogFlowsBatchJobsList).mockResolvedValue([])logic = sendCalendarLogic()logic.mount()logic.actions.setView('week')logic.actions.setAnchor(SEND_AT.format('YYYY-MM-DD'))- await expectLogic(logic).toDispatchActions(['loadScheduledFlowsSuccess'])+ await expectLogic(logic).toDispatchActions(['loadScheduledFlowsSuccess']).toFinishAllListeners()})afterEach(() => logic.unmount())@@ -155,6 +148,30 @@ describe('sendCalendarLogic', () => {)})+ it('loads the runs of the new range when the person moves to another week', async () => {+ await expectLogic(logic, () => logic.actions.goForward()).toDispatchActions(['loadScheduledFlowsSuccess'])++ expect(hogFlowsSendCalendarRetrieve).toHaveBeenLastCalledWith(expect.any(String), {+ start: logic.values.range.start.toISOString(),+ end: logic.values.range.end.toISOString(),+ })+ })++ it('ignores a failed request for a week the person already left', async () => {+ let rejectFirst: (error: Error) => void = () => {}+ jest.mocked(hogFlowsSendCalendarRetrieve)+ .mockImplementationOnce(() => new Promise((_resolve, reject) => (rejectFirst = reject)))+ .mockResolvedValueOnce([FLOW])++ logic.actions.goForward()+ await expectLogic(logic, () => logic.actions.goForward()).toDispatchActions(['loadScheduledFlowsSuccess'])+ rejectFirst(new Error('Network error'))+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.loadFailed).toBe(false)+ expect(logic.values.scheduledFlows).toEqual([FLOW])+ })+it('puts the send back when the server rejects the move', async () => {jest.mocked(hogFlowsSchedulesPartialUpdate).mockRejectedValue({detail: 'Schedule must have at least one future occurrence.',diff --git a/products/workflows/frontend/SendCalendar/sendCalendarLogic.ts b/products/workflows/frontend/SendCalendar/sendCalendarLogic.tsindex b88b15ff266a..2201fae7a9b8 100644--- a/products/workflows/frontend/SendCalendar/sendCalendarLogic.ts+++ b/products/workflows/frontend/SendCalendar/sendCalendarLogic.ts@@ -1,5 +1,6 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'@@ -13,16 +14,14 @@ import { cohortsModel } from '~/models/cohortsModel'import type { CohortType } from '~/types'import {- hogFlowsBatchJobsList,- hogFlowsList,hogFlowsSchedulesList,hogFlowsSchedulesPartialUpdate,+ hogFlowsSendCalendarRetrieve,} from 'products/workflows/frontend/generated/api'-import type { HogFlowScheduleApi } from 'products/workflows/frontend/generated/api.schemas'+import type { HogFlowScheduleApi, SendCalendarFlowApi } from 'products/workflows/frontend/generated/api.schemas'import { newBroadcastAgentLogic } from '../Broadcasts/newBroadcastAgentLogic'import { MessageCategory, optOutCategoriesLogic } from '../OptOuts/optOutCategoriesLogic'-import { SCHEDULED_TRIGGER_TYPES } from '../Workflows/hogflows/steps/types'import { newWorkflowLogic } from '../Workflows/newWorkflowLogic'import {CalendarRange,@@ -30,14 +29,12 @@ import {CalendarSendKind,CalendarTypeFilter,CalendarView,- ScheduledEmailFlow,calendarDays,calendarRange,calendarSendsForFlow,describeRepeat,dropTarget,groupSendsByDay,- isScheduledEmailFlow,matchesTypeFilter,moveBlockedReason,movedScheduleFields,@@ -46,10 +43,6 @@ import {shiftAnchor,} from './sendCalendarUtils'-/** The list endpoint's page limit. A project with more scheduled flows shows the first page. */-const FLOWS_LIMIT = 500-/** Each flow needs its own schedule and run requests, so flows load in small groups. */-const FLOWS_PER_GROUP = 8const SCHEDULE_CHANGED = 'Its schedule changed after the calendar loaded. Check the reloaded calendar and try again.'/** False when the schedule changed after the calendar loaded it. A move saves the whole rule, so it would undo that change. */@@ -79,7 +72,7 @@ export interface sendCalendarLogicValues {periodLabel: stringrange: CalendarRangesavingScheduleIds: Record<string, boolean>- scheduledFlows: ScheduledEmailFlow[] | null+ scheduledFlows: SendCalendarFlowApi[] | nullscheduledFlowsLoading: booleansends: CalendarSend[]sendsByDay: Record<string, CalendarSend[]>@@ -117,7 +110,7 @@ export interface sendCalendarLogicActions {goToToday: () => {value: true}- loadScheduledFlows: () => any+ loadScheduledFlows: (_: void) => voidloadScheduledFlowsFailure: (error: string,errorObject?: any@@ -126,11 +119,11 @@ export interface sendCalendarLogicActions {errorObject?: any}loadScheduledFlowsSuccess: (- scheduledFlows: ScheduledEmailFlow[],- payload?: any+ scheduledFlows: SendCalendarFlowApi[],+ payload?: void) => {- scheduledFlows: ScheduledEmailFlow[]- payload?: any+ scheduledFlows: SendCalendarFlowApi[]+ payload?: void}moveSend: (send: CalendarSend,@@ -192,7 +185,7 @@ export interface sendCalendarLogicMeta {range: (days: string[], timezone: string) => CalendarRangeperiodLabel: (view: CalendarView, anchorDate: string, days: string[]) => stringsends: (- scheduledFlows: ScheduledEmailFlow[] | null,+ scheduledFlows: SendCalendarFlowApi[] | null,range: CalendarRange,typeFilter: CalendarTypeFilter) => CalendarSend[]@@ -253,36 +246,23 @@ export const sendCalendarLogic = kea<sendCalendarLogicType>([}),loaders(({ values }) => ({scheduledFlows: [- null as ScheduledEmailFlow[] | null,+ null as SendCalendarFlowApi[] | null,{- loadScheduledFlows: async () => {- const projectId = String(values.currentProjectId)- const pages = await Promise.all(- SCHEDULED_TRIGGER_TYPES.map((type) =>- hogFlowsList(projectId, {- status: 'active',- trigger: JSON.stringify({ type }),- limit: FLOWS_LIMIT,- })- )- )- const flows = pages.flatMap((page) => page.results).filter(isScheduledEmailFlow)- const loaded: ScheduledEmailFlow[] = []- for (let index = 0; index < flows.length; index += FLOWS_PER_GROUP) {- const group = await Promise.all(- flows.slice(index, index + FLOWS_PER_GROUP).map(async (flow) => {- // A schedule trigger runs without a batch job, so only batch triggers have runs to show.- const isBatch = (flow.trigger as { type?: string } | null)?.type === 'batch'- const [schedules, batchJobs] = await Promise.all([- hogFlowsSchedulesList(projectId, flow.id),- isBatch ? hogFlowsBatchJobsList(projectId, flow.id) : Promise.resolve([]),- ])- return { flow, schedules, batchJobs }- })- )- loaded.push(...group)+ loadScheduledFlows: async (_: void, breakpoint) => {+ // The server returns only the runs inside the shown range, so each new range loads again.+ let flows: SendCalendarFlowApi[]+ try {+ flows = await hogFlowsSendCalendarRetrieve(String(values.currentProjectId), {+ start: values.range.start.toISOString(),+ end: values.range.end.toISOString(),+ })+ } catch (error) {+ // A failed request for a period the person already left must not show the error.+ breakpoint()+ throw error}- return loaded+ breakpoint()+ return flows},},],@@ -307,10 +287,10 @@ export const sendCalendarLogic = kea<sendCalendarLogicType>([],scheduledFlows: {scheduleChanged: (state, { flowId, schedule }) =>- state?.map((item) =>- item.flow.id === flowId- ? { ...item, schedules: item.schedules.map((s) => (s.id === schedule.id ? schedule : s)) }- : item+ state?.map((flow) =>+ flow.id === flowId+ ? { ...flow, schedules: flow.schedules.map((s) => (s.id === schedule.id ? schedule : s)) }+ : flow) ?? state,},savingScheduleIds: [@@ -337,14 +317,14 @@ export const sendCalendarLogic = kea<sendCalendarLogicType>([sends: [(s) => [s.scheduledFlows, s.range, s.typeFilter],(- scheduledFlows: ScheduledEmailFlow[] | null,+ scheduledFlows: SendCalendarFlowApi[] | null,range: CalendarRange,typeFilter: CalendarTypeFilter): CalendarSend[] => {const now = dayjs()return (scheduledFlows ?? [])- .filter((item) => matchesTypeFilter(item.flow, typeFilter))- .flatMap((item) => calendarSendsForFlow(item, range, now))+ .filter((flow) => matchesTypeFilter(flow, typeFilter))+ .flatMap((flow) => calendarSendsForFlow(flow, range, now))},],sendsByDay: [@@ -358,7 +338,7 @@ export const sendCalendarLogic = kea<sendCalendarLogicType>([Object.fromEntries(categories.map((category) => [category.id, category.name])),],}),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({moveSend: ({ send, day }) => {const target = dropTarget(send, day, values.timezone, dayjs())if (!target) {@@ -464,24 +444,25 @@ export const sendCalendarLogic = kea<sendCalendarLogicType>([goBackward: () => actions.setAnchor(shiftAnchor(values.view, values.anchorDate, -1)),loadScheduledFlowsSuccess: ({ scheduledFlows }) => {// The shared cohort list can miss a cohort that an audience uses, so ask for the missing ones by id.- const cohortIds = [...new Set(scheduledFlows.flatMap(({ flow }) => sendAudience(flow).cohortIds))]+ const cohortIds = [...new Set(scheduledFlows.flatMap((flow) => sendAudience(flow).cohortIds))].filter(+ (id) => !values.cohortsById[id]+ )if (cohortIds.length) {actions.loadCohortsByIds({ ids: cohortIds })}- // pinned: analytics event name- posthog.capture('send calendar viewed', {- view: values.view,- scheduled_flows: scheduledFlows?.length ?? 0,- sends_in_range: values.sends.length,- })+ // Report the first load and each change of view, after the sends of that view loaded.+ if (cache.reportView) {+ // pinned: analytics event name+ posthog.capture('send calendar viewed', {+ view: values.view,+ scheduled_flows: scheduledFlows.length,+ sends_in_range: values.sends.length,+ })+ cache.reportView = false+ }},- setView: ({ view }) => {- // pinned: analytics event name- posthog.capture('send calendar viewed', {- view,- scheduled_flows: values.scheduledFlows?.length ?? 0,- sends_in_range: values.sends.length,- })+ setView: () => {+ cache.reportView = true},startNewSend: ({ kind, day }) => {// pinned: analytics event name@@ -504,7 +485,15 @@ export const sendCalendarLogic = kea<sendCalendarLogicType>([})},})),- afterMount(({ actions }) => {+ subscriptions(({ actions }) => ({+ range: (range: CalendarRange, previous: CalendarRange | undefined) => {+ if (previous && !(range.start.isSame(previous.start) && range.end.isSame(previous.end))) {+ actions.loadScheduledFlows()+ }+ },+ })),+ afterMount(({ actions, cache }) => {+ cache.reportView = trueactions.loadScheduledFlows()}),])diff --git a/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.ts b/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.tsindex b98b297d4059..4c7d5a325ce4 100644--- a/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.ts+++ b/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.ts@@ -1,9 +1,9 @@import { dayjs } from 'lib/dayjs'import type {- HogFlowBatchJobApi,- HogFlowMinimalApi,HogFlowScheduleApi,+ SendCalendarBatchJobApi,+ SendCalendarFlowApi,} from 'products/workflows/frontend/generated/api.schemas'import {@@ -13,7 +13,6 @@ import {calendarSendsForFlow,describeRepeat,dropTarget,- isScheduledEmailFlow,moveBlockedReason,movedScheduleFields,periodLabel,@@ -21,15 +20,6 @@ import {sendAudience,} from './sendCalendarUtils'-const EMAIL_STEP = { type: 'function_email' }--const flow = (- trigger: string,- actions: unknown[] = [EMAIL_STEP],- status: string = 'active'-): Pick<HogFlowMinimalApi, 'status' | 'trigger' | 'actions'> =>- ({ status, trigger: { type: trigger }, actions }) as Pick<HogFlowMinimalApi, 'status' | 'trigger' | 'actions'>-const schedule = (rrule: string,starts_at: string,@@ -46,22 +36,15 @@ const schedule = (updated_at: starts_at,})-const job = (id: string, status: HogFlowBatchJobApi['status'], created_at: string): HogFlowBatchJobApi =>- ({ id, status, hog_flow: 'flow', created_at }) as HogFlowBatchJobApi+const job = (id: string, status: SendCalendarBatchJobApi['status'], created_at: string): SendCalendarBatchJobApi => ({+ id,+ status,+ created_at,+})const LONDON_OCT_19_TO_NOV_1 = calendarRange(['2026-10-19', '2026-11-01'], 'Europe/London')describe('sendCalendarUtils', () => {- it.each([- ['a batch workflow with an email step', flow('batch'), true],- ['a scheduled workflow with an email step', flow('schedule'), true],- ['an event-triggered workflow', flow('event'), false],- ['a batch workflow without an email step', flow('batch', [{ type: 'delay' }]), false],- ['a draft', flow('batch', [EMAIL_STEP], 'draft'), false],- ])('decides whether to show %s', (_, value, expected) => {- expect(isScheduledEmailFlow(value)).toBe(expected)- })-const COHORT_FILTER = { key: 'id', type: 'cohort', value: 21 }const EMAIL_IS_SET = { key: 'email', type: 'person', operator: 'is_set', value: 'is_set' }const COHORT_EXCLUSION = { key: 'id', type: 'cohort', operator: 'not_in', value: 22 }@@ -69,35 +52,28 @@ describe('sendCalendarUtils', () => {it.each([['a broadcast that filters on a cohort and a person property',- { type: 'batch', filters: { properties: [COHORT_FILTER, EMAIL_IS_SET] } },- [EMAIL_STEP],+ { trigger_type: 'batch', audience_properties: [COHORT_FILTER, EMAIL_IS_SET] },{ cohortIds: [21], filters: [EMAIL_IS_SET], accounts: false, address: null },],['a broadcast that leaves out a cohort',- { type: 'batch', filters: { properties: [COHORT_FILTER, COHORT_EXCLUSION] } },- [EMAIL_STEP],+ { trigger_type: 'batch', audience_properties: [COHORT_FILTER, COHORT_EXCLUSION] },{ cohortIds: [21], filters: [COHORT_EXCLUSION], accounts: false, address: null },],['a batch workflow that runs for each account',- { type: 'batch', filters: { properties: [], audience_type: 'accounts' } },- [EMAIL_STEP],+ { trigger_type: 'batch', audience_properties: [], audience_type: 'accounts' },{ cohortIds: [], filters: [], accounts: true, address: null },],['a scheduled workflow, which sends to the To address of its email',- { type: 'schedule' },- [- {- type: 'function_email',- config: { inputs: { email: { value: { to: { email: '[email protected]' } } } } },- },- ],+ { trigger_type: 'schedule', audience_properties: [], email_to: '[email protected]' },{ cohortIds: [], filters: [], accounts: false, address: '[email protected]' },],- ])('reads who %s sends to', (_, trigger, actions, expected) => {- expect(sendAudience({ trigger, actions } as Pick<HogFlowMinimalApi, 'trigger' | 'actions'>)).toEqual(expected)+ ])('reads who %s sends to', (_, value, expected) => {+ expect(+ sendAudience({ audience_type: null, email_to: null, ...value } as unknown as SendCalendarFlowApi)+ ).toEqual(expected)})it.each([@@ -123,18 +99,22 @@ describe('sendCalendarUtils', () => {it('takes future sends from schedules and past sends from batch jobs', () => {const sends = calendarSendsForFlow({- flow: { id: 'flow', name: 'Weekly digest', origin_product: null } as HogFlowMinimalApi,+ id: 'flow',+ name: 'Weekly digest',+ origin_product: null,+ trigger_type: 'batch',+ audience_properties: [],schedules: [schedule('FREQ=WEEKLY;BYDAY=TU', '2026-09-01T08:00:00Z'),schedule('FREQ=WEEKLY;BYDAY=FR', '2026-09-04T15:00:00Z', 'paused'),schedule('FREQ=DAILY;COUNT=1', '2026-10-22T10:00:00Z', 'completed'),],- batchJobs: [+ batch_jobs: [job('sent', 'completed', '2026-10-20T08:00:05Z'),job('failed', 'failed', '2026-10-19T09:00:00Z'),job('outside', 'completed', '2026-10-05T08:00:00Z'),],- },+ } as unknown as SendCalendarFlowApi,LONDON_OCT_19_TO_NOV_1,dayjs('2026-10-21T12:00:00Z'))diff --git a/products/workflows/frontend/SendCalendar/sendCalendarUtils.ts b/products/workflows/frontend/SendCalendar/sendCalendarUtils.tsindex 4614c1cebd07..7be135141650 100644--- a/products/workflows/frontend/SendCalendar/sendCalendarUtils.ts+++ b/products/workflows/frontend/SendCalendar/sendCalendarUtils.ts@@ -5,9 +5,9 @@ import { dayjs } from 'lib/dayjs'import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'import type {- HogFlowBatchJobApi,- HogFlowMinimalApi,HogFlowScheduleApi,+ SendCalendarBatchJobApi,+ SendCalendarFlowApi,UserBasicApi,} from 'products/workflows/frontend/generated/api.schemas'@@ -21,20 +21,12 @@ import {scheduleToText,stateToRRule,} from '../Workflows/hogflows/steps/components/rrule-helpers'-import { SCHEDULED_TRIGGER_TYPES } from '../Workflows/hogflows/steps/types'-import type { HogFlowAction } from '../Workflows/hogflows/types'export type CalendarView = 'month' | 'week'export type CalendarTypeFilter = 'all' | 'broadcasts' | 'workflows'export type CalendarSendKind = 'broadcast' | 'workflow'export type CalendarSendState = 'planned' | 'paused' | 'sending' | 'sent' | 'failed'-export interface ScheduledEmailFlow {- flow: HogFlowMinimalApi- schedules: HogFlowScheduleApi[]- batchJobs: HogFlowBatchJobApi[]-}-export interface CalendarSend {key: stringflowId: string@@ -50,7 +42,8 @@ export interface CalendarSend {schedule: HogFlowScheduleApi | nulluserAccessLevel: string | nullaudience: SendAudience- category: SendCategory+ /** The message category of the email, which decides who can opt out of it. */+ categoryId: string | null}/** Who the sends of a flow go to. */@@ -65,12 +58,6 @@ export interface SendAudience {address: string | null}-/** The message category of the email, which decides if people who opted out still get it. */-export interface SendCategory {- id: string | null- type: 'marketing' | 'transactional' | null-}-/** From the start of the first day to the start of the day after the last day, in the project time zone. */export interface CalendarRange {start: dayjs.Dayjs@@ -81,46 +68,26 @@ export interface CalendarRange {// Stop at a number that the grid can still show.const MAX_SENDS_PER_SCHEDULE = 200-type EmailAction = Extract<HogFlowAction, { type: 'function_email' }>--function emailAction(flow: Pick<HogFlowMinimalApi, 'actions'>): EmailAction | null {- const actions = Array.isArray(flow.actions) ? (flow.actions as (HogFlowAction | null)[]) : []- return actions.find((action): action is EmailAction => action?.type === 'function_email') ?? null-}--export function isScheduledEmailFlow(flow: Pick<HogFlowMinimalApi, 'status' | 'trigger' | 'actions'>): boolean {- const triggerType = (flow.trigger as { type?: string } | null)?.type ?? ''- return flow.status === 'active' && SCHEDULED_TRIGGER_TYPES.includes(triggerType) && !!emailAction(flow)-}--export function sendAudience(flow: Pick<HogFlowMinimalApi, 'trigger' | 'actions'>): SendAudience {- const trigger = flow.trigger as {- type?: string- filters?: { properties?: AnyPropertyFilter[]; audience_type?: string }- } | null- if (trigger?.type !== 'batch') {- const email = emailAction(flow)?.config.inputs.email?.value as { to?: { email?: string } } | undefined- return { cohortIds: [], filters: [], accounts: false, address: email?.to?.email || null }+export function sendAudience(+ flow: Pick<SendCalendarFlowApi, 'trigger_type' | 'audience_properties' | 'audience_type' | 'email_to'>+): SendAudience {+ if (flow.trigger_type !== 'batch') {+ return { cohortIds: [], filters: [], accounts: false, address: flow.email_to || null }}- const properties = trigger.filters?.properties ?? []+ const properties = flow.audience_properties as unknown as AnyPropertyFilter[]// An excluded cohort is not a recipient list, so it stays a filter with its operator.const isCohortInclusion = (filter: AnyPropertyFilter): boolean =>filter.type === PropertyFilterType.Cohort && filter.operator !== PropertyOperator.NotInreturn {cohortIds: audienceCohortIds(properties.filter(isCohortInclusion)),filters: properties.filter((filter) => !isCohortInclusion(filter)),- accounts: trigger.filters?.audience_type === 'accounts',+ accounts: flow.audience_type === 'accounts',address: null,}}-export function sendCategory(flow: Pick<HogFlowMinimalApi, 'actions'>): SendCategory {- const config = emailAction(flow)?.config- return { id: config?.message_category_id ?? null, type: config?.message_category_type ?? null }-}-export function matchesTypeFilter(- flow: Pick<HogFlowMinimalApi, 'origin_product'>,+ flow: Pick<SendCalendarFlowApi, 'origin_product'>,filter: CalendarTypeFilter): boolean {if (filter === 'all') {@@ -187,7 +154,7 @@ export function scheduleSendTimes(}export function calendarSendsForFlow(- { flow, schedules, batchJobs }: ScheduledEmailFlow,+ flow: SendCalendarFlowApi,range: CalendarRange,now: dayjs.Dayjs): CalendarSend[] {@@ -198,14 +165,14 @@ export function calendarSendsForFlow(createdBy: flow.created_by ?? null,userAccessLevel: flow.user_access_level ?? null,audience: sendAudience(flow),- category: sendCategory(flow),+ categoryId: flow.message_category_id,}const sends: CalendarSend[] = []// A schedule shows only the sends still to come. An occurrence in the past is not proof that a send// went out, so past sends come from the batch jobs instead.const future: CalendarRange = { start: now.isAfter(range.start) ? now : range.start, end: range.end }if (future.start.isBefore(future.end)) {- for (const schedule of schedules) {+ for (const schedule of flow.schedules) {if (schedule.status === 'completed') {continue}@@ -224,7 +191,7 @@ export function calendarSendsForFlow(}}}- for (const job of batchJobs) {+ for (const job of flow.batch_jobs) {const at = dayjs(job.created_at)if (at.isBefore(range.start) || !at.isBefore(range.end)) {continue@@ -242,7 +209,7 @@ export function calendarSendsForFlow(return sends}-function batchJobState(status: HogFlowBatchJobApi['status']): CalendarSendState {+function batchJobState(status: SendCalendarBatchJobApi['status']): CalendarSendState {if (status === 'completed') {return 'sent'}diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 5cc707b7db04..61e5674c192d 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -2054,6 +2054,70 @@ export interface TeamEmailReputationResponseApi {readonly sending_allowance: EmailSendingAllowanceApi | null}+export type SendCalendarFlowApiAudiencePropertiesItem = { [key: string]: unknown }++export interface SendCalendarBatchJobApi {+ /** ID of the batch run. */+ readonly id: string+ /** Status of the batch run.+ *+ * * `waiting` - Waiting+ * * `queued` - Queued+ * * `active` - Active+ * * `completed` - Completed+ * * `cancelled` - Cancelled+ * * `failed` - Failed */+ readonly status: HogFlowBatchJobStateEnumApi+ /** When the batch run started. */+ readonly created_at: string+}++export interface SendCalendarFlowApi {+ /** ID of the workflow. */+ readonly id: string+ /**+ * Name of the workflow.+ * @nullable+ */+ readonly name: string | null+ /** The product surface that owns the workflow, such as broadcasts. Null for a plain workflow.+ *+ * * `loops` - Loops+ * * `broadcasts` - Broadcasts+ * * `transactional_emails` - Transactional emails */+ readonly origin_product: HogFlowOriginProductEnumApi | null+ /** User who created the workflow. */+ readonly created_by: UserBasicApi | null+ /**+ * The reader's access level on the workflow.+ * @nullable+ */+ readonly user_access_level: string | null+ /** The trigger type: batch or schedule. */+ readonly trigger_type: string+ /** The property filters of a batch trigger's audience. Empty for a schedule trigger. */+ readonly audience_properties: readonly SendCalendarFlowApiAudiencePropertiesItem[]+ /**+ * persons or accounts for a batch trigger's audience. Null when the trigger does not set it.+ * @nullable+ */+ readonly audience_type: string | null+ /**+ * The 'To' address of the first email step. A schedule trigger has no audience, so it sends here.+ * @nullable+ */+ readonly email_to: string | null+ /**+ * ID of the message category of the first email step.+ * @nullable+ */+ readonly message_category_id: string | null+ /** The schedules that still have sends to come. */+ readonly schedules: readonly HogFlowScheduleApi[]+ /** The batch runs that started inside the requested range. */+ readonly batch_jobs: readonly SendCalendarBatchJobApi[]+}+/*** Property filters to apply*/@@ -2900,3 +2964,14 @@ export type HogFlowsReputationRetrieveParams = {*/search?: string}++export type HogFlowsSendCalendarRetrieveParams = {+ /**+ * End of the shown range, exclusive, as an ISO 8601 datetime. At most 92 days after start.+ */+ end: string+ /**+ * Start of the shown range, inclusive, as an ISO 8601 datetime.+ */+ start: string+}diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.tsindex 1f9fb598fd3c..cb379bad9085 100644--- a/products/workflows/frontend/generated/api.ts+++ b/products/workflows/frontend/generated/api.ts@@ -50,6 +50,7 @@ import type {HogFlowsProposalsListParams,HogFlowsReputationRetrieveParams,HogFlowsRevisionsListParams,+ HogFlowsSendCalendarRetrieveParams,HogInvocationCancelRequestApi,HogInvocationCancelResponseApi,HogInvocationRerunRequestApi,@@ -69,6 +70,7 @@ import type {PatchedHogFlowUpdateApi,PeopleImportApi,PeopleImportCreateApi,+ SendCalendarFlowApi,TeamEmailReputationResponseApi,WorkflowEmailPauseStatusApi,WorkflowProposalApi,@@ -1320,6 +1322,37 @@ export const hogFlowsReputationRetrieve = async (})}+export const getHogFlowsSendCalendarRetrieveUrl = (projectId: string, params: HogFlowsSendCalendarRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/hog_flows/send_calendar/?${stringifiedParams}`+ : `/api/projects/${projectId}/hog_flows/send_calendar/`+}++/**+ * Active batch and schedule workflows with an email step that is not transactional, and that have a schedule with sends to come or a batch run inside the range. Each carries only the fields a calendar card shows. Read a single workflow for its full configuration.+ * @summary List the scheduled sends for the send calendar+ */+export const hogFlowsSendCalendarRetrieve = async (+ projectId: string,+ params: HogFlowsSendCalendarRetrieveParams,+ options?: RequestInit+): Promise<SendCalendarFlowApi[]> => {+ return apiMutator<SendCalendarFlowApi[]>(getHogFlowsSendCalendarRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getHogFlowsUserBlastRadiusCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/hog_flows/user_blast_radius/`}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6cd49c4bd80b..c9d002476ed8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -102046,6 +102046,70 @@ export namespace Schemas {queries: string[];}+ export interface SendCalendarBatchJob {+ /** ID of the batch run. */+ readonly id: string;+ /** Status of the batch run.+ *+ * * `waiting` - Waiting+ * * `queued` - Queued+ * * `active` - Active+ * * `completed` - Completed+ * * `cancelled` - Cancelled+ * * `failed` - Failed */+ readonly status: HogFlowBatchJobStateEnum;+ /** When the batch run started. */+ readonly created_at: string;+ }++ export type SendCalendarFlowAudiencePropertiesItem = { [key: string]: unknown };++ export interface SendCalendarFlow {+ /** ID of the workflow. */+ readonly id: string;+ /**+ * Name of the workflow.+ * @nullable+ */+ readonly name: string | null;+ /** The product surface that owns the workflow, such as broadcasts. Null for a plain workflow.+ *+ * * `loops` - Loops+ * * `broadcasts` - Broadcasts+ * * `transactional_emails` - Transactional emails */+ readonly origin_product: HogFlowOriginProductEnum | null;+ /** User who created the workflow. */+ readonly created_by: UserBasic | null;+ /**+ * The reader's access level on the workflow.+ * @nullable+ */+ readonly user_access_level: string | null;+ /** The trigger type: batch or schedule. */+ readonly trigger_type: string;+ /** The property filters of a batch trigger's audience. Empty for a schedule trigger. */+ readonly audience_properties: readonly SendCalendarFlowAudiencePropertiesItem[];+ /**+ * persons or accounts for a batch trigger's audience. Null when the trigger does not set it.+ * @nullable+ */+ readonly audience_type: string | null;+ /**+ * The 'To' address of the first email step. A schedule trigger has no audience, so it sends here.+ * @nullable+ */+ readonly email_to: string | null;+ /**+ * ID of the message category of the first email step.+ * @nullable+ */+ readonly message_category_id: string | null;+ /** The schedules that still have sends to come. */+ readonly schedules: readonly HogFlowSchedule[];+ /** The batch runs that started inside the requested range. */+ readonly batch_jobs: readonly SendCalendarBatchJob[];+ }+export interface SendCommentToSlack {/** ID of the Slack integration (kind='slack') whose bot posts the thread. */integration_id: number;@@ -126849,6 +126913,17 @@ export namespace Schemas {search?: string;};+ export type HogFlowsSendCalendarRetrieveParams = {+ /**+ * End of the shown range, exclusive, as an ISO 8601 datetime. At most 92 days after start.+ */+ end: string;+ /**+ * Start of the shown range, inclusive, as an ISO 8601 datetime.+ */+ start: string;+ };+export type HogFunctionTemplatesListParams = {/*** Number of results to return per page.