: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
feat(workflows): add a send calendar to view and move scheduled emails (#118437)
Meikel Ratzc330811815b7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6db341f17541..f06ce3b3b7fa 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8206,6 +8206,26 @@ snapshots:hash: v1.k794b7964.5cf1b5557a39a1c56f57778a8f93fae97a2369d6a0d9debeaf9a32888867e76f.YVfscq34vkHHNa-V3zETBCtGV5g2HUXGoUCZTtdwwTgproducts-workflows-reputation--shared-sending-domain--light:hash: v1.k794b7964.d2f19057ecd63916468e49499852f4b90854405ad3d4f8bbb04e766a6180a0bf.SIZeFe7wNudMSeL2euN2W8tSq5ATz9vp6KGnFbgeUmw+ products-workflows-send-calendar--busy-week--dark:+ hash: v1.k794b7964.39afa422487dc061f94a4ec6398437e7eec01d3d2af64abc161bc52f9190ea54.-lZbR8UwepYyXHdTtBKYA6fO_oE3GnJxWofpm3LfjsY+ products-workflows-send-calendar--busy-week--light:+ hash: v1.k794b7964.de536a827450a4177db2b69dab61584db5f9d76a88f7f13e0de28fb09a03c490.Mc2K6bqJx4Fww7yaS7gS5BpFaJ5YktzZdL-EUXUBUCw+ products-workflows-send-calendar--month-view--dark:+ hash: v1.k794b7964.cecd17eafa4403fc327696ca01e18d89e9ab20055147174bc1cf4d3b9e01e542.OziIUxzKe2NSoO_dsw75-h9W1G2-JXARS9Y-vWCnCL4+ products-workflows-send-calendar--month-view--light:+ hash: v1.k794b7964.ec1c298f638778f07b234cc8ccbab29e07518762aa2df6964df155164a03fb2d.EF5lJojKTeDEG9EulMEK3sHHvxvxfkv_kj-D7uZV4Qo+ products-workflows-send-calendar--narrow-width--dark:+ hash: v1.k794b7964.69ec31afe8d91cde95130a01137235085229d7eefb3982e46efae482e2ca5541.m6sFedELuEDLHQdH3I9Vii81Jns-2-PhbyCFi1S_7oQ+ products-workflows-send-calendar--narrow-width--light:+ hash: v1.k794b7964.f81d64ad25f9dd5c324de05f3486e4670e231384b6ef9f1218b71264a56f6fc9.qiSArgztEf8Bgy-CigvE-2Wrn8D6AyZ7QMDNh5of-j8+ products-workflows-send-calendar--nothing-scheduled--dark:+ hash: v1.k794b7964.e49af2419c9e74175a1cabbfe01f44acf29c8fea8bff95eb425e00b7163413fe.Ah8ueSoHSilObSRoM-KsXH_RKl5xqKpapInbI6zD3OI+ products-workflows-send-calendar--nothing-scheduled--light:+ hash: v1.k794b7964.7b96f8bc40e1099363decb68e74dc99f0c94770e357faf6ecf2002f1b6ca748f.MbSByJrs9lR7-T6XxqCAhD1MyjpuO74VJ5jYW8j7C-4+ products-workflows-send-calendar--send-details--dark:+ hash: v1.k794b7964.5ec26f2be0e3ccc0c66d4c76a053b2297f161987d8b07789d3812e276310f4bb.gUaDqSUhaUWckeDBW5u172smdN7GTZipTrfrolPQhnw+ products-workflows-send-calendar--send-details--light:+ hash: v1.k794b7964.4baf13346e5c827c9c8eeeafa125b5ee89b026a1e664dcbdc1892b67f8582b6a.dOFZmzdzpwwtnnC3MHbRTRI55VeKeBvxvYo0Istk6YMproducts-workflows-steps-customer-task-reference-input--account--dark:hash: v1.k794b7964.884dda5b1415d9a041c053804964a19d7a9adb2b28edc1797a9cbed8f5dc6782.YXjfbjz9Kxh9TbLWc8Dai7nySVQz9UByZVxWqopauE8products-workflows-steps-customer-task-reference-input--account--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 14319940a753..607914afca95 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -643,6 +643,7 @@ export const FEATURE_FLAGS = {WORKFLOWS_LINEAR_VIEW: 'workflows-linear-view', // owner: #team-workflowsWORKFLOWS_OVERVIEW_TAB: 'workflows-overview-tab', // owner: @dmarchuk #team-workflows, experimental Overview tab on a workflowWORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflows+ WORKFLOWS_SEND_CALENDAR: 'workflows-send-calendar', // owner: @meikelmosby #team-workflows, calendar of scheduled email sends in Broadcasts and WorkflowsWORKFLOWS_TRANSACTIONAL_EMAIL_API: 'workflows-transactional-email-api', // owner: @mayteio #team-workflowsWORKFLOWS_TRIGGER_VOLUME_ESTIMATE: 'workflows-trigger-volume-estimate', // owner: @mayteio #team-workflowsXAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-featuresdiff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex ef920c95fcc3..38f8d1ed0b69 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -382,6 +382,7 @@ export const productRoutes: Record<string, [string, string]> = {'/broadcasts/suppression': ['Broadcasts', 'broadcasts'],'/broadcasts/reputation': ['Broadcasts', 'broadcasts'],'/broadcasts/settings': ['Broadcasts', 'broadcasts'],+ '/broadcasts/calendar': ['Broadcasts', 'broadcasts'],'/broadcasts/new': ['Broadcast', 'broadcast'],'/broadcasts/:id': ['Broadcast', 'broadcast'],}@@ -1977,7 +1978,7 @@ export const productUrls = {workflowsLibraryTemplate: (id?: string): string => `/workflows/library/templates/${id}`,workflowsLibraryTemplateNew: (): string => '/workflows/library/templates/new',workflowsLibraryTemplateFromMessage: (id?: string): string => `/workflows/library/templates/new?messageId=${id}`,- broadcasts: (tab?: MessagingNavTabKey): string => `/broadcasts${tab ? `/${tab}` : ''}`,+ broadcasts: (tab?: MessagingNavTabKey | 'calendar'): string => `/broadcasts${tab ? `/${tab}` : ''}`,broadcast: (id: string): string => `/broadcasts/${id}`,broadcastNew: (): string => '/broadcasts/new',}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ca7c585f5e27..546e8ae0d2c5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -5422,6 +5422,9 @@ importers:products/workflows:dependencies:+ '@dnd-kit/core':+ specifier: '*''@posthog/brand':specifier: 'catalog:'version: 0.12.3([email protected])diff --git a/products/workflows/backend/facade/activity.py b/products/workflows/backend/facade/activity.pyindex 48a27d3faff9..1d396990f36e 100644--- a/products/workflows/backend/facade/activity.py+++ b/products/workflows/backend/facade/activity.py@@ -3,11 +3,13 @@from products.workflows.backend.services.hog_flow_activity import (bulk_delete_archived_workflows,log_workflow_activity,+ log_workflow_schedule_activity,resume_workflow_email_sending,)__all__ = ["bulk_delete_archived_workflows","log_workflow_activity",+ "log_workflow_schedule_activity","resume_workflow_email_sending",]diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex f2a890f702d3..633521e82c6e 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -139,6 +139,7 @@ from products.tasks.backend.facade.workflow_tasks import (from products.workflows.backend.facade.activity import (bulk_delete_archived_workflows,log_workflow_activity,+ log_workflow_schedule_activity,resume_workflow_email_sending,)from products.workflows.backend.facade.batch_jobs import (@@ -180,6 +181,7 @@ from products.workflows.backend.facade.contracts import (WorkflowRef,WorkflowRevisionNotFound,WorkflowRevisionSummary,+ WorkflowSchedule,WorkflowScheduleNotFound,WorkflowStale,WorkflowWriteResult,@@ -5043,6 +5045,13 @@ class HogFlowViewSet(destroy_workflow(team_id=self.team_id, hog_flow_id=instance.id)self._report_workflow_action("hog_flow_deleted", instance, {"via": "destroy"})+ def _log_schedule_activity(+ self, hog_flow: WorkflowRef, *, before: Optional[WorkflowSchedule], after: Optional[WorkflowSchedule]+ ) -> None:+ log_workflow_schedule_activity(+ actor=self._activity_actor(), workflow_id=hog_flow.id, name=hog_flow.name, before=before, after=after+ )+def _activity_actor(self) -> WorkflowActor:return WorkflowActor(organization_id=self.organization.id,@@ -6613,6 +6622,7 @@ class HogFlowViewSet(serializer.is_valid(raise_exception=True)self._require_replay_vision_caller_access(request, self._edit_state().actions)schedule = create_schedule(team_id=self.team_id, hog_flow_id=hog_flow.id, fields=serializer.validated_data)+ self._log_schedule_activity(hog_flow, before=None, after=schedule)self._report_workflow_action("hog_flow_schedule_created", hog_flow, {"schedule_id": str(schedule.id)})return Response(HogFlowScheduleSerializer(schedule).data, status=201)@@ -6642,6 +6652,7 @@ class HogFlowViewSet(if request.method == "DELETE":schedule_id_str = str(schedule.id)delete_schedule(team_id=self.team_id, hog_flow_id=hog_flow.id, schedule_id=schedule.id)+ self._log_schedule_activity(hog_flow, before=schedule, after=None)self._report_workflow_action("hog_flow_schedule_deleted", hog_flow, {"schedule_id": schedule_id_str})return Response(status=204)@@ -6651,9 +6662,11 @@ class HogFlowViewSet(serializer.is_valid(raise_exception=True)if "variables" in serializer.validated_data:self._require_replay_vision_caller_access(request, self._edit_state().actions)+ previous = scheduleschedule = update_schedule(team_id=self.team_id, hog_flow_id=hog_flow.id, schedule_id=schedule.id, fields=serializer.validated_data)+ self._log_schedule_activity(hog_flow, before=previous, after=schedule)self._report_workflow_action("hog_flow_schedule_updated", hog_flow, {"schedule_id": str(schedule.id)})return Response(HogFlowScheduleSerializer(schedule).data)diff --git a/products/workflows/backend/services/hog_flow_activity.py b/products/workflows/backend/services/hog_flow_activity.pyindex 3b71729cfd6d..a4ffaf269832 100644--- a/products/workflows/backend/services/hog_flow_activity.py+++ b/products/workflows/backend/services/hog_flow_activity.py@@ -8,10 +8,10 @@ from uuid import UUIDfrom django.db import models, transaction-from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity+from posthog.models.activity_logging.activity_log import Change, ChangeAction, Detail, changes_between, log_activityfrom products.access_control.backend.facade.user_access_control import UserAccessControl-from products.workflows.backend.facade.contracts import WorkflowActor+from products.workflows.backend.facade.contracts import WorkflowActor, WorkflowSchedulefrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.services.hog_flow_writes import field_valuesfrom products.workflows.backend.services.workflow_email_health import resume_email_sending@@ -56,6 +56,47 @@ def log_workflow_activity(pass+def log_workflow_schedule_activity(+ *,+ actor: WorkflowActor,+ workflow_id: UUID,+ name: Optional[str],+ before: Optional[WorkflowSchedule],+ after: Optional[WorkflowSchedule],+) -> None:+ """Log a schedule change as an update of its workflow, so the workflow history shows who moved a send.++ A change that keeps the send times, such as new variables, logs nothing."""+ previous = _schedule_timing(before)+ current = _schedule_timing(after)+ if previous == current:+ return+ action: ChangeAction = "created" if previous is None else "deleted" if current is None else "changed"+ try:+ log_activity(+ organization_id=actor.organization_id,+ team_id=actor.team_id,+ user=actor.user,+ was_impersonated=actor.was_impersonated,+ item_id=str(workflow_id),+ scope=_SCOPE,+ activity="updated",+ detail=Detail(+ name=name or _SCOPE,+ changes=[Change(type=_SCOPE, action=action, field="schedule", before=previous, after=current)],+ ),+ )+ except Exception:+ # A failed audit write must not fail the change it describes.+ pass+++def _schedule_timing(schedule: Optional[WorkflowSchedule]) -> Optional[dict[str, str]]:+ if schedule is None:+ return None+ return {"rrule": schedule.rrule, "starts_at": schedule.starts_at.isoformat(), "timezone": schedule.timezone}++def resume_workflow_email_sending(*, team_id: int, hog_flow_id: UUID, actor: WorkflowActor) -> datetime | None:"""Resume a paused workflow's email as a customer and log it. Returns the resume time, or None whensending was not paused. Raises StaffPausedError when only staff may resume."""diff --git a/products/workflows/backend/test/test_hog_flow_schedule.py b/products/workflows/backend/test/test_hog_flow_schedule.pyindex b925b1fc799a..8ea26a2b3ecc 100644--- a/products/workflows/backend/test/test_hog_flow_schedule.py+++ b/products/workflows/backend/test/test_hog_flow_schedule.py@@ -12,6 +12,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.constants import AvailableFeature+from posthog.models.activity_logging.activity_log import ActivityLogfrom products.access_control.backend.models.access_control import AccessControlfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow@@ -205,6 +206,46 @@ class TestHogFlowScheduleAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()["schedules"] == []+ @parameterized.expand(+ [+ ("moving the start", {"starts_at": "2030-01-02T09:00:00Z"}, "changed"),+ ("changing the repeat rule", {"rrule": "FREQ=WEEKLY;INTERVAL=1;BYDAY=TU"}, "changed"),+ ("changing only the variables", {"variables": {"key": "value"}}, None),+ ]+ )+ def test_update_schedule_logs_changes_to_the_send_times(self, _name, payload, expected_action):+ workflow = self._create_batch_workflow()+ schedule_id = self.client.post(self._schedules_url(workflow["id"]), SCHEDULE_DATA).json()["id"]+ logged_before = ActivityLog.objects.filter(scope="HogFlow", item_id=workflow["id"]).count()++ response = self.client.patch(self._schedule_detail_url(workflow["id"], schedule_id), payload)++ assert response.status_code == status.HTTP_200_OK+ entries = list(ActivityLog.objects.filter(scope="HogFlow", item_id=workflow["id"]).order_by("created_at"))+ new_changes = [(entry.detail or {})["changes"][0] for entry in entries[logged_before:]]+ if expected_action is None:+ assert new_changes == []+ else:+ assert [(change["field"], change["action"]) for change in new_changes] == [("schedule", expected_action)]+ assert new_changes[0]["before"]["starts_at"] == "2030-01-01T09:00:00+00:00"+ assert new_changes[0]["after"] == {+ "rrule": payload.get("rrule", SCHEDULE_DATA["rrule"]),+ "starts_at": payload.get("starts_at", SCHEDULE_DATA["starts_at"]).replace("Z", "+00:00"),+ "timezone": "UTC",+ }++ def test_creating_and_deleting_a_schedule_logs_both(self):+ workflow = self._create_batch_workflow()+ schedule_id = self.client.post(self._schedules_url(workflow["id"]), SCHEDULE_DATA).json()["id"]+ self.client.delete(self._schedule_detail_url(workflow["id"], schedule_id))++ entries = ActivityLog.objects.filter(scope="HogFlow", item_id=workflow["id"], activity="updated")+ changes = [(entry.detail or {})["changes"][0] for entry in entries.order_by("created_at")]+ assert [(change["field"], change["action"]) for change in changes] == [+ ("schedule", "created"),+ ("schedule", "deleted"),+ ]+def test_delete_schedule(self):workflow = self._create_batch_workflow()create_response = self.client.post(self._schedules_url(workflow["id"]), SCHEDULE_DATA)diff --git a/products/workflows/frontend/Broadcasts/BroadcastsScene.tsx b/products/workflows/frontend/Broadcasts/BroadcastsScene.tsxindex 1a6b935f14ae..41f77d412b6a 100644--- a/products/workflows/frontend/Broadcasts/BroadcastsScene.tsx+++ b/products/workflows/frontend/Broadcasts/BroadcastsScene.tsx@@ -4,6 +4,7 @@ import { router } from 'kea-router'import { LemonButton } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -22,6 +23,9 @@ import {MessagingNavTabKey,isMessagingSetupTab,} from '../messagingTabs'+import { SendCalendar } from '../SendCalendar/SendCalendar'+import { SendCalendarTabLabel } from '../SendCalendar/SendCalendarTabLabel'+import { NewWorkflowModal } from '../Workflows/NewWorkflowModal'import { BroadcastsFeaturePreview } from './BroadcastsFeaturePreview'import { BroadcastsTable } from './BroadcastsTable'import { newBroadcastAgentLogic } from './newBroadcastAgentLogic'@@ -35,10 +39,16 @@ export function BroadcastsScene(): JSX.Element {const { location } = useValues(router)const { startNewBroadcast } = useActions(newBroadcastAgentLogic)// The tab routes are literal paths, so the tab is the last path segment rather than a route param.- const lastSegment = location.pathname.split('/').pop() as MessagingNavTabKey- const currentTab: MessagingNavTabKey | 'broadcasts' = MESSAGING_NAV_TAB_KEYS.includes(lastSegment)- ? lastSegment- : 'broadcasts'+ const showCalendar = useFeatureFlag('WORKFLOWS_SEND_CALENDAR')+ const lastSegment = location.pathname.split('/').pop() as MessagingNavTabKey | 'calendar'+ const currentTab: MessagingNavTabKey | 'broadcasts' | 'calendar' =+ lastSegment === 'calendar'+ ? showCalendar+ ? 'calendar'+ : 'broadcasts'+ : MESSAGING_NAV_TAB_KEYS.includes(lastSegment)+ ? lastSegment+ : 'broadcasts'const broadcastsTab = {label: 'Broadcasts',@@ -59,7 +69,7 @@ export function BroadcastsScene(): JSX.Element {description="Send a one-time or scheduled email to a group of people"resourceType={{ type: 'broadcasts' }}actions={- currentTab === 'broadcasts' ? (+ currentTab === 'broadcasts' || currentTab === 'calendar' ? (<AccessControlActionresourceType={AccessControlResourceType.Workflow}minAccessLevel={AccessControlLevel.Editor}@@ -79,10 +89,22 @@ export function BroadcastsScene(): JSX.Element {}/><EmailSuspensionBanner />- <LemonTabs<'broadcasts' | 'library' | 'messaging-setup'>- activeKey={currentTab === 'broadcasts' || currentTab === 'library' ? currentTab : 'messaging-setup'}+ <LemonTabs<'broadcasts' | 'calendar' | 'library' | 'messaging-setup'>+ activeKey={+ currentTab === 'broadcasts' || currentTab === 'calendar' || currentTab === 'library'+ ? currentTab+ : 'messaging-setup'+ }tabs={[broadcastsTab,+ showCalendar+ ? {+ label: <SendCalendarTabLabel />,+ key: 'calendar',+ link: urls.broadcasts('calendar'),+ content: <SendCalendar />,+ }+ : null,{label: 'Templates',key: 'library',@@ -103,6 +125,8 @@ export function BroadcastsScene(): JSX.Element {]}sceneInset/>+ {/* The calendar can start a workflow, and its template picker lives in this modal. */}+ {showCalendar ? <NewWorkflowModal /> : null}</SceneContent>)}diff --git a/products/workflows/frontend/Broadcasts/broadcastsRoutes.test.ts b/products/workflows/frontend/Broadcasts/broadcastsRoutes.test.tsindex 2d2d072295d8..9716fb2d1ea1 100644--- a/products/workflows/frontend/Broadcasts/broadcastsRoutes.test.ts+++ b/products/workflows/frontend/Broadcasts/broadcastsRoutes.test.ts@@ -41,6 +41,7 @@ describe('broadcasts routes', () => {['/broadcasts/suppression', 'Broadcasts'],['/broadcasts/reputation', 'Broadcasts'],['/broadcasts/settings', 'Broadcasts'],+ ['/broadcasts/calendar', 'Broadcasts'],['/broadcasts/new', 'Broadcast'],['/broadcasts/01a05e5e-38c2-0000-b81a-21fe48581914', 'Broadcast'],])('opens %s in the %s scene', (url, scene) => {diff --git a/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsx b/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsxnew file mode 100644index 000000000000..02531fc20f7a--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsx@@ -0,0 +1,303 @@+import { Meta, StoryFn } from '@storybook/react'+import { useActions, useMountedLogic } from 'kea'+import { useEffect } from 'react'++import { dayjs } from 'lib/dayjs'++import { useStorybookMocks } from '~/mocks/browser'+import { toPaginatedResponse } from '~/mocks/handlers'++import type { MessageCategoryApi } from 'products/messaging/frontend/generated/api.schemas'+import type {+ HogFlowBatchJobApi,+ HogFlowMinimalApi,+ HogFlowScheduleApi,+ 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'++const meta: Meta<typeof SendCalendar> = {+ title: 'Products/Workflows/Send calendar',+ component: SendCalendar,+ parameters: {+ layout: 'padded',+ mockDate: '2026-10-16 12:00:00',+ testOptions: { waitForLoadersToDisappear: true, waitForSelector: '[data-attr=send-calendar-month]' },+ },+}+export default meta++const person = (id: number, first_name: string): UserBasicApi =>+ ({+ id,+ uuid: `0199e0aa-0000-7000-8000-00000000010${id}`,+ first_name,+ email: `${first_name}@example.com`,+ }) as UserBasicApi++const PRIYA = person(1, 'Priya')+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 =>+ ({+ id: `0199e0aa-0000-7000-8000-0000000003${String(n).padStart(2, '0')}`,+ key: name.toLowerCase().replace(/\W+/g, '-'),+ name,+ category_type,+ }) 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 cohort = (id: number, name: string, count: number, is_static = false): Record<string, unknown> => ({+ id,+ name,+ count,+ is_static,+ is_calculating: false,+ deleted: false,+ filters: { properties: { type: 'OR', values: [] } },+ groups: [],+})++const COHORTS = [+ cohort(21, 'Active trial users', 1204),+ cohort(22, 'Newsletter subscribers', 18450),+ cohort(23, 'Webinar sign-ups', 312, true),+ cohort(24, 'Partners', 86, true),+]++const inCohort = (id: number): Record<string, unknown> => ({ key: 'id', type: 'cohort', value: id })+const personProperty = (key: string, operator: string, value: unknown): Record<string, unknown> => ({+ key,+ type: 'person',+ operator,+ value,+})++interface FlowRecipients {+ audience?: Record<string, unknown>[]+ to?: string+ category?: MessageCategoryApi+}++const flow = (+ n: number,+ name: string,+ origin_product: 'broadcasts' | null,+ trigger: 'batch' | 'schedule',+ created_by: UserBasicApi,+ { audience = [], to = '{{ person.properties.email }}', category }: FlowRecipients = {}+): HogFlowMinimalApi =>+ ({+ 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++const schedule = (+ n: number,+ rrule: string,+ starts_at: string,+ status: HogFlowScheduleApi['status'] = 'active'+): HogFlowScheduleApi => ({+ id: `0199e0aa-0000-7000-8000-0000000002${String(n).padStart(2, '0')}`,+ rrule,+ starts_at,+ timezone: 'UTC',+ status,+ next_run_at: null,+ created_at: starts_at,+ 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 SCHEDULES: Record<string, HogFlowScheduleApi[]> = {+ [flowId(1)]: [schedule(1, 'FREQ=DAILY;COUNT=1', '2026-10-20T11:00:00Z')],+ [flowId(2)]: [schedule(2, 'FREQ=WEEKLY;BYDAY=TU', '2026-09-01T09:00:00Z')],+ [flowId(3)]: [schedule(3, 'FREQ=DAILY;COUNT=1', '2026-10-20T15:00:00Z')],+ [flowId(4)]: [schedule(4, 'FREQ=DAILY;COUNT=1', '2026-10-20T17:30:00Z')],+ [flowId(6)]: [schedule(6, 'FREQ=DAILY;COUNT=1', '2026-10-14T10:00:00Z', 'completed')],+ [flowId(7)]: [schedule(7, 'FREQ=WEEKLY;INTERVAL=2;BYDAY=TH', '2026-10-08T10:00:00Z')],+ [flowId(8)]: [schedule(8, 'FREQ=WEEKLY;BYDAY=FR', '2026-09-04T16:00:00Z', 'paused')],+ [flowId(9)]: [schedule(9, 'FREQ=MONTHLY;BYMONTHDAY=25', '2026-09-25T08:00:00Z')],+}++const BATCH_JOBS: Record<string, HogFlowBatchJobApi[]> = {+ [flowId(2)]: [+ job('digest-oct-13', 'completed', '2026-10-13T09:00:04Z'),+ job('digest-oct-6', 'completed', '2026-10-06T09:00:03Z'),+ job('digest-sep-29', 'completed', '2026-09-29T09:00:05Z'),+ ],+ [flowId(5)]: [job('partner-oct-16', 'active', '2026-10-16T09:00:02Z')],+ [flowId(6)]: [job('survey-oct-14', 'completed', '2026-10-14T10:00:04Z')],+ [flowId(7)]: [job('win-back-oct-8', 'failed', '2026-10-08T10:00:06Z')],+}++function useCalendarMocks(flows: HogFlowMinimalApi[]): 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 }]+ },+ '/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)+ return match ? [200, match] : [404, { detail: 'Not found.' }]+ },+ '/api/projects/:team_id/messaging_categories/': toPaginatedResponse(CATEGORIES),+ },+ })+}++// The test runner shrinks the story root to its content, and a container query root has no width of its own.+function FullWidthCalendar(): JSX.Element {+ return (+ <div className="w-[75rem]">+ <SendCalendar />+ </div>+ )+}++function CalendarAt({ view, anchor }: { view: 'month' | 'week'; anchor: string }): JSX.Element {+ useMountedLogic(sendCalendarLogic)+ const { setView, setAnchor } = useActions(sendCalendarLogic)+ useEffect(() => {+ setView(view)+ setAnchor(anchor)+ }, [setView, setAnchor, view, anchor])+ return <FullWidthCalendar />+}++export const MonthView: StoryFn = () => {+ useCalendarMocks(FLOWS)+ return <FullWidthCalendar />+}++// The week with four sends on one day, which a month cell cuts to three.+export const BusyWeek: StoryFn = () => {+ useCalendarMocks(FLOWS)+ return <CalendarAt view="week" anchor="2026-10-20" />+}+BusyWeek.parameters = {+ testOptions: { waitForLoadersToDisappear: true, waitForSelector: '[data-attr=send-calendar-week]' },+}++// Below 40rem the grid changes to a list of the days that have sends.+export const NarrowWidth: StoryFn = () => {+ useCalendarMocks(FLOWS)+ return (+ <div className="w-[28rem]">+ <SendCalendar />+ </div>+ )+}+NarrowWidth.parameters = {+ testOptions: { waitForLoadersToDisappear: true, waitForSelector: '[data-attr=send-calendar-list]' },+}++export const NothingScheduled: StoryFn = () => {+ useCalendarMocks([])+ return <FullWidthCalendar />+}+NothingScheduled.parameters = {+ testOptions: { waitForLoadersToDisappear: true, waitForSelector: '[data-attr=send-calendar]' },+}++const detailsSend = (item: HogFlowMinimalApi): CalendarSend => {+ const itemSchedule = SCHEDULES[item.id][0]+ return {+ key: `details-${item.id}`,+ flowId: item.id,+ name: item.name ?? '',+ kind: item.origin_product === 'broadcasts' ? 'broadcast' : 'workflow',+ state: 'planned',+ at: dayjs(itemSchedule.starts_at),+ repeat: describeRepeat(itemSchedule),+ isRecurring: itemSchedule.rrule !== 'FREQ=DAILY;COUNT=1',+ createdBy: item.created_by,+ schedule: itemSchedule,+ userAccessLevel: item.user_access_level ?? null,+ audience: sendAudience(item),+ category: sendCategory(item),+ }+}++// Who a send goes to: a broadcast with a cohort audience, and a scheduled workflow that sends to one address.+export const SendDetails: StoryFn = () => {+ useCalendarMocks(FLOWS)+ return (+ <div className="flex items-start gap-4">+ {[detailsSend(FLOWS[0]), detailsSend(FLOWS[8])].map((send) => (+ <div key={send.key} className="rounded border bg-surface-primary">+ <SendCalendarSendDetails send={send} />+ </div>+ ))}+ </div>+ )+}+SendDetails.parameters = {+ testOptions: { waitForLoadersToDisappear: true, waitForSelector: '[data-attr=send-calendar-audience]' },+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendar.tsx b/products/workflows/frontend/SendCalendar/SendCalendar.tsxnew file mode 100644index 000000000000..bccbe801ccfb--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendar.tsx@@ -0,0 +1,134 @@+import {+ DndContext,+ DragEndEvent,+ DragOverlay,+ PointerSensor,+ pointerWithin,+ useSensor,+ useSensors,+} from '@dnd-kit/core'+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { IconChevronLeft, IconChevronRight } from '@posthog/icons'+import { LemonButton, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'++import { Spinner } from 'lib/lemon-ui/Spinner'++import { SendCalendarLegend } from './SendCalendarLegend'+import { SendCalendarList } from './SendCalendarList'+import { sendCalendarLogic } from './sendCalendarLogic'+import { SendCalendarMonth } from './SendCalendarMonth'+import { SendCalendarSendLabel } from './SendCalendarSendLabel'+import { CalendarSend, CalendarTypeFilter, CalendarView } from './sendCalendarUtils'+import { SendCalendarWeek } from './SendCalendarWeek'++export function SendCalendar(): JSX.Element {+ const { view, typeFilter, periodLabel, timezone, scheduledFlows, scheduledFlowsLoading, loadFailed } =+ useValues(sendCalendarLogic)+ const { setView, setTypeFilter, goToToday, goForward, goBackward, moveSend } = useActions(sendCalendarLogic)+ const [draggedSend, setDraggedSend] = useState<CalendarSend | null>(null)+ // A drag starts only after the pointer moves a few pixels, so a click on a send still opens its details.+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }))++ const onDragEnd = ({ active, over }: DragEndEvent): void => {+ setDraggedSend(null)+ const send = active.data.current?.send as CalendarSend | undefined+ if (send && over) {+ moveSend(send, String(over.id))+ }+ }++ return (+ <div className="@container flex flex-col gap-2" data-attr="send-calendar">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex items-center gap-1">+ <LemonButton type="secondary" size="small" onClick={goToToday} data-attr="send-calendar-today">+ Today+ </LemonButton>+ <LemonButton+ size="small"+ icon={<IconChevronLeft />}+ onClick={goBackward}+ tooltip={view === 'month' ? 'Previous month' : 'Previous week'}+ data-attr="send-calendar-previous"+ />+ <LemonButton+ size="small"+ icon={<IconChevronRight />}+ onClick={goForward}+ tooltip={view === 'month' ? 'Next month' : 'Next week'}+ data-attr="send-calendar-next"+ />+ <h3 className="mb-0 ml-1 text-base font-semibold">{periodLabel}</h3>+ </div>+ <div className="flex items-center gap-2">+ <LemonSegmentedButton<CalendarView>+ size="small"+ value={view}+ onChange={setView}+ options={[+ { value: 'month', label: 'Month' },+ { value: 'week', label: 'Week' },+ ]}+ data-attr="send-calendar-view"+ />+ <LemonSelect<CalendarTypeFilter>+ size="small"+ value={typeFilter}+ onChange={setTypeFilter}+ dropdownMatchSelectWidth={false}+ options={[+ { value: 'all', label: 'All sends' },+ { value: 'broadcasts', label: 'Broadcasts' },+ { value: 'workflows', label: 'Workflows' },+ ]}+ data-attr="send-calendar-type"+ />+ </div>+ </div>+ <div className="text-xs text-secondary">+ Times use the project time zone ({timezone}). Drafts 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 />+ {scheduledFlowsLoading && !scheduledFlows ? (+ <div className="flex justify-center p-8">+ <Spinner className="text-2xl" />+ </div>+ ) : loadFailed ? (+ <div className="rounded border bg-surface-primary p-8 text-center text-secondary">+ Couldn't load the scheduled sends. Refresh the page to try again.+ </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.+ </div>+ ) : (+ <DndContext+ sensors={sensors}+ // The day under the pointer takes the drop, as in other calendars, even when the dragged+ // label overlaps the next day.+ collisionDetection={pointerWithin}+ onDragStart={({ active }) => setDraggedSend((active.data.current?.send as CalendarSend) ?? null)}+ onDragEnd={onDragEnd}+ onDragCancel={() => setDraggedSend(null)}+ >+ <div className="hidden @min-[40rem]:block">+ {view === 'month' ? <SendCalendarMonth /> : <SendCalendarWeek />}+ </div>+ <div className="@min-[40rem]:hidden">+ <SendCalendarList />+ </div>+ <DragOverlay dropAnimation={null}>+ {draggedSend ? (+ <div className="cursor-grabbing rounded border bg-surface-primary px-2 py-1 text-xs shadow">+ <SendCalendarSendLabel send={draggedSend} timezone={timezone} />+ </div>+ ) : null}+ </DragOverlay>+ </DndContext>+ )}+ </div>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarAudience.tsx b/products/workflows/frontend/SendCalendar/SendCalendarAudience.tsxnew file mode 100644index 000000000000..e46d43986e40--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarAudience.tsx@@ -0,0 +1,44 @@+import { useValues } from 'kea'++import { Link } from '@posthog/lemon-ui'++import PropertyFiltersDisplay from 'lib/components/PropertyFilters/components/PropertyFiltersDisplay'+import { IconCohort } from 'lib/lemon-ui/icons'+import { humanFriendlyNumber } from 'lib/utils/numbers'+import { urls } from 'scenes/urls'++import { sendCalendarLogic } from './sendCalendarLogic'+import { SendAudience } from './sendCalendarUtils'++export function SendCalendarAudience({ audience }: { audience: SendAudience }): JSX.Element {+ const { cohortsById } = useValues(sendCalendarLogic)++ if (audience.address) {+ return <div className="font-mono break-all">{audience.address}</div>+ }+ if (!audience.cohortIds.length && !audience.filters.length) {+ return <div>{audience.accounts ? 'All accounts' : 'Everyone'}</div>+ }+ return (+ <div className="flex flex-col gap-1" data-attr="send-calendar-audience">+ {audience.cohortIds.map((id) => {+ const cohort = cohortsById[id]+ return (+ <div key={id} className="flex min-w-0 items-center gap-1">+ <IconCohort className="shrink-0 text-secondary" />+ <Link to={urls.cohort(id)} className="truncate" data-attr="send-calendar-cohort">+ {cohort?.name || `Cohort ${id}`}+ </Link>+ {typeof cohort?.count === 'number' ? (+ <span className="shrink-0 text-secondary">+ {humanFriendlyNumber(cohort.count)} {cohort.count === 1 ? 'person' : 'people'}+ </span>+ ) : null}+ </div>+ )+ })}+ {audience.filters.length ? <PropertyFiltersDisplay filters={audience.filters} compact /> : null}+ {audience.accounts ? <div className="text-secondary">One send for each matching account.</div> : null}+ </div>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarDraggableSend.tsx b/products/workflows/frontend/SendCalendar/SendCalendarDraggableSend.tsxnew file mode 100644index 000000000000..4f35cce90b8e--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarDraggableSend.tsx@@ -0,0 +1,30 @@+import { useDraggable } from '@dnd-kit/core'+import clsx from 'clsx'+import { useValues } from 'kea'++import { sendCalendarLogic } from './sendCalendarLogic'+import { SendCalendarSendButton } from './SendCalendarSendButton'+import { CalendarSend, moveBlockedReason } from './sendCalendarUtils'++export function SendCalendarDraggableSend({ send }: { send: CalendarSend }): JSX.Element {+ const { savingScheduleIds } = useValues(sendCalendarLogic)+ const canMove = !moveBlockedReason(send) && !(send.schedule && savingScheduleIds[send.schedule.id])+ // dnd-kit keeps one node for each draggable id. If a send renders as a draggable twice, the drag can+ // measure the wrong node, and the drop then finds no day.+ const { setNodeRef, listeners, isDragging } = useDraggable({+ id: send.key,+ data: { send },+ disabled: !canMove,+ })++ return (+ // The drag listeners sit on a wrapper, so a short click still reaches the button and opens the details.+ <div+ ref={setNodeRef}+ {...listeners}+ className={clsx('min-w-0', canMove && 'cursor-grab', isDragging && 'opacity-40')}+ >+ <SendCalendarSendButton send={send} />+ </div>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarDropZone.tsx b/products/workflows/frontend/SendCalendar/SendCalendarDropZone.tsxnew file mode 100644index 000000000000..3c44d7ec9a00--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarDropZone.tsx@@ -0,0 +1,33 @@+import { useDroppable } from '@dnd-kit/core'+import clsx from 'clsx'+import { useValues } from 'kea'++import { dayjs } from 'lib/dayjs'++import { sendCalendarLogic } from './sendCalendarLogic'+import { CalendarSend, dropTarget } from './sendCalendarUtils'++export function SendCalendarDropZone({+ day,+ className,+ children,+}: {+ day: string+ className?: string+ children: React.ReactNode+}): JSX.Element {+ const { timezone } = useValues(sendCalendarLogic)+ const { setNodeRef, isOver, active } = useDroppable({ id: day })+ const send = active?.data.current?.send as CalendarSend | undefined+ const accepts = !!send && !!dropTarget(send, day, timezone, dayjs())++ return (+ <div+ ref={setNodeRef}+ className={clsx(className, isOver && accepts && 'bg-primary-highlight')}+ data-attr="send-calendar-day"+ >+ {children}+ </div>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarLegend.tsx b/products/workflows/frontend/SendCalendar/SendCalendarLegend.tsxnew file mode 100644index 000000000000..c2e38c6d722d--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarLegend.tsx@@ -0,0 +1,39 @@+import { IconCheck, IconPause, IconRefresh, IconSend, IconWarning } from '@posthog/icons'++export function SendCalendarLegend(): JSX.Element {+ return (+ <div+ className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-secondary"+ data-attr="send-calendar-legend"+ >+ <span className="flex items-center gap-1">+ <span className="size-2 shrink-0 rounded-full bg-accent" />+ Broadcast+ </span>+ <span className="flex items-center gap-1">+ <span className="size-2 shrink-0 rounded-full bg-[var(--color-product-workflows-light)]" />+ Workflow+ </span>+ <span className="flex items-center gap-1">+ <IconRefresh className="shrink-0" />+ Repeats+ </span>+ <span className="flex items-center gap-1">+ <IconPause className="shrink-0" />+ Paused+ </span>+ <span className="flex items-center gap-1">+ <IconSend className="shrink-0" />+ Sending+ </span>+ <span className="flex items-center gap-1">+ <IconCheck className="shrink-0 text-success" />+ Sent+ </span>+ <span className="flex items-center gap-1">+ <IconWarning className="shrink-0 text-danger" />+ Failed+ </span>+ </div>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarList.tsx b/products/workflows/frontend/SendCalendar/SendCalendarList.tsxnew file mode 100644index 000000000000..3c28893dc233--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarList.tsx@@ -0,0 +1,35 @@+import { useValues } from 'kea'++import { dayjs } from 'lib/dayjs'++import { sendCalendarLogic } from './sendCalendarLogic'+import { SendCalendarSendButton } from './SendCalendarSendButton'++export function SendCalendarList(): JSX.Element {+ const { days, sendsByDay } = useValues(sendCalendarLogic)+ const daysWithSends = days.filter((day) => sendsByDay[day]?.length)++ if (!daysWithSends.length) {+ return (+ <div className="rounded border bg-surface-primary p-4 text-center text-secondary">+ No sends in this period.+ </div>+ )+ }+ return (+ <div className="flex flex-col gap-2" data-attr="send-calendar-list">+ {daysWithSends.map((day) => (+ <div key={day} className="overflow-hidden rounded border bg-surface-primary">+ <div className="border-b bg-surface-secondary px-2 py-1 text-xs font-semibold">+ {dayjs.utc(day).format('ddd, MMM D')}+ </div>+ <div className="flex flex-col gap-0.5 p-1">+ {sendsByDay[day].map((send) => (+ <SendCalendarSendButton key={send.key} send={send} />+ ))}+ </div>+ </div>+ ))}+ </div>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarMonth.tsx b/products/workflows/frontend/SendCalendar/SendCalendarMonth.tsxnew file mode 100644index 000000000000..06620ffe13d9--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarMonth.tsx@@ -0,0 +1,96 @@+import clsx from 'clsx'+import { useValues } from 'kea'+import { useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { Popover } from 'lib/lemon-ui/Popover'++import { SendCalendarDraggableSend } from './SendCalendarDraggableSend'+import { SendCalendarDropZone } from './SendCalendarDropZone'+import { sendCalendarLogic } from './sendCalendarLogic'+import { SendCalendarNewSendButton } from './SendCalendarNewSendButton'+import { CalendarSend } from './sendCalendarUtils'++const MAX_VISIBLE_SENDS = 3++export function SendCalendarMonth(): JSX.Element {+ const { days, sendsByDay, today, anchorDate } = useValues(sendCalendarLogic)+ const month = anchorDate.slice(0, 7)++ return (+ // On a wide screen the weeks share the height under the toolbar, so the grid fills the screen.+ <div+ className="flex flex-col overflow-hidden rounded border bg-surface-primary @min-[60rem]:min-h-[calc(100vh-16rem)]"+ data-attr="send-calendar-month"+ >+ <div className="grid grid-cols-7 border-b bg-surface-secondary">+ {days.slice(0, 7).map((day) => (+ <div key={day} className="px-2 py-1 text-xs font-semibold uppercase text-secondary">+ {dayjs.utc(day).format('ddd')}+ </div>+ ))}+ </div>+ <div className="grid flex-1 auto-rows-fr grid-cols-7">+ {days.map((day, index) => {+ const sends = sendsByDay[day] ?? []+ const date = dayjs.utc(day)+ return (+ <SendCalendarDropZone+ key={day}+ day={day}+ className={clsx(+ 'group flex min-h-28 min-w-0 flex-col gap-0.5 p-1',+ index % 7 !== 6 && 'border-r',+ index < days.length - 7 && 'border-b',+ !day.startsWith(month) && 'bg-surface-secondary'+ )}+ >+ <div className="flex h-6 items-center justify-between pl-1 text-xs font-semibold">+ <span+ className={clsx(+ day === today && 'rounded-full bg-accent px-1.5 py-0.5 text-primary-inverse',+ day !== today && !day.startsWith(month) && 'text-muted'+ )}+ >+ {date.date() === 1 ? date.format('MMM D') : date.format('D')}+ </span>+ {day >= today ? <SendCalendarNewSendButton day={day} /> : null}+ </div>+ {sends.slice(0, MAX_VISIBLE_SENDS).map((send) => (+ <SendCalendarDraggableSend key={send.key} send={send} />+ ))}+ {sends.length > MAX_VISIBLE_SENDS ? <MoreSends day={day} sends={sends} /> : null}+ </SendCalendarDropZone>+ )+ })}+ </div>+ </div>+ )+}++function MoreSends({ day, sends }: { day: string; sends: CalendarSend[] }): JSX.Element {+ const [open, setOpen] = useState(false)+ // The first sends already show in the day cell, and each send can render as a draggable only once.+ const hiddenSends = sends.slice(MAX_VISIBLE_SENDS)+ return (+ <Popover+ visible={open}+ onClickOutside={() => setOpen(false)}+ placement="bottom-start"+ overlay={+ <div className="flex w-64 flex-col gap-0.5 p-1">+ <div className="px-1 pb-1 text-xs font-semibold">{dayjs.utc(day).format('ddd, MMM D')}</div>+ {hiddenSends.map((send) => (+ <SendCalendarDraggableSend key={send.key} send={send} />+ ))}+ </div>+ }+ >+ <LemonButton size="xsmall" sideIcon={null} onClick={() => setOpen(!open)} data-attr="send-calendar-more">+ +{hiddenSends.length} more+ </LemonButton>+ </Popover>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarNewSendButton.tsx b/products/workflows/frontend/SendCalendar/SendCalendarNewSendButton.tsxnew file mode 100644index 000000000000..643e797762a7--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarNewSendButton.tsx@@ -0,0 +1,34 @@+import { useActions } from 'kea'++import { IconPlus } from '@posthog/icons'+import { LemonButton, LemonMenu } from '@posthog/lemon-ui'++import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { sendCalendarLogic } from './sendCalendarLogic'++export function SendCalendarNewSendButton({ day }: { day: string }): JSX.Element {+ const { startNewSend } = useActions(sendCalendarLogic)+ const disabledReason = getAccessControlDisabledReason(AccessControlResourceType.Workflow, AccessControlLevel.Editor)++ return (+ <LemonMenu+ items={[+ { label: 'New broadcast', onClick: () => startNewSend('broadcast', day) },+ { label: 'New workflow', onClick: () => startNewSend('workflow', day) },+ ]}+ >+ <LemonButton+ size="xsmall"+ icon={<IconPlus />}+ tooltip="Create a broadcast or workflow"+ disabledReason={disabledReason}+ // Hidden until the day is hovered, so the grid stays calm. Focus shows it for keyboard users.+ className="opacity-0 group-hover:opacity-100 focus-visible:opacity-100"+ data-attr="send-calendar-new-send"+ />+ </LemonMenu>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarSendButton.tsx b/products/workflows/frontend/SendCalendar/SendCalendarSendButton.tsxnew file mode 100644index 000000000000..a7b0f6f7c9ba--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarSendButton.tsx@@ -0,0 +1,41 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { Popover } from 'lib/lemon-ui/Popover'++import { sendCalendarLogic } from './sendCalendarLogic'+import { SendCalendarSendDetails } from './SendCalendarSendDetails'+import { SendCalendarSendLabel } from './SendCalendarSendLabel'+import { CalendarSend } from './sendCalendarUtils'++export function SendCalendarSendButton({ send }: { send: CalendarSend }): JSX.Element {+ const { timezone } = useValues(sendCalendarLogic)+ const { reportSendOpened } = useActions(sendCalendarLogic)+ const [open, setOpen] = useState(false)++ return (+ <Popover+ visible={open}+ onClickOutside={() => setOpen(false)}+ placement="bottom-start"+ overlay={<SendCalendarSendDetails send={send} />}+ >+ <LemonButton+ size="xsmall"+ fullWidth+ sideIcon={null}+ onClick={() => {+ if (!open) {+ reportSendOpened(send)+ }+ setOpen(!open)+ }}+ data-attr="send-calendar-send"+ >+ <SendCalendarSendLabel send={send} timezone={timezone} />+ </LemonButton>+ </Popover>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarSendDetails.tsx b/products/workflows/frontend/SendCalendar/SendCalendarSendDetails.tsxnew file mode 100644index 000000000000..e5c1e293f041--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarSendDetails.tsx@@ -0,0 +1,106 @@+import { useValues } from 'kea'++import { LemonButton, LemonTag, LemonTagType } from '@posthog/lemon-ui'++import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { urls } from 'scenes/urls'++import { SendCalendarAudience } from './SendCalendarAudience'+import { sendCalendarLogic } from './sendCalendarLogic'+import { CalendarSend, CalendarSendState, SendCategory, moveBlockedReason } from './sendCalendarUtils'++const STATE_TAGS: Record<CalendarSendState, { label: string; type: LemonTagType }> = {+ planned: { label: 'Scheduled', type: 'warning' },+ paused: { label: 'Paused', type: 'muted' },+ sending: { label: 'Sending', type: 'completion' },+ sent: { label: 'Sent', type: 'success' },+ failed: { 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++ return (+ <div className="flex w-96 max-w-[calc(100vw-2rem)] flex-col gap-3 p-3" data-attr="send-calendar-send-details">+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-1">+ <LemonTag type={isBroadcast ? 'primary' : 'muted'}>+ {isBroadcast ? 'Broadcast' : 'Workflow'}+ </LemonTag>+ <LemonTag type={STATE_TAGS[send.state].type}>{STATE_TAGS[send.state].label}</LemonTag>+ </div>+ <div className="text-base font-semibold">{send.name}</div>+ </div>+ <dl className="m-0 grid grid-cols-[auto_1fr] items-baseline gap-x-4 gap-y-2 text-sm">+ <dt className="text-secondary">When</dt>+ <dd className="m-0">{send.at.tz(timezone).format('ddd, MMM D [at] h:mm A')}</dd>+ {send.repeat ? (+ <>+ <dt className="text-secondary">Repeats</dt>+ <dd className="m-0">{send.repeat}</dd>+ </>+ ) : null}+ <dt className="text-secondary">Sends to</dt>+ <dd className="m-0 min-w-0">+ <SendCalendarAudience audience={send.audience} />+ </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>+ ) : (+ <span className="text-secondary">No category</span>+ )}+ </dd>+ {send.createdBy ? (+ <>+ <dt className="text-secondary">Created by</dt>+ <dd className="m-0 flex items-center gap-1">+ <ProfilePicture+ user={{ first_name: send.createdBy.first_name, email: send.createdBy.email }}+ size="xs"+ />+ {send.createdBy.first_name || send.createdBy.email}+ </dd>+ </>+ ) : 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.+ </div>+ ) : moveReason ? (+ <div className="text-xs text-secondary">{moveReason}</div>+ ) : null}+ <LemonButton+ type="primary"+ size="small"+ to={isBroadcast ? urls.broadcast(send.flowId) : urls.workflow(send.flowId, 'workflow')}+ data-attr="send-calendar-open"+ >+ {isBroadcast ? 'Open broadcast' : 'Open workflow'}+ </LemonButton>+ </div>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarSendLabel.tsx b/products/workflows/frontend/SendCalendar/SendCalendarSendLabel.tsxnew file mode 100644index 000000000000..d6680466f4c6--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarSendLabel.tsx@@ -0,0 +1,28 @@+import clsx from 'clsx'++import { IconCheck, IconPause, IconRefresh, IconSend, IconWarning } from '@posthog/icons'++import { CalendarSend } from './sendCalendarUtils'++export function SendCalendarSendLabel({ send, timezone }: { send: CalendarSend; timezone: string }): JSX.Element {+ const isPast = send.state === 'sent' || send.state === 'failed'+ return (+ <span className={clsx('flex min-w-0 items-center gap-1', isPast && 'text-secondary')}>+ <span+ className={clsx(+ 'size-2 shrink-0 rounded-full',+ send.kind === 'broadcast' ? 'bg-accent' : 'bg-[var(--color-product-workflows-light)]'+ )}+ />+ <span className="shrink-0 font-semibold">{send.at.tz(timezone).format('h:mm A')}</span>+ <span className="truncate font-normal">{send.name}</span>+ {send.state === 'planned' && send.isRecurring ? (+ <IconRefresh className="shrink-0 text-secondary" aria-label="Repeats" />+ ) : null}+ {send.state === 'paused' ? <IconPause className="shrink-0" aria-label="Paused" /> : null}+ {send.state === 'sending' ? <IconSend className="shrink-0" aria-label="Sending" /> : null}+ {send.state === 'sent' ? <IconCheck className="shrink-0 text-success" aria-label="Sent" /> : null}+ {send.state === 'failed' ? <IconWarning className="shrink-0 text-danger" aria-label="Failed" /> : null}+ </span>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarTabLabel.tsx b/products/workflows/frontend/SendCalendar/SendCalendarTabLabel.tsxnew file mode 100644index 000000000000..bb99dcd5c36b--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarTabLabel.tsx@@ -0,0 +1,12 @@+import { LemonTag } from '@posthog/lemon-ui'++export function SendCalendarTabLabel(): JSX.Element {+ return (+ <span className="flex items-center gap-1">+ Calendar+ <LemonTag type="highlight" size="small">+ New+ </LemonTag>+ </span>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendCalendarWeek.tsx b/products/workflows/frontend/SendCalendar/SendCalendarWeek.tsxnew file mode 100644index 000000000000..53a9cfb0ab62--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendCalendarWeek.tsx@@ -0,0 +1,45 @@+import clsx from 'clsx'+import { useValues } from 'kea'++import { dayjs } from 'lib/dayjs'++import { SendCalendarDraggableSend } from './SendCalendarDraggableSend'+import { SendCalendarDropZone } from './SendCalendarDropZone'+import { sendCalendarLogic } from './sendCalendarLogic'+import { SendCalendarNewSendButton } from './SendCalendarNewSendButton'++export function SendCalendarWeek(): JSX.Element {+ const { days, sendsByDay, today } = useValues(sendCalendarLogic)++ return (+ <div+ className="grid grid-cols-7 overflow-hidden rounded border bg-surface-primary @min-[60rem]:min-h-[calc(100vh-16rem)]"+ data-attr="send-calendar-week"+ >+ {days.map((day, index) => {+ const sends = sendsByDay[day] ?? []+ return (+ <div key={day} className={clsx('group flex min-w-0 flex-col', index < 6 && 'border-r')}>+ <div className="flex h-8 items-center justify-between border-b bg-surface-secondary pl-2 pr-1 text-xs font-semibold">+ <span+ className={clsx(+ day === today && 'rounded-full bg-accent px-1.5 py-0.5 text-primary-inverse'+ )}+ >+ {dayjs.utc(day).format('ddd D')}+ </span>+ {day >= today ? <SendCalendarNewSendButton day={day} /> : null}+ </div>+ <SendCalendarDropZone day={day} className="flex min-h-80 flex-1 flex-col gap-0.5 p-1">+ {sends.length ? (+ sends.map((send) => <SendCalendarDraggableSend key={send.key} send={send} />)+ ) : (+ <span className="px-1 py-2 text-xs text-muted">No sends</span>+ )}+ </SendCalendarDropZone>+ </div>+ )+ })}+ </div>+ )+}diff --git a/products/workflows/frontend/SendCalendar/sendCalendarLogic.test.ts b/products/workflows/frontend/SendCalendar/sendCalendarLogic.test.tsnew file mode 100644index 000000000000..c4cca993dd8e--- /dev/null+++ b/products/workflows/frontend/SendCalendar/sendCalendarLogic.test.ts@@ -0,0 +1,170 @@+import { expectLogic } from 'kea-test-utils'++import { lemonToast } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'++import { initKeaTests } from '~/test/init'++import {+ hogFlowsBatchJobsList,+ hogFlowsList,+ hogFlowsSchedulesList,+ hogFlowsSchedulesPartialUpdate,+} from 'products/workflows/frontend/generated/api'+import type { HogFlowMinimalApi, HogFlowScheduleApi } from 'products/workflows/frontend/generated/api.schemas'++import { sendCalendarLogic } from './sendCalendarLogic'++jest.mock('products/workflows/frontend/generated/api', () => ({+ hogFlowsList: jest.fn(),+ hogFlowsSchedulesList: jest.fn(),+ hogFlowsBatchJobsList: jest.fn(),+ hogFlowsSchedulesPartialUpdate: jest.fn(),+}))+jest.mock('@posthog/lemon-ui', () => ({+ ...jest.requireActual('@posthog/lemon-ui'),+ lemonToast: { success: jest.fn(), error: jest.fn() },+}))++// The send sits a few days from the real clock, so the move into the future holds on any day the test runs.+const SEND_AT = dayjs.utc().add(3, 'day').startOf('day').add(10, 'hour')+const MOVED_AT = SEND_AT.add(2, 'day')++const SCHEDULE: HogFlowScheduleApi = {+ id: 'schedule-1',+ rrule: 'FREQ=DAILY;COUNT=1',+ starts_at: SEND_AT.toISOString(),+ timezone: 'UTC',+ status: 'active',+ next_run_at: SEND_AT.toISOString(),+ created_at: SEND_AT.toISOString(),+ updated_at: SEND_AT.toISOString(),+}++const FLOW = {+ id: 'flow-1',+ name: 'October product update',+ status: 'active',+ origin_product: 'broadcasts',+ trigger: { type: 'batch' },+ actions: [{ type: 'function_email' }],+ user_access_level: 'editor',+} as unknown as HogFlowMinimalApi++describe('sendCalendarLogic', () => {+ let logic: ReturnType<typeof sendCalendarLogic.build>++ const savedStart = (): string | undefined => logic.values.scheduledFlows?.[0].schedules[0].starts_at++ const dropOnMovedDay = async (): Promise<void> => {+ const send = logic.values.sends.find((item) => item.flowId === FLOW.id)+ await expectLogic(logic, () =>+ logic.actions.moveSend(send!, MOVED_AT.format('YYYY-MM-DD'))+ ).toFinishAllListeners()+ }++ 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(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'])+ })++ afterEach(() => logic.unmount())++ // The server keeps what the last save wrote, so the check before Undo sees the moved schedule.+ const saveOnServer = (): void => {+ jest.mocked(hogFlowsSchedulesPartialUpdate).mockImplementation(async (_projectId, _id, _scheduleId, fields) => {+ const saved = { ...SCHEDULE, ...fields }+ jest.mocked(hogFlowsSchedulesList).mockResolvedValue([saved])+ return saved+ })+ }+ const TEAMMATE_EDIT = { ...SCHEDULE, rrule: 'FREQ=WEEKLY;BYDAY=TU,TH' }++ it('moves a one-time send to the day it was dropped on, and Undo moves it back', async () => {+ saveOnServer()++ await dropOnMovedDay()++ expect(hogFlowsSchedulesPartialUpdate).toHaveBeenLastCalledWith(expect.any(String), FLOW.id, SCHEDULE.id, {+ starts_at: MOVED_AT.toISOString(),+ rrule: SCHEDULE.rrule,+ })+ expect(savedStart()).toEqual(MOVED_AT.toISOString())++ const undo = jest.mocked(lemonToast.success).mock.calls[0][1]?.button?.action+ await expectLogic(logic, () => undo?.()).toFinishAllListeners()++ expect(hogFlowsSchedulesPartialUpdate).toHaveBeenLastCalledWith(expect.any(String), FLOW.id, SCHEDULE.id, {+ starts_at: SCHEDULE.starts_at,+ rrule: SCHEDULE.rrule,+ })+ expect(savedStart()).toEqual(SCHEDULE.starts_at)+ })++ it('refuses a move when a teammate changed the schedule after the calendar loaded, and reloads', async () => {+ jest.mocked(hogFlowsSchedulesList).mockResolvedValue([TEAMMATE_EDIT])++ await dropOnMovedDay()++ expect(hogFlowsSchedulesPartialUpdate).not.toHaveBeenCalled()+ expect(lemonToast.error).toHaveBeenCalledWith(+ "Couldn't move October product update. Its schedule changed after the calendar loaded. Check the reloaded calendar and try again."+ )+ expect(savedStart()).toEqual(SCHEDULE.starts_at)+ })++ it('refuses Undo when a teammate changed the schedule after the move', async () => {+ saveOnServer()+ await dropOnMovedDay()+ jest.mocked(hogFlowsSchedulesList).mockResolvedValue([TEAMMATE_EDIT])++ const undo = jest.mocked(lemonToast.success).mock.calls[0][1]?.button?.action+ await expectLogic(logic, () => undo?.()).toFinishAllListeners()++ expect(hogFlowsSchedulesPartialUpdate).toHaveBeenCalledTimes(1)+ expect(lemonToast.error).toHaveBeenCalledWith(+ "Couldn't undo the move. Its schedule changed after the calendar loaded. Check the reloaded calendar and try again."+ )+ })++ it('refuses to move a send whose time passed while the calendar was open, and reloads', async () => {+ const send = logic.values.sends.find((item) => item.flowId === FLOW.id)!+ const elapsed = { ...send, at: dayjs.utc().subtract(1, 'hour') }++ await expectLogic(logic, () => logic.actions.applyMove(elapsed, 2, MOVED_AT.toISOString())).toDispatchActions([+ 'loadScheduledFlows',+ ])++ expect(hogFlowsSchedulesPartialUpdate).not.toHaveBeenCalled()+ expect(lemonToast.error).toHaveBeenCalledWith(+ "Couldn't move October product update. This send already went out."+ )+ })++ 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.',+ })++ await dropOnMovedDay()++ expect(savedStart()).toEqual(SCHEDULE.starts_at)+ expect(lemonToast.error).toHaveBeenCalledWith(+ "Couldn't move October product update. Schedule must have at least one future occurrence."+ )+ })+})diff --git a/products/workflows/frontend/SendCalendar/sendCalendarLogic.ts b/products/workflows/frontend/SendCalendar/sendCalendarLogic.tsnew file mode 100644index 000000000000..b88b15ff266a--- /dev/null+++ b/products/workflows/frontend/SendCalendar/sendCalendarLogic.ts@@ -0,0 +1,510 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { lemonToast } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { projectLogic } from 'scenes/projectLogic'+import { teamLogic } from 'scenes/teamLogic'++import { cohortsModel } from '~/models/cohortsModel'+import type { CohortType } from '~/types'++import {+ hogFlowsBatchJobsList,+ hogFlowsList,+ hogFlowsSchedulesList,+ hogFlowsSchedulesPartialUpdate,+} from 'products/workflows/frontend/generated/api'+import type { HogFlowScheduleApi } 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,+ CalendarSend,+ CalendarSendKind,+ CalendarTypeFilter,+ CalendarView,+ ScheduledEmailFlow,+ calendarDays,+ calendarRange,+ calendarSendsForFlow,+ describeRepeat,+ dropTarget,+ groupSendsByDay,+ isScheduledEmailFlow,+ matchesTypeFilter,+ moveBlockedReason,+ movedScheduleFields,+ periodLabel,+ sendAudience,+ 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 = 8+const 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. */+async function scheduleIsCurrent(projectId: string, flowId: string, schedule: HogFlowScheduleApi): Promise<boolean> {+ const current = (await hogFlowsSchedulesList(projectId, flowId)).find((item) => item.id === schedule.id)+ return (+ !!current &&+ current.rrule === schedule.rrule &&+ dayjs(current.starts_at).isSame(schedule.starts_at) &&+ current.timezone === schedule.timezone &&+ current.status === schedule.status+ )+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface sendCalendarLogicValues {+ cohortsById: Partial<Record<number | string, CohortType>> // cohortsModel+ categories: MessageCategory[] // optOutCategoriesLogic+ currentProjectId: number | null // projectLogic+ timezone: string // teamLogic+ weekStartDay: number // teamLogic+ anchor: string | null+ anchorDate: string+ days: string[]+ loadFailed: boolean+ messageCategoryNames: Record<string, string>+ periodLabel: string+ range: CalendarRange+ savingScheduleIds: Record<string, boolean>+ scheduledFlows: ScheduledEmailFlow[] | null+ scheduledFlowsLoading: boolean+ sends: CalendarSend[]+ sendsByDay: Record<string, CalendarSend[]>+ today: string+ typeFilter: CalendarTypeFilter+ view: CalendarView+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface sendCalendarLogicActions {+ loadCohortsByIds: (args_0: { ids: number[] }) => {+ ids: number[]+ } // cohortsModel+ startNewBroadcast: () => {+ value: true+ } // newBroadcastAgentLogic+ startNewWorkflow: () => {+ value: true+ } // newWorkflowLogic+ applyMove: (+ send: CalendarSend,+ days: number,+ at: string+ ) => {+ at: string+ days: number+ send: CalendarSend+ }+ goBackward: () => {+ value: true+ }+ goForward: () => {+ value: true+ }+ goToToday: () => {+ value: true+ }+ loadScheduledFlows: () => any+ loadScheduledFlowsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadScheduledFlowsSuccess: (+ scheduledFlows: ScheduledEmailFlow[],+ payload?: any+ ) => {+ scheduledFlows: ScheduledEmailFlow[]+ payload?: any+ }+ moveSend: (+ send: CalendarSend,+ day: string+ ) => {+ day: string+ send: CalendarSend+ }+ reportSendOpened: (send: CalendarSend) => {+ send: CalendarSend+ }+ scheduleChanged: (+ flowId: string,+ schedule: HogFlowScheduleApi+ ) => {+ flowId: string+ schedule: HogFlowScheduleApi+ }+ setAnchor: (anchor: string | null) => {+ anchor: string | null+ }+ setScheduleSaving: (+ scheduleId: string,+ saving: boolean+ ) => {+ saving: boolean+ scheduleId: string+ }+ setTypeFilter: (typeFilter: CalendarTypeFilter) => {+ typeFilter: CalendarTypeFilter+ }+ setView: (view: CalendarView) => {+ view: CalendarView+ }+ startNewSend: (+ kind: CalendarSendKind,+ day: string+ ) => {+ day: string+ kind: CalendarSendKind+ }+ undoMove: (+ send: CalendarSend,+ previous: HogFlowScheduleApi,+ saved: HogFlowScheduleApi+ ) => {+ previous: HogFlowScheduleApi+ saved: HogFlowScheduleApi+ send: CalendarSend+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface sendCalendarLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ today: (timezone: string) => string+ anchorDate: (anchor: string | null, today: string) => string+ days: (view: CalendarView, anchorDate: string, weekStartDay: number) => string[]+ range: (days: string[], timezone: string) => CalendarRange+ periodLabel: (view: CalendarView, anchorDate: string, days: string[]) => string+ sends: (+ scheduledFlows: ScheduledEmailFlow[] | null,+ range: CalendarRange,+ typeFilter: CalendarTypeFilter+ ) => CalendarSend[]+ sendsByDay: (sends: CalendarSend[], timezone: string) => Record<string, CalendarSend[]>+ messageCategoryNames: (+ categories: import('products/messaging/frontend/generated/api.schemas').MessageCategoryApi[]+ ) => Record<string, string>+ }+}++export type sendCalendarLogicType = MakeLogicType<+ sendCalendarLogicValues,+ sendCalendarLogicActions,+ Record<string, any>,+ sendCalendarLogicMeta+>++export const sendCalendarLogic = kea<sendCalendarLogicType>([+ path(['products', 'workflows', 'frontend', 'SendCalendar', 'sendCalendarLogic']),+ connect(() => ({+ values: [+ projectLogic,+ ['currentProjectId'],+ teamLogic,+ ['timezone', 'weekStartDay'],+ cohortsModel,+ ['cohortsById'],+ optOutCategoriesLogic,+ ['categories'],+ ],+ actions: [+ cohortsModel,+ ['loadCohortsByIds'],+ newBroadcastAgentLogic,+ ['startNewBroadcast'],+ newWorkflowLogic,+ ['startNewWorkflow'],+ ],+ })),+ actions({+ setView: (view: CalendarView) => ({ view }),+ setTypeFilter: (typeFilter: CalendarTypeFilter) => ({ typeFilter }),+ setAnchor: (anchor: string | null) => ({ anchor }),+ goToToday: true,+ goForward: true,+ goBackward: true,+ reportSendOpened: (send: CalendarSend) => ({ send }),+ startNewSend: (kind: CalendarSendKind, day: string) => ({ kind, day }),+ moveSend: (send: CalendarSend, day: string) => ({ send, day }),+ applyMove: (send: CalendarSend, days: number, at: string) => ({ send, days, at }),+ undoMove: (send: CalendarSend, previous: HogFlowScheduleApi, saved: HogFlowScheduleApi) => ({+ send,+ previous,+ saved,+ }),+ scheduleChanged: (flowId: string, schedule: HogFlowScheduleApi) => ({ flowId, schedule }),+ setScheduleSaving: (scheduleId: string, saving: boolean) => ({ scheduleId, saving }),+ }),+ loaders(({ values }) => ({+ scheduledFlows: [+ null as ScheduledEmailFlow[] | 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)+ }+ return loaded+ },+ },+ ],+ })),+ reducers({+ view: ['month' as CalendarView, { setView: (_, { view }) => view }],+ typeFilter: ['all' as CalendarTypeFilter, { setTypeFilter: (_, { typeFilter }) => typeFilter }],+ // Null follows today. A date pins the period that the person moved to.+ anchor: [+ null as string | null,+ {+ setAnchor: (_, { anchor }) => anchor,+ goToToday: () => null,+ },+ ],+ loadFailed: [+ false,+ {+ loadScheduledFlows: () => false,+ loadScheduledFlowsFailure: () => true,+ },+ ],+ 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,+ },+ savingScheduleIds: [+ {} as Record<string, boolean>,+ { setScheduleSaving: (state, { scheduleId, saving }) => ({ ...state, [scheduleId]: saving }) },+ ],+ }),+ selectors({+ today: [(s) => [s.timezone], (timezone: string): string => dayjs().tz(timezone).format('YYYY-MM-DD')],+ anchorDate: [(s) => [s.anchor, s.today], (anchor: string | null, today: string): string => anchor ?? today],+ days: [+ (s) => [s.view, s.anchorDate, s.weekStartDay],+ (view: CalendarView, anchorDate: string, weekStartDay: number): string[] =>+ calendarDays(view, anchorDate, weekStartDay),+ ],+ range: [+ (s) => [s.days, s.timezone],+ (days: string[], timezone: string): CalendarRange => calendarRange(days, timezone),+ ],+ periodLabel: [+ (s) => [s.view, s.anchorDate, s.days],+ (view: CalendarView, anchorDate: string, days: string[]): string => periodLabel(view, anchorDate, days),+ ],+ sends: [+ (s) => [s.scheduledFlows, s.range, s.typeFilter],+ (+ scheduledFlows: ScheduledEmailFlow[] | null,+ range: CalendarRange,+ typeFilter: CalendarTypeFilter+ ): CalendarSend[] => {+ const now = dayjs()+ return (scheduledFlows ?? [])+ .filter((item) => matchesTypeFilter(item.flow, typeFilter))+ .flatMap((item) => calendarSendsForFlow(item, range, now))+ },+ ],+ sendsByDay: [+ (s) => [s.sends, s.timezone],+ (sends: CalendarSend[], timezone: string): Record<string, CalendarSend[]> =>+ groupSendsByDay(sends, timezone),+ ],+ messageCategoryNames: [+ (s) => [s.categories],+ (categories: MessageCategory[]): Record<string, string> =>+ Object.fromEntries(categories.map((category) => [category.id, category.name])),+ ],+ }),+ listeners(({ actions, values }) => ({+ moveSend: ({ send, day }) => {+ const target = dropTarget(send, day, values.timezone, dayjs())+ if (!target) {+ return+ }+ if (!send.isRecurring) {+ actions.applyMove(send, target.days, target.at.toISOString())+ return+ }+ const distance = `${Math.abs(target.days)} ${Math.abs(target.days) === 1 ? 'day' : 'days'}`+ LemonDialog.open({+ title: 'Move every future send?',+ description: `${send.name} repeats. This moves every future send ${target.days > 0 ? 'later' : 'earlier'} by ${distance}.`,+ primaryButton: {+ children: 'Move all future sends',+ onClick: () => actions.applyMove(send, target.days, target.at.toISOString()),+ 'data-attr': 'send-calendar-move-series',+ },+ secondaryButton: { children: 'Cancel' },+ })+ },+ applyMove: async ({ send, days, at }) => {+ const previous = send.schedule+ if (!previous) {+ return+ }+ // The calendar loads once, so a send can look planned after it went out. Saving a move then would+ // send it again, so check now and reload to show what really happened.+ const blockedReason = moveBlockedReason(send, dayjs())+ if (blockedReason) {+ lemonToast.error(`Couldn't move ${send.name}. ${blockedReason}`)+ actions.loadScheduledFlows()+ return+ }+ actions.setScheduleSaving(previous.id, true)+ try {+ if (!(await scheduleIsCurrent(String(values.currentProjectId), send.flowId, previous))) {+ lemonToast.error(`Couldn't move ${send.name}. ${SCHEDULE_CHANGED}`)+ actions.loadScheduledFlows()+ return+ }+ const fields = movedScheduleFields(previous, days, dayjs())+ // Show the move at once, and put the schedule back if the server rejects it.+ actions.scheduleChanged(send.flowId, { ...previous, ...fields, next_run_at: null })+ const saved = await hogFlowsSchedulesPartialUpdate(+ String(values.currentProjectId),+ send.flowId,+ previous.id,+ fields+ )+ actions.scheduleChanged(send.flowId, saved)+ // pinned: analytics event name+ posthog.capture('send rescheduled', {+ kind: send.kind,+ is_recurring: send.isRecurring,+ days_moved: days,+ source: 'drag',+ })+ const repeat = describeRepeat(fields)+ const message = send.isRecurring+ ? `Moved ${send.name}. It now sends ${repeat.charAt(0).toLowerCase()}${repeat.slice(1)}.`+ : `Moved ${send.name} to ${dayjs(at).tz(values.timezone).format('ddd, MMM D [at] h:mm A')}.`+ lemonToast.success(message, {+ button: {+ label: 'Undo',+ action: () => actions.undoMove(send, previous, saved),+ dataAttr: 'send-calendar-undo',+ },+ })+ } catch (error) {+ actions.scheduleChanged(send.flowId, previous)+ const detail = (error as { detail?: string } | null)?.detail+ lemonToast.error(`Couldn't move ${send.name}. ${detail ?? 'Try again.'}`)+ } finally {+ actions.setScheduleSaving(previous.id, false)+ }+ },+ undoMove: async ({ send, previous, saved: moved }) => {+ actions.setScheduleSaving(previous.id, true)+ try {+ if (!(await scheduleIsCurrent(String(values.currentProjectId), send.flowId, moved))) {+ lemonToast.error(`Couldn't undo the move. ${SCHEDULE_CHANGED}`)+ actions.loadScheduledFlows()+ return+ }+ const saved = await hogFlowsSchedulesPartialUpdate(+ String(values.currentProjectId),+ send.flowId,+ previous.id,+ { starts_at: previous.starts_at, rrule: previous.rrule }+ )+ actions.scheduleChanged(send.flowId, saved)+ // pinned: analytics event name+ posthog.capture('send reschedule undone', { kind: send.kind, is_recurring: send.isRecurring })+ lemonToast.success(`Moved ${send.name} back.`)+ } catch {+ lemonToast.error(`Couldn't undo the move. Open ${send.name} to check its schedule.`)+ } finally {+ actions.setScheduleSaving(previous.id, false)+ }+ },+ goForward: () => actions.setAnchor(shiftAnchor(values.view, values.anchorDate, 1)),+ 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))]+ 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,+ })+ },+ setView: ({ view }) => {+ // pinned: analytics event name+ posthog.capture('send calendar viewed', {+ view,+ scheduled_flows: values.scheduledFlows?.length ?? 0,+ sends_in_range: values.sends.length,+ })+ },+ startNewSend: ({ kind, day }) => {+ // pinned: analytics event name+ posthog.capture('send calendar new send started', {+ kind,+ days_from_today: dayjs.utc(day).diff(dayjs.utc(values.today), 'day'),+ })+ if (kind === 'broadcast') {+ actions.startNewBroadcast()+ } else {+ actions.startNewWorkflow()+ }+ },+ reportSendOpened: ({ send }) => {+ // pinned: analytics event name+ posthog.capture('send calendar send opened', {+ kind: send.kind,+ state: send.state,+ is_recurring: send.isRecurring,+ })+ },+ })),+ afterMount(({ actions }) => {+ actions.loadScheduledFlows()+ }),+])diff --git a/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.ts b/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.tsnew file mode 100644index 000000000000..b98b297d4059--- /dev/null+++ b/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.ts@@ -0,0 +1,301 @@+import { dayjs } from 'lib/dayjs'++import type {+ HogFlowBatchJobApi,+ HogFlowMinimalApi,+ HogFlowScheduleApi,+} from 'products/workflows/frontend/generated/api.schemas'++import {+ CalendarSend,+ calendarDays,+ calendarRange,+ calendarSendsForFlow,+ describeRepeat,+ dropTarget,+ isScheduledEmailFlow,+ moveBlockedReason,+ movedScheduleFields,+ periodLabel,+ scheduleSendTimes,+ 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,+ status: HogFlowScheduleApi['status'] = 'active',+ timezone = 'Europe/London'+): HogFlowScheduleApi => ({+ id: `schedule-${rrule}-${status}`,+ rrule,+ starts_at,+ timezone,+ status,+ next_run_at: null,+ created_at: starts_at,+ 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 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 }++ it.each([+ [+ 'a broadcast that filters on a cohort and a person property',+ { type: 'batch', filters: { properties: [COHORT_FILTER, EMAIL_IS_SET] } },+ [EMAIL_STEP],+ { 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],+ { 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],+ { 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]' } } } } },+ },+ ],+ { 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)+ })++ it.each([+ [+ 'keeps a weekly send at 09:00 local time across the DST change on Oct 25',+ schedule('FREQ=WEEKLY;BYDAY=TU', '2026-09-01T08:00:00Z'),+ ['2026-10-20T08:00:00.000Z', '2026-10-27T09:00:00.000Z'],+ ],+ [+ 'returns a one-time send inside the range',+ schedule('FREQ=DAILY;COUNT=1', '2026-10-21T10:00:00Z'),+ ['2026-10-21T10:00:00.000Z'],+ ],+ [+ 'returns nothing for a one-time send outside the range',+ schedule('FREQ=DAILY;COUNT=1', '2026-11-05T10:00:00Z'),+ [],+ ],+ ])('%s', (_, value, expected) => {+ expect(scheduleSendTimes(value, LONDON_OCT_19_TO_NOV_1).map((time) => time.toISOString())).toEqual(expected)+ })++ 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,+ 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: [+ job('sent', 'completed', '2026-10-20T08:00:05Z'),+ job('failed', 'failed', '2026-10-19T09:00:00Z'),+ job('outside', 'completed', '2026-10-05T08:00:00Z'),+ ],+ },+ LONDON_OCT_19_TO_NOV_1,+ dayjs('2026-10-21T12:00:00Z')+ )++ expect(sends.map(({ state, at, repeat }) => [state, at.toISOString(), repeat])).toEqual([+ ['planned', '2026-10-27T09:00:00.000Z', 'Every week on Tuesday'],+ ['paused', '2026-10-23T15:00:00.000Z', 'Every week on Friday'],+ ['paused', '2026-10-30T16:00:00.000Z', 'Every week on Friday'],+ ['sent', '2026-10-20T08:00:05.000Z', null],+ ['failed', '2026-10-19T09:00:00.000Z', null],+ ])+ })++ it.each([+ ['a month that starts on Monday weeks', 'month', '2026-10-16', 1, '2026-09-28', 35],+ ['a month that starts on Sunday weeks', 'month', '2026-10-16', 0, '2026-09-27', 35],+ ['a week around its anchor day', 'week', '2026-10-21', 1, '2026-10-19', 7],+ ] as const)('lays out %s', (_, view, anchor, weekStartDay, firstDay, length) => {+ const days = calendarDays(view, anchor, weekStartDay)++ expect([days[0], days.length]).toEqual([firstDay, length])+ })++ it.each([+ ['a month', 'month', '2026-10-16', 'October 2026'],+ ['a week inside one month', 'week', '2026-10-21', 'Oct 19 to 25, 2026'],+ ['a week across two months', 'week', '2026-09-30', 'Sep 28 to Oct 4, 2026'],+ ] as const)('labels %s', (_, view, anchor, expected) => {+ expect(periodLabel(view, anchor, calendarDays(view, anchor, 1))).toBe(expected)+ })++ it.each([+ ['a one-time send', 'FREQ=DAILY;COUNT=1', 'Once'],+ ['a weekly send', 'FREQ=WEEKLY;BYDAY=TU', 'Every week on Tuesday'],+ ['an hourly send from the API', 'FREQ=HOURLY', 'Every hour'],+ ['a monthly send on a set date', 'FREQ=MONTHLY;BYMONTHDAY=15', 'Every month on the 15th'],+ ])('describes the repeat rule of %s', (_, rrule, expected) => {+ expect(describeRepeat({ rrule, starts_at: '2026-09-01T08:00:00Z' })).toBe(expected)+ })++ const NOW = dayjs('2026-10-16T12:00:00Z')++ const plannedSend = (rrule: string, overrides: Partial<CalendarSend> = {}): CalendarSend =>+ ({+ state: 'planned',+ at: dayjs('2026-10-20T10:00:00Z'),+ schedule: schedule(rrule, '2026-10-20T10:00:00Z', 'active', 'UTC'),+ userAccessLevel: 'editor',+ ...overrides,+ }) as CalendarSend++ it.each([+ ['a one-time send', plannedSend('FREQ=DAILY;COUNT=1'), null],+ ['a weekly send', plannedSend('FREQ=WEEKLY;BYDAY=TU'), null],+ [+ 'a send that already went out',+ plannedSend('FREQ=DAILY;COUNT=1', { state: 'sent', schedule: null }),+ 'This send already went out.',+ ],+ [+ 'a paused schedule',+ plannedSend('FREQ=WEEKLY;BYDAY=TU', { state: 'paused' }),+ 'This schedule is paused. Open it to schedule it again.',+ ],+ [+ 'a send whose time passed while the calendar was open',+ plannedSend('FREQ=DAILY;COUNT=1', { at: dayjs('2026-10-16T09:00:00Z') }),+ 'This send already went out.',+ ],+ [+ 'an hourly send from the API',+ plannedSend('FREQ=HOURLY'),+ 'Open the schedule to move a send that repeats this way.',+ ],+ ['a send that repeats every 2 weeks', plannedSend('FREQ=WEEKLY;INTERVAL=2;BYDAY=TH'), null],+ [+ 'a send that repeats every 2 weeks on two weekdays',+ plannedSend('FREQ=WEEKLY;INTERVAL=2;BYDAY=TU,FR'),+ 'Open the schedule to move a send that repeats this way.',+ ],+ [+ 'a send that the person can only view',+ plannedSend('FREQ=DAILY;COUNT=1', { userAccessLevel: 'viewer' }),+ expect.any(String),+ ],+ ])('decides whether %s can move', (_, send, expected) => {+ expect(moveBlockedReason(send, NOW)).toEqual(expected)+ })++ it.each([+ ['the same day', '2026-10-20', null],+ ['a day in the past', '2026-10-14', null],+ ['a later day', '2026-10-22', { days: 2, at: '2026-10-22T10:00:00.000Z' }],+ ])('drops a send on %s', (_, day, expected) => {+ const send = {+ at: dayjs('2026-10-20T10:00:00Z'),+ schedule: schedule('FREQ=DAILY;COUNT=1', '2026-10-20T10:00:00Z', 'active', 'UTC'),+ }+ const target = dropTarget(send, day, 'UTC', dayjs('2026-10-16T12:00:00Z'))++ expect(target && { days: target.days, at: target.at.toISOString() }).toEqual(expected)+ })++ it.each([+ [+ 'keeps the local time of a one-time send across the DST change',+ schedule('FREQ=DAILY;COUNT=1', '2026-10-23T15:00:00Z'),+ 3,+ { starts_at: '2026-10-26T16:00:00.000Z', rrule: 'FREQ=DAILY;COUNT=1' },+ ],+ [+ 'moves the weekday of a weekly send',+ schedule('FREQ=WEEKLY;BYDAY=TU', '2026-09-01T09:00:00Z', 'active', 'UTC'),+ 1,+ { starts_at: '2026-09-02T09:00:00.000Z', rrule: 'FREQ=WEEKLY;INTERVAL=1;BYDAY=WE' },+ ],+ [+ 'wraps a weekday past the end of the week',+ schedule('FREQ=WEEKLY;BYDAY=SU', '2026-09-06T09:00:00Z', 'active', 'UTC'),+ 1,+ { starts_at: '2026-09-07T09:00:00.000Z', rrule: 'FREQ=WEEKLY;INTERVAL=1;BYDAY=MO' },+ ],+ [+ 'keeps the interval of a send that repeats every 2 weeks',+ schedule('FREQ=WEEKLY;INTERVAL=2;BYDAY=TU', '2026-09-01T16:00:00Z', 'active', 'UTC'),+ 2,+ { starts_at: '2026-09-03T16:00:00.000Z', rrule: 'FREQ=WEEKLY;INTERVAL=2;BYDAY=TH' },+ ],+ ])('%s', (_, value, days, expected) => {+ expect(movedScheduleFields(value, days, dayjs('2026-08-31T00:00:00Z'))).toEqual(expected)+ })++ it.each([+ [+ 'a series that ends after a count keeps only the sends left',+ schedule('FREQ=WEEKLY;BYDAY=TU;COUNT=10', '2026-09-01T09:00:00Z', 'active', 'UTC'),+ { starts_at: '2026-10-21T09:00:00.000Z', rrule: 'FREQ=WEEKLY;INTERVAL=1;BYDAY=WE;COUNT=3' },+ ],+ [+ 'a series that ends on a date keeps its last send',+ schedule('FREQ=WEEKLY;BYDAY=TU;UNTIL=20261124T235959Z', '2026-10-20T09:00:00Z', 'active', 'UTC'),+ {+ starts_at: '2026-10-21T09:00:00.000Z',+ rrule: 'FREQ=WEEKLY;INTERVAL=1;BYDAY=WE;UNTIL=20261125T235959Z',+ },+ ],+ [+ 'a one-time send that names a weekday becomes a plain one-time send',+ schedule('FREQ=WEEKLY;BYDAY=TU;COUNT=1', '2026-10-20T09:00:00Z', 'active', 'UTC'),+ { starts_at: '2026-10-21T09:00:00.000Z', rrule: 'FREQ=DAILY;COUNT=1' },+ ],+ ])('moves %s', (_, value, expected) => {+ expect(movedScheduleFields(value, 1, NOW)).toEqual(expected)+ })++ it('starts a moved weekly send from its next send, so no past send comes back', () => {+ const weekly = schedule('FREQ=WEEKLY;BYDAY=TU', '2026-09-01T09:00:00Z', 'active', 'UTC')++ expect(movedScheduleFields(weekly, 6, NOW)).toEqual({+ starts_at: '2026-10-26T09:00:00.000Z',+ rrule: 'FREQ=WEEKLY;INTERVAL=1;BYDAY=MO',+ })+ })+})diff --git a/products/workflows/frontend/SendCalendar/sendCalendarUtils.ts b/products/workflows/frontend/SendCalendar/sendCalendarUtils.tsnew file mode 100644index 000000000000..4614c1cebd07--- /dev/null+++ b/products/workflows/frontend/SendCalendar/sendCalendarUtils.ts@@ -0,0 +1,388 @@+import { RRule } from 'rrule'++import { dayjs } from 'lib/dayjs'++import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'++import type {+ HogFlowBatchJobApi,+ HogFlowMinimalApi,+ HogFlowScheduleApi,+ UserBasicApi,+} from 'products/workflows/frontend/generated/api.schemas'++import { audienceCohortIds } from '../Broadcasts/audience/audienceList'+import { manageDisabledReason } from '../Broadcasts/broadcastLifecycle'+import {+ fakeUtcToReal,+ ONE_TIME_RRULE,+ isOneTimeSchedule,+ parseRRuleToState,+ 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: string+ flowId: string+ name: string+ kind: CalendarSendKind+ state: CalendarSendState+ at: dayjs.Dayjs+ /** "Once" or the repeat rule. Null for a run without a schedule, such as a broadcast sent right away. */+ repeat: string | null+ isRecurring: boolean+ createdBy: UserBasicApi | null+ /** The schedule behind a planned or paused send. Null for a past run. */+ schedule: HogFlowScheduleApi | null+ userAccessLevel: string | null+ audience: SendAudience+ category: SendCategory+}++/** Who the sends of a flow go to. */+export interface SendAudience {+ /** The cohorts that the audience filters on, once each. */+ cohortIds: number[]+ /** The other audience filters, such as person properties. */+ filters: AnyPropertyFilter[]+ /** True when the flow runs once for each matching account, not for each person. */+ accounts: boolean+ /** The "To" address of the email. Only a schedule trigger uses it, because that trigger has no audience. */+ 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+ end: dayjs.Dayjs+}++// The server allows one run per hour at most, so one schedule can put about 1,000 sends in a 6-week grid.+// 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 }+ }+ const properties = trigger.filters?.properties ?? []+ // 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.NotIn+ return {+ cohortIds: audienceCohortIds(properties.filter(isCohortInclusion)),+ filters: properties.filter((filter) => !isCohortInclusion(filter)),+ accounts: trigger.filters?.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'>,+ filter: CalendarTypeFilter+): boolean {+ if (filter === 'all') {+ return true+ }+ return (flow.origin_product === 'broadcasts') === (filter === 'broadcasts')+}++/** A rule in one spelling, so two spellings of the same rule compare equal. The start date is not part of it. */+function normalizedRule(rrule: string): string | null {+ try {+ const { dtstart: _dtstart, ...options } = RRule.parseString(rrule)+ const text = new RRule({ ...options, interval: options.interval ?? 1 }).toString().replace('RRULE:', '')+ return text.split(';').sort().join(';')+ } catch {+ return null+ }+}++/** Whether the schedule editor can hold the rule. Other rules, such as hourly ones from the API, come back changed. */+function fitsScheduleEditor(schedule: Pick<HogFlowScheduleApi, 'rrule' | 'starts_at'>): boolean {+ const original = normalizedRule(schedule.rrule)+ return (+ original !== null &&+ normalizedRule(stateToRRule(parseRRuleToState(schedule.rrule), schedule.starts_at)) === original+ )+}++export function describeRepeat(schedule: Pick<HogFlowScheduleApi, 'rrule' | 'starts_at'>): string {+ if (isOneTimeSchedule(schedule.rrule)) {+ return 'Once'+ }+ const text = fitsScheduleEditor(schedule)+ ? scheduleToText(parseRRuleToState(schedule.rrule), schedule.starts_at)+ : normalizedRule(schedule.rrule) !== null+ ? new RRule(RRule.parseString(schedule.rrule)).toText()+ : ''+ return text ? text.charAt(0).toUpperCase() + text.slice(1) : 'Repeats'+}++/** The send times of a schedule inside a range, as real moments. */+export function scheduleSendTimes(+ schedule: Pick<HogFlowScheduleApi, 'rrule' | 'starts_at' | 'timezone'>,+ range: CalendarRange+): dayjs.Dayjs[] {+ const timezone = schedule.timezone || 'UTC'+ // RRule expands dates in "fake UTC": the UTC fields hold the wall-clock time in the schedule time+ // zone. That keeps a 09:00 send at 09:00 local time across a DST change, as the scheduler does.+ const toFakeUtc = (time: dayjs.Dayjs): Date => {+ const local = time.tz(timezone)+ return new Date(+ Date.UTC(local.year(), local.month(), local.date(), local.hour(), local.minute(), local.second())+ )+ }+ try {+ const rule = new RRule({ ...RRule.parseString(schedule.rrule), dtstart: toFakeUtc(dayjs(schedule.starts_at)) })+ return rule+ .between(toFakeUtc(range.start), toFakeUtc(range.end), true, (_, index) => index < MAX_SENDS_PER_SCHEDULE)+ .map((date) => fakeUtcToReal(date, timezone))+ .filter((time) => !time.isBefore(range.start) && time.isBefore(range.end))+ } catch {+ return []+ }+}++export function calendarSendsForFlow(+ { flow, schedules, batchJobs }: ScheduledEmailFlow,+ range: CalendarRange,+ now: dayjs.Dayjs+): CalendarSend[] {+ const base = {+ flowId: flow.id,+ name: flow.name || 'Untitled',+ kind: (flow.origin_product === 'broadcasts' ? 'broadcast' : 'workflow') as CalendarSendKind,+ createdBy: flow.created_by ?? null,+ userAccessLevel: flow.user_access_level ?? null,+ audience: sendAudience(flow),+ category: sendCategory(flow),+ }+ 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) {+ if (schedule.status === 'completed') {+ continue+ }+ const repeat = describeRepeat(schedule)+ const isRecurring = !isOneTimeSchedule(schedule.rrule)+ for (const at of scheduleSendTimes(schedule, future)) {+ sends.push({+ ...base,+ key: `${schedule.id}:${at.valueOf()}`,+ state: schedule.status === 'paused' ? 'paused' : 'planned',+ at,+ repeat,+ isRecurring,+ schedule,+ })+ }+ }+ }+ for (const job of batchJobs) {+ const at = dayjs(job.created_at)+ if (at.isBefore(range.start) || !at.isBefore(range.end)) {+ continue+ }+ sends.push({+ ...base,+ key: job.id,+ state: batchJobState(job.status),+ at,+ repeat: null,+ isRecurring: false,+ schedule: null,+ })+ }+ return sends+}++function batchJobState(status: HogFlowBatchJobApi['status']): CalendarSendState {+ if (status === 'completed') {+ return 'sent'+ }+ if (status === 'failed' || status === 'cancelled') {+ return 'failed'+ }+ return 'sending'+}++/** Why a send cannot move with drag and drop, or null when it can. */+export function moveBlockedReason(+ send: Pick<CalendarSend, 'state' | 'schedule' | 'userAccessLevel' | 'at'>,+ now: dayjs.Dayjs = dayjs()+): string | null {+ // The calendar loads once, so a send can show as planned after its time passed. Moving it would send it again.+ if (send.state === 'sent' || send.state === 'failed' || !send.at.isAfter(now)) {+ return 'This send already went out.'+ }+ if (send.state === 'sending') {+ return 'This send is in progress.'+ }+ if (send.state === 'paused' || !send.schedule) {+ return 'This schedule is paused. Open it to schedule it again.'+ }+ const accessReason = manageDisabledReason(send.userAccessLevel)+ if (accessReason) {+ return accessReason+ }+ if (!isOneTimeSchedule(send.schedule.rrule)) {+ if (!fitsScheduleEditor(send.schedule)) {+ return 'Open the schedule to move a send that repeats this way.'+ }+ const state = parseRRuleToState(send.schedule.rrule)+ // Shifting the weekdays keeps a weekly cadence. Other repeat rules have no single shift that keeps+ // their pattern, for example "the last day of the month". Every N weeks keeps its pattern only with+ // one weekday: with two, a shift across the week start moves one of them into the skipped week.+ if (state.frequency !== 'weekly' || (state.interval !== 1 && state.weekdays.length !== 1)) {+ return 'Open the schedule to move a send that repeats this way.'+ }+ }+ return null+}++/** Moves a time by whole calendar days, so it keeps its wall-clock time in the time zone across a DST change. */+function shiftDays(time: dayjs.Dayjs, days: number, timezone: string): dayjs.Dayjs {+ const local = time.tz(timezone)+ const date = dayjs.utc(local.format('YYYY-MM-DD')).add(days, 'day').format('YYYY-MM-DD')+ return dayjs.tz(`${date} ${local.format('HH:mm:ss')}`, timezone)+}++/** Where a send lands when someone drops it on a day, or null when that day cannot take it. */+export function dropTarget(+ send: Pick<CalendarSend, 'at' | 'schedule'>,+ day: string,+ timezone: string,+ now: dayjs.Dayjs+): { days: number; at: dayjs.Dayjs } | null {+ const days = dayjs.utc(day).diff(dayjs.utc(send.at.tz(timezone).format('YYYY-MM-DD')), 'day')+ if (days === 0 || !send.schedule) {+ return null+ }+ const at = shiftDays(send.at, days, send.schedule.timezone || 'UTC')+ return at.isAfter(now) ? { days, at } : null+}++/** The schedule fields that move every future send of a schedule by a number of days. */+export function movedScheduleFields(+ schedule: Pick<HogFlowScheduleApi, 'rrule' | 'starts_at' | 'timezone'>,+ days: number,+ now: dayjs.Dayjs = dayjs()+): { starts_at: string; rrule: string } {+ const timezone = schedule.timezone || 'UTC'+ const startsAt = dayjs(schedule.starts_at)+ if (isOneTimeSchedule(schedule.rrule)) {+ // A one-time rule can still name a weekday, which would move the send off the target day. Save the send+ // as a plain one-time rule at the time it actually goes out, shifted.+ const sendsAt = scheduleSendTimes(schedule, { start: startsAt, end: startsAt.add(1, 'year') })[0] ?? startsAt+ return { starts_at: shiftDays(sendsAt, days, timezone).toISOString(), rrule: ONE_TIME_RRULE }+ }+ // Start the shifted rule at the next send. Shifting the original start instead can bring a past send back+ // into the future, so the next send lands on the wrong day.+ const nextSend =+ scheduleSendTimes(schedule, { start: now, end: now.add(1, 'year') })[0] ?? dayjs(schedule.starts_at)+ const starts_at = shiftDays(nextSend, days, timezone).toISOString()+ const state = parseRRuleToState(schedule.rrule)+ const weekdays = state.weekdays.map((weekday) => (((weekday + days) % 7) + 7) % 7)+ // The shifted rule starts at the next send, so a series that ends after a count keeps only the sends left.+ const endCount =+ state.endType === 'after_count'+ ? Math.max(1, state.endCount - scheduleSendTimes(schedule, { start: startsAt, end: now }).length)+ : state.endCount+ // The end date moves with the sends, or the last send falls after it. stateToRRule reads the date in the+ // browser time zone, so pass a plain date, not the UTC instant from parseRRuleToState.+ const endDate = state.endDate ? dayjs.utc(state.endDate).add(days, 'day').format('YYYY-MM-DD') : null+ return { starts_at, rrule: stateToRRule({ ...state, weekdays, endCount, endDate }, starts_at) }+}++/** The days that the grid shows, as YYYY-MM-DD. A month view starts and ends on full weeks. */+export function calendarDays(view: CalendarView, anchor: string, weekStartDay: number): string[] {+ // Calendar dates have no time zone, so the arithmetic runs in UTC, where every day has 24 hours.+ const anchorDay = dayjs.utc(anchor)+ const first = view === 'month' ? anchorDay.startOf('month') : anchorDay+ const offset = (first.day() - weekStartDay + 7) % 7+ const gridStart = first.subtract(offset, 'day')+ const length = view === 'week' ? 7 : Math.ceil((offset + first.daysInMonth()) / 7) * 7+ return Array.from({ length }, (_, index) => gridStart.add(index, 'day').format('YYYY-MM-DD'))+}++export function calendarRange(days: string[], timezone: string): CalendarRange {+ const dayAfterLast = dayjs+ .utc(days[days.length - 1])+ .add(1, 'day')+ .format('YYYY-MM-DD')+ return { start: dayjs.tz(days[0], timezone), end: dayjs.tz(dayAfterLast, timezone) }+}++export function shiftAnchor(view: CalendarView, anchor: string, direction: 1 | -1): string {+ return dayjs.utc(anchor).add(direction, view).format('YYYY-MM-DD')+}++export function periodLabel(view: CalendarView, anchor: string, days: string[]): string {+ if (view === 'month') {+ return dayjs.utc(anchor).format('MMMM YYYY')+ }+ const first = dayjs.utc(days[0])+ const last = dayjs.utc(days[days.length - 1])+ if (first.year() !== last.year()) {+ return `${first.format('MMM D, YYYY')} to ${last.format('MMM D, YYYY')}`+ }+ if (first.month() !== last.month()) {+ return `${first.format('MMM D')} to ${last.format('MMM D, YYYY')}`+ }+ return `${first.format('MMM D')} to ${last.format('D, YYYY')}`+}++export function groupSendsByDay(sends: CalendarSend[], timezone: string): Record<string, CalendarSend[]> {+ const byDay: Record<string, CalendarSend[]> = {}+ for (const send of [...sends].sort((a, b) => a.at.valueOf() - b.at.valueOf())) {+ const day = send.at.tz(timezone).format('YYYY-MM-DD')+ ;(byDay[day] ??= []).push(send)+ }+ return byDay+}diff --git a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.test.tsx b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.test.tsxindex e23fd2ae56d2..273212b4b864 100644--- a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.test.tsx+++ b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.test.tsx@@ -39,6 +39,37 @@ describe('workflowActivityDescriber', () => {expect(text).toContain('updated actions')})+ const ONE_TIME_OCT_20 = {+ rrule: 'FREQ=DAILY;COUNT=1',+ starts_at: '2026-10-20T10:00:00+00:00',+ timezone: 'Europe/London',+ }+ const ONE_TIME_OCT_22 = { ...ONE_TIME_OCT_20, starts_at: '2026-10-22T10:00:00+00:00' }+ const WEEKLY = { rrule: 'FREQ=WEEKLY;BYDAY=TU', starts_at: '2026-09-01T09:00:00+00:00', timezone: 'UTC' }++ it.each([+ [+ 'moved',+ 'changed',+ ONE_TIME_OCT_20,+ ONE_TIME_OCT_22,+ 'moved a schedule from Oct 20, 2026 at 11:00 AM (Europe/London) to Oct 22, 2026 at 11:00 AM (Europe/London)',+ ],+ ['added', 'created', null, WEEKLY, 'added a schedule: every week on Tuesday at 9:00 AM (UTC)'],+ ['removed', 'deleted', WEEKLY, null, 'removed a schedule: every week on Tuesday at 9:00 AM (UTC)'],+ ])('describes a schedule that was %s', (_label, action, before, after, expected) => {+ const scheduleChange = {+ type: ActivityScope.HOG_FLOW,+ action,+ field: 'schedule',+ before,+ after,+ } as ActivityChange+ const text = getTextContent(workflowActivityDescriber(workflowLogItem([scheduleChange])))++ expect(text).toContain(expected)+ })+it('still diffs individual items when both sides really are arrays', () => {const text = getTextContent(workflowActivityDescriber(diff --git a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsxindex 0716e758367f..0f04e0e70c16 100644--- a/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx+++ b/products/workflows/frontend/Workflows/misc/workflowActivityDescriber.tsx@@ -7,9 +7,13 @@ import {defaultDescriber,} from 'lib/components/ActivityLog/humanizeActivity'import { SentenceList } from 'lib/components/ActivityLog/SentenceList'+import { dayjs } from 'lib/dayjs'import { Link } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'+import { describeRepeat } from '../../SendCalendar/sendCalendarUtils'+import { isOneTimeSchedule } from '../hogflows/steps/components/rrule-helpers'+const nameOrLinkToWorkflow = (id?: string | null, name?: string | null): string | JSX.Element => {const displayName = name || '(empty string)'return id ? <Link to={urls.workflow(id, 'workflow')}>{displayName}</Link> : displayName@@ -103,6 +107,49 @@ function describeWorkflowItems(change: ActivityChange, itemType: 'action' | 'var)}+interface ScheduleTiming {+ rrule: string+ starts_at: string+ timezone: string+}++function describeScheduleTiming(timing: ScheduleTiming): string {+ const start = dayjs(timing.starts_at).tz(timing.timezone || 'UTC')+ if (isOneTimeSchedule(timing.rrule)) {+ return `${start.format('MMM D, YYYY [at] h:mm A')} (${timing.timezone})`+ }+ const repeat = describeRepeat(timing)+ return `${repeat.charAt(0).toLowerCase()}${repeat.slice(1)} at ${start.format('h:mm A')} (${timing.timezone})`+}++function describeScheduleChange(change: ActivityChange): JSX.Element {+ const before = change.before as ScheduleTiming | null+ const after = change.after as ScheduleTiming | null+ if (change.action === 'created' && after) {+ return (+ <>+ added a schedule: <strong>{describeScheduleTiming(after)}</strong>+ </>+ )+ }+ if (change.action === 'deleted' && before) {+ return (+ <>+ removed a schedule: <strong>{describeScheduleTiming(before)}</strong>+ </>+ )+ }+ if (before && after) {+ return (+ <>+ moved a schedule from <strong>{describeScheduleTiming(before)}</strong> to{' '}+ <strong>{describeScheduleTiming(after)}</strong>+ </>+ )+ }+ return <>updated a schedule</>+}+function describeWorkflowField(change: ActivityChange): JSX.Element[] {switch (change.field) {case 'name':@@ -119,6 +166,8 @@ function describeWorkflowField(change: ActivityChange): JSX.Element[] {return describeWorkflowItems(change, 'action')case 'variables':return describeWorkflowItems(change, 'variable')+ case 'schedule':+ return [describeScheduleChange(change)]default:return [<>updated {change.field}</>]}diff --git a/products/workflows/frontend/WorkflowsScene.tsx b/products/workflows/frontend/WorkflowsScene.tsxindex 21b2bdd49139..b1f1be94c822 100644--- a/products/workflows/frontend/WorkflowsScene.tsx+++ b/products/workflows/frontend/WorkflowsScene.tsx@@ -4,6 +4,7 @@ import { router, urlToAction } from 'kea-router'import { LemonButton } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'@@ -23,6 +24,8 @@ import { workflowsEmptyState } from './emptyState/workflowsEmptyState'import { MessagingSetup } from './MessagingSetup'import { MessagingTabActions } from './MessagingTabActions'import { isMessagingSetupTab } from './messagingTabs'+import { SendCalendar } from './SendCalendar/SendCalendar'+import { SendCalendarTabLabel } from './SendCalendar/SendCalendarTabLabel'import { MessagingSetupTabLabel } from './setupGuide/MessagingSetupTabLabel'import { WorkflowsOnboardingWizard } from './setupGuide/wizard/WorkflowsOnboardingWizard'import { newWorkflowLogic } from './Workflows/newWorkflowLogic'@@ -36,6 +39,7 @@ import { WorkflowsTemplates } from './WorkflowsTemplates'// pinned: URL path segments under /workflows - renaming breaks bookmarksconst WORKFLOW_SCENE_TABS = ['workflows',+ 'calendar','templates','library','channels',@@ -62,6 +66,7 @@ export interface workflowsSceneLogicValues {export interface workflowsSceneLogicActions {setCurrentTab: (tab: WorkflowsSceneTab) => {tab:+ | 'calendar'| 'channels'| 'library'| 'onboarding'@@ -80,6 +85,7 @@ export interface workflowsSceneLogicMeta {logicProps: (arg: any) => anybreadcrumbs: (currentTab:+ | 'calendar'| 'channels'| 'library'| 'onboarding'@@ -165,9 +171,12 @@ export const scene: SceneExport<WorkflowsSceneProps> = {emptyState: workflowsEmptyState,}-type WorkflowsTopTab = 'workflows' | 'templates' | 'messaging-setup'+type WorkflowsTopTab = 'workflows' | 'calendar' | 'templates' | 'messaging-setup'function topTabFor(tab: WorkflowsSceneTab): WorkflowsTopTab {+ if (tab === 'calendar') {+ return 'calendar'+ }if (tab === 'templates' || tab === 'library') {return 'templates'}@@ -179,6 +188,7 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {const { startNewWorkflow } = useActions(newWorkflowLogic)const { setTypeFilter } = useActions(workflowTemplatesLogic)const { filters } = useValues(workflowsLogic)+ const showCalendar = useFeatureFlag('WORKFLOWS_SEND_CALENDAR')const workflowsTab = {label: 'Workflows',@@ -186,7 +196,7 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {content: <WorkflowsTable />,link: urls.workflows(),}- const showsNewWorkflowButton = currentTab === 'workflows' || currentTab === 'templates'+ const showsNewWorkflowButton = currentTab === 'workflows' || currentTab === 'templates' || currentTab === 'calendar'if (currentTab === 'onboarding') {return (@@ -232,7 +242,7 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {</LemonButton></AccessControlAction>)}- {currentTab !== 'workflows' && currentTab !== 'templates' && (+ {currentTab !== 'workflows' && currentTab !== 'templates' && currentTab !== 'calendar' && (<MessagingTabActions tab={currentTab} channelsUrl={urls.workflows('channels')} />)}</>@@ -240,9 +250,17 @@ export function WorkflowsScene(props: WorkflowsSceneProps = {}): JSX.Element {/><EmailSuspensionBanner /><LemonTabs<WorkflowsTopTab>- activeKey={topTabFor(currentTab)}+ activeKey={currentTab === 'calendar' && !showCalendar ? 'workflows' : topTabFor(currentTab)}tabs={[workflowsTab,+ showCalendar+ ? {+ label: <SendCalendarTabLabel />,+ key: 'calendar',+ link: urls.workflows('calendar'),+ content: <SendCalendar />,+ }+ : null,{label: 'Templates',key: 'templates',diff --git a/products/workflows/manifest.tsx b/products/workflows/manifest.tsxindex 542faf180567..4e4b6c24f0e7 100644--- a/products/workflows/manifest.tsx+++ b/products/workflows/manifest.tsx@@ -63,6 +63,7 @@ export const manifest: ProductManifest = {'/broadcasts/suppression': ['Broadcasts', 'broadcasts'],'/broadcasts/reputation': ['Broadcasts', 'broadcasts'],'/broadcasts/settings': ['Broadcasts', 'broadcasts'],+ '/broadcasts/calendar': ['Broadcasts', 'broadcasts'],// kea-router matches in declaration order, so the literal 'new' comes before ':id'.'/broadcasts/new': ['Broadcast', 'broadcast'],'/broadcasts/:id': ['Broadcast', 'broadcast'],@@ -76,7 +77,7 @@ export const manifest: ProductManifest = {workflowsLibraryTemplateNew: (): string => '/workflows/library/templates/new',workflowsLibraryTemplateFromMessage: (id?: string): string =>`/workflows/library/templates/new?messageId=${id}`,- broadcasts: (tab?: MessagingNavTabKey): string => `/broadcasts${tab ? `/${tab}` : ''}`,+ broadcasts: (tab?: MessagingNavTabKey | 'calendar'): string => `/broadcasts${tab ? `/${tab}` : ''}`,broadcast: (id: string): string => `/broadcasts/${id}`,broadcastNew: (): string => '/broadcasts/new',},diff --git a/products/workflows/package.json b/products/workflows/package.jsonindex f4cfe23cb6f7..3e76fa6fd78c 100644--- a/products/workflows/package.json+++ b/products/workflows/package.json@@ -25,6 +25,7 @@"kea-test-utils": "catalog:"},"peerDependencies": {+ "@dnd-kit/core": "*","@posthog/brand": "catalog:","@posthog/icons": "catalog:","@types/react": "*",