Skip to content

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

16.8 KB
Raw Blame
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()
            }
        },
    })),
])