: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): pick a broadcast send day on the send calendar (#118503)
Meikel Ratz0ebfb79ed625
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7d8a542fdfb4..9f2122a4b4f2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8258,10 +8258,14 @@ snapshots:hash: v1.k794b7964.0df0c80ba3b1e4f56a9ca297d55adb4b6cd5c58aa7968e638c55b01e25eda308.jBDSsX-jXLcOHSDudHiI18nzeBKTH_XUJ4UxHnmx7qwproducts-workflows-send-calendar--nothing-scheduled--light:hash: v1.k794b7964.f962c9fb4ae9bd548a4f110e3230649791194c60409c13575dbdd33d9f11324f.dalGC0qyruSRv__DR2AYm8X1wGM_YCGpMPpYxmkhBhQ+ products-workflows-send-calendar--send-day-picker-crowded--dark:+ hash: v1.k794b7964.7c5cd6152ce884e204cfb1550ed96023edc09a8aa54d26bdd0182701f5f4d6bf.uH8YLjLwNQFNI98fNc7Tat9s4unEDMu04Z3cwpcM0do+ products-workflows-send-calendar--send-day-picker-crowded--light:+ hash: v1.k794b7964.7514379d0334e3a9a137d70cb76d60bcdc274238d414c1780196dabe9a80ca69.fhfYlxxUSSbPHgNugpncNnE6dH58GN5k9khYpg2Flugproducts-workflows-send-calendar--send-details--dark:- hash: v1.k794b7964.4e302efcdf3bbe84471a1db8de00985e0137bdf4e412e1a9bd11767b902bab45.9SLKWqpXIRSSN_LgMQrrlfxdesKpYm6vdX2DpwP2nmQ+ hash: v1.k794b7964.28e7325599a166ebdde2cc8eab6dabb0d7ba3b5e5df913d1b76fb2224a229c87.nRQXprg32aKQzMAzy-J8DfQk1LQRLCm3X84TteNCQqEproducts-workflows-send-calendar--send-details--light:- hash: v1.k794b7964.a4ebf0a739215b12953d9c17ec9b0cfa7f09251da07043ebc9117a8ac61cbeb4.SWCmephcDTdKIK5x2P0Li8lIQ1p8rYU4kqdEiQI0T_k+ hash: v1.k794b7964.1a0cb5668e8c2fe73218b2118faf1c85638177e2d39cc4f2977773113c69d707.6hib0IE0LtK1kv-uHDyU10IVnyAa1PZqkwVNyrH_SDYproducts-workflows-steps-customer-task-reference-input--account--dark:hash: v1.k794b7964.884dda5b1415d9a041c053804964a19d7a9adb2b28edc1797a9cbed8f5dc6782.YXjfbjz9Kxh9TbLWc8Dai7nySVQz9UByZVxWqopauE8products-workflows-steps-customer-task-reference-input--account--light:diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsxindex dc9b2e70d83f..231cf09e43ba 100644--- a/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsx+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastScheduleStep.tsx@@ -4,10 +4,12 @@ import { useMemo } from 'react'import { LemonCalendarSelectInput, LemonSearchableSelect } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonRadio } from 'lib/lemon-ui/LemonRadio'import { timeZoneLabel } from 'lib/utils/timezones'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { SendDayPicker } from '../../SendCalendar/SendDayPicker'import { EmailSendingRateLimitPicker } from '../../Workflows/hogflows/steps/components/EmailSendingRateLimitPicker'import { RecurringSchedulePicker } from '../../Workflows/hogflows/steps/components/RecurringSchedulePicker'import { broadcastWizardLogic } from '../broadcastWizardLogic'@@ -63,6 +65,7 @@ export function BroadcastScheduleStep(): JSX.Element {setRecurringRepeating,setScheduleTimezone,} = useActions(broadcastWizardLogic)+ const showSendCalendar = useFeatureFlag('WORKFLOWS_SEND_CALENDAR')return (<div className="flex flex-col gap-4">@@ -106,6 +109,8 @@ export function BroadcastScheduleStep(): JSX.Element {</div>)}+ {scheduleMode === 'later' && showSendCalendar ? <SendDayPicker /> : null}+{scheduleMode === 'recurring' && (<div className="max-w-160"><RecurringSchedulePickerdiff --git a/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsx b/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsxindex 4ca56ace78d6..754634fac50f 100644--- a/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsx+++ b/products/workflows/frontend/SendCalendar/SendCalendar.stories.tsx@@ -1,11 +1,12 @@import { Meta, StoryFn } from '@storybook/react'-import { useActions, useMountedLogic } from 'kea'+import { BindLogic, 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 { AnyPropertyFilter } from '~/types'import type { MessageCategoryApi } from 'products/messaging/frontend/generated/api.schemas'import type {@@ -15,10 +16,12 @@ import type {UserBasicApi,} from 'products/workflows/frontend/generated/api.schemas'+import { broadcastWizardLogic } from '../Broadcasts/broadcastWizardLogic'import { SendCalendar } from './SendCalendar'import { sendCalendarLogic } from './sendCalendarLogic'import { SendCalendarSendDetails } from './SendCalendarSendDetails'-import { CalendarSend, describeRepeat, sendAudience } from './sendCalendarUtils'+import { CalendarSend, describeRepeat, scheduleSendTimes, sendAudience } from './sendCalendarUtils'+import { SendDayPicker } from './SendDayPicker'const meta: Meta<typeof SendCalendar> = {title: 'Products/Workflows/Send calendar',@@ -260,7 +263,10 @@ const detailsSend = (item: SendCalendarFlowApi): CalendarSend => {name: item.name ?? '',kind: item.origin_product === 'broadcasts' ? 'broadcast' : 'workflow',state: 'planned',- at: dayjs(itemSchedule.starts_at),+ // The calendar shows each send at its next occurrence, not at the schedule's first one.+ at:+ scheduleSendTimes(itemSchedule, { start: dayjs(), end: dayjs().add(1, 'year') })[0] ??+ dayjs(itemSchedule.starts_at),repeat: describeRepeat(itemSchedule),isRecurring: itemSchedule.rrule !== 'FREQ=DAILY;COUNT=1',createdBy: item.created_by,@@ -287,3 +293,33 @@ export const SendDetails: StoryFn = () => {SendDetails.parameters = {testOptions: { waitForLoadersToDisappear: true, waitForSelector: '[data-attr=send-calendar-audience]' },}++function SendDayPickerFor({ sendAt }: { sendAt: string }): JSX.Element {+ const props = { id: 'new' }+ const { prefillFromLink, setScheduleMode, setSendAt } = useActions(broadcastWizardLogic(props))+ useEffect(() => {+ // A link prefill sets the audience without the recipient count that the audience picker starts.+ prefillFromLink({ properties: [inCohort(21)] as unknown as AnyPropertyFilter[] })+ setScheduleMode('later')+ setSendAt(sendAt)+ }, [prefillFromLink, setScheduleMode, setSendAt, sendAt])+ return (+ <BindLogic logic={broadcastWizardLogic} props={props}>+ <div className="w-[60rem]">+ <SendDayPicker />+ </div>+ </BindLogic>+ )+}++// A broadcast to a cohort that two other sends on the same day also reach, so the picker suggests another day.+export const SendDayPickerCrowded: StoryFn = () => {+ useCalendarMocks(FLOWS)+ return <SendDayPickerFor sendAt="2026-10-20T10:00:00.000Z" />+}+SendDayPickerCrowded.parameters = {+ testOptions: {+ waitForLoadersToDisappear: true,+ waitForSelector: '[data-attr=send-day-picker-use-suggestion] >> visible=true',+ },+}diff --git a/products/workflows/frontend/SendCalendar/SendDayPicker.tsx b/products/workflows/frontend/SendCalendar/SendDayPicker.tsxnew file mode 100644index 000000000000..0cb3e56eb6ee--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendDayPicker.tsx@@ -0,0 +1,189 @@+import clsx from 'clsx'+import { useActions, useMountedLogic, useValues } from 'kea'++import * as mailboxPng from '@posthog/brand/hoggies/png/mailbox'+import { IconChevronLeft, IconChevronRight } from '@posthog/icons'+import { LemonButton, LemonTag } from '@posthog/lemon-ui'++import { pngHoggie } from 'lib/brand/hoggies'+import { dayjs } from 'lib/dayjs'+import { Tooltip } from 'lib/lemon-ui/Tooltip'++import { broadcastWizardLogic } from '../Broadcasts/broadcastWizardLogic'+import { SendCalendarSendLabel } from './SendCalendarSendLabel'+import { SendDayPickerLegend } from './SendDayPickerLegend'+import { sendDayPickerLogic } from './sendDayPickerLogic'+import { SendDayPickerStatus } from './SendDayPickerStatus'+import { describeRule } from './sendSpacing'++const MAX_SENDS_PER_DAY = 2+const MAX_DOTS_PER_DAY = 6++const HedgehogMailbox = pngHoggie(mailboxPng)++export function SendDayPicker(): JSX.Element {+ const { props } = useMountedLogic(broadcastWizardLogic)+ const logic = sendDayPickerLogic(props)+ const {+ days,+ anchorDate,+ today,+ sendsByDay,+ countingKeys,+ crowdedDays,+ selectedDay,+ suggestion,+ rule,+ isTransactional,+ effectiveTimezone,+ sendAt,+ } = useValues(logic)+ const { pickDay, goForward, goBackward } = useActions(logic)+ const month = anchorDate.slice(0, 7)+ const suggestedDay = suggestion?.tz(effectiveTimezone).format('YYYY-MM-DD') ?? null++ return (+ <div className="@container flex max-w-240 flex-col gap-2" data-attr="send-day-picker">+ <SendDayPickerStatus />+ <div className="overflow-hidden rounded border bg-surface-primary">+ <div className="flex items-center gap-1 border-b px-2 py-1">+ <LemonButton+ size="xsmall"+ icon={<IconChevronLeft />}+ onClick={goBackward}+ tooltip="Previous month"+ data-attr="send-day-picker-previous"+ />+ <LemonButton+ size="xsmall"+ icon={<IconChevronRight />}+ onClick={goForward}+ tooltip="Next month"+ data-attr="send-day-picker-next"+ />+ <span className="ml-1 text-sm font-semibold">{dayjs.utc(anchorDate).format('MMMM YYYY')}</span>+ </div>+ <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 grid-cols-7">+ {days.map((day, index) => {+ const sends = sendsByDay[day] ?? []+ const isPast = day < today+ const crowded = !isTransactional && !isPast && crowdedDays[day]+ const suggested = !isPast && day === suggestedDay && day !== selectedDay+ return (+ <Tooltip+ key={day}+ title={+ crowded+ ? `A send at this time gives some people more than ${describeRule(rule)}.`+ : undefined+ }+ >+ <button+ type="button"+ disabled={isPast}+ aria-pressed={day === selectedDay}+ onClick={() => pickDay(day)}+ className={clsx(+ 'relative flex min-h-16 min-w-0 flex-col gap-0.5 p-1 text-left @min-[44rem]:min-h-20',+ index % 7 !== 6 && 'border-r',+ index < days.length - 7 && 'border-b',+ !day.startsWith(month) && !crowded && 'bg-surface-secondary',+ crowded && 'bg-warning-highlight',+ isPast && 'cursor-not-allowed opacity-50',+ !isPast && day !== selectedDay && 'cursor-pointer hover:bg-fill-highlight-100',+ suggested && 'outline-2 -outline-offset-4 outline-dashed outline-success',+ day === selectedDay && 'bg-primary-highlight ring-2 ring-inset ring-accent'+ )}+ data-attr="send-day-picker-day"+ >+ <span className="flex items-center justify-between gap-1 px-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(dayjs.utc(day).date() === 1 ? 'MMM D' : 'D')}+ </span>+ {suggested ? (+ <LemonTag+ type="success"+ size="small"+ className="hidden @min-[44rem]:inline-flex"+ >+ Suggested+ </LemonTag>+ ) : null}+ </span>+ {day === selectedDay && sendAt ? (+ <span className="px-1 text-xs font-semibold text-accent">+ {dayjs(sendAt).tz(effectiveTimezone).format('h:mm A')}+ </span>+ ) : null}+ {/* Names need room. A narrow picker shows one dot for each send. */}+ <span className="flex flex-wrap gap-0.5 px-1 @min-[44rem]:hidden">+ {sends.slice(0, MAX_DOTS_PER_DAY).map((send) => (+ <span+ key={send.key}+ className={clsx(+ 'size-2 rounded-full',+ send.kind === 'broadcast'+ ? 'bg-accent'+ : 'bg-[var(--color-product-workflows-light)]',+ !countingKeys[send.key] && 'opacity-40'+ )}+ />+ ))}+ {sends.length > MAX_DOTS_PER_DAY ? (+ <span className="text-xs leading-2 text-secondary">+ +{sends.length - MAX_DOTS_PER_DAY}+ </span>+ ) : null}+ </span>+ <span className="hidden min-w-0 flex-col gap-0.5 @min-[44rem]:flex">+ {sends.slice(0, MAX_SENDS_PER_DAY).map((send) => (+ <span+ key={send.key}+ className={clsx(+ 'min-w-0 overflow-hidden px-1 text-xs',+ !countingKeys[send.key] && 'opacity-40'+ )}+ >+ <SendCalendarSendLabel send={send} timezone={effectiveTimezone} />+ </span>+ ))}+ {sends.length > MAX_SENDS_PER_DAY ? (+ <span className="px-1 text-xs text-secondary">+ +{sends.length - MAX_SENDS_PER_DAY} more+ </span>+ ) : null}+ </span>+ {suggested ? (+ <HedgehogMailbox+ size="2.25rem"+ loading="eager"+ className="pointer-events-none absolute right-1.5 bottom-1.5"+ />+ ) : null}+ </button>+ </Tooltip>+ )+ })}+ </div>+ </div>+ <SendDayPickerLegend />+ <div className="text-xs text-secondary">+ {rule.fromCap+ ? `The rule comes from your frequency cap: ${describeRule(rule)}.`+ : `No frequency cap is set, so the rule is ${describeRule(rule)}.`}+ </div>+ </div>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendDayPickerLegend.tsx b/products/workflows/frontend/SendCalendar/SendDayPickerLegend.tsxnew file mode 100644index 000000000000..2876b30e8787--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendDayPickerLegend.tsx@@ -0,0 +1,17 @@+export function SendDayPickerLegend(): JSX.Element {+ return (+ <div+ className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-secondary"+ data-attr="send-day-picker-legend"+ >+ <span className="flex items-center gap-1">+ <span className="size-3 shrink-0 rounded-sm border bg-warning-highlight" />+ Too close to other sends+ </span>+ <span className="flex items-center gap-1">+ <span className="size-3 shrink-0 rounded-sm border-2 border-dashed border-success" />+ Suggested+ </span>+ </div>+ )+}diff --git a/products/workflows/frontend/SendCalendar/SendDayPickerStatus.tsx b/products/workflows/frontend/SendCalendar/SendDayPickerStatus.tsxnew file mode 100644index 000000000000..0795ec4c2c27--- /dev/null+++ b/products/workflows/frontend/SendCalendar/SendDayPickerStatus.tsx@@ -0,0 +1,88 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { Spinner } from 'lib/lemon-ui/Spinner'++import { broadcastWizardLogic } from '../Broadcasts/broadcastWizardLogic'+import { sendDayPickerLogic } from './sendDayPickerLogic'+import { SUGGESTION_HORIZON_DAYS, describeRule } from './sendSpacing'++export function SendDayPickerStatus(): JSX.Element {+ const { props } = useMountedLogic(broadcastWizardLogic)+ const {+ scheduledFlows,+ loadFailed,+ sendAt,+ selectedCrowding,+ suggestion,+ rule,+ isTransactional,+ effectiveTimezone,+ } = useValues(sendDayPickerLogic(props))+ const { applySuggestion, loadScheduledFlows } = useActions(sendDayPickerLogic(props))++ if (loadFailed) {+ return (+ <LemonBanner+ type="error"+ action={{+ children: 'Retry',+ onClick: () => loadScheduledFlows(),+ 'data-attr': 'send-day-picker-retry-load',+ }}+ >+ Couldn't load your other sends, so we can't check this day against them. You can still pick a day.+ </LemonBanner>+ )+ }+ if (!scheduledFlows) {+ return (+ <div className="flex items-center gap-2 text-sm text-secondary">+ <Spinner /> Checking your other sends…+ </div>+ )+ }+ if (isTransactional) {+ return (+ <LemonBanner type="info">+ Transactional emails don't count toward the frequency cap, so any day works.+ </LemonBanner>+ )+ }+ if (sendAt && !selectedCrowding.length) {+ return <LemonBanner type="success">This time stays within {describeRule(rule)}.</LemonBanner>+ }++ const suggestionLabel = suggestion?.tz(effectiveTimezone).format('ddd, MMM D [at] h:mm A')+ const action = suggestion+ ? {+ children: 'Use this day',+ onClick: applySuggestion,+ 'data-attr': 'send-day-picker-use-suggestion',+ }+ : undefined+ const suggestionText = suggestion ? (+ <>+ The first day that keeps to {describeRule(rule)} is <strong>{suggestionLabel}</strong>.+ </>+ ) : (+ <>+ No day in the next {SUGGESTION_HORIZON_DAYS} days keeps to {describeRule(rule)}.+ </>+ )++ if (sendAt) {+ const names = [...new Set(selectedCrowding.map((send) => send.name))].join(', ')+ return (+ <LemonBanner type="warning" action={action}>+ Some people in this audience also get {names} within {rule.windowDays}{' '}+ {rule.windowDays === 1 ? 'day' : 'days'}. {suggestionText}+ </LemonBanner>+ )+ }+ return (+ <LemonBanner type="info" action={action}>+ {suggestionText}+ </LemonBanner>+ )+}diff --git a/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.ts b/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.tsindex 4c7d5a325ce4..626569352e69 100644--- a/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.ts+++ b/products/workflows/frontend/SendCalendar/sendCalendarUtils.test.ts@@ -12,12 +12,14 @@ import {calendarRange,calendarSendsForFlow,describeRepeat,+ mergeCalendarFlows,dropTarget,moveBlockedReason,movedScheduleFields,periodLabel,scheduleSendTimes,sendAudience,+ splitRange,} from './sendCalendarUtils'const schedule = (@@ -278,4 +280,32 @@ describe('sendCalendarUtils', () => {rrule: 'FREQ=WEEKLY;INTERVAL=1;BYDAY=MO',})})++ it('splits a long range into pieces the endpoint accepts', () => {+ const start = dayjs.utc('2026-09-01')+ const pieces = splitRange({ start, end: start.add(121, 'day') }, 92)++ expect(pieces.map((piece) => [piece.start.toISOString(), piece.end.toISOString()])).toEqual([+ ['2026-09-01T00:00:00.000Z', '2026-12-02T00:00:00.000Z'],+ ['2026-12-02T00:00:00.000Z', '2026-12-31T00:00:00.000Z'],+ ])+ })++ it('joins the runs of a flow that two range pieces returned', () => {+ const run = (id: string): SendCalendarBatchJobApi => ({ id }) as SendCalendarBatchJobApi+ const piece = (runs: SendCalendarBatchJobApi[]): SendCalendarFlowApi =>+ ({ id: 'flow-1', batch_jobs: runs }) as unknown as SendCalendarFlowApi++ const merged = mergeCalendarFlows([[piece([run('a'), run('b')])], [piece([run('b'), run('c')])]])++ expect(merged.map((flow) => flow.batch_jobs.map((job) => job.id))).toEqual([['a', 'b', 'c']])+ })++ it('counts every send of an hourly schedule when given a higher limit', () => {+ const hourly = { rrule: 'FREQ=HOURLY', starts_at: '2026-10-01T00:00:00Z', timezone: 'UTC' }+ const range = { start: dayjs.utc('2026-10-01'), end: dayjs.utc('2026-10-31') }++ expect(scheduleSendTimes(hourly, range)).toHaveLength(200)+ expect(scheduleSendTimes(hourly, range, 5000)).toHaveLength(720)+ })})diff --git a/products/workflows/frontend/SendCalendar/sendCalendarUtils.ts b/products/workflows/frontend/SendCalendar/sendCalendarUtils.tsindex 7be135141650..422a43fcfb8f 100644--- a/products/workflows/frontend/SendCalendar/sendCalendarUtils.ts+++ b/products/workflows/frontend/SendCalendar/sendCalendarUtils.ts@@ -74,14 +74,20 @@ export function sendAudience(if (flow.trigger_type !== 'batch') {return { cohortIds: [], filters: [], accounts: false, address: flow.email_to || null }}- const properties = flow.audience_properties as unknown as AnyPropertyFilter[]- // An excluded cohort is not a recipient list, so it stays a filter with its operator.+ return audienceFromProperties(+ flow.audience_properties as unknown as AnyPropertyFilter[],+ flow.audience_type === 'accounts'+ )+}++export function audienceFromProperties(properties: AnyPropertyFilter[], accounts = false): SendAudience {+ // An excluded cohort says nothing about who else the audience reaches, so it counts like any other filter.const isCohortInclusion = (filter: AnyPropertyFilter): boolean =>filter.type === PropertyFilterType.Cohort && filter.operator !== PropertyOperator.NotInreturn {cohortIds: audienceCohortIds(properties.filter(isCohortInclusion)),filters: properties.filter((filter) => !isCohortInclusion(filter)),- accounts: flow.audience_type === 'accounts',+ accounts,address: null,}}@@ -131,7 +137,8 @@ export function describeRepeat(schedule: Pick<HogFlowScheduleApi, 'rrule' | 'sta/** The send times of a schedule inside a range, as real moments. */export function scheduleSendTimes(schedule: Pick<HogFlowScheduleApi, 'rrule' | 'starts_at' | 'timezone'>,- range: CalendarRange+ range: CalendarRange,+ maxSends: number = MAX_SENDS_PER_SCHEDULE): 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@@ -145,7 +152,7 @@ export function scheduleSendTimes(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)+ .between(toFakeUtc(range.start), toFakeUtc(range.end), true, (_, index) => index < maxSends).map((date) => fakeUtcToReal(date, timezone)).filter((time) => !time.isBefore(range.start) && time.isBefore(range.end))} catch {@@ -156,7 +163,8 @@ export function scheduleSendTimes(export function calendarSendsForFlow(flow: SendCalendarFlowApi,range: CalendarRange,- now: dayjs.Dayjs+ now: dayjs.Dayjs,+ maxSendsPerSchedule: number = MAX_SENDS_PER_SCHEDULE): CalendarSend[] {const base = {flowId: flow.id,@@ -178,7 +186,7 @@ export function calendarSendsForFlow(}const repeat = describeRepeat(schedule)const isRecurring = !isOneTimeSchedule(schedule.rrule)- for (const at of scheduleSendTimes(schedule, future)) {+ for (const at of scheduleSendTimes(schedule, future, maxSendsPerSchedule)) {sends.push({...base,key: `${schedule.id}:${at.valueOf()}`,@@ -353,3 +361,33 @@ export function groupSendsByDay(sends: CalendarSend[], timezone: string): Record}return byDay}++/** Splits a range into consecutive pieces of at most `maxDays`, for an endpoint that limits the range it takes. */+export function splitRange(range: CalendarRange, maxDays: number): CalendarRange[] {+ const pieces: CalendarRange[] = []+ let start = range.start+ while (start.isBefore(range.end)) {+ const end = start.add(maxDays, 'day').isBefore(range.end) ? start.add(maxDays, 'day') : range.end+ pieces.push({ start, end })+ start = end+ }+ return pieces+}++/** Joins the flows of several range loads. A flow shows up in each piece, with only the runs of that piece. */+export function mergeCalendarFlows(loads: SendCalendarFlowApi[][]): SendCalendarFlowApi[] {+ const byId = new Map<string, SendCalendarFlowApi>()+ for (const flow of loads.flat()) {+ const known = byId.get(flow.id)+ if (!known) {+ byId.set(flow.id, flow)+ continue+ }+ const runIds = new Set(known.batch_jobs.map((run) => run.id))+ byId.set(flow.id, {+ ...known,+ batch_jobs: [...known.batch_jobs, ...flow.batch_jobs.filter((run) => !runIds.has(run.id))],+ })+ }+ return [...byId.values()]+}diff --git a/products/workflows/frontend/SendCalendar/sendDayPickerLogic.ts b/products/workflows/frontend/SendCalendar/sendDayPickerLogic.tsnew file mode 100644index 000000000000..122e4e7f8335--- /dev/null+++ b/products/workflows/frontend/SendCalendar/sendDayPickerLogic.ts@@ -0,0 +1,415 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'+import posthog from 'posthog-js'++import { dayjs } from 'lib/dayjs'+import { projectLogic } from 'scenes/projectLogic'+import { teamLogic } from 'scenes/teamLogic'++import { AnyPropertyFilter, TeamPublicType, TeamType } from '~/types'++import { hogFlowsSendCalendarRetrieve } from 'products/workflows/frontend/generated/api'+import type { SendCalendarFlowApi } from 'products/workflows/frontend/generated/api.schemas'++import {+ BroadcastEmailSettings,+ BroadcastWizardLogicProps,+ broadcastWizardLogic,+} from '../Broadcasts/broadcastWizardLogic'+import {+ CalendarRange,+ CalendarSend,+ SendAudience,+ audienceFromProperties,+ calendarDays,+ calendarRange,+ calendarSendsForFlow,+ mergeCalendarFlows,+ sendAudience,+ splitRange,+ groupSendsByDay,+ shiftAnchor,+} from './sendCalendarUtils'+import {+ SUGGESTION_HORIZON_DAYS,+ SendingRule,+ countsTowardRule,+ crowdingSends,+ sendingRule,+ suggestSendTime,+ timeOnDay,+} from './sendSpacing'++// The time of day that the picker uses until the person picks a time.+const DEFAULT_TIME_OF_DAY = '10:00:00'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface sendDayPickerLogicValues {+ audienceProperties: AnyPropertyFilter[] // broadcastWizardLogic+ effectiveTimezone: string // broadcastWizardLogic+ emailSettings: BroadcastEmailSettings // broadcastWizardLogic+ sendAt: string | null // broadcastWizardLogic+ currentProjectId: number | null // projectLogic+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ weekStartDay: number // teamLogic+ anchor: string | null+ anchorDate: string+ countingKeys: Record<string, boolean>+ countingSends: CalendarSend[]+ crowdedDays: Record<string, boolean>+ days: string[]+ draftAudience: SendAudience+ isTransactional: boolean+ loadFailed: boolean+ loadRange: CalendarRange+ otherFlows: SendCalendarFlowApi[]+ otherSends: CalendarSend[]+ rule: SendingRule+ scheduledFlows: SendCalendarFlowApi[] | null+ scheduledFlowsLoading: boolean+ selectedCrowding: CalendarSend[]+ selectedDay: string | null+ sendsByDay: Record<string, CalendarSend[]>+ suggestion: dayjs.Dayjs | null+ timeOfDay: string+ today: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface sendDayPickerLogicActions {+ setSendAt: (sendAt: string | null) => {+ sendAt: string | null+ } // broadcastWizardLogic+ applySuggestion: () => {+ value: true+ }+ goBackward: () => {+ value: true+ }+ goForward: () => {+ value: true+ }+ loadScheduledFlows: (_: void) => void+ loadScheduledFlowsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadScheduledFlowsSuccess: (+ scheduledFlows: SendCalendarFlowApi[],+ payload?: void+ ) => {+ scheduledFlows: SendCalendarFlowApi[]+ payload?: void+ }+ pickDay: (day: string) => {+ day: string+ }+ setAnchor: (anchor: string | null) => {+ anchor: string | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface sendDayPickerLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ rule: (currentTeam: TeamPublicType | TeamType | null) => SendingRule+ isTransactional: (emailSettings: BroadcastEmailSettings) => boolean+ draftAudience: (audienceProperties: AnyPropertyFilter[]) => SendAudience+ timeOfDay: (sendAt: string | null, effectiveTimezone: string) => string+ today: (effectiveTimezone: string) => string+ selectedDay: (sendAt: string | null, effectiveTimezone: string) => string | null+ anchorDate: (anchor: string | null, selectedDay: string | null, today: string) => string+ days: (anchorDate: string, weekStartDay: number) => string[]+ loadRange: (days: string[], effectiveTimezone: string, rule: SendingRule) => CalendarRange+ otherFlows: (scheduledFlows: SendCalendarFlowApi[] | null, id: string) => SendCalendarFlowApi[]+ otherSends: (otherFlows: SendCalendarFlowApi[], days: string[], effectiveTimezone: string) => CalendarSend[]+ countingSends: (+ otherFlows: SendCalendarFlowApi[],+ loadRange: CalendarRange,+ draftAudience: SendAudience,+ isTransactional: boolean+ ) => CalendarSend[]+ countingKeys: (+ otherSends: CalendarSend[],+ draftAudience: SendAudience,+ isTransactional: boolean+ ) => Record<string, boolean>+ sendsByDay: (otherSends: CalendarSend[], effectiveTimezone: string) => Record<string, CalendarSend[]>+ crowdedDays: (+ days: string[],+ countingSends: CalendarSend[],+ timeOfDay: string,+ effectiveTimezone: string,+ rule: SendingRule+ ) => Record<string, boolean>+ selectedCrowding: (sendAt: string | null, countingSends: CalendarSend[], rule: SendingRule) => CalendarSend[]+ suggestion: (+ countingSends: CalendarSend[],+ timeOfDay: string,+ effectiveTimezone: string,+ rule: SendingRule,+ isTransactional: boolean+ ) => dayjs.Dayjs | null+ }+}++export type sendDayPickerLogicType = MakeLogicType<+ sendDayPickerLogicValues,+ sendDayPickerLogicActions,+ BroadcastWizardLogicProps,+ sendDayPickerLogicMeta+>++// Kept in step with SEND_CALENDAR_MAX_RANGE_DAYS on the server, which rejects longer ranges.+const SEND_CALENDAR_MAX_RANGE_DAYS = 92+// The calendar shows 200 sends of a schedule at most, but the cap counts every send. An hourly schedule over+// the whole range of the picker stays below this.+const MAX_COUNTED_SENDS_PER_SCHEDULE = 5000++export const sendDayPickerLogic = kea<sendDayPickerLogicType>([+ props({} as BroadcastWizardLogicProps),+ key((props) => props.id),+ path((key) => ['products', 'workflows', 'frontend', 'SendCalendar', 'sendDayPickerLogic', key]),+ connect((props: BroadcastWizardLogicProps) => ({+ values: [+ teamLogic,+ ['currentTeam', 'weekStartDay'],+ projectLogic,+ ['currentProjectId'],+ broadcastWizardLogic(props),+ ['sendAt', 'effectiveTimezone', 'audienceProperties', 'emailSettings'],+ ],+ actions: [broadcastWizardLogic(props), ['setSendAt']],+ })),+ actions({+ setAnchor: (anchor: string | null) => ({ anchor }),+ goForward: true,+ goBackward: true,+ pickDay: (day: string) => ({ day }),+ applySuggestion: true,+ }),+ loaders(({ values }) => ({+ scheduledFlows: [+ null as SendCalendarFlowApi[] | null,+ {+ loadScheduledFlows: async (_: void, breakpoint) => {+ let flows: SendCalendarFlowApi[]+ try {+ // The range runs past the endpoint's limit, so it loads in pieces.+ const loads = await Promise.all(+ splitRange(values.loadRange, SEND_CALENDAR_MAX_RANGE_DAYS).map((piece) =>+ hogFlowsSendCalendarRetrieve(String(values.currentProjectId), {+ start: piece.start.toISOString(),+ end: piece.end.toISOString(),+ })+ )+ )+ flows = mergeCalendarFlows(loads)+ } catch (error) {+ // A failed request for a month the person already left must not show the error.+ breakpoint()+ throw error+ }+ breakpoint()+ return flows+ },+ },+ ],+ })),+ reducers({+ // Null follows the picked day, or today. A date pins the month that the person moved to.+ anchor: [null as string | null, { setAnchor: (_, { anchor }) => anchor }],+ loadFailed: [+ false,+ {+ loadScheduledFlows: () => false,+ loadScheduledFlowsFailure: () => true,+ },+ ],+ }),+ selectors({+ rule: [+ (s) => [s.currentTeam],+ (currentTeam: TeamPublicType | TeamType | null): SendingRule =>+ sendingRule(currentTeam && 'workflows_config' in currentTeam ? currentTeam.workflows_config : null),+ ],+ isTransactional: [+ (s) => [s.emailSettings],+ (emailSettings: BroadcastEmailSettings): boolean => emailSettings.messageCategoryType === 'transactional',+ ],+ draftAudience: [+ (s) => [s.audienceProperties],+ (audienceProperties: AnyPropertyFilter[]): SendAudience => audienceFromProperties(audienceProperties),+ ],+ timeOfDay: [+ (s) => [s.sendAt, s.effectiveTimezone],+ (sendAt: string | null, timezone: string): string =>+ sendAt ? dayjs(sendAt).tz(timezone).format('HH:mm:ss') : DEFAULT_TIME_OF_DAY,+ ],+ today: [(s) => [s.effectiveTimezone], (timezone: string): string => dayjs().tz(timezone).format('YYYY-MM-DD')],+ selectedDay: [+ (s) => [s.sendAt, s.effectiveTimezone],+ (sendAt: string | null, timezone: string): string | null =>+ sendAt ? dayjs(sendAt).tz(timezone).format('YYYY-MM-DD') : null,+ ],+ anchorDate: [+ (s) => [s.anchor, s.selectedDay, s.today],+ (anchor: string | null, selectedDay: string | null, today: string): string =>+ anchor ?? selectedDay ?? today,+ ],+ days: [+ (s) => [s.anchorDate, s.weekStartDay],+ (anchorDate: string, weekStartDay: number): string[] => calendarDays('month', anchorDate, weekStartDay),+ ],+ loadRange: [+ (s) => [s.days, s.effectiveTimezone, s.rule],+ (days: string[], timezone: string, rule: SendingRule): CalendarRange => {+ // The hour keeps the range steady across renders, so it only loads again when the month changes.+ const now = dayjs().startOf('hour')+ const grid = calendarRange(days, timezone)+ // The suggestion looks ahead past the grid. Every day it checks counts the sends a full cap+ // window either side of it, so the range reaches one window past both ends.+ const firstChecked = grid.start.isBefore(now) ? grid.start : now+ const horizonEnd = now.add(SUGGESTION_HORIZON_DAYS + 1, 'day')+ const lastChecked = grid.end.isAfter(horizonEnd) ? grid.end : horizonEnd+ return {+ start: firstChecked.subtract(rule.windowDays, 'day'),+ end: lastChecked.add(rule.windowDays, 'day'),+ }+ },+ ],+ otherFlows: [+ (s, p) => [s.scheduledFlows, p.id],+ (scheduledFlows: SendCalendarFlowApi[] | null, id: string): SendCalendarFlowApi[] =>+ (scheduledFlows ?? []).filter((flow) => flow.id !== id),+ ],+ // The sends the grid shows: only the month on screen, at the calendar's usual limit per schedule.+ otherSends: [+ (s) => [s.otherFlows, s.days, s.effectiveTimezone],+ (otherFlows: SendCalendarFlowApi[], days: string[], timezone: string): CalendarSend[] => {+ const now = dayjs()+ const grid = calendarRange(days, timezone)+ return otherFlows+ .flatMap((flow) => calendarSendsForFlow(flow, grid, now))+ .filter((send) => send.state !== 'paused' && send.state !== 'failed')+ },+ ],+ // The sends the cap counts, over the whole range and without the display limit. Only flows that can reach+ // the same people are expanded, and these are never sorted for display.+ countingSends: [+ (s) => [s.otherFlows, s.loadRange, s.draftAudience, s.isTransactional],+ (+ otherFlows: SendCalendarFlowApi[],+ loadRange: CalendarRange,+ draftAudience: SendAudience,+ isTransactional: boolean+ ): CalendarSend[] => {+ if (isTransactional) {+ return []+ }+ const now = dayjs()+ return (+ otherFlows+ .filter((flow) => countsTowardRule({ audience: sendAudience(flow) }, draftAudience))+ .flatMap((flow) => calendarSendsForFlow(flow, loadRange, now, MAX_COUNTED_SENDS_PER_SCHEDULE))+ // A run cancelled partway shows as failed, but the emails it already sent still count.+ .filter((send) => send.state !== 'paused')+ )+ },+ ],+ countingKeys: [+ (s) => [s.otherSends, s.draftAudience, s.isTransactional],+ (+ otherSends: CalendarSend[],+ draftAudience: SendAudience,+ isTransactional: boolean+ ): Record<string, boolean> =>+ isTransactional+ ? {}+ : Object.fromEntries(+ otherSends+ .filter((send) => countsTowardRule(send, draftAudience))+ .map((send) => [send.key, true])+ ),+ ],+ sendsByDay: [+ (s) => [s.otherSends, s.effectiveTimezone],+ (otherSends: CalendarSend[], timezone: string): Record<string, CalendarSend[]> =>+ groupSendsByDay(otherSends, timezone),+ ],+ crowdedDays: [+ (s) => [s.days, s.countingSends, s.timeOfDay, s.effectiveTimezone, s.rule],+ (+ days: string[],+ countingSends: CalendarSend[],+ timeOfDay: string,+ timezone: string,+ rule: SendingRule+ ): Record<string, boolean> =>+ Object.fromEntries(+ days.map((day) => [+ day,+ crowdingSends(timeOnDay(day, timeOfDay, timezone), countingSends, rule).length > 0,+ ])+ ),+ ],+ selectedCrowding: [+ (s) => [s.sendAt, s.countingSends, s.rule],+ (sendAt: string | null, countingSends: CalendarSend[], rule: SendingRule): CalendarSend[] =>+ sendAt ? crowdingSends(dayjs(sendAt), countingSends, rule) : [],+ ],+ suggestion: [+ (s) => [s.countingSends, s.timeOfDay, s.effectiveTimezone, s.rule, s.isTransactional],+ (+ countingSends: CalendarSend[],+ timeOfDay: string,+ timezone: string,+ rule: SendingRule,+ isTransactional: boolean+ ): dayjs.Dayjs | null =>+ isTransactional+ ? null+ : suggestSendTime({ timeOfDay, timezone, now: dayjs(), others: countingSends, rule }),+ ],+ }),+ listeners(({ actions, values }) => ({+ goForward: () => actions.setAnchor(shiftAnchor('month', values.anchorDate, 1)),+ goBackward: () => actions.setAnchor(shiftAnchor('month', values.anchorDate, -1)),+ pickDay: ({ day }) => {+ const at = timeOnDay(day, values.timeOfDay, values.effectiveTimezone)+ actions.setSendAt(at.toISOString())+ // pinned: analytics event name+ posthog.capture('broadcast send day picked', {+ source: 'calendar',+ crowded: values.crowdedDays[day] ?? false,+ rule_from_cap: values.rule.fromCap,+ })+ },+ applySuggestion: () => {+ if (!values.suggestion) {+ return+ }+ actions.setSendAt(values.suggestion.toISOString())+ actions.setAnchor(null)+ // pinned: analytics event name+ posthog.capture('broadcast send day picked', {+ source: 'suggestion',+ crowded: false,+ rule_from_cap: values.rule.fromCap,+ })+ },+ })),+ subscriptions(({ actions }) => ({+ // The endpoint returns only the runs inside the range, so a new month loads again.+ loadRange: (range: CalendarRange, previous?: CalendarRange) => {+ if (!previous || !range.start.isSame(previous.start) || !range.end.isSame(previous.end)) {+ actions.loadScheduledFlows()+ }+ },+ })),+])diff --git a/products/workflows/frontend/SendCalendar/sendSpacing.test.ts b/products/workflows/frontend/SendCalendar/sendSpacing.test.tsnew file mode 100644index 000000000000..32fd8923b184--- /dev/null+++ b/products/workflows/frontend/SendCalendar/sendSpacing.test.ts@@ -0,0 +1,85 @@+import { dayjs } from 'lib/dayjs'++import { type SendAudience, audienceFromProperties } from './sendCalendarUtils'+import { SendingRule, mayShareRecipients, sendingRule, suggestSendTime } from './sendSpacing'++const DEFAULT_RULE = sendingRule(null)+const TWO_PER_WEEK: SendingRule = { maxMessages: 2, windowDays: 7, fromCap: true }++const send = (iso: string): { at: dayjs.Dayjs } => ({ at: dayjs.utc(iso) })++const audience = (cohortIds: number[], filters: SendAudience['filters'] = []): SendAudience => ({+ cohortIds,+ filters,+ accounts: false,+ address: null,+})++describe('sendSpacing', () => {+ it.each([+ [+ 'skips the days within 2 days of another send when no cap is set',+ DEFAULT_RULE,+ '2026-10-20T08:00:00Z',+ [send('2026-10-21T10:00:00Z')],+ '2026-10-23T10:00:00.000Z',+ ],+ [+ 'takes today when the cap allows a second send',+ TWO_PER_WEEK,+ '2026-10-20T08:00:00Z',+ [send('2026-10-21T10:00:00Z')],+ '2026-10-20T10:00:00.000Z',+ ],+ [+ 'counts a past send inside the cap window',+ TWO_PER_WEEK,+ '2026-10-20T08:00:00Z',+ [send('2026-10-18T10:00:00Z'), send('2026-10-21T10:00:00Z')],+ '2026-10-25T10:00:00.000Z',+ ],+ [+ 'starts tomorrow when the time already passed today',+ DEFAULT_RULE,+ '2026-10-20T12:00:00Z',+ [],+ '2026-10-21T10:00:00.000Z',+ ],+ ])('%s', (_, rule, now, others, expected) => {+ const suggestion = suggestSendTime({+ timeOfDay: '10:00:00',+ timezone: 'UTC',+ now: dayjs.utc(now),+ others,+ rule,+ })++ expect(suggestion?.toISOString()).toBe(expected)+ })++ it.each([+ ['two audiences that share a cohort', audience([21, 22]), audience([22]), true],+ ['two audiences of different cohorts', audience([21]), audience([24]), false],+ ['an audience of everyone', audience([]), audience([24]), true],+ [+ 'an audience that filters on a person property',+ audience([21], [+ { key: 'plan', type: 'person', operator: 'exact', value: ['free'] },+ ] as SendAudience['filters']),+ audience([24]),+ true,+ ],+ [+ 'two audiences that each leave out a different cohort',+ audienceFromProperties([+ { key: 'id', type: 'cohort', operator: 'not_in', value: 21 },+ ] as SendAudience['filters']),+ audienceFromProperties([+ { key: 'id', type: 'cohort', operator: 'not_in', value: 24 },+ ] as SendAudience['filters']),+ true,+ ],+ ])('decides whether %s can share people', (_, a, b, expected) => {+ expect(mayShareRecipients(a, b)).toBe(expected)+ })+})diff --git a/products/workflows/frontend/SendCalendar/sendSpacing.ts b/products/workflows/frontend/SendCalendar/sendSpacing.tsnew file mode 100644index 000000000000..14c495627cfe--- /dev/null+++ b/products/workflows/frontend/SendCalendar/sendSpacing.ts@@ -0,0 +1,110 @@+import { dayjs } from 'lib/dayjs'++import type { CalendarSend, SendAudience } from './sendCalendarUtils'++/** The most marketing emails that one person gets in a window of days. */+export interface SendingRule {+ maxMessages: number+ windowDays: number+ /** False when the project has no frequency cap, so the rule is the default spacing. */+ fromCap: boolean+}++// Without a frequency cap, the suggestions keep marketing sends to the same people at least 2 days apart.+const DEFAULT_RULE: SendingRule = { maxMessages: 1, windowDays: 2, fromCap: false }+export const SUGGESTION_HORIZON_DAYS = 60+// The broadcast editor rejects a send time in the past, so a suggestion for today leaves a margin.+const SUGGESTION_LEAD_MINUTES = 15++export function sendingRule(+ config:+ | {+ marketing_frequency_cap_max_messages?: number | null+ marketing_frequency_cap_window_days?: number | null+ }+ | null+ | undefined+): SendingRule {+ const maxMessages = config?.marketing_frequency_cap_max_messages+ const windowDays = config?.marketing_frequency_cap_window_days+ return maxMessages && windowDays ? { maxMessages, windowDays, fromCap: true } : DEFAULT_RULE+}++export function describeRule(rule: SendingRule): string {+ const emails = `${rule.maxMessages} marketing ${rule.maxMessages === 1 ? 'email' : 'emails'}`+ return `${emails} per person every ${rule.windowDays} ${rule.windowDays === 1 ? 'day' : 'days'}`+}++/**+ * Whether two audiences can hold the same people. Without a count of the shared people, only two+ * audiences of cohorts with no cohort in common count as apart.+ */+export function mayShareRecipients(a: SendAudience, b: SendAudience): boolean {+ const cohortsOnly = (audience: SendAudience): boolean =>+ audience.cohortIds.length > 0 && audience.filters.length === 0+ if (!cohortsOnly(a) || !cohortsOnly(b)) {+ return true+ }+ return a.cohortIds.some((id) => b.cohortIds.includes(id))+}++/**+ * Whether another send counts against a new send to `audience`, as the frequency cap counts it at send+ * time: a send to a fixed address has no person to count. The calendar endpoint already leaves out+ * transactional email, which the cap never counts.+ */+export function countsTowardRule(send: Pick<CalendarSend, 'audience'>, audience: SendAudience): boolean {+ return !send.audience.address && mayShareRecipients(audience, send.audience)+}++/**+ * The sends that would give someone more than the rule allows if a new send goes out at `at`, or an+ * empty list when `at` is fine. The cap counts the sends in a rolling window, so every window of+ * `windowDays` that holds `at` must stay at `maxMessages` or below, the new send included.+ */+export function crowdingSends<T extends { at: dayjs.Dayjs }>(at: dayjs.Dayjs, others: T[], rule: SendingRule): T[] {+ const windowMs = rule.windowDays * 24 * 60 * 60 * 1000+ const near = others+ .filter((send) => Math.abs(send.at.valueOf() - at.valueOf()) < windowMs)+ .sort((a, b) => a.at.valueOf() - b.at.valueOf())+ // The fullest window that holds `at` starts at `at` or at one of the earlier sends near it.+ const starts = [at.valueOf(), ...near.filter((send) => send.at.isBefore(at)).map((send) => send.at.valueOf())]+ for (const start of starts) {+ const inWindow = near.filter((send) => send.at.valueOf() >= start && send.at.valueOf() < start + windowMs)+ if (inWindow.length + 1 > rule.maxMessages) {+ return inWindow+ }+ }+ return []+}++/** A time of day ("HH:mm:ss") on a calendar day ("YYYY-MM-DD"), in a time zone. */+export function timeOnDay(day: string, timeOfDay: string, timezone: string): dayjs.Dayjs {+ return dayjs.tz(`${day} ${timeOfDay}`, timezone)+}++/** The first day, from today, where a send at `timeOfDay` keeps everyone within the rule. */+export function suggestSendTime<T extends { at: dayjs.Dayjs }>({+ timeOfDay,+ timezone,+ now,+ others,+ rule,+}: {+ timeOfDay: string+ timezone: string+ now: dayjs.Dayjs+ others: T[]+ rule: SendingRule+}): dayjs.Dayjs | null {+ const earliest = now.add(SUGGESTION_LEAD_MINUTES, 'minute')+ // Calendar days have no time zone, so the day arithmetic runs in UTC, where every day has 24 hours.+ const firstDay = dayjs.utc(now.tz(timezone).format('YYYY-MM-DD'))+ for (let offset = 0; offset <= SUGGESTION_HORIZON_DAYS; offset++) {+ const at = timeOnDay(firstDay.add(offset, 'day').format('YYYY-MM-DD'), timeOfDay, timezone)+ if (at.isAfter(earliest) && crowdingSends(at, others, rule).length === 0) {+ return at+ }+ }+ return null+}diff --git a/products/workflows/frontend/setupGuide/wizard/WizardBroadcastStep.tsx b/products/workflows/frontend/setupGuide/wizard/WizardBroadcastStep.tsxindex 1082bfd11a5d..4d79afe31c9c 100644--- a/products/workflows/frontend/setupGuide/wizard/WizardBroadcastStep.tsx+++ b/products/workflows/frontend/setupGuide/wizard/WizardBroadcastStep.tsx@@ -1,5 +1,7 @@import { IconCalendar, IconLetter, IconPeople } from '@posthog/icons'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+const NEXT_STEPS = [{ icon: <IconPeople />, title: 'Recipients', description: 'Pick a cohort, or filter people by their properties.' },{ icon: <IconLetter />, title: 'Email', description: 'Choose the sender, write the subject and design the email.' },@@ -10,10 +12,20 @@ const NEXT_STEPS = [},]+const SEND_ON_CALENDAR = {+ icon: <IconCalendar />,+ title: 'Send',+ description:+ 'Send it now, or pick a day on a calendar of your other sends. It suggests a day that keeps people within your frequency cap.',+}+export function WizardBroadcastStep(): JSX.Element {+ const showSendCalendar = useFeatureFlag('WORKFLOWS_SEND_CALENDAR')+ const steps = showSendCalendar ? [...NEXT_STEPS.slice(0, -1), SEND_ON_CALENDAR] : NEXT_STEPS+return (<ol className="m-0 flex list-none flex-col gap-4 p-0">- {NEXT_STEPS.map((step) => (+ {steps.map((step) => (<li key={step.title} className="flex items-start gap-3"><span className="flex size-8 shrink-0 items-center justify-center rounded bg-surface-secondary text-lg">{step.icon}diff --git a/products/workflows/frontend/setupGuide/wizard/WizardSendingRulesStep.tsx b/products/workflows/frontend/setupGuide/wizard/WizardSendingRulesStep.tsxindex a8c962717710..2627319b2ec6 100644--- a/products/workflows/frontend/setupGuide/wizard/WizardSendingRulesStep.tsx+++ b/products/workflows/frontend/setupGuide/wizard/WizardSendingRulesStep.tsx@@ -2,6 +2,7 @@ import { useActions, useValues } from 'kea'import { LemonDivider, LemonSwitch } from '@posthog/lemon-ui'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonInput } from 'lib/lemon-ui/LemonInput'import { LemonRadio, LemonRadioOption } from 'lib/lemon-ui/LemonRadio'@@ -55,12 +56,17 @@ export function WizardSendingRulesStep(): JSX.Element {useActions(workflowsOnboardingWizardLogic)const disabledReason = canEditSendingRules ? undefined : ADMIN_ONLY_REASONconst { maxMessages, windowDays } = shownCustomFrequencyCap+ const showSendCalendar = useFeatureFlag('WORKFLOWS_SEND_CALENDAR')return (<div className="flex flex-col gap-6"><SendingRuletitle="Frequency cap"- description="The most marketing emails one person gets across all workflows and broadcasts. Transactional email is never capped."+ description={`The most marketing emails one person gets across all workflows and broadcasts. Transactional email is never capped.${+ showSendCalendar+ ? ' When you schedule a broadcast, its calendar suggests a day within this cap. With no cap, it keeps sends to the same people 2 days apart.'+ : ''+ }`}><LemonRadiovalue={shownFrequencyCapChoice}