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.

14.3 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, path, reducers, selectors, useValues } from 'kea'
import { actionToUrl, combineUrl, router, urlToAction } from 'kea-router'
import React from 'react'

import { IconInfo } from '@posthog/icons'

import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { TitleWithIcon } from 'lib/components/TitleWithIcon'
import { FEATURE_FLAGS, FeatureFlagKey } from 'lib/constants'
import { LemonTab } from 'lib/lemon-ui/LemonTabs'
import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { CoreEventsSettings } from 'scenes/settings/environment/CoreEventsSettings'
import { urls } from 'scenes/urls'

import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { ActivityScope, Breadcrumb } from '~/types'

import { ActionsTable } from 'products/actions/frontend/components/ActionsTable'
import { NewActionButton } from 'products/actions/frontend/components/NewActionButton'
import { RevenueAnalyticsSettings } from 'products/revenue_analytics/frontend/settings/RevenueAnalyticsSettings'

import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import { DefinitionsSceneTabs } from './DefinitionsSceneTabs'
import { EventDefinitionsTable } from './events/EventDefinitionsTable'
import { IngestionWarningsV2View } from './ingestion-warnings-v2/IngestionWarningsV2View'
import { IngestionWarningsView } from './ingestion-warnings/IngestionWarningsView'
import { DataWarehouseManagedViewsetsScene } from './managed-viewsets/DataWarehouseManagedViewsetsScene'
import { PropertyDefinitionsTable } from './properties/PropertyDefinitionsTable'
import { SchemaManagement } from './schema/SchemaManagement'
import { SqlVariablesTable } from './variables/SqlVariablesTable'

export enum DataManagementTab {
    Actions = 'actions',
    EventDefinitions = 'events',
    PropertyDefinitions = 'properties',
    SchemaManagement = 'schema',
    History = 'history',
    IngestionWarnings = 'warnings',
    IngestionWarningsV2 = 'warnings-v2',
    Revenue = 'revenue',
    CoreEvents = 'core-events',
    DataWarehouseManagedViewsets = 'data-warehouse-managed-viewsets',
    Variables = 'variables',
}

type TabConfig = {
    url: string
    label: LemonTab<any>['label']
    content: JSX.Element
    buttons?: React.ReactNode
    flag?: FeatureFlagKey
    tooltipDocLink?: string
    children?: {
        [path: string]: {
            component?: JSX.Element
        }
    }
}

