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.

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

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

import { groupsModel } from '~/models/groupsModel'
import { HOGQL_COLUMNS_KEY } from '~/queries/nodes/DataTable/defaultEventsQuery'
import { GroupTypeIndex } from '~/types'

export interface ColumnConfiguratorLogicProps {
    key: string
    columns: string[]
    setColumns: (columns: string[]) => void
    isPersistent?: boolean
    contextKey?: string
    showTableViews?: boolean
    context?: {
        type: 'event_definition' | 'groups' | 'team_columns'
        eventDefinitionId?: string
        groupTypeIndex?: GroupTypeIndex
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface columnConfiguratorLogicValues {
    columns: string[]
    context: {
        eventDefinitionId?: string | undefined
        groupTypeIndex?: GroupTypeIndex | undefined
        type: 'event_definition' | 'groups' | 'team_columns'
    }
    modalVisible: boolean
    saveAsDefault: boolean
    savedColumnConfiguration: {
        columns: string[]
        id: string
    } | null
    savedColumnConfigurationLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface columnConfiguratorLogicActions {
    reportDataTableColumnsUpdated: (context_type: string) => {
        context_type: string
    } // eventUsageLogic
    setDefaultColumns: (args_0: { defaultColumns: string[]; groupTypeIndex: number }) => {
        defaultColumns: string[]
        groupTypeIndex: number
    } // groupsModel
    hideModal: () => {
        value: true
    }
    loadSavedColumnConfiguration: () => any
    loadSavedColumnConfigurationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSavedColumnConfigurationSuccess: (
        savedColumnConfiguration: {
            columns: string[]
            id: string
        } | null,
        payload?: any
    ) => {
        savedColumnConfiguration: {
            columns: string[]
            id: string
        } | null
        payload?: any
    }
    moveColumn: (
        oldIndex: number,
        newIndex: number
    ) => {
        newIndex: number
        oldIndex: number
    }
    save: () => {
        value: true
    }
    selectColumn: (column: string) => {
        column: string
    }
    setColumns: (columns: string[]) => {
        columns: string[]
    }
    showModal: () => {
        value: true
    }
    toggleSaveAsDefault: () => {
        value: true
    }
    unselectColumn: (column: string) => {
        column: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface columnConfiguratorLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        context: (arg: any) => {
            eventDefinitionId?: string | undefined
            groupTypeIndex?: GroupTypeIndex | undefined
            type: 'event_definition' | 'groups' | 'team_columns'
        }
    }
}

export type columnConfiguratorLogicType = MakeLogicType<
    columnConfiguratorLogicValues,
    columnConfiguratorLogicActions,
    ColumnConfiguratorLogicProps,
    columnConfiguratorLogicMeta
>

export const columnConfiguratorLogic = kea<columnConfiguratorLogicType>([
    props({} as ColumnConfiguratorLogicProps),
    path(['queries', 'nodes', 'DataTable', 'columnConfiguratorLogic']),
    key((props) => props.key),
    connect(() => ({
        actions: [eventUsageLogic, ['reportDataTableColumnsUpdated'], groupsModel, ['setDefaultColumns']],
    })),
    actions({
        showModal: true,
        hideModal: true,
        selectColumn: (column: string) => ({ column }),
        unselectColumn: (column: string) => ({ column }),
        setColumns: (columns: string[]) => ({ columns }),
        moveColumn: (oldIndex: number, newIndex: number) => ({ oldIndex, newIndex }),
        save: true,
        toggleSaveAsDefault: true,
    }),
    selectors(() => ({
        context: [
            () => [(_, props) => props.context],
            (context: NonNullable<ColumnConfiguratorLogicProps['context']>) => context,
        ],
    })),
    loaders(({ props }) => ({
        savedColumnConfiguration: [
            null as { id: string; columns: string[] } | null,
            {
                loadSavedColumnConfiguration: async (): Promise<{ id: string; columns: string[] } | null> => {
                    if (!props.contextKey) {
                        return null
                    }
                    const response = await api.columnConfigurations.list({
                        teamId: teamLogic.values.currentTeamId || undefined,
                        context_key: props.contextKey,
                    })
                    if (response.results && response.results.length > 0) {
                        return { id: response.results[0].id, columns: response.results[0].columns || [] }
                    }
                    return null
                },
            },
        ],
    })),
    reducers(({ props }) => ({
        saveAsDefault: [
            false,
            {
                toggleSaveAsDefault: (state) => !state,
                showModal: () => false,
            },
        ],
        modalVisible: [
            false,
            {
                showModal: () => true,
                hideModal: () => false,
                save: () => false,
            },
        ],
        columns: [
            props.columns,
            {
                setColumns: (_, { columns }) => columns,
                selectColumn: (state, { column }) => Array.from(new Set([...state, column])),
                unselectColumn: (state, { column }) => state.filter((c) => c !== column),
                moveColumn: (state, { oldIndex, newIndex }) => {
                    const newColumns = [...state]
                    const [removed] = newColumns.splice(oldIndex, 1)
                    newColumns.splice(newIndex, 0, removed)
                    return newColumns
                },
            },
        ],
    })),
    propsChanged(({ actions, props }, oldProps) => {
        if (JSON.stringify(props.columns) !== JSON.stringify(oldProps.columns)) {
            actions.setColumns(props.columns)
        }
    }),
    listeners(({ actions, values, props }) => ({
        loadSavedColumnConfigurationSuccess: ({ savedColumnConfiguration }) => {
            if (savedColumnConfiguration) {
                props.setColumns(savedColumnConfiguration.columns)
            }
        },
        save: async () => {
            actions.reportDataTableColumnsUpdated(props.contextKey ?? props.context?.type ?? 'live_events')
            if (!props.isPersistent || !values.saveAsDefault) {
                props.setColumns(values.columns)
                return
            }

            if (props.contextKey) {
                try {
                    if (values.savedColumnConfiguration?.id) {
                        await api.columnConfigurations.update({
                            teamId: teamLogic.values.currentTeamId || undefined,
                            id: values.savedColumnConfiguration.id,
                            data: { columns: values.columns },
                        })
                    } else {
                        const response = await api.columnConfigurations.create({
                            teamId: teamLogic.values.currentTeamId || undefined,
                            data: {
                                context_key: props.contextKey,
                                columns: values.columns,
                            },
                        })
                        actions.loadSavedColumnConfigurationSuccess({
                            id: response.id,
                            columns: response.columns || [],
                        })
                    }

                    lemonToast.success('Default columns saved')
                } catch (error: any) {
                    console.error('Error saving column configuration:', error)
                    lemonToast.error(error.detail || 'Failed to save column configuration')
                }
                props.setColumns(values.columns)
                return
            }

            if (props.context?.type === 'groups' && typeof props.context.groupTypeIndex === 'number') {
                try {
                    actions.setDefaultColumns({
                        groupTypeIndex: props.context.groupTypeIndex,
                        defaultColumns: values.columns,
                    })
                    lemonToast.success('Default columns saved for this group type')
                } catch (error) {
                    console.error('Error saving default columns to group type:', error)
                    lemonToast.error('Failed to save columns to group type')
                }
            } else if (props.context?.type === 'event_definition' && props.context.eventDefinitionId) {
                try {
                    await api.eventDefinitions.update({
                        eventDefinitionId: props.context.eventDefinitionId,
                        eventDefinitionData: {
                            default_columns: values.columns,
                        },
                    })
                    lemonToast.success('Default columns saved for this event')
                } catch (error: any) {
                    console.error('Error saving default columns to event definition:', error)
                    lemonToast.error(error.detail || 'Failed to save columns to event definition')
                }
            } else {
                // Team-wide default columns
                teamLogic.actions.updateCurrentTeam({ live_events_columns: [HOGQL_COLUMNS_KEY, ...values.columns] })
            }

            // Always update the columns in the query
            props.setColumns(values.columns)
        },
    })),
    afterMount(({ actions, props }) => {
        // Only load saved column configuration if table views aren't handling persistence
        if (props.contextKey && !props.showTableViews) {
            actions.loadSavedColumnConfiguration()
        }
    }),
])