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.0 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { uuid } from 'lib/utils/dom'
import { teamLogic } from 'scenes/teamLogic'

import { isBIVisualizationNode } from '~/queries/schema/node-guards'
import { BIField, BIHierarchy } from '~/queries/schema/schema-business-intelligence'

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

import type { BIConfig } from '../../../frontend/src/queries/schema/schema-business-intelligence'
import type { InsightApi, PaginatedInsightListApi } from '../../product_analytics/frontend/generated/api.schemas'
import { biEditorLogic } from './biEditorLogic'
import { BIEditorView, parseBIEditorState } from './biEditorTypes'
import type { BIDataPaneFields } from './biEditorTypes'
import { hierarchyError, hierarchyFieldKey } from './biHierarchies'

export interface BIHierarchyProps {
    tabId: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biHierarchyLogicValues {
    config: BIConfig // biEditorLogic
    dataPaneFields: BIDataPaneFields // biEditorLogic
    currentTeamId: number | null // teamLogic
    availableFields: BIField[]
    draft: BIHierarchy | null
    draftError: string | undefined
    fields: BIField[]
    hierarchySource: Awaited<ReturnType<typeof insightsRetrieve>> | null
    hierarchySourceLoading: boolean
    importError: string | null
    importHierarchies: BIHierarchy[]
    importOpen: boolean
    page: number
    search: string
    selectedWorksheetId: number | string | null
    worksheets: Awaited<ReturnType<typeof insightsList>> | null
    worksheetsLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biHierarchyLogicActions {
    addFieldToShelf: (
        field: BIField,
        shelf: import('./biEditorTypes').BIShelf
    ) => {
        field: BIField
        shelf: import('./biEditorTypes').BIShelf
    } // biEditorLogic
    upsertHierarchy: (hierarchy: BIHierarchy) => {
        hierarchy: BIHierarchy
    } // biEditorLogic
    addLevel: (fieldId: string) => {
        fieldId: string
    }
    closeImport: () => {
        value: true
    }
    editHierarchy: (hierarchy?: BIHierarchy) => {
        hierarchy: BIHierarchy | undefined
    }
    importHierarchy: (id: string) => {
        id: string
    }
    loadHierarchySource: (id: number | string) => number | string
    loadHierarchySourceFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadHierarchySourceSuccess: (
        hierarchySource: InsightApi | null,
        payload?: number | string
    ) => {
        hierarchySource: InsightApi | null
        payload?: number | string
    }
    loadWorksheets: (_: void) => void
    loadWorksheetsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadWorksheetsSuccess: (
        worksheets: PaginatedInsightListApi,
        payload?: void
    ) => {
        worksheets: PaginatedInsightListApi
        payload?: void
    }
    moveLevel: (
        index: number,
        offset: 1 | -1
    ) => {
        index: number
        offset: 1 | -1
    }
    openImport: () => {
        value: true
    }
    removeLevel: (index: number) => {
        index: number
    }
    retryImport: () => {
        value: true
    }
    saveHierarchy: () => {
        value: true
    }
    setDraft: (draft: BIHierarchy | null) => {
        draft: BIHierarchy | null
    }
    setPage: (page: number) => {
        page: number
    }
    setSearch: (search: string) => {
        search: string
    }
    startHierarchy: (
        id: string,
        shelf: 'columns' | 'rows'
    ) => {
        id: string
        shelf: 'columns' | 'rows'
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface biHierarchyLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        fields: (dataPaneFields: BIDataPaneFields) => BIField[]
        availableFields: (fields: BIField[], draft: BIHierarchy | null) => BIField[]
        draftError: (draft: BIHierarchy | null, config: BIConfig) => string | undefined
        importHierarchies: (hierarchySource: InsightApi | null) => BIHierarchy[]
    }
}

export type biHierarchyLogicType = MakeLogicType<
    biHierarchyLogicValues,
    biHierarchyLogicActions,
    BIHierarchyProps,
    biHierarchyLogicMeta
>

export const biHierarchyLogic = kea<biHierarchyLogicType>([
    props({} as BIHierarchyProps),
    key((props) => props.tabId),
    path((key) => ['products', 'business_intelligence', 'biHierarchyLogic', key]),
    connect((props: BIHierarchyProps) => ({
        values: [biEditorLogic(props), ['config', 'dataPaneFields'], teamLogic, ['currentTeamId']],
        actions: [biEditorLogic(props), ['upsertHierarchy', 'addFieldToShelf']],
    })),
    actions({
        editHierarchy: (hierarchy?: BIHierarchy) => ({ hierarchy }),
        setDraft: (draft: BIHierarchy | null) => ({ draft }),
        saveHierarchy: true,
        openImport: true,
        closeImport: true,
        setSearch: (search: string) => ({ search }),
        setPage: (page: number) => ({ page }),
        importHierarchy: (id: string) => ({ id }),
        addLevel: (fieldId: string) => ({ fieldId }),
        removeLevel: (index: number) => ({ index }),
        moveLevel: (index: number, offset: -1 | 1) => ({ index, offset }),
        startHierarchy: (id: string, shelf: 'rows' | 'columns') => ({ id, shelf }),
        retryImport: true,
    }),
    reducers({
        selectedWorksheetId: [
            null as number | string | null,
            {
                loadHierarchySource: (_, id) => id,
                loadWorksheets: () => null,
            },
        ],
        hierarchySource: [
            null as Awaited<ReturnType<typeof insightsRetrieve>> | null,
            {
                openImport: () => null,
                loadHierarchySource: () => null,
                loadWorksheets: () => null,
            },
        ],
        draft: [
            null as BIHierarchy | null,
            {
                editHierarchy: (_, { hierarchy }) => hierarchy ?? { id: uuid(), name: '', levels: [] },
                setDraft: (_, { draft }) => draft,
                upsertHierarchy: () => null,
                removeLevel: (draft, { index }) =>
                    draft ? { ...draft, levels: draft.levels.filter((_, i) => i !== index) } : draft,
                moveLevel: (draft, { index, offset }) => {
                    if (!draft || index + offset < 0 || index + offset >= draft.levels.length) {
                        return draft
                    }
                    const levels = [...draft.levels]
                    ;[levels[index], levels[index + offset]] = [levels[index + offset], levels[index]]
                    return { ...draft, levels }
                },
            },
        ],
        importOpen: [false, { openImport: () => true, closeImport: () => false, editHierarchy: () => false }],
        search: ['', { setSearch: (_, { search }) => search, openImport: () => '' }],
        page: [0, { setPage: (_, { page }) => page, setSearch: () => 0, openImport: () => 0 }],
        importError: [
            null as string | null,
            {
                openImport: () => null,
                loadWorksheets: () => null,
                loadWorksheetsFailure: (_, { error }) => error,
                loadHierarchySource: () => null,
                loadHierarchySourceFailure: (_, { error }) => error,
            },
        ],
    }),
    loaders(({ values }) => ({
        worksheets: [
            null as Awaited<ReturnType<typeof insightsList>> | null,
            {
                loadWorksheets: async (_: void, breakpoint) => {
                    await breakpoint(250)
                    const response = await insightsList(String(values.currentTeamId), {
                        insight: 'BI',
                        basic: true,
                        saved: true,
                        limit: 20,
                        offset: values.page * 20,
                        search: values.search.trim() || undefined,
                    })
                    breakpoint()
                    return response
                },
            },
        ],
        hierarchySource: [
            null as Awaited<ReturnType<typeof insightsRetrieve>> | null,
            {
                loadHierarchySource: async (id: number | string, breakpoint) => {
                    const response = await insightsRetrieve(String(values.currentTeamId), id)
                    breakpoint()
                    return values.selectedWorksheetId === id ? response : null
                },
            },
        ],
    })),
    selectors({
        fields: [
            (s) => [s.dataPaneFields],
            (fields: BIDataPaneFields): BIField[] =>
                [...fields.dimensions, ...fields.measures].filter(
                    (field) => !(field.localDefinition?.kind === 'expression' && field.localDefinition.aggregate)
                ),
        ],
        availableFields: [
            (s) => [s.fields, s.draft],
            (fields: BIField[], draft: BIHierarchy | null): BIField[] =>
                fields.filter(
                    (field) => !draft?.levels.some((level) => hierarchyFieldKey(level) === hierarchyFieldKey(field))
                ),
        ],
        draftError: [
            (s) => [s.draft, s.config],
            (draft: BIHierarchy | null, config: BIConfig): string | undefined =>
                draft ? hierarchyError(draft, config) : 'Create a hierarchy',
        ],
        importHierarchies: [
            (s) => [s.hierarchySource],
            (source: InsightApi | null): BIHierarchy[] => {
                const query: unknown = source?.query
                return query && isBIVisualizationNode(query)
                    ? (parseBIEditorState(BIEditorView.BI, query.config)?.config.hierarchies ?? [])
                    : []
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        retryImport: () => {
            if (values.selectedWorksheetId !== null) {
                actions.loadHierarchySource(values.selectedWorksheetId)
            } else {
                actions.loadWorksheets()
            }
        },
        addLevel: ({ fieldId }) => {
            const field = values.availableFields.find((field) => field.id === fieldId)
            if (values.draft && field && values.draft.levels.length < 10) {
                actions.setDraft({ ...values.draft, levels: [...values.draft.levels, field] })
            }
        },
        startHierarchy: ({ id, shelf }) => {
            const hierarchy = values.config.hierarchies?.find((item) => item.id === id)
            if (hierarchy && !hierarchyError(hierarchy, values.config)) {
                const field = hierarchy.levels[0]
                actions.addFieldToShelf(
                    {
                        ...field,
                        id: uuid(),
                        localFieldId: field.localFieldId ?? (field.localDefinition ? field.id : undefined),
                    },
                    shelf
                )
            }
        },
        saveHierarchy: () => {
            if (values.draft && !values.draftError) {
                actions.upsertHierarchy({ ...values.draft, name: values.draft.name.trim() })
            }
        },
        openImport: () => actions.loadWorksheets(),
        setSearch: () => actions.loadWorksheets(),
        setPage: () => actions.loadWorksheets(),
        importHierarchy: ({ id }) => {
            const hierarchy = values.importHierarchies.find((item) => item.id === id)
            if (hierarchy) {
                actions.editHierarchy({
                    ...hierarchy,
                    id: uuid(),
                    levels: hierarchy.levels.map((field) => ({ ...field, id: uuid(), localFieldId: undefined })),
                })
            }
        },
    })),
])