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.

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

import api from 'lib/api'
import { Sorting } from 'lib/lemon-ui/LemonTable'
import { objectsEqual } from 'lib/utils/objects'
import { toParams } from 'lib/utils/url'
import { InsightsResult, SavedInsightFilters, cleanFilters } from 'scenes/saved-insights/savedInsightsLogic'
import { teamLogic } from 'scenes/teamLogic'

export interface EventInsightsLogicProps {
    event: string
}

export const INSIGHTS_PER_PAGE = 10

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface eventInsightsLogicValues {
    currentTeamId: number | null // teamLogic
    count: number
    filters: SavedInsightFilters
    insights: InsightsResult
    insightsLoading: boolean
    page: number
    rawFilters: Partial<SavedInsightFilters> | null
    sorting: Sorting | null
    usingFilters: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface eventInsightsLogicActions {
    loadInsights: () => {
        value: true
    }
    loadInsightsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInsightsSuccess: (
        insights: InsightsResult,
        payload?: {
            value: true
        }
    ) => {
        insights: InsightsResult
        payload?: {
            value: true
        }
    }
    setFilters: (filters: Partial<SavedInsightFilters>) => {
        filters: Partial<SavedInsightFilters>
    }
    setPage: (page: number) => {
        page: number
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface eventInsightsLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        filters: (rawFilters: Partial<SavedInsightFilters> | null) => SavedInsightFilters
        count: (insights: InsightsResult) => number
        sorting: (filters: SavedInsightFilters) => Sorting | null
        page: (filters: SavedInsightFilters) => number
        usingFilters: (filters: SavedInsightFilters) => boolean
    }
}

export type eventInsightsLogicType = MakeLogicType<
    eventInsightsLogicValues,
    eventInsightsLogicActions,
    EventInsightsLogicProps,
    eventInsightsLogicMeta
>

export const eventInsightsLogic = kea<eventInsightsLogicType>([
    path(['scenes', 'data-management', 'events', 'eventInsightsLogic']),
    props({} as EventInsightsLogicProps),
    key(({ event }) => event),
    connect(() => ({
        values: [teamLogic, ['currentTeamId']],
    })),
    actions({
        setFilters: (filters: Partial<SavedInsightFilters>) => ({ filters }),
        loadInsights: true,
        setPage: (page: number) => ({ page }),
    }),
    loaders(({ values, props }) => ({
        insights: {
            __default: { results: [], count: 0, filters: null, offset: 0 } as InsightsResult,
            loadInsights: async () => {
                const { filters } = values
                const { order, page, search } = filters

                const params: Record<string, any> = {
                    order,
                    limit: INSIGHTS_PER_PAGE,
                    offset: Math.max(0, (page - 1) * INSIGHTS_PER_PAGE),
                    saved: true,
                    basic: true,
                }

                if (search) {
                    params.search = search
                }

                params.events = [props.event]

                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use insightsList() from 'products/product_analytics/frontend/generated/api' instead.
                const response = await api.get(`api/projects/${values.currentTeamId}/insights/?${toParams(params)}`)

                return {
                    ...response,
                    filters,
                    results: response?.results ?? [],
                } as InsightsResult
            },
        },
    })),
    reducers({
        rawFilters: [
            null as Partial<SavedInsightFilters> | null,
            {
                setFilters: (state, { filters }) => {
                    return cleanFilters({
                        ...state,
                        ...filters,
                        ...('page' in filters ? {} : { page: 1 }),
                    })
                },
            },
        ],
    }),
    selectors({
        filters: [(s) => [s.rawFilters], (rawFilters: object): SavedInsightFilters => cleanFilters(rawFilters || {})],
        count: [(s) => [s.insights], (insights: InsightsResult) => insights.count],
        sorting: [
            (s) => [s.filters],
            (filters: SavedInsightFilters): Sorting | null =>
                filters.order
                    ? filters.order.startsWith('-')
                        ? { columnKey: filters.order.slice(1), order: -1 }
                        : { columnKey: filters.order, order: 1 }
                    : null,
        ],
        page: [(s) => [s.filters], (filters: SavedInsightFilters) => filters.page],
        usingFilters: [
            (s) => [s.filters],
            (filters: SavedInsightFilters) =>
                !objectsEqual(cleanFilters({ ...filters, events: undefined }), cleanFilters({})),
        ],
    }),
    listeners(({ actions, values, selectors }) => ({
        setPage: async ({ page }) => {
            actions.setFilters({ page })
            actions.loadInsights()
        },
        setFilters: async ({}, breakpoint, __, previousState) => {
            const oldFilters = selectors.filters(previousState)
            const newFilters = values.filters
            await breakpoint(300)
            if (!objectsEqual(oldFilters, newFilters)) {
                actions.loadInsights()
            }
        },
    })),
    events(({ actions }) => ({
        afterMount: () => {
            actions.loadInsights()
        },
    })),
])