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.

6.1 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props } from 'kea'
import { loaders } from 'kea-loaders'

import { projectLogic } from 'scenes/projectLogic'
import { teamLogic } from 'scenes/teamLogic'

import type { TeamPublicType, TeamType } from '~/types'

import { hogFlowsBatchJobsList, hogFlowsList, hogFlowsSchedulesList } from 'products/workflows/frontend/generated/api'
import type { HogFlowBatchJobApi } from 'products/workflows/frontend/generated/api.schemas'

import { loadRunMetricTotals } from './broadcastsLogic'

export interface BroadcastPreviousSendLogicProps {
    /** The record the new broadcast is about, as "<kind>:<id>". */
    sourceRecord: string
}

export type PreviousSendState = 'sent' | 'sending' | 'scheduled'

export interface PreviousSend {
    broadcastId: string
    state: PreviousSendState
    /** The run that went out, for its date and count. Null when nothing has run yet. */
    job: HogFlowBatchJobApi | null
}

/** Broadcasts about one record are few, so the newest handful covers the history worth warning about. */
const RECENT_BROADCASTS = 5
const PENDING_JOB_STATES = new Set(['waiting', 'queued', 'active'])

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastPreviousSendLogicValues {
    currentProjectId: number | null // projectLogic
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    previousSend: PreviousSend | null
    previousSendLoading: boolean
    sentCount: number | null
    sentCountLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastPreviousSendLogicActions {
    loadPreviousSend: () => any
    loadPreviousSendFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPreviousSendSuccess: (
        previousSend: PreviousSend | null,
        payload?: any
    ) => {
        previousSend: PreviousSend | null
        payload?: any
    }
    loadSentCount: (job: HogFlowBatchJobApi) => HogFlowBatchJobApi
    loadSentCountFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSentCountSuccess: (
        sentCount: number | null,
        payload?: HogFlowBatchJobApi
    ) => {
        sentCount: number | null
        payload?: HogFlowBatchJobApi
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastPreviousSendLogicMeta {
    key: string
}

export type broadcastPreviousSendLogicType = MakeLogicType<
    broadcastPreviousSendLogicValues,
    broadcastPreviousSendLogicActions,
    BroadcastPreviousSendLogicProps,
    broadcastPreviousSendLogicMeta
>

export const broadcastPreviousSendLogic = kea<broadcastPreviousSendLogicType>([
    path(['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastPreviousSendLogic']),
    props({} as BroadcastPreviousSendLogicProps),
    key((props) => props.sourceRecord),
    connect(() => ({
        values: [projectLogic, ['currentProjectId'], teamLogic, ['currentTeam']],
    })),

    loaders(({ props, values }) => ({
        previousSend: [
            null as PreviousSend | null,
            {
                loadPreviousSend: async (): Promise<PreviousSend | null> => {
                    const projectId = String(values.currentProjectId)
                    // Filtered by record only: archived broadcasts still emailed people, and a status filter
                    // would evaluate every workflow in the project before the record narrows it.
                    const page = await hogFlowsList(projectId, {
                        source_record: props.sourceRecord,
                        limit: RECENT_BROADCASTS,
                    })
                    let pending: PreviousSend | null = null
                    for (const flow of (page.results ?? []).filter((flow) => flow.status !== 'draft')) {
                        const jobs = await hogFlowsBatchJobsList(projectId, flow.id)
                        // A partly failed run still reached some people, so it counts as a send.
                        const sent = jobs.find((job) => job.status === 'completed' || job.status === 'partially_failed')
                        if (sent) {
                            return { broadcastId: flow.id, state: 'sent', job: sent }
                        }
                        const running = jobs.find((job) => PENDING_JOB_STATES.has(job.status ?? ''))
                        if (!pending && running) {
                            pending = {
                                broadcastId: flow.id,
                                state: running.status === 'active' ? 'sending' : 'scheduled',
                                job: null,
                            }
                        }
                        if (!pending && !jobs.length && flow.status === 'active') {
                            const schedules = await hogFlowsSchedulesList(projectId, flow.id)
                            if (schedules.some((schedule) => schedule.status === 'active')) {
                                pending = { broadcastId: flow.id, state: 'scheduled', job: null }
                            }
                        }
                    }
                    return pending
                },
            },
        ],
        sentCount: [
            null as number | null,
            {
                loadSentCount: async (job: HogFlowBatchJobApi): Promise<number | null> => {
                    const totals = await loadRunMetricTotals(job, values.currentTeam?.timezone ?? 'UTC')
                    return totals.email_sent ?? null
                },
            },
        ],
    })),

    listeners(({ actions }) => ({
        // The count reads app metrics, which can be slow, so the warning shows before it arrives.
        loadPreviousSendSuccess: ({ previousSend }) => {
            if (previousSend?.state === 'sent' && previousSend.job) {
                actions.loadSentCount(previousSend.job)
            }
        },
    })),

    afterMount(({ actions }) => {
        actions.loadPreviousSend()
    }),
])