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.

19.1 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'

import { lemonToast } from '@posthog/lemon-ui'

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 {
    hogFlowsSchedulesList,
    hogFlowsSchedulesPartialUpdate,
    hogFlowsSendCalendarRetrieve,
} from 'products/workflows/frontend/generated/api'
import type { HogFlowScheduleApi, SendCalendarFlowApi } from 'products/workflows/frontend/generated/api.schemas'

import { newBroadcastAgentLogic } from '../Broadcasts/newBroadcastAgentLogic'
import { MessageCategory, optOutCategoriesLogic } from '../OptOuts/optOutCategoriesLogic'
import { newWorkflowLogic } from '../Workflows/newWorkflowLogic'
import {
    CalendarRange,
    CalendarSend,
    CalendarSendKind,
    CalendarTypeFilter,
    CalendarView,
    calendarDays,
    calendarRange,
    calendarSendsForFlow,
    describeRepeat,
    dropTarget,
    groupSendsByDay,
    matchesTypeFilter,
    moveBlockedReason,
    movedScheduleFields,
    periodLabel,
    sendAudience,
    shiftAnchor,
} from './sendCalendarUtils'

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: SendCalendarFlowApi[] | 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: (_: void) => void
    loadScheduledFlowsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadScheduledFlowsSuccess: (
        scheduledFlows: SendCalendarFlowApi[],
        payload?: void
    ) => {
        scheduledFlows: SendCalendarFlowApi[]
        payload?: void
    }
    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: SendCalendarFlowApi[] | 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 SendCalendarFlowApi[] | null,
            {
                loadScheduledFlows: async (_: void, breakpoint) => {
                    // The server returns only the runs inside the shown range, so each new range loads again.
                    let flows: SendCalendarFlowApi[]
                    try {
                        flows = await hogFlowsSendCalendarRetrieve(String(values.currentProjectId), {
                            start: values.range.start.toISOString(),
                            end: values.range.end.toISOString(),
                        })
                    } catch (error) {
                        // A failed request for a period the person already left must not show the error.
                        breakpoint()
                        throw error
                    }
                    breakpoint()
                    return flows
                },
            },
        ],
    })),
    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((flow) =>
                    flow.id === flowId
                        ? { ...flow, schedules: flow.schedules.map((s) => (s.id === schedule.id ? schedule : s)) }
                        : flow
                ) ?? 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: SendCalendarFlowApi[] | null,
                range: CalendarRange,
                typeFilter: CalendarTypeFilter
            ): CalendarSend[] => {
                const now = dayjs()
                return (scheduledFlows ?? [])
                    .filter((flow) => matchesTypeFilter(flow, typeFilter))
                    .flatMap((flow) => calendarSendsForFlow(flow, 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, cache }) => ({
        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))].filter(
                (id) => !values.cohortsById[id]
            )
            if (cohortIds.length) {
                actions.loadCohortsByIds({ ids: cohortIds })
            }
            // Report the first load and each change of view, after the sends of that view loaded.
            if (cache.reportView) {
                // pinned: analytics event name
                posthog.capture('send calendar viewed', {
                    view: values.view,
                    scheduled_flows: scheduledFlows.length,
                    sends_in_range: values.sends.length,
                })
                cache.reportView = false
            }
        },
        setView: () => {
            cache.reportView = true
        },
        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,
            })
        },
    })),
    subscriptions(({ actions }) => ({
        range: (range: CalendarRange, previous: CalendarRange | undefined) => {
            if (previous && !(range.start.isSame(previous.start) && range.end.isSame(previous.end))) {
                actions.loadScheduledFlows()
            }
        },
    })),
    afterMount(({ actions, cache }) => {
        cache.reportView = true
        actions.loadScheduledFlows()
    }),
])