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.3 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

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

import { stamphogDigestRunsList } from '../../generated/api'
import type { DigestRunApi, PaginatedDigestRunListApi } from '../../generated/api.schemas'

export const DIGESTS_PAGE_SIZE = 50

function digestRunEventProperties(run: DigestRunApi): Record<string, string | number> {
    return { digest_run_id: run.id, status: run.status, pr_count: run.pr_count }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface stamphogDigestsSceneLogicValues {
    currentProjectId: number | string // teamLogic
    digestRuns: DigestRunApi[]
    digestRunsCount: number
    digestRunsFailed: boolean
    digestRunsResponse: PaginatedDigestRunListApi | null
    digestRunsResponseLoading: boolean
    page: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface stamphogDigestsSceneLogicActions {
    digestPrLinkClicked: (run: DigestRunApi) => {
        run: DigestRunApi
    }
    digestRunExpanded: (run: DigestRunApi) => {
        run: DigestRunApi
    }
    loadDigestRuns: () => {
        value: true
    }
    loadDigestRunsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDigestRunsSuccess: (
        digestRunsResponse: PaginatedDigestRunListApi,
        payload?: {
            value: true
        }
    ) => {
        digestRunsResponse: PaginatedDigestRunListApi
        payload?: {
            value: true
        }
    }
    setPage: (page: number) => {
        page: number
    }
    slackMessageLinkClicked: (run: DigestRunApi) => {
        run: DigestRunApi
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface stamphogDigestsSceneLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        digestRuns: (digestRunsResponse: PaginatedDigestRunListApi | null) => DigestRunApi[]
        digestRunsCount: (digestRunsResponse: PaginatedDigestRunListApi | null) => number
    }
}

export type stamphogDigestsSceneLogicType = MakeLogicType<
    stamphogDigestsSceneLogicValues,
    stamphogDigestsSceneLogicActions,
    Record<string, any>,
    stamphogDigestsSceneLogicMeta
>

export const stamphogDigestsSceneLogic = kea<stamphogDigestsSceneLogicType>([
    path(['products', 'stamphog', 'frontend', 'scenes', 'StamphogDigestsScene', 'stamphogDigestsSceneLogic']),

    connect(() => ({
        values: [teamLogic, ['currentProjectId']],
    })),

    actions({
        // Declared explicitly rather than left to the loaders builder: the loader takes a breakpoint,
        // so typegen would otherwise infer a required payload from its first parameter and every
        // `loadDigestRuns()` call site would stop compiling.
        loadDigestRuns: true,
        setPage: (page: number) => ({ page }),
        digestRunExpanded: (run: DigestRunApi) => ({ run }),
        slackMessageLinkClicked: (run: DigestRunApi) => ({ run }),
        digestPrLinkClicked: (run: DigestRunApi) => ({ run }),
    }),

    reducers({
        page: [1, { setPage: (_, { page }) => page }],
        // A failed request resolves the loader with a null response, which the runs selector turns into
        // an empty list. Without this the table would claim there are no digests when it simply could
        // not ask. Loading, empty and error are three different screens.
        digestRunsFailed: [
            false,
            {
                loadDigestRuns: () => false,
                loadDigestRunsSuccess: () => false,
                loadDigestRunsFailure: () => true,
            },
        ],
    }),

    loaders(({ values }) => ({
        digestRunsResponse: [
            null as PaginatedDigestRunListApi | null,
            {
                loadDigestRuns: async (_, breakpoint) => {
                    // urlToAction replays on mount, so a deep link sets the page through its own
                    // listener. Debounce so only the settled page loads.
                    await breakpoint(1)
                    return stamphogDigestRunsList(String(values.currentProjectId), {
                        limit: DIGESTS_PAGE_SIZE,
                        offset: (values.page - 1) * DIGESTS_PAGE_SIZE,
                    })
                },
            },
        ],
    })),

    selectors({
        digestRuns: [
            (s) => [s.digestRunsResponse],
            (digestRunsResponse: PaginatedDigestRunListApi | null): DigestRunApi[] => digestRunsResponse?.results ?? [],
        ],
        digestRunsCount: [
            (s) => [s.digestRunsResponse],
            (digestRunsResponse: PaginatedDigestRunListApi | null): number => digestRunsResponse?.count ?? 0,
        ],
    }),

    listeners(({ actions }) => ({
        setPage: () => actions.loadDigestRuns(),
        // The event names are frozen: insights on digest usage break if one is renamed.
        digestRunExpanded: ({ run }) => {
            posthog.capture('stamphog digest expanded', digestRunEventProperties(run))
        },
        slackMessageLinkClicked: ({ run }) => {
            posthog.capture('stamphog digest slack message opened', digestRunEventProperties(run))
        },
        digestPrLinkClicked: ({ run }) => {
            posthog.capture('stamphog digest pull request opened', digestRunEventProperties(run))
        },
    })),

    actionToUrl(({ values }) => {
        const toUrl = (): [string, Record<string, string>] => [
            urls.stamphogDigests(),
            values.page > 1 ? { page: String(values.page) } : {},
        ]
        return { setPage: toUrl }
    }),

    urlToAction(({ actions, values }) => ({
        [urls.stamphogDigests()]: (_: any, searchParams: Record<string, any>) => {
            const page = Number(searchParams.page ?? 1) || 1
            // Guarded against the current value so replaying an unchanged page on mount does not
            // fire a second load.
            if (page !== values.page) {
                actions.setPage(page)
            }
        },
    })),

    afterMount(({ actions }) => {
        posthog.capture('stamphog digests viewed')
        actions.loadDigestRuns()
    }),
])