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.

9.7 KB
Raw Blame
import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { dayjs } from 'lib/dayjs'

import { MessageAsset, getMessageAssets } from '../Workflows/messageAssetsApi'
import { BroadcastWizardLogicProps } from './broadcastWizardLogic'

/** How many recipients a page holds. A run can reach far more, so further pages load on request. */
const SENT_ROW_LIMIT = 500

/** Matches MESSAGE_ASSETS_TTL_DAYS: ClickHouse drops a day's sends at UTC midnight this many days after that day. */
const SEND_RETENTION_DAYS = 30

interface SendsQuery {
    search: string
}

export interface BroadcastSentLogicProps extends BroadcastWizardLogicProps {
    /** The batch run whose sends to list. Every send of a broadcast belongs to one. */
    parentRunId: string | null
    /** When the run started. Its sends go out at or after this time. */
    runCreatedAt: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastSentLogicValues {
    hasMoreRecipients: boolean
    recipientCount: number
    recipientSearch: string
    runPastRetention: boolean
    selectedInvocationId: string | null
    selectedSend: MessageAsset | null
    sends: MessageAsset[]
    sendsFailed: boolean
    sendsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastSentLogicActions {
    loadMoreSends: () => any
    loadMoreSendsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadMoreSendsSuccess: (
        sends: MessageAsset[],
        payload?: any
    ) => {
        sends: MessageAsset[]
        payload?: any
    }
    loadSends: (_: void) => void
    loadSendsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSendsSuccess: (
        sends: MessageAsset[],
        payload?: void
    ) => {
        sends: MessageAsset[]
        payload?: void
    }
    selectInvocation: (invocationId: string | null) => {
        invocationId: string | null
    }
    setHasMoreRecipients: (hasMore: boolean) => {
        hasMore: boolean
    }
    setRecipientSearch: (search: string) => {
        search: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface broadcastSentLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        selectedSend: (sends: MessageAsset[], selectedInvocationId: string | null) => MessageAsset | null
        recipientCount: (sends: MessageAsset[]) => number
        runPastRetention: (runCreatedAt: string | null) => boolean
    }
}

export type broadcastSentLogicType = MakeLogicType<
    broadcastSentLogicValues,
    broadcastSentLogicActions,
    BroadcastSentLogicProps,
    broadcastSentLogicMeta
>

export const broadcastSentLogic = kea<broadcastSentLogicType>([
    path(['products', 'workflows', 'frontend', 'Broadcasts', 'broadcastSentLogic']),
    props({} as BroadcastSentLogicProps),
    key((props) => `${props.id}-${props.parentRunId ?? 'none'}`),

    actions({
        selectInvocation: (invocationId: string | null) => ({ invocationId }),
        setRecipientSearch: (search: string) => ({ search }),
        setHasMoreRecipients: (hasMore: boolean) => ({ hasMore }),
    }),

    loaders(({ props, values, actions, cache }) => {
        const loadPage = async (query: SendsQuery, offset: number): Promise<MessageAsset[]> => {
            if (!props.id || props.id === 'new' || !props.parentRunId) {
                return []
            }
            // Scoped to the run rather than the flow: a recurring broadcast has one set of
            // sends per run, and mixing them would double-count a recipient.
            const page = await getMessageAssets(props.id, {
                parent_run_id: props.parentRunId,
                // Searched and filtered on the server: a run can reach far more people than one page
                // holds, so filtering the loaded pages would cover only the first slice of them.
                search: query.search || undefined,
                limit: SENT_ROW_LIMIT,
                offset,
            })
            return page
        }
        return {
            sends: [
                [] as MessageAsset[],
                {
                    loadSends: async (_: void, breakpoint) => {
                        cache.queryVersion = (cache.queryVersion ?? 0) + 1
                        const version = cache.queryVersion
                        // The API trims the search and rejects a blank one, so spaces alone count as no search.
                        const query = { search: values.recipientSearch.trim() }
                        let page: MessageAsset[]
                        try {
                            page = await loadPage(query, 0)
                        } catch (error) {
                            // A newer search has started, so this failure no longer describes what is shown.
                            breakpoint()
                            throw error
                        }
                        // Drops a response that lands after a newer search or filter started.
                        breakpoint()
                        cache.loadedQuery = query
                        cache.loadedVersion = version
                        cache.nextOffset = page.length
                        actions.setHasMoreRecipients(page.length >= SENT_ROW_LIMIT)
                        return page
                    },
                    // Pages the query the shown rows came from, so a search typed since cannot be
                    // appended at an offset that belongs to the previous results. A page that lands
                    // after a newer query started is dropped rather than written over its results.
                    loadMoreSends: async () => {
                        const version = cache.queryVersion
                        // The first page of a newer query has not landed yet, so the shown rows and the
                        // offset still belong to the old query. Any load-more success clears the shared
                        // loading flag, so the button can be clicked in this window.
                        if (cache.loadedVersion !== version) {
                            return values.sends
                        }
                        const shown = values.sends
                        const offset: number = cache.nextOffset ?? shown.length
                        const page = await loadPage(cache.loadedQuery ?? { search: '' }, offset)
                        if (version !== cache.queryVersion) {
                            return values.sends
                        }
                        cache.nextOffset = offset + page.length
                        actions.setHasMoreRecipients(page.length >= SENT_ROW_LIMIT)
                        // A run that is still sending adds rows at the top, which pushes rows from the end
                        // of the shown pages onto this one. Dropping them keeps each recipient listed once.
                        // The offset counts every row the server returned, so it moves past the repeats
                        // instead of fetching them again.
                        const shownKeys = new Set(shown.map((send) => `${send.invocation_id}:${send.action_id}`))
                        return [
                            ...shown,
                            ...page.filter((send) => !shownKeys.has(`${send.invocation_id}:${send.action_id}`)),
                        ]
                    },
                },
            ],
        }
    }),

    reducers({
        // An empty list and a failed request both render as no rows, but they mean different things
        // to someone checking whether a send reached anyone.
        sendsFailed: [
            false,
            {
                loadSends: () => false,
                loadSendsSuccess: () => false,
                loadSendsFailure: () => true,
            },
        ],
        selectedInvocationId: [
            null as string | null,
            {
                selectInvocation: (_, { invocationId }) => invocationId,
                loadSends: () => null,
            },
        ],
        hasMoreRecipients: [
            false,
            {
                setHasMoreRecipients: (_, { hasMore }) => hasMore,
            },
        ],
        recipientSearch: [
            '',
            {
                setRecipientSearch: (_, { search }) => search,
            },
        ],
    }),

    listeners(({ actions }) => ({
        setRecipientSearch: async ({ search }, breakpoint) => {
            // A cleared search loads at once. During a delay the old search's empty results would show
            // with no search, which reads as a run with no sends and replaces the search input.
            if (search) {
                await breakpoint(300)
            }
            actions.loadSends()
        },
    })),

    selectors({
        selectedSend: [
            (s) => [s.sends, s.selectedInvocationId],
            (sends: MessageAsset[], selectedInvocationId: string | null): MessageAsset | null =>
                sends.find((send) => send.invocation_id === selectedInvocationId) ?? null,
        ],
        recipientCount: [(s) => [s.sends], (sends: MessageAsset[]): number => sends.length],
        // An empty list for an older run can mean its sends expired, not that it reached nobody.
        runPastRetention: [
            (_, p) => [p.runCreatedAt],
            (runCreatedAt: string | null): boolean =>
                !!runCreatedAt &&
                dayjs().isSameOrAfter(dayjs.utc(runCreatedAt).startOf('day').add(SEND_RETENTION_DAYS, 'day')),
        ],
    }),
])