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.

4.6 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path } from 'kea'

import { LemonDialog, LemonInput } from '@posthog/lemon-ui'

import { LemonField } from 'lib/lemon-ui/LemonField'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { insightsApi } from 'scenes/insights/utils/api'
import { teamLogic } from 'scenes/teamLogic'

import { InsightModel, InsightShortId } from '~/types'

import type { Node } from '../queries/schema/schema-general'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface insightsModelActions {
    duplicateInsight: (item: InsightModel) => {
        item: InsightModel<Node<Record<string, any>>>
    }
    duplicateInsightSuccess: (item: InsightModel) => {
        item: InsightModel<Node<Record<string, any>>>
    }
    insightSaved: (shortId: InsightShortId) => {
        shortId: InsightShortId
    }
    insightsAddedToDashboard: ({
        dashboardId,
        tiles,
    }: {
        dashboardId: number
        tiles: {
            id: number
            insightId: number
        }[]
    }) => {
        dashboardId: number
        tiles: {
            id: number
            insightId: number
        }[]
    }
    renameInsight: (item: InsightModel) => {
        item: InsightModel<Node<Record<string, any>>>
    }
    renameInsightSuccess: (item: InsightModel) => {
        item: InsightModel<Node<Record<string, any>>>
    }
    updateInsightDirect: (
        item: InsightModel,
        updates: Partial<InsightModel>
    ) => {
        item: InsightModel<Node<Record<string, any>>>
        updates: Partial<InsightModel<Node<Record<string, any>>>>
    }
}

export type insightsModelType = MakeLogicType<{}, insightsModelActions>

export const insightsModel = kea<insightsModelType>([
    path(['models', 'insightsModel']),
    connect(() => ({ logic: [teamLogic] })),
    actions(() => ({
        insightSaved: (shortId: InsightShortId) => ({ shortId }),
        renameInsight: (item: InsightModel) => ({ item }),
        updateInsightDirect: (item: InsightModel, updates: Partial<InsightModel>) => ({
            item,
            updates,
        }),
        renameInsightSuccess: (item: InsightModel) => ({ item }),
        // TODO: this duplicates the insight but not the dashboard tile (e.g. if duplicated from dashboard you lose tile color
        duplicateInsight: (item: InsightModel) => ({ item }),
        duplicateInsightSuccess: (item: InsightModel) => ({ item }),
        insightsAddedToDashboard: ({
            dashboardId,
            tiles,
        }: {
            dashboardId: number
            tiles: { id: number; insightId: number }[]
        }) => ({
            dashboardId,
            tiles,
        }),
    })),
    listeners(({ actions }) => ({
        renameInsight: async ({ item }) => {
            LemonDialog.openForm({
                title: 'Rename insight',
                initialValues: { insightName: item.name },
                content: (
                    <LemonField name="insightName">
                        <LemonInput data-attr="insight-name" placeholder="Please enter the new name" autoFocus />
                    </LemonField>
                ),
                errors: {
                    insightName: (name) => (!name ? 'You must enter a name' : undefined),
                },
                onSubmit: async ({ insightName }) => {
                    const updatedItem = await insightsApi.update(item.id, { name: insightName })
                    lemonToast.success(
                        <>
                            Renamed insight from <b>{item.name}</b> to <b>{insightName}</b>
                        </>
                    )
                    actions.renameInsightSuccess(updatedItem)
                },
            })
        },
        updateInsightDirect: async ({ item, updates }) => {
            try {
                const updatedItem = await insightsApi.update(item.id, updates)
                actions.renameInsightSuccess(updatedItem)
                lemonToast.success('Insight updated')
            } catch (e) {
                lemonToast.error('Failed to update insight')
                throw e
            }
        },
        duplicateInsight: async ({ item }) => {
            // get the insight, to ensure we duplicate it without any changes that might have been made to it
            // e.g. any dashboard filters that were applied to it
            const insight = await insightsApi.getByNumericId(item.id)
            const addedItem = await insightsApi.duplicate(insight!)

            actions.duplicateInsightSuccess(addedItem)
            lemonToast.success('Insight duplicated')
        },
    })),
])