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.

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

import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import type { LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { organizationLogic } from 'scenes/organizationLogic'

import { insightsList } from 'products/product_analytics/frontend/generated/api'

import { crossProjectDashboardLogic } from './crossProjectDashboardLogic'
import { crossProjectDashboardTracking } from './crossProjectDashboardTracking'
import { crossProjectDashboardsTilesCreate } from './generated/api'

export interface InsightOption {
    id: number
    name: string
    /** Shown next to the name, so the picker can tell apart insights that share one. */
    createdBy?: string
    lastModifiedAt?: string
}

export interface InsightPage {
    insights: InsightOption[]
    hasMore: boolean
    /** Insights in the project that match the search, across all pages. */
    total?: number
}

export interface AddCrossProjectTileLogicProps {
    dashboardId: string
}

const INSIGHT_PAGE_SIZE = 50
const INSIGHT_SEARCH_DEBOUNCE_MS = 300
const EMPTY_INSIGHT_PAGE: InsightPage = { insights: [], hasMore: false }

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addCrossProjectTileLogicValues {
    canAdd: boolean
    insightOptions: LemonInputSelectOption[]
    insightPage: InsightPage
    insightPageLoading: boolean
    insightSearch: string
    isAdding: boolean
    isOpen: boolean
    projectId: number | null
    projectOptions: LemonInputSelectOption[]
    selectedInsight: InsightOption | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addCrossProjectTileLogicActions {
    addTile: () => {
        value: true
    }
    addTileFailure: () => {
        value: true
    }
    closeModal: () => {
        value: true
    }
    loadInsights: () => any
    loadInsightsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadInsightsSuccess: (
        insightPage: InsightPage,
        payload?: any
    ) => {
        insightPage: InsightPage
        payload?: any
    }
    loadMoreInsights: () => any
    loadMoreInsightsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadMoreInsightsSuccess: (
        insightPage: InsightPage,
        payload?: any
    ) => {
        insightPage: InsightPage
        payload?: any
    }
    openModal: () => {
        value: true
    }
    requestOpenModal: () => {
        value: true
    }
    setInsight: (insight: InsightOption | null) => {
        insight: InsightOption | null
    }
    setInsightSearch: (search: string) => {
        search: string
    }
    setProjectId: (projectId: number | null) => {
        projectId: number | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface addCrossProjectTileLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        projectOptions: (currentOrganization: null | import('~/types').OrganizationType) => LemonInputSelectOption[]
        insightOptions: (insightPage: InsightPage, selectedInsight: InsightOption | null) => LemonInputSelectOption[]
        canAdd: (projectId: number | null, selectedInsight: InsightOption | null) => boolean
    }
}

export type addCrossProjectTileLogicType = MakeLogicType<
    addCrossProjectTileLogicValues,
    addCrossProjectTileLogicActions,
    AddCrossProjectTileLogicProps,
    addCrossProjectTileLogicMeta
>

export const addCrossProjectTileLogic = kea<addCrossProjectTileLogicType>([
    path((key) => ['products', 'cross_project_dashboards', 'frontend', 'addCrossProjectTileLogic', key]),
    props({} as AddCrossProjectTileLogicProps),
    key((props) => props.dashboardId),
    actions({
        requestOpenModal: true,
        openModal: true,
        closeModal: true,
        setProjectId: (projectId: number | null) => ({ projectId }),
        setInsightSearch: (search: string) => ({ search }),
        setInsight: (insight: InsightOption | null) => ({ insight }),
        addTile: true,
        addTileFailure: true,
    }),
    reducers({
        isOpen: [false, { openModal: () => true, closeModal: () => false }],
        projectId: [null as number | null, { setProjectId: (_, { projectId }) => projectId, closeModal: () => null }],
        insightSearch: [
            '',
            {
                setInsightSearch: (_, { search }) => search,
                setProjectId: () => '',
                closeModal: () => '',
            },
        ],
        selectedInsight: [
            null as InsightOption | null,
            {
                setInsight: (_, { insight }) => insight,
                setProjectId: () => null,
                closeModal: () => null,
            },
        ],
        isAdding: [false, { addTile: () => true, addTileFailure: () => false, closeModal: () => false }],
    }),
    loaders(({ values }) => {
        const fetchInsightPage = async (projectId: number, search: string, offset: number): Promise<InsightPage> => {
            const response = await insightsList(String(projectId), {
                basic: true,
                limit: INSIGHT_PAGE_SIZE,
                offset,
                search: search.trim() || undefined,
            })
            return {
                insights: response.results.map((insight) => ({
                    id: insight.id,
                    name: insight.name || insight.derived_name || `Insight ${insight.id}`,
                    createdBy: insight.created_by?.first_name || insight.created_by?.email || undefined,
                    lastModifiedAt: insight.last_modified_at ?? undefined,
                })),
                hasMore: !!response.next,
                total: response.count,
            }
        }

        // A response for a project or search the person has since changed belongs to a different list.
        const isStale = (projectId: number, search: string): boolean =>
            values.projectId !== projectId || values.insightSearch !== search

        return {
            insightPage: [
                EMPTY_INSIGHT_PAGE,
                {
                    loadInsights: async (): Promise<InsightPage> => {
                        const { projectId, insightSearch } = values
                        if (!projectId) {
                            return EMPTY_INSIGHT_PAGE
                        }
                        const page = await fetchInsightPage(projectId, insightSearch, 0)
                        return isStale(projectId, insightSearch) ? values.insightPage : page
                    },
                    loadMoreInsights: async (): Promise<InsightPage> => {
                        const { projectId, insightSearch, insightPage } = values
                        if (!projectId) {
                            return insightPage
                        }
                        const next = await fetchInsightPage(projectId, insightSearch, insightPage.insights.length)
                        if (isStale(projectId, insightSearch)) {
                            return values.insightPage
                        }
                        return {
                            insights: [...values.insightPage.insights, ...next.insights],
                            hasMore: next.hasMore,
                            total: next.total,
                        }
                    },
                },
            ],
        }
    }),
    selectors({
        projectOptions: [
            () => [organizationLogic.selectors.currentOrganization],
            (organization: null | import('~/types').OrganizationType): LemonInputSelectOption[] =>
                [...(organization?.projects ?? [])]
                    .sort((a, b) => a.name.localeCompare(b.name))
                    .map((project) => ({ key: String(project.id), label: project.name })),
        ],
        // Keeps the picked insight in the options, so the field still shows its name after the search moves on.
        insightOptions: [
            (s) => [s.insightPage, s.selectedInsight],
            (insightPage: InsightPage, selectedInsight: InsightOption | null): LemonInputSelectOption[] => {
                const insights =
                    selectedInsight && !insightPage.insights.some((insight) => insight.id === selectedInsight.id)
                        ? [selectedInsight, ...insightPage.insights]
                        : insightPage.insights
                return insights.map((insight) => ({ key: String(insight.id), label: insight.name }))
            },
        ],
        canAdd: [
            (s) => [s.projectId, s.selectedInsight],
            (projectId: number | null, selectedInsight: InsightOption | null) => !!projectId && !!selectedInsight,
        ],
    }),
    listeners(({ values, props, actions }) => ({
        requestOpenModal: () => {
            const dashboardLogic = crossProjectDashboardLogic.findMounted({ id: props.dashboardId })
            // Adding a tile reloads the dashboard, and the reload drops any layout edit in progress.
            const leaveLayoutEditAndOpen = (): void => {
                if (dashboardLogic?.values.layoutEditMode) {
                    dashboardLogic.actions.exitLayoutEdit()
                }
                actions.openModal()
            }
            if (!dashboardLogic?.values.hasUnsavedLayoutChanges) {
                leaveLayoutEditAndOpen()
                return
            }
            LemonDialog.open({
                title: 'Discard unsaved changes?',
                description:
                    'You have unsaved layout changes. Adding an insight reloads the dashboard and discards them.',
                primaryButton: {
                    children: 'Discard changes',
                    status: 'danger',
                    onClick: leaveLayoutEditAndOpen,
                    'data-attr': 'cross-project-dashboard-add-tile-discard-confirm',
                },
                secondaryButton: { children: 'Keep editing' },
            })
        },
        openModal: () => {
            crossProjectDashboardTracking.addInsightOpened(
                props.dashboardId,
                crossProjectDashboardLogic.findMounted({ id: props.dashboardId })?.values.tiles ?? []
            )
        },
        setProjectId: () => {
            actions.loadInsights()
        },
        setInsightSearch: async (_, breakpoint) => {
            await breakpoint(INSIGHT_SEARCH_DEBOUNCE_MS)
            actions.loadInsights()
        },
        addTile: async () => {
            const organizationId = organizationLogic.values.currentOrganization?.id
            if (!organizationId || !values.projectId || !values.selectedInsight) {
                actions.closeModal()
                return
            }
            const projectId = values.projectId
            const usedSearch = !!values.insightSearch.trim()
            try {
                await crossProjectDashboardsTilesCreate(organizationId, props.dashboardId, {
                    project_id: projectId,
                    insight_id: values.selectedInsight.id,
                } as any)
                const tilesBefore =
                    crossProjectDashboardLogic.findMounted({ id: props.dashboardId })?.values.tiles ?? []
                crossProjectDashboardTracking.insightAdded(
                    props.dashboardId,
                    [...tilesBefore, { project_id: projectId }],
                    usedSearch
                )
                actions.closeModal()
                // findMounted, not a direct reference: referencing another logic's actions
                // mounts it and fires its afterMount.
                crossProjectDashboardLogic.findMounted({ id: props.dashboardId })?.actions.loadDashboard()
            } catch (error: any) {
                lemonToast.error(error?.detail || 'Could not add that insight. Try again.')
                crossProjectDashboardTracking.insightAddFailed(props.dashboardId, error?.status)
                actions.addTileFailure()
            }
        },
    })),
    afterMount(({ actions }) => {
        actions.loadInsights()
    }),
])