const tabs: Record<DataManagementTab, TabConfig> = {
    [DataManagementTab.EventDefinitions]: {
        url: urls.eventDefinitions(),
        label: 'Event definitions',
        content: <EventDefinitionsTable />,
        tooltipDocLink: 'https://posthog.com/docs/data/events',
    },
    [DataManagementTab.Actions]: {
        url: urls.actions(),
        label: (
            <TitleWithIcon
                icon={
                    <Tooltip title="Actions consist of one or more events that you have decided to put into a deliberately-labeled bucket. They're used in insights and dashboards.">
                        <IconInfo />
                    </Tooltip>
                }
            >
                Actions
            </TitleWithIcon>
        ),
        buttons: <NewActionButton />,
        content: <ActionsTable />,
        tooltipDocLink: 'https://posthog.com/docs/data/actions',
    },
    [DataManagementTab.PropertyDefinitions]: {
        url: urls.propertyDefinitions(),
        label: (
            <TitleWithIcon
                icon={
                    <Tooltip title="Properties are additional data sent along with an event capture. Use properties to understand additional information about events and the actors that generate them.">
                        <IconInfo />
                    </Tooltip>
                }
            >
                Properties
            </TitleWithIcon>
        ),
        content: <PropertyDefinitionsTable />,
        tooltipDocLink: 'https://posthog.com/docs/new-to-posthog/understand-posthog#properties',
    },
    [DataManagementTab.SchemaManagement]: {
        url: urls.schemaManagement(),
        label: 'Property Groups',
        content: <SchemaManagement />,
        flag: FEATURE_FLAGS.SCHEMA_MANAGEMENT,
    },
    [DataManagementTab.History]: {
        url: urls.dataManagementHistory(),
        label: 'History',
        content: (
            <ActivityLog
                scope={ActivityScope.DATA_MANAGEMENT}
                caption="Only actions taken in the UI are captured in History. Automatic creation of definitions by ingestion is not shown here."
            />
        ),
        tooltipDocLink: 'https://posthog.com/docs/data#history',
    },
    [DataManagementTab.Revenue]: {
        url: urls.revenueSettings(),
        label: (
            <>
                Revenue{' '}
                <LemonTag type="warning" size="small" className="ml-2">
                    BETA
                </LemonTag>
            </>
        ),
        content: <RevenueAnalyticsSettings />,
    },
    [DataManagementTab.CoreEvents]: {
        url: urls.coreEvents(),
        label: (
            <TitleWithIcon
                icon={
                    <Tooltip title="Core events are key business events used across Marketing analytics, Customer analytics, and Revenue analytics.">
                        <IconInfo />
                    </Tooltip>
                }
            >
                Core events
            </TitleWithIcon>
        ),
        content: (
            <SceneContent>
                <DefinitionsSceneTabs activeKey="core-events" />
                <CoreEventsSettings />
            </SceneContent>
        ),
        flag: FEATURE_FLAGS.NEW_TEAM_CORE_EVENTS,
    },
    [DataManagementTab.IngestionWarnings]: {
        url: urls.ingestionWarnings(),
        label: 'Event ingestion warnings',
        content: <IngestionWarningsView />,
        tooltipDocLink: 'https://posthog.com/docs/data/ingestion-warnings',
    },
    [DataManagementTab.IngestionWarningsV2]: {
        url: urls.ingestionWarningsV2(),
        label: (
            <>
                Event ingestion warnings{' '}
                <LemonTag type="warning" size="small" className="ml-2">
                    V2
                </LemonTag>
            </>
        ),
        content: <IngestionWarningsV2View />,
        tooltipDocLink: 'https://posthog.com/docs/data/ingestion-warnings',
    },
    [DataManagementTab.DataWarehouseManagedViewsets]: {
        url: urls.dataWarehouseManagedViewsets(),
        label: 'Managed viewsets',
        content: <DataWarehouseManagedViewsetsScene />,
        flag: FEATURE_FLAGS.MANAGED_VIEWSETS,
    },
    [DataManagementTab.Variables]: {
        url: urls.variables(),
        label: 'SQL variables',
        content: <SqlVariablesTable />,
        tooltipDocLink: 'https://posthog.com/docs/sql',
    },
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataManagementSceneLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    breadcrumbs: Breadcrumb[]
    enabledTabs: DataManagementTab[]
    sidePanelContext: SidePanelSceneContext | null
    tab: DataManagementTab
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataManagementSceneLogicActions {
    setTab: (tab: DataManagementTab) => {
        tab: DataManagementTab
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataManagementSceneLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        breadcrumbs: (tab: DataManagementTab) => Breadcrumb[]
        enabledTabs: (featureFlags: FeatureFlagsSet) => DataManagementTab[]
        sidePanelContext: (tab: DataManagementTab) => SidePanelSceneContext | null
    }
}

export type dataManagementSceneLogicType = MakeLogicType<
    dataManagementSceneLogicValues,
    dataManagementSceneLogicActions,
    Record<string, any>,
    dataManagementSceneLogicMeta
>

const dataManagementSceneLogic = kea<dataManagementSceneLogicType>([
    path(['scenes', 'events', 'dataManagementSceneLogic']),
    connect(() => ({
        values: [featureFlagLogic, ['featureFlags']],
    })),
    actions({
        setTab: (tab: DataManagementTab) => ({ tab }),
    }),
    reducers({
        tab: [
            DataManagementTab.EventDefinitions as DataManagementTab,
            {
                setTab: (_, { tab }) => tab,
            },
        ],
    }),
    selectors({
        breadcrumbs: [
            (s) => [s.tab],
            (tab: DataManagementTab): Breadcrumb[] => {
                if (tab === DataManagementTab.EventDefinitions) {
                    return [
                        {
                            key: Scene.EventDefinition,
                            name: sceneConfigurations[Scene.EventDefinition].name,
                            path: urls.eventDefinitions(),
                            iconType: sceneConfigurations[Scene.EventDefinition].iconType || 'default_icon_type',
                        },
                    ]
                } else if (tab === DataManagementTab.PropertyDefinitions) {
                    return [
                        {
                            key: Scene.PropertyDefinition,
                            name: sceneConfigurations[Scene.PropertyDefinition].name,
                            path: urls.propertyDefinitions(),
                            iconType: sceneConfigurations[Scene.PropertyDefinition].iconType || 'default_icon_type',
                        },
                    ]
                } else if (tab === DataManagementTab.Revenue) {
                    return [
                        {
                            key: 'RevenueDefinitions',
                            name: 'Revenue analytics',
                            path: urls.revenueSettings(),
                            iconType: 'revenue_analytics',
                        },
                    ]
                } else if (tab === DataManagementTab.IngestionWarnings) {
                    return [
                        {
                            key: Scene.IngestionWarnings,
                            name: sceneConfigurations[Scene.IngestionWarnings].name,
                            path: urls.ingestionWarnings(),
                            iconType: sceneConfigurations[Scene.IngestionWarnings].iconType || 'default_icon_type',
                        },
                    ]
                } else if (tab === DataManagementTab.IngestionWarningsV2) {
                    return [
                        {
                            key: DataManagementTab.IngestionWarningsV2,
                            name: 'Event ingestion warnings v2',
                            path: urls.ingestionWarningsV2(),
                            iconType: sceneConfigurations[Scene.IngestionWarnings].iconType || 'default_icon_type',
                        },
                    ]
                }
                return [
                    {
                        key: tab,
                        name: capitalizeFirstLetter(tab),
                        path: tabs[tab].url,
                        iconType: 'event_definition',
                    },
                ]
            },
        ],
        enabledTabs: [
            (s) => [s.featureFlags],
            (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet): DataManagementTab[] => {
                const allTabs = Object.entries(tabs)

                return allTabs
                    .filter(([_, tab]) => {
                        return !tab.flag || !!featureFlags[tab.flag]
                    })
                    .map(([tabName, _]) => tabName) as DataManagementTab[]
            },
        ],
        [SIDE_PANEL_CONTEXT_KEY]: [
            (s) => [s.tab],
            (tab: DataManagementTab): SidePanelSceneContext | null => {
                const tabToScopeMap: Partial<Record<DataManagementTab, ActivityScope>> = {
                    [DataManagementTab.EventDefinitions]: ActivityScope.EVENT_DEFINITION,
                    [DataManagementTab.PropertyDefinitions]: ActivityScope.PROPERTY_DEFINITION,
                    [DataManagementTab.Actions]: ActivityScope.ACTION,
                }

                const currentScope = tabToScopeMap[tab]
                if (currentScope) {
                    return {
                        activity_scope: currentScope,
                    }
                }
                return null
            },
        ],
    }),
    actionToUrl(() => ({
        setTab: ({ tab }) => {
            const tabUrl = tabs[tab as DataManagementTab]?.url || tabs.events.url
            if (combineUrl(tabUrl).pathname === router.values.location.pathname) {
                // don't clear the parameters if we're already on the right page
                // otherwise we can't use a url with parameters as a landing page
                return
            }
            return [tabUrl, router.values.searchParams, router.values.hashParams]
        },
    })),
    urlToAction(({ actions, values }) => {
        const mappings: Record<string, () => void> = {}

        Object.entries(tabs).forEach(([tabKey, tabConfig]) => {
            const tabEnum = tabKey as DataManagementTab

            // First main tab URLs
            mappings[tabConfig.url] = () => {
                if (values.tab !== tabEnum) {
                    actions.setTab(tabEnum)
                }
            }

            // Then child URLs
            if (tabConfig.children) {
                Object.keys(tabConfig.children).forEach((childUrl) => {
                    mappings[childUrl] = () => {
                        if (values.tab !== tabEnum) {
                            actions.setTab(tabEnum)
                        }
                    }
                })
            }
        })

        return mappings
    }),
])

export function DataManagementScene(): JSX.Element | null {
    const { enabledTabs, tab } = useValues(dataManagementSceneLogic)

    if (enabledTabs.includes(tab)) {
        return <>{tabs[tab].content}</>
    }
    return null
}

export const scene: SceneExport = {
    component: DataManagementScene,
    logic: dataManagementSceneLogic,
